Add Cross SDKs support (part 2)
[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/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         MFolder     *model.Folder
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(1)
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         // TODO allow to redirect stdout/sterr into logs file
119         //logFilename := filepath.Join(ctx.Config.FileConf.LogsDir + "xds-server.log")
120
121         // FIXME - add a builder interface and support other builder type (eg. native)
122         builderType := "syncthing"
123
124         switch builderType {
125         case "syncthing":
126
127                 // Start local instance of Syncthing and Syncthing-notify
128                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
129
130                 ctx.Log.Infof("Starting Syncthing...")
131                 ctx.SThgCmd, err = ctx.SThg.Start()
132                 if err != nil {
133                         return cli.NewExitError(err, 2)
134                 }
135                 ctx.Log.Infof("Syncthing started (PID %d)", ctx.SThgCmd.Process.Pid)
136
137                 ctx.Log.Infof("Starting Syncthing-inotify...")
138                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
139                 if err != nil {
140                         return cli.NewExitError(err, 2)
141                 }
142                 ctx.Log.Infof("Syncthing-inotify started (PID %d)", ctx.SThgInotCmd.Process.Pid)
143
144                 // Establish connection with local Syncthing (retry if connection fail)
145                 time.Sleep(2 * time.Second)
146                 retry := 10
147                 err = nil
148                 for retry > 0 {
149                         if err = ctx.SThg.Connect(); err == nil {
150                                 break
151                         }
152                         ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/10)", retry)
153                         time.Sleep(time.Second)
154                         retry--
155                 }
156                 if err != nil || retry == 0 {
157                         return cli.NewExitError(err, 2)
158                 }
159
160                 // Retrieve Syncthing config
161                 id, err := ctx.SThg.IDGet()
162                 if err != nil {
163                         return cli.NewExitError(err, 2)
164                 }
165
166                 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(id); err != nil {
167                         return cli.NewExitError(err, 2)
168                 }
169
170                 // Retrieve initial Syncthing config
171
172                 // FIXME: cannot retrieve default SDK, need to save on disk or somewhere
173                 // else all config to be able to restore it.
174                 defaultSdk := ""
175                 stCfg, err := ctx.SThg.ConfigGet()
176                 if err != nil {
177                         return cli.NewExitError(err, 2)
178                 }
179                 for _, stFld := range stCfg.Folders {
180                         relativePath := strings.TrimPrefix(stFld.RawPath, ctx.Config.ShareRootDir)
181                         if relativePath == "" {
182                                 relativePath = stFld.RawPath
183                         }
184
185                         newFld := xdsconfig.NewFolderConfig(stFld.ID, stFld.Label, ctx.Config.ShareRootDir, strings.Trim(relativePath, "/"), defaultSdk)
186                         ctx.Config.Folders = ctx.Config.Folders.Update(xdsconfig.FoldersConfig{newFld})
187                 }
188
189                 // Init model folder
190                 ctx.MFolder = model.NewFolder(ctx.Config, ctx.SThg)
191
192         default:
193                 err = fmt.Errorf("Unsupported builder type")
194                 return cli.NewExitError(err, 3)
195         }
196
197         // Init cross SDKs
198         ctx.SDKs, err = crosssdk.Init(ctx.Config, ctx.Log)
199         if err != nil {
200                 return cli.NewExitError(err, 2)
201         }
202
203         // Create and start Web Server
204         ctx.WWWServer = webserver.New(ctx.Config, ctx.MFolder, ctx.SDKs, ctx.Log)
205         if err = ctx.WWWServer.Serve(); err != nil {
206                 ctx.Log.Println(err)
207                 return cli.NewExitError(err, 3)
208         }
209
210         return cli.NewExitError("Program exited ", 4)
211 }
212
213 // main
214 func main() {
215
216         // Create a new instance of the logger
217         log := logrus.New()
218
219         // Create a new App instance
220         app := cli.NewApp()
221         app.Name = appName
222         app.Description = appDescription
223         app.Usage = appUsage
224         app.Version = AppVersion + " (" + AppSubVersion + ")"
225         app.Authors = appAuthors
226         app.Copyright = appCopyright
227         app.Metadata = make(map[string]interface{})
228         app.Metadata["version"] = AppVersion
229         app.Metadata["git-tag"] = AppSubVersion
230         app.Metadata["logger"] = log
231
232         app.Flags = []cli.Flag{
233                 cli.StringFlag{
234                         Name:   "config, c",
235                         Usage:  "JSON config file to use\n\t",
236                         EnvVar: "APP_CONFIG",
237                 },
238                 cli.StringFlag{
239                         Name:   "log, l",
240                         Value:  "error",
241                         Usage:  "logging level (supported levels: panic, fatal, error, warn, info, debug)\n\t",
242                         EnvVar: "LOG_LEVEL",
243                 },
244         }
245
246         // only one action: Web Server
247         app.Action = xdsApp
248
249         app.Run(os.Args)
250 }