Added -logfile option.
[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         "strings"
12         "syscall"
13         "time"
14
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"
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         MFolder     *model.Folder
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(1)
103 }
104
105 // XDS Server application main routine
106 func xdsApp(cliCtx *cli.Context) error {
107         var err error
108
109         // Create XDS server context
110         ctx := NewContext(cliCtx)
111
112         // Load config
113         cfg, err := xdsconfig.Init(ctx.Cli, ctx.Log)
114         if err != nil {
115                 return cli.NewExitError(err, 2)
116         }
117         ctx.Config = cfg
118
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"
124                 }
125                 // is it an absolute path ?
126                 logFile := logfilename
127                 if logfilename[0] == '.' || logfilename[0] != '/' {
128                         logFile = filepath.Join(ctx.Config.FileConf.LogsDir, logfilename)
129                 }
130                 fmt.Printf("Logging file: %s\n", logFile)
131                 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
132                 if err != nil {
133                         msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
134                         return cli.NewExitError(msgErr, int(syscall.EPERM))
135                 }
136                 ctx.Log.Out = fdL
137         }
138
139         // FIXME - add a builder interface and support other builder type (eg. native)
140         builderType := "syncthing"
141
142         switch builderType {
143         case "syncthing":
144
145                 // Start local instance of Syncthing and Syncthing-notify
146                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
147
148                 ctx.Log.Infof("Starting Syncthing...")
149                 ctx.SThgCmd, err = ctx.SThg.Start()
150                 if err != nil {
151                         return cli.NewExitError(err, 2)
152                 }
153                 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
154
155                 ctx.Log.Infof("Starting Syncthing-inotify...")
156                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
157                 if err != nil {
158                         return cli.NewExitError(err, 2)
159                 }
160                 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
161
162                 // Establish connection with local Syncthing (retry if connection fail)
163                 fmt.Printf("Establishing connection with Syncthing...\n")
164                 time.Sleep(2 * time.Second)
165                 maxRetry := 30
166                 retry := maxRetry
167                 err = nil
168                 for retry > 0 {
169                         if err = ctx.SThg.Connect(); err == nil {
170                                 break
171                         }
172                         ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
173                         time.Sleep(time.Second)
174                         retry--
175                 }
176                 if err != nil || retry == 0 {
177                         return cli.NewExitError(err, 2)
178                 }
179
180                 // Retrieve Syncthing config
181                 id, err := ctx.SThg.IDGet()
182                 if err != nil {
183                         return cli.NewExitError(err, 2)
184                 }
185
186                 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(id); err != nil {
187                         return cli.NewExitError(err, 2)
188                 }
189
190                 // Retrieve initial Syncthing config
191
192                 // FIXME: cannot retrieve default SDK, need to save on disk or somewhere
193                 // else all config to be able to restore it.
194                 defaultSdk := ""
195                 stCfg, err := ctx.SThg.ConfigGet()
196                 if err != nil {
197                         return cli.NewExitError(err, 2)
198                 }
199                 for _, stFld := range stCfg.Folders {
200                         relativePath := strings.TrimPrefix(stFld.RawPath, ctx.Config.FileConf.ShareRootDir)
201                         if relativePath == "" {
202                                 relativePath = stFld.RawPath
203                         }
204
205                         newFld := xdsconfig.NewFolderConfig(stFld.ID,
206                                 stFld.Label,
207                                 ctx.Config.FileConf.ShareRootDir,
208                                 strings.TrimRight(relativePath, "/"),
209                                 defaultSdk)
210                         ctx.Config.Folders = ctx.Config.Folders.Update(xdsconfig.FoldersConfig{newFld})
211                 }
212
213                 // Init model folder
214                 ctx.MFolder = model.NewFolder(ctx.Config, ctx.SThg)
215
216         default:
217                 err = fmt.Errorf("Unsupported builder type")
218                 return cli.NewExitError(err, 3)
219         }
220
221         // Init cross SDKs
222         ctx.SDKs, err = crosssdk.Init(ctx.Config, ctx.Log)
223         if err != nil {
224                 return cli.NewExitError(err, 2)
225         }
226
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 {
230                 ctx.Log.Println(err)
231                 return cli.NewExitError(err, 3)
232         }
233
234         return cli.NewExitError("Program exited ", 4)
235 }
236
237 // main
238 func main() {
239
240         // Create a new instance of the logger
241         log := logrus.New()
242
243         // Create a new App instance
244         app := cli.NewApp()
245         app.Name = appName
246         app.Description = appDescription
247         app.Usage = appUsage
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
255
256         app.Flags = []cli.Flag{
257                 cli.StringFlag{
258                         Name:   "config, c",
259                         Usage:  "JSON config file to use\n\t",
260                         EnvVar: "APP_CONFIG",
261                 },
262                 cli.StringFlag{
263                         Name:   "log, l",
264                         Value:  "error",
265                         Usage:  "logging level (supported levels: panic, fatal, error, warn, info, debug)\n\t",
266                         EnvVar: "LOG_LEVEL",
267                 },
268                 cli.StringFlag{
269                         Name:   "logfile",
270                         Value:  "stdout",
271                         Usage:  "filename where logs will be redirected (default stdout)\n\t",
272                         EnvVar: "LOG_FILENAME",
273                 },
274         }
275
276         // only one action: Web Server
277         app.Action = xdsApp
278
279         app.Run(os.Args)
280 }