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
56 // NewXdsServer Create a new instance of XDS server
57 func NewXdsServer(cliCtx *cli.Context) *Context {
60 // Set logger level and formatter
61 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
63 logLevel := cliCtx.GlobalString("log")
65 logLevel = "error" // FIXME get from Config DefaultLogLevel
67 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
68 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
71 log.Formatter = &logrus.TextFormatter{}
73 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
75 // Define default configuration
77 ProgName: cliCtx.App.Name,
80 LogLevelSilly: (sillyLog && sillyVal == "1"),
81 Exit: make(chan os.Signal, 1),
84 // register handler on SIGTERM / exit
85 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
86 go handlerSigTerm(&ctx)
91 // Run Main function called to run XDS Server
92 func (ctx *Context) Run() (int, error) {
95 // Logs redirected into a file when logfile option or logsDir config is set
96 ctx.Config.LogVerboseOut = os.Stderr
97 if ctx.Config.FileConf.LogsDir != "" {
98 if ctx.Config.Options.LogFile != "stdout" {
99 logFile := ctx.Config.Options.LogFile
101 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
103 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
104 return int(syscall.EPERM), fmt.Errorf(msgErr)
108 ctx._logPrint("Logging file: %s\n", logFile)
111 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
112 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
114 msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
115 return int(syscall.EPERM), fmt.Errorf(msgErr)
117 ctx.Config.LogVerboseOut = fdLH
119 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
122 // Create syncthing instance when section "syncthing" is present in config.json
123 if ctx.Config.FileConf.SThgConf != nil {
124 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
127 // Start local instance of Syncthing and Syncthing-notify
129 ctx.Log.Infof("Starting Syncthing...")
130 ctx.SThgCmd, err = ctx.SThg.Start()
134 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
136 ctx.Log.Infof("Starting Syncthing-inotify...")
137 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
141 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
143 // Establish connection with local Syncthing (retry if connection fail)
144 ctx._logPrint("Establishing connection with Syncthing...\n")
145 time.Sleep(2 * time.Second)
150 if err = ctx.SThg.Connect(); err == nil {
153 ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
154 time.Sleep(time.Second)
157 if err != nil || retry == 0 {
161 // FIXME: do we still need Builder notion ? if no cleanup
162 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
165 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
169 ctx.mfolders = FoldersNew(ctx)
171 // Load initial folders config from disk
172 if err := ctx.mfolders.LoadConfig(); err != nil {
177 ctx.sdks, err = NewSDKs(ctx)
183 ctx.WWWServer = NewWebServer(ctx)
186 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
188 // Run Web Server until exit requested (blocking call)
189 if err = ctx.WWWServer.Serve(); err != nil {
194 return -99, fmt.Errorf("Program exited ")
197 // Helper function to log message on both stdout and logger
198 func (ctx *Context) _logPrint(format string, args ...interface{}) {
199 fmt.Printf(format, args...)
200 if ctx.Log.Out != os.Stdout {
201 ctx.Log.Infof(format, args...)
205 // Handle exit and properly stop/close all stuff
206 func handlerSigTerm(ctx *Context) {
209 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
211 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
212 ctx.SThg.StopInotify()
214 if ctx.WWWServer != nil {
215 ctx.Log.Infof("Stoping Web server...")