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