14 "github.com/Sirupsen/logrus"
15 "github.com/codegangsta/cli"
16 "github.com/iotbzh/xds-server/lib/crosssdk"
17 "github.com/iotbzh/xds-server/lib/folder"
18 "github.com/iotbzh/xds-server/lib/model"
19 "github.com/iotbzh/xds-server/lib/syncthing"
20 "github.com/iotbzh/xds-server/lib/webserver"
21 "github.com/iotbzh/xds-server/lib/xdsconfig"
25 appName = "xds-server"
26 appDescription = "X(cross) Development System Server is a web server that allows to remotely cross build applications."
27 appCopyright = "Apache-2.0"
28 appUsage = "X(cross) Development System Server"
31 var appAuthors = []cli.Author{
32 cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
35 // AppVersion is the version of this application
36 var AppVersion = "?.?.?"
38 // AppSubVersion is the git tag id added to version string
39 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
40 var AppSubVersion = "unknown-dev"
42 // Context holds the XDS server context
46 Config *xdsconfig.Config
51 MFolders *model.Folders
53 WWWServer *webserver.Server
57 // NewContext Create a new instance of XDS server
58 func NewContext(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 // Define default configuration
76 ProgName: cliCtx.App.Name,
79 Exit: make(chan os.Signal, 1),
82 // register handler on SIGTERM / exit
83 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
84 go handlerSigTerm(&ctx)
89 // Handle exit and properly stop/close all stuff
90 func handlerSigTerm(ctx *Context) {
93 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
95 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
96 ctx.SThg.StopInotify()
98 if ctx.WWWServer != nil {
99 ctx.Log.Infof("Stoping Web server...")
105 // Helper function to log message on both stdout and logger
106 func logPrint(ctx *Context, format string, args ...interface{}) {
107 fmt.Printf(format, args...)
108 if ctx.Log.Out != os.Stdout {
109 ctx.Log.Infof(format, args...)
113 // XDS Server application main routine
114 func xdsApp(cliCtx *cli.Context) error {
117 // Create XDS server context
118 ctx := NewContext(cliCtx)
121 cfg, err := xdsconfig.Init(ctx.Cli, ctx.Log)
123 return cli.NewExitError(err, -2)
127 // Logs redirected into a file when logfile option or logsDir config is set
128 ctx.Config.LogVerboseOut = os.Stderr
129 if ctx.Config.FileConf.LogsDir != "" {
130 if ctx.Config.Options.LogFile != "stdout" {
131 logFile := ctx.Config.Options.LogFile
133 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
135 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
136 return cli.NewExitError(msgErr, int(syscall.EPERM))
140 logPrint(ctx, "Logging file: %s\n", logFile)
143 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
144 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
146 msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
147 return cli.NewExitError(msgErr, int(syscall.EPERM))
149 ctx.Config.LogVerboseOut = fdLH
151 logPrint(ctx, "Logging file for HTTP requests: %s\n", logFileHTTPReq)
154 // Create syncthing instance when section "syncthing" is present in config.json
155 if ctx.Config.FileConf.SThgConf != nil {
156 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
159 // Start local instance of Syncthing and Syncthing-notify
161 ctx.Log.Infof("Starting Syncthing...")
162 ctx.SThgCmd, err = ctx.SThg.Start()
164 return cli.NewExitError(err, -4)
166 logPrint(ctx, "Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
168 ctx.Log.Infof("Starting Syncthing-inotify...")
169 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
171 return cli.NewExitError(err, -4)
173 logPrint(ctx, "Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
175 // Establish connection with local Syncthing (retry if connection fail)
176 logPrint(ctx, "Establishing connection with Syncthing...\n")
177 time.Sleep(2 * time.Second)
182 if err = ctx.SThg.Connect(); err == nil {
185 ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
186 time.Sleep(time.Second)
189 if err != nil || retry == 0 {
190 return cli.NewExitError(err, -4)
193 // FIXME: do we still need Builder notion ? if no cleanup
194 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
195 return cli.NewExitError(err, -4)
197 ctx.Config.SupportedSharing[folder.TypeCloudSync] = true
201 ctx.MFolders = model.FoldersNew(ctx.Config, ctx.SThg)
203 // Load initial folders config from disk
204 if err := ctx.MFolders.LoadConfig(); err != nil {
205 return cli.NewExitError(err, -5)
209 ctx.SDKs, err = crosssdk.Init(ctx.Config, ctx.Log)
211 return cli.NewExitError(err, -6)
215 ctx.WWWServer = webserver.New(ctx.Config, ctx.MFolders, ctx.SDKs, ctx.Log)
217 // Run Web Server until exit requested (blocking call)
218 if err = ctx.WWWServer.Serve(); err != nil {
220 return cli.NewExitError(err, -7)
223 return cli.NewExitError("Program exited ", -99)
229 // Create a new instance of the logger
232 // Create a new App instance
235 app.Description = appDescription
237 app.Version = AppVersion + " (" + AppSubVersion + ")"
238 app.Authors = appAuthors
239 app.Copyright = appCopyright
240 app.Metadata = make(map[string]interface{})
241 app.Metadata["version"] = AppVersion
242 app.Metadata["git-tag"] = AppSubVersion
243 app.Metadata["logger"] = log
245 app.Flags = []cli.Flag{
248 Usage: "JSON config file to use\n\t",
249 EnvVar: "APP_CONFIG",
254 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)\n\t",
260 Usage: "filename where logs will be redirected (default stdout)\n\t",
261 EnvVar: "LOG_FILENAME",
264 Name: "no-folderconfig, nfc",
265 Usage: fmt.Sprintf("Do not read folder config file (%s)\n\t", xdsconfig.FoldersConfigFilename),
266 EnvVar: "NO_FOLDERCONFIG",
270 // only one action: Web Server