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/model"
18 "github.com/iotbzh/xds-server/lib/syncthing"
19 "github.com/iotbzh/xds-server/lib/webserver"
20 "github.com/iotbzh/xds-server/lib/xdsconfig"
24 appName = "xds-server"
25 appDescription = "X(cross) Development System Server is a web server that allows to remotely cross build applications."
26 appCopyright = "Apache-2.0"
27 appUsage = "X(cross) Development System Server"
30 var appAuthors = []cli.Author{
31 cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
34 // AppVersion is the version of this application
35 var AppVersion = "?.?.?"
37 // AppSubVersion is the git tag id added to version string
38 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
39 var AppSubVersion = "unknown-dev"
41 // Context holds the XDS server context
45 Config *xdsconfig.Config
50 MFolders *model.Folders
52 WWWServer *webserver.Server
56 // NewContext Create a new instance of XDS server
57 func NewContext(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 // Define default configuration
75 ProgName: cliCtx.App.Name,
78 Exit: make(chan os.Signal, 1),
81 // register handler on SIGTERM / exit
82 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
83 go handlerSigTerm(&ctx)
88 // Handle exit and properly stop/close all stuff
89 func handlerSigTerm(ctx *Context) {
92 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
94 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
95 ctx.SThg.StopInotify()
97 if ctx.WWWServer != nil {
98 ctx.Log.Infof("Stoping Web server...")
104 // Helper function to log message on both stdout and logger
105 func logPrint(ctx *Context, format string, args ...interface{}) {
106 fmt.Printf(format, args...)
107 if ctx.Log.Out != os.Stdout {
108 ctx.Log.Infof(format, args...)
112 // XDS Server application main routine
113 func xdsApp(cliCtx *cli.Context) error {
116 // Create XDS server context
117 ctx := NewContext(cliCtx)
120 cfg, err := xdsconfig.Init(ctx.Cli, ctx.Log)
122 return cli.NewExitError(err, -2)
126 // Logs redirected into a file when logfile option or logsDir config is set
127 ctx.Config.LogVerboseOut = os.Stderr
128 if ctx.Config.FileConf.LogsDir != "" {
129 if ctx.Config.Options.LogFile != "stdout" {
130 logFile := ctx.Config.Options.LogFile
132 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
134 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
135 return cli.NewExitError(msgErr, int(syscall.EPERM))
139 logPrint(ctx, "Logging file: %s\n", logFile)
142 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
143 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
145 msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
146 return cli.NewExitError(msgErr, int(syscall.EPERM))
148 ctx.Config.LogVerboseOut = fdLH
150 logPrint(ctx, "Logging file for HTTP requests: %s\n", logFileHTTPReq)
153 // Create syncthing instance when section "syncthing" is present in config.json
154 if ctx.Config.FileConf.SThgConf != nil {
155 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
158 // Start local instance of Syncthing and Syncthing-notify
160 ctx.Log.Infof("Starting Syncthing...")
161 ctx.SThgCmd, err = ctx.SThg.Start()
163 return cli.NewExitError(err, -4)
165 logPrint(ctx, "Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
167 ctx.Log.Infof("Starting Syncthing-inotify...")
168 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
170 return cli.NewExitError(err, -4)
172 logPrint(ctx, "Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
174 // Establish connection with local Syncthing (retry if connection fail)
175 logPrint(ctx, "Establishing connection with Syncthing...\n")
176 time.Sleep(2 * time.Second)
181 if err = ctx.SThg.Connect(); err == nil {
184 ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
185 time.Sleep(time.Second)
188 if err != nil || retry == 0 {
189 return cli.NewExitError(err, -4)
192 // FIXME: do we still need Builder notion ? if no cleanup
193 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
194 return cli.NewExitError(err, -4)
199 ctx.MFolders = model.FoldersNew(ctx.Config, ctx.SThg)
201 // Load initial folders config from disk
202 if err := ctx.MFolders.LoadConfig(); err != nil {
203 return cli.NewExitError(err, -5)
207 ctx.SDKs, err = crosssdk.Init(ctx.Config, ctx.Log)
209 return cli.NewExitError(err, -6)
213 ctx.WWWServer = webserver.New(ctx.Config, ctx.MFolders, ctx.SDKs, ctx.Log)
215 // Run Web Server until exit requested (blocking call)
216 if err = ctx.WWWServer.Serve(); err != nil {
218 return cli.NewExitError(err, -7)
221 return cli.NewExitError("Program exited ", -99)
227 // Create a new instance of the logger
230 // Create a new App instance
233 app.Description = appDescription
235 app.Version = AppVersion + " (" + AppSubVersion + ")"
236 app.Authors = appAuthors
237 app.Copyright = appCopyright
238 app.Metadata = make(map[string]interface{})
239 app.Metadata["version"] = AppVersion
240 app.Metadata["git-tag"] = AppSubVersion
241 app.Metadata["logger"] = log
243 app.Flags = []cli.Flag{
246 Usage: "JSON config file to use\n\t",
247 EnvVar: "APP_CONFIG",
252 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)\n\t",
258 Usage: "filename where logs will be redirected (default stdout)\n\t",
259 EnvVar: "LOG_FILENAME",
262 Name: "no-folderconfig, nfc",
263 Usage: fmt.Sprintf("Do not read folder config file (%s)\n\t", xdsconfig.FoldersConfigFilename),
264 EnvVar: "NO_FOLDERCONFIG",
268 // only one action: Web Server