12 "github.com/Sirupsen/logrus"
13 "github.com/codegangsta/cli"
14 "github.com/iotbzh/xds-server/lib/xsapiv1"
16 "github.com/iotbzh/xds-server/lib/syncthing"
17 "github.com/iotbzh/xds-server/lib/xdsconfig"
20 const cookieMaxAge = "3600"
22 // Context holds the XDS server context
26 Config *xdsconfig.Config
39 // NewXdsServer Create a new instance of XDS server
40 func NewXdsServer(cliCtx *cli.Context) *Context {
43 // Set logger level and formatter
44 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
46 logLevel := cliCtx.GlobalString("log")
48 logLevel = "error" // FIXME get from Config DefaultLogLevel
50 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
51 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
54 log.Formatter = &logrus.TextFormatter{}
56 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
58 // Define default configuration
60 ProgName: cliCtx.App.Name,
63 LogLevelSilly: (sillyLog && sillyVal == "1"),
64 Exit: make(chan os.Signal, 1),
67 // register handler on SIGTERM / exit
68 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
69 go handlerSigTerm(&ctx)
74 // Run Main function called to run XDS Server
75 func (ctx *Context) Run() (int, error) {
78 // Logs redirected into a file when logfile option or logsDir config is set
79 ctx.Config.LogVerboseOut = os.Stderr
80 if ctx.Config.FileConf.LogsDir != "" {
81 if ctx.Config.Options.LogFile != "stdout" {
82 logFile := ctx.Config.Options.LogFile
84 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
86 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
87 return int(syscall.EPERM), fmt.Errorf(msgErr)
91 ctx._logPrint("Logging file: %s\n", logFile)
94 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
95 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
97 msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
98 return int(syscall.EPERM), fmt.Errorf(msgErr)
100 ctx.Config.LogVerboseOut = fdLH
102 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
105 // Create syncthing instance when section "syncthing" is present in config.json
106 if ctx.Config.FileConf.SThgConf != nil {
107 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
110 // Start local instance of Syncthing and Syncthing-notify
112 ctx.Log.Infof("Starting Syncthing...")
113 ctx.SThgCmd, err = ctx.SThg.Start()
117 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
119 ctx.Log.Infof("Starting Syncthing-inotify...")
120 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
124 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
126 // Establish connection with local Syncthing (retry if connection fail)
127 ctx._logPrint("Establishing connection with Syncthing...\n")
128 time.Sleep(2 * time.Second)
133 if err = ctx.SThg.Connect(); err == nil {
136 ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
137 time.Sleep(time.Second)
140 if err != nil || retry == 0 {
144 // FIXME: do we still need Builder notion ? if no cleanup
145 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
148 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
152 ctx.mfolders = FoldersNew(ctx)
154 // Load initial folders config from disk
155 if err := ctx.mfolders.LoadConfig(); err != nil {
160 ctx.sdks, err = NewSDKs(ctx)
166 ctx.WWWServer = NewWebServer(ctx)
169 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
171 // Run Web Server until exit requested (blocking call)
172 if err = ctx.WWWServer.Serve(); err != nil {
177 return -99, fmt.Errorf("Program exited ")
180 // Helper function to log message on both stdout and logger
181 func (ctx *Context) _logPrint(format string, args ...interface{}) {
182 fmt.Printf(format, args...)
183 if ctx.Log.Out != os.Stdout {
184 ctx.Log.Infof(format, args...)
188 // Handle exit and properly stop/close all stuff
189 func handlerSigTerm(ctx *Context) {
192 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
194 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
195 ctx.SThg.StopInotify()
197 if ctx.WWWServer != nil {
198 ctx.Log.Infof("Stoping Web server...")