2 * Copyright (C) 2017 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
29 "github.com/Sirupsen/logrus"
30 "github.com/codegangsta/cli"
31 "github.com/iotbzh/xds-server/lib/xsapiv1"
33 "github.com/iotbzh/xds-server/lib/syncthing"
34 "github.com/iotbzh/xds-server/lib/xdsconfig"
37 const cookieMaxAge = "3600"
39 // Context holds the XDS server context
43 Config *xdsconfig.Config
46 LogSillyf func(format string, args ...interface{})
57 // NewXdsServer Create a new instance of XDS server
58 func NewXdsServer(cliCtx *cli.Context) *Context {
61 // Set logger level and formatter
62 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
64 logLevel := cliCtx.GlobalString("log")
66 logLevel = "error" // FIXME get from Config DefaultLogLevel
68 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
69 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
72 log.Formatter = &logrus.TextFormatter{}
74 // Support silly logging (printed on log.debug)
75 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
76 logSilly := sillyLog && sillyVal == "1"
77 sillyFunc := func(format string, args ...interface{}) {
79 log.Debugf("SILLY: "+format, args...)
83 // Define default configuration
85 ProgName: cliCtx.App.Name,
88 LogLevelSilly: logSilly,
90 Exit: make(chan os.Signal, 1),
93 // register handler on SIGTERM / exit
94 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
95 go handlerSigTerm(&ctx)
100 // Run Main function called to run XDS Server
101 func (ctx *Context) Run() (int, error) {
104 // Logs redirected into a file when logfile option or logsDir config is set
105 ctx.Config.LogVerboseOut = os.Stderr
106 if ctx.Config.FileConf.LogsDir != "" {
107 if ctx.Config.Options.LogFile != "stdout" {
108 logFile := ctx.Config.Options.LogFile
110 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
112 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
113 return int(syscall.EPERM), fmt.Errorf(msgErr)
117 ctx._logPrint("Logging file: %s\n", logFile)
120 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
121 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
123 msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
124 return int(syscall.EPERM), fmt.Errorf(msgErr)
126 ctx.Config.LogVerboseOut = fdLH
128 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
131 // Create syncthing instance when section "syncthing" is present in config.json
132 if ctx.Config.FileConf.SThgConf != nil {
133 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
136 // Start local instance of Syncthing and Syncthing-notify
138 ctx.Log.Infof("Starting Syncthing...")
139 ctx.SThgCmd, err = ctx.SThg.Start()
143 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
145 ctx.Log.Infof("Starting Syncthing-inotify...")
146 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
150 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
152 // Establish connection with local Syncthing (retry if connection fail)
153 ctx._logPrint("Establishing connection with Syncthing...\n")
154 time.Sleep(2 * time.Second)
159 if err = ctx.SThg.Connect(); err == nil {
162 ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
163 time.Sleep(time.Second)
166 if err != nil || retry == 0 {
170 // FIXME: do we still need Builder notion ? if no cleanup
171 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
174 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
178 ctx.mfolders = FoldersNew(ctx)
180 // Load initial folders config from disk
181 if err := ctx.mfolders.LoadConfig(); err != nil {
186 ctx.sdks, err = NewSDKs(ctx)
192 ctx.WWWServer = NewWebServer(ctx)
195 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
197 // Run Web Server until exit requested (blocking call)
198 if err = ctx.WWWServer.Serve(); err != nil {
203 return -99, fmt.Errorf("Program exited ")
206 // Helper function to log message on both stdout and logger
207 func (ctx *Context) _logPrint(format string, args ...interface{}) {
208 fmt.Printf(format, args...)
209 if ctx.Log.Out != os.Stdout {
210 ctx.Log.Infof(format, args...)
214 // Handle exit and properly stop/close all stuff
215 func handlerSigTerm(ctx *Context) {
218 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
220 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
221 ctx.SThg.StopInotify()
223 if ctx.WWWServer != nil {
224 ctx.Log.Infof("Stoping Web server...")