Auto start Syncthing and Syncthing-inotify.
[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         "strings"
11         "syscall"
12         "time"
13
14         "github.com/Sirupsen/logrus"
15         "github.com/codegangsta/cli"
16         "github.com/iotbzh/xds-server/lib/model"
17         "github.com/iotbzh/xds-server/lib/syncthing"
18         "github.com/iotbzh/xds-server/lib/webserver"
19         "github.com/iotbzh/xds-server/lib/xdsconfig"
20 )
21
22 const (
23         appName        = "xds-server"
24         appDescription = "X(cross) Development System Server is a web server that allows to remotely cross build applications."
25         appCopyright   = "Apache-2.0"
26         appUsage       = "X(cross) Development System Server"
27 )
28
29 var appAuthors = []cli.Author{
30         cli.Author{Name: "Sebastien Douheret", Email: "sebastien@iot.bzh"},
31 }
32
33 // AppVersion is the version of this application
34 var AppVersion = "?.?.?"
35
36 // AppSubVersion is the git tag id added to version string
37 // Should be set by compilation -ldflags "-X main.AppSubVersion=xxx"
38 var AppSubVersion = "unknown-dev"
39
40 // Context holds the XDS server context
41 type Context struct {
42         ProgName  string
43         Cli       *cli.Context
44         Config    *xdsconfig.Config
45         Log       *logrus.Logger
46         SThg      *st.SyncThing
47         SThgCmd   *exec.Cmd
48         MFolder   *model.Folder
49         WWWServer *webserver.ServerService
50         Exit      chan os.Signal
51 }
52
53 // NewContext Create a new instance of XDS server
54 func NewContext(cliCtx *cli.Context) *Context {
55         var err error
56
57         // Set logger level and formatter
58         log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
59
60         logLevel := cliCtx.GlobalString("log")
61         if logLevel == "" {
62                 logLevel = "error" // FIXME get from Config DefaultLogLevel
63         }
64         if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
65                 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
66                 os.Exit(1)
67         }
68         log.Formatter = &logrus.TextFormatter{}
69
70         // Define default configuration
71         ctx := Context{
72                 ProgName: cliCtx.App.Name,
73                 Cli:      cliCtx,
74                 Log:      log,
75                 Exit:     make(chan os.Signal, 1),
76         }
77
78         // register handler on SIGTERM / exit
79         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
80         go handlerSigTerm(&ctx)
81
82         return &ctx
83 }
84
85 // Handle exit and properly stop/close all stuff
86 func handlerSigTerm(ctx *Context) {
87         <-ctx.Exit
88         if ctx.SThg != nil {
89                 ctx.Log.Infof("Stopping Syncthing... (PID %d)",
90                         ctx.SThgCmd.Process.Pid)
91                 ctx.SThg.Stop()
92         }
93         if ctx.WWWServer != nil {
94                 ctx.Log.Infof("Stoping Web server...")
95                 ctx.WWWServer.Stop()
96         }
97         os.Exit(1)
98 }
99
100 // xdsServer main routine
101 func xdsApp(cliCtx *cli.Context) error {
102         var err error
103
104         // Create XDS server context
105         ctx := NewContext(cliCtx)
106
107         // Load config
108         cfg, err := xdsconfig.Init(ctx.Cli, ctx.Log)
109         if err != nil {
110                 return cli.NewExitError(err, 2)
111         }
112         ctx.Config = cfg
113
114         // TODO allow to redirect stdout/sterr into logs file
115         //logFilename := filepath.Join(ctx.Config.FileConf.LogsDir + "xds-server.log")
116
117         // FIXME - add a builder interface and support other builder type (eg. native)
118         builderType := "syncthing"
119
120         switch builderType {
121         case "syncthing":
122
123                 // Start local instance of Syncthing and Syncthing-notify
124                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
125
126                 ctx.Log.Infof("Starting Syncthing...")
127                 ctx.SThgCmd, err = ctx.SThg.Start()
128                 if err != nil {
129                         return cli.NewExitError(err, 2)
130                 }
131                 ctx.Log.Infof("Syncthing started (PID %d)", ctx.SThgCmd.Process.Pid)
132
133                 // Establish connection with local Syncthing (retry if connection fail)
134                 retry := 10
135                 err = nil
136                 for retry > 0 {
137                         if err = ctx.SThg.Connect(); err == nil {
138                                 break
139                         }
140                         ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/10)", retry)
141                         time.Sleep(time.Second)
142                         retry--
143                 }
144                 if err != nil || retry == 0 {
145                         return cli.NewExitError(err, 2)
146                 }
147
148                 // Retrieve Syncthing config
149                 id, err := ctx.SThg.IDGet()
150                 if err != nil {
151                         return cli.NewExitError(err, 2)
152                 }
153
154                 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(id); err != nil {
155                         return cli.NewExitError(err, 2)
156                 }
157
158                 // Retrieve initial Syncthing config
159                 stCfg, err := ctx.SThg.ConfigGet()
160                 if err != nil {
161                         return cli.NewExitError(err, 2)
162                 }
163                 for _, stFld := range stCfg.Folders {
164                         relativePath := strings.TrimPrefix(stFld.RawPath, ctx.Config.ShareRootDir)
165                         if relativePath == "" {
166                                 relativePath = stFld.RawPath
167                         }
168                         newFld := xdsconfig.NewFolderConfig(stFld.ID, stFld.Label, ctx.Config.ShareRootDir, strings.Trim(relativePath, "/"))
169                         ctx.Config.Folders = ctx.Config.Folders.Update(xdsconfig.FoldersConfig{newFld})
170                 }
171
172                 // Init model folder
173                 ctx.MFolder = model.NewFolder(ctx.Config, ctx.SThg)
174
175         default:
176                 err = fmt.Errorf("Unsupported builder type")
177                 return cli.NewExitError(err, 3)
178         }
179
180         // Create and start Web Server
181         ctx.WWWServer = webserver.NewServer(ctx.Config, ctx.MFolder, ctx.Log)
182         if err = ctx.WWWServer.Serve(); err != nil {
183                 ctx.Log.Println(err)
184                 return cli.NewExitError(err, 3)
185         }
186
187         return cli.NewExitError("Program exited ", 4)
188 }
189
190 // main
191 func main() {
192
193         // Create a new instance of the logger
194         log := logrus.New()
195
196         // Create a new App instance
197         app := cli.NewApp()
198         app.Name = appName
199         app.Description = appDescription
200         app.Usage = appUsage
201         app.Version = AppVersion + " (" + AppSubVersion + ")"
202         app.Authors = appAuthors
203         app.Copyright = appCopyright
204         app.Metadata = make(map[string]interface{})
205         app.Metadata["version"] = AppVersion
206         app.Metadata["git-tag"] = AppSubVersion
207         app.Metadata["logger"] = log
208
209         app.Flags = []cli.Flag{
210                 cli.StringFlag{
211                         Name:   "config, c",
212                         Usage:  "JSON config file to use\n\t",
213                         EnvVar: "APP_CONFIG",
214                 },
215                 cli.StringFlag{
216                         Name:   "log, l",
217                         Value:  "error",
218                         Usage:  "logging level (supported levels: panic, fatal, error, warn, info, debug)\n\t",
219                         EnvVar: "LOG_LEVEL",
220                 },
221         }
222
223         // only one action: Web Server
224         app.Action = xdsApp
225
226         app.Run(os.Args)
227 }