15 "github.com/Sirupsen/logrus"
16 "github.com/codegangsta/cli"
17 "github.com/iotbzh/xds-server/lib/crosssdk"
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
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 // XDS Server application main routine
106 func xdsApp(cliCtx *cli.Context) error {
109 // Create XDS server context
110 ctx := NewContext(cliCtx)
113 cfg, err := xdsconfig.Init(ctx.Cli, ctx.Log)
115 return cli.NewExitError(err, 2)
119 // Logs redirected into a file when logsDir is set
120 logfilename := cliCtx.GlobalString("logfile")
121 if ctx.Config.FileConf.LogsDir != "" && logfilename != "stdout" {
122 if logfilename == "" {
123 logfilename = "xds-server.log"
125 // is it an absolute path ?
126 logFile := logfilename
127 if logfilename[0] == '.' || logfilename[0] != '/' {
128 logFile = filepath.Join(ctx.Config.FileConf.LogsDir, logfilename)
130 fmt.Printf("Logging file: %s\n", logFile)
131 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
133 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
134 return cli.NewExitError(msgErr, int(syscall.EPERM))
139 // FIXME - add a builder interface and support other builder type (eg. native)
140 builderType := "syncthing"
145 // Start local instance of Syncthing and Syncthing-notify
146 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
148 ctx.Log.Infof("Starting Syncthing...")
149 ctx.SThgCmd, err = ctx.SThg.Start()
151 return cli.NewExitError(err, 2)
153 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
155 ctx.Log.Infof("Starting Syncthing-inotify...")
156 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
158 return cli.NewExitError(err, 2)
160 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
162 // Establish connection with local Syncthing (retry if connection fail)
163 fmt.Printf("Establishing connection with Syncthing...\n")
164 time.Sleep(2 * time.Second)
169 if err = ctx.SThg.Connect(); err == nil {
172 ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
173 time.Sleep(time.Second)
176 if err != nil || retry == 0 {
177 return cli.NewExitError(err, 2)
180 // Retrieve Syncthing config
181 id, err := ctx.SThg.IDGet()
183 return cli.NewExitError(err, 2)
186 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(id); err != nil {
187 return cli.NewExitError(err, 2)
190 // Retrieve initial Syncthing config
192 // FIXME: cannot retrieve default SDK, need to save on disk or somewhere
193 // else all config to be able to restore it.
195 stCfg, err := ctx.SThg.ConfigGet()
197 return cli.NewExitError(err, 2)
199 for _, stFld := range stCfg.Folders {
200 relativePath := strings.TrimPrefix(stFld.RawPath, ctx.Config.FileConf.ShareRootDir)
201 if relativePath == "" {
202 relativePath = stFld.RawPath
205 newFld := xdsconfig.NewFolderConfig(stFld.ID,
207 ctx.Config.FileConf.ShareRootDir,
208 strings.TrimRight(relativePath, "/"),
210 ctx.Config.Folders = ctx.Config.Folders.Update(xdsconfig.FoldersConfig{newFld})
214 ctx.MFolder = model.NewFolder(ctx.Config, ctx.SThg)
217 err = fmt.Errorf("Unsupported builder type")
218 return cli.NewExitError(err, 3)
222 ctx.SDKs, err = crosssdk.Init(ctx.Config, ctx.Log)
224 return cli.NewExitError(err, 2)
227 // Create and start Web Server
228 ctx.WWWServer = webserver.New(ctx.Config, ctx.MFolder, ctx.SDKs, ctx.Log)
229 if err = ctx.WWWServer.Serve(); err != nil {
231 return cli.NewExitError(err, 3)
234 return cli.NewExitError("Program exited ", 4)
240 // Create a new instance of the logger
243 // Create a new App instance
246 app.Description = appDescription
248 app.Version = AppVersion + " (" + AppSubVersion + ")"
249 app.Authors = appAuthors
250 app.Copyright = appCopyright
251 app.Metadata = make(map[string]interface{})
252 app.Metadata["version"] = AppVersion
253 app.Metadata["git-tag"] = AppSubVersion
254 app.Metadata["logger"] = log
256 app.Flags = []cli.Flag{
259 Usage: "JSON config file to use\n\t",
260 EnvVar: "APP_CONFIG",
265 Usage: "logging level (supported levels: panic, fatal, error, warn, info, debug)\n\t",
271 Usage: "filename where logs will be redirected (default stdout)\n\t",
272 EnvVar: "LOG_FILENAME",
276 // only one action: Web Server