Add Server UUID and use it build CmdID.
[src/xds/xds-server.git] / main.go
1 // TODO add Doc
2 //
3 package main
4
5 import (
6         "fmt"
7         "os"
8         "os/exec"
9         "os/signal"
10         "path/filepath"
11         "syscall"
12         "time"
13
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"
22 )
23
24 const (
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"
29 )
30
31 var appAuthors = []cli.Author{
32         cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
33 }
34
35 // AppVersion is the version of this application
36 var AppVersion = "?.?.?"
37
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"
41
42 // Context holds the XDS server context
43 type Context struct {
44         ProgName    string
45         Cli         *cli.Context
46         Config      *xdsconfig.Config
47         Log         *logrus.Logger
48         SThg        *st.SyncThing
49         SThgCmd     *exec.Cmd
50         SThgInotCmd *exec.Cmd
51         MFolders    *model.Folders
52         SDKs        *crosssdk.SDKs
53         WWWServer   *webserver.Server
54         Exit        chan os.Signal
55 }
56
57 // NewContext Create a new instance of XDS server
58 func NewContext(cliCtx *cli.Context) *Context {
59         var err error
60
61         // Set logger level and formatter
62         log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
63
64         logLevel := cliCtx.GlobalString("log")
65         if logLevel == "" {
66                 logLevel = "error" // FIXME get from Config DefaultLogLevel
67         }
68         if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
69                 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
70                 os.Exit(1)
71         }
72         log.Formatter = &logrus.TextFormatter{}
73
74         // Define default configuration
75         ctx := Context{
76                 ProgName: cliCtx.App.Name,
77                 Cli:      cliCtx,
78                 Log:      log,
79                 Exit:     make(chan os.Signal, 1),
80         }
81
82         // register handler on SIGTERM / exit
83         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
84         go handlerSigTerm(&ctx)
85
86         return &ctx
87 }
88
89 // Handle exit and properly stop/close all stuff
90 func handlerSigTerm(ctx *Context) {
91         <-ctx.Exit
92         if ctx.SThg != nil {
93                 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
94                 ctx.SThg.Stop()
95                 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
96                 ctx.SThg.StopInotify()
97         }
98         if ctx.WWWServer != nil {
99                 ctx.Log.Infof("Stoping Web server...")
100                 ctx.WWWServer.Stop()
101         }
102         os.Exit(0)
103 }
104
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...)
110         }
111 }
112
113 // XDS Server application main routine
114 func xdsApp(cliCtx *cli.Context) error {
115         var err error
116
117         // Create XDS server context
118         ctx := NewContext(cliCtx)
119
120         // Load config
121         cfg, err := xdsconfig.Init(ctx.Cli, ctx.Log)
122         if err != nil {
123                 return cli.NewExitError(err, -2)
124         }
125         ctx.Config = cfg
126
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
132
133                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
134                         if err != nil {
135                                 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
136                                 return cli.NewExitError(msgErr, int(syscall.EPERM))
137                         }
138                         ctx.Log.Out = fdL
139
140                         logPrint(ctx, "Logging file: %s\n", logFile)
141                 }
142
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)
145                 if err != nil {
146                         msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
147                         return cli.NewExitError(msgErr, int(syscall.EPERM))
148                 }
149                 ctx.Config.LogVerboseOut = fdLH
150
151                 logPrint(ctx, "Logging file for HTTP requests:  %s\n", logFileHTTPReq)
152         }
153
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)
157         }
158
159         // Start local instance of Syncthing and Syncthing-notify
160         if ctx.SThg != nil {
161                 ctx.Log.Infof("Starting Syncthing...")
162                 ctx.SThgCmd, err = ctx.SThg.Start()
163                 if err != nil {
164                         return cli.NewExitError(err, -4)
165                 }
166                 logPrint(ctx, "Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
167
168                 ctx.Log.Infof("Starting Syncthing-inotify...")
169                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
170                 if err != nil {
171                         return cli.NewExitError(err, -4)
172                 }
173                 logPrint(ctx, "Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
174
175                 // Establish connection with local Syncthing (retry if connection fail)
176                 logPrint(ctx, "Establishing connection with Syncthing...\n")
177                 time.Sleep(2 * time.Second)
178                 maxRetry := 30
179                 retry := maxRetry
180                 err = nil
181                 for retry > 0 {
182                         if err = ctx.SThg.Connect(); err == nil {
183                                 break
184                         }
185                         ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
186                         time.Sleep(time.Second)
187                         retry--
188                 }
189                 if err != nil || retry == 0 {
190                         return cli.NewExitError(err, -4)
191                 }
192
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)
196                 }
197                 ctx.Config.SupportedSharing[folder.TypeCloudSync] = true
198         }
199
200         // Init model folder
201         ctx.MFolders = model.FoldersNew(ctx.Config, ctx.SThg)
202
203         // Load initial folders config from disk
204         if err := ctx.MFolders.LoadConfig(); err != nil {
205                 return cli.NewExitError(err, -5)
206         }
207
208         // Init cross SDKs
209         ctx.SDKs, err = crosssdk.Init(ctx.Config, ctx.Log)
210         if err != nil {
211                 return cli.NewExitError(err, -6)
212         }
213
214         // Create Web Server
215         ctx.WWWServer = webserver.New(ctx.Config, ctx.MFolders, ctx.SDKs, ctx.Log)
216
217         // Run Web Server until exit requested (blocking call)
218         if err = ctx.WWWServer.Serve(); err != nil {
219                 ctx.Log.Println(err)
220                 return cli.NewExitError(err, -7)
221         }
222
223         return cli.NewExitError("Program exited ", -99)
224 }
225
226 // main
227 func main() {
228
229         // Create a new instance of the logger
230         log := logrus.New()
231
232         // Create a new App instance
233         app := cli.NewApp()
234         app.Name = appName
235         app.Description = appDescription
236         app.Usage = appUsage
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
244
245         app.Flags = []cli.Flag{
246                 cli.StringFlag{
247                         Name:   "config, c",
248                         Usage:  "JSON config file to use\n\t",
249                         EnvVar: "APP_CONFIG",
250                 },
251                 cli.StringFlag{
252                         Name:   "log, l",
253                         Value:  "error",
254                         Usage:  "logging level (supported levels: panic, fatal, error, warn, info, debug)\n\t",
255                         EnvVar: "LOG_LEVEL",
256                 },
257                 cli.StringFlag{
258                         Name:   "logfile",
259                         Value:  "stdout",
260                         Usage:  "filename where logs will be redirected (default stdout)\n\t",
261                         EnvVar: "LOG_FILENAME",
262                 },
263                 cli.BoolFlag{
264                         Name:   "no-folderconfig, nfc",
265                         Usage:  fmt.Sprintf("Do not read folder config file (%s)\n\t", xdsconfig.FoldersConfigFilename),
266                         EnvVar: "NO_FOLDERCONFIG",
267                 },
268         }
269
270         // only one action: Web Server
271         app.Action = xdsApp
272
273         app.Run(os.Args)
274 }