bb8f75596d2fa7304f6f6826ea4bc0066da0fdf9
[src/xds/xds-server.git] / lib / xdsserver / xdsserver.go
1 /*
2  * Copyright (C) 2017-2018 "IoT.bzh"
3  * Author Sebastien Douheret <sebastien@iot.bzh>
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package xdsserver
19
20 import (
21         "fmt"
22         "os"
23         "os/exec"
24         "os/signal"
25         "path/filepath"
26         "syscall"
27         "time"
28
29         st "gerrit.automotivelinux.org/gerrit/src/xds/xds-server/lib/syncthing"
30         "gerrit.automotivelinux.org/gerrit/src/xds/xds-server/lib/xdsconfig"
31         "gerrit.automotivelinux.org/gerrit/src/xds/xds-server/lib/xsapiv1"
32         "github.com/Sirupsen/logrus"
33         "github.com/codegangsta/cli"
34 )
35
36 const cookieMaxAge = "3600"
37
38 // Context holds the XDS server context
39 type Context struct {
40         ProgName      string
41         Cli           *cli.Context
42         Config        *xdsconfig.Config
43         Log           *logrus.Logger
44         LogLevelSilly bool
45         LogSillyf     func(format string, args ...interface{})
46         SThg          *st.SyncThing
47         SThgCmd       *exec.Cmd
48         SThgInotCmd   *exec.Cmd
49         mfolders      *Folders
50         sdks          *SDKs
51         WWWServer     *WebServer
52         sessions      *Sessions
53         events        *Events
54         Exit          chan os.Signal
55 }
56
57 // NewXdsServer Create a new instance of XDS server
58 func NewXdsServer(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         // Support silly logging (printed on log.debug)
75         sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
76         logSilly := sillyLog && sillyVal == "1"
77         sillyFunc := func(format string, args ...interface{}) {
78                 if logSilly {
79                         log.Debugf("SILLY: "+format, args...)
80                 }
81         }
82
83         // Define default configuration
84         ctx := Context{
85                 ProgName:      cliCtx.App.Name,
86                 Cli:           cliCtx,
87                 Log:           log,
88                 LogLevelSilly: logSilly,
89                 LogSillyf:     sillyFunc,
90                 Exit:          make(chan os.Signal, 1),
91         }
92
93         // register handler on SIGTERM / exit
94         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
95         go handlerSigTerm(&ctx)
96
97         return &ctx
98 }
99
100 // Run Main function called to run XDS Server
101 func (ctx *Context) Run() (int, error) {
102         var err error
103
104         // Logs redirected into a file when logfile option or logsDir config is set
105         ctx.Config.LogVerboseOut = os.Stderr
106         if ctx.Config.FileConf.LogsDir != "" {
107                 if ctx.Config.Options.LogFile != "stdout" {
108                         logFile := ctx.Config.Options.LogFile
109
110                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
111                         if err != nil {
112                                 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
113                                 return int(syscall.EPERM), fmt.Errorf(msgErr)
114                         }
115                         ctx.Log.Out = fdL
116
117                         ctx._logPrint("Logging file: %s\n", logFile)
118                 }
119
120                 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
121                 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
122                 if err != nil {
123                         msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
124                         return int(syscall.EPERM), fmt.Errorf(msgErr)
125                 }
126                 ctx.Config.LogVerboseOut = fdLH
127
128                 ctx._logPrint("Logging file for HTTP requests:  %s\n", logFileHTTPReq)
129         }
130
131         // Create events management
132         ctx.events = NewEvents(ctx)
133
134         // Create syncthing instance when section "syncthing" is present in server-config.json
135         if ctx.Config.FileConf.SThgConf != nil {
136                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
137         }
138
139         // Start local instance of Syncthing and Syncthing-notify
140         if ctx.SThg != nil {
141                 ctx.Log.Infof("Starting Syncthing...")
142                 ctx.SThgCmd, err = ctx.SThg.Start()
143                 if err != nil {
144                         return -4, err
145                 }
146                 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
147
148                 ctx.Log.Infof("Starting Syncthing-inotify...")
149                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
150                 if err != nil {
151                         return -4, err
152                 }
153                 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
154
155                 // Establish connection with local Syncthing (retry if connection fail)
156                 ctx._logPrint("Establishing connection with Syncthing...\n")
157                 time.Sleep(2 * time.Second)
158                 maxRetry := 30
159                 retry := maxRetry
160                 err = nil
161                 for retry > 0 {
162                         if err = ctx.SThg.Connect(); err == nil {
163                                 break
164                         }
165                         ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
166                         time.Sleep(time.Second)
167                         retry--
168                 }
169                 if err != nil || retry == 0 {
170                         return -4, err
171                 }
172
173                 // FIXME: do we still need Builder notion ? if no cleanup
174                 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
175                         return -4, err
176                 }
177                 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
178         }
179
180         // Init model folder
181         ctx.mfolders = FoldersNew(ctx)
182
183         // Load initial folders config from disk
184         if err := ctx.mfolders.LoadConfig(); err != nil {
185                 return -5, err
186         }
187
188         // Init cross SDKs
189         ctx.sdks, err = NewSDKs(ctx)
190         if err != nil {
191                 return -6, err
192         }
193
194         // Create Web Server
195         ctx.WWWServer = NewWebServer(ctx)
196
197         // Sessions manager
198         ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
199
200         // Run Web Server until exit requested (blocking call)
201         if err = ctx.WWWServer.Serve(); err != nil {
202                 ctx.Log.Println(err)
203                 return -7, err
204         }
205
206         return -99, fmt.Errorf("Program exited ")
207 }
208
209 // Helper function to log message on both stdout and logger
210 func (ctx *Context) _logPrint(format string, args ...interface{}) {
211         fmt.Printf(format, args...)
212         if ctx.Log.Out != os.Stdout {
213                 ctx.Log.Infof(format, args...)
214         }
215 }
216
217 // Handle exit and properly stop/close all stuff
218 func handlerSigTerm(ctx *Context) {
219         <-ctx.Exit
220         if ctx.SThg != nil {
221                 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
222                 ctx.SThg.Stop()
223                 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
224                 ctx.SThg.StopInotify()
225         }
226         if ctx.WWWServer != nil {
227                 ctx.Log.Infof("Stoping Web server...")
228                 ctx.WWWServer.Stop()
229         }
230         os.Exit(0)
231 }