Use go module as dependency tool instead of glide
[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.git/lib/syncthing"
30         "gerrit.automotivelinux.org/gerrit/src/xds/xds-server.git/lib/xdsconfig"
31         "gerrit.automotivelinux.org/gerrit/src/xds/xds-server.git/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         targets          *Targets
52         WWWServer        *WebServer
53         sessions         *Sessions
54         events           *Events
55         lockXdsSrvUpdate LockXdsUpdate
56         Exit             chan os.Signal
57 }
58
59 // NewXdsServer Create a new instance of XDS server
60 func NewXdsServer(cliCtx *cli.Context) *Context {
61         var err error
62
63         // Set logger level and formatter
64         log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
65
66         logLevel := cliCtx.GlobalString("log")
67         if logLevel == "" {
68                 logLevel = "error" // FIXME get from Config DefaultLogLevel
69         }
70         if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
71                 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
72                 os.Exit(1)
73         }
74         log.Formatter = &logrus.TextFormatter{}
75
76         // Support silly logging (printed on log.debug)
77         sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
78         logSilly := sillyLog && sillyVal == "1"
79         sillyFunc := func(format string, args ...interface{}) {
80                 if logSilly {
81                         log.Debugf("SILLY: "+format, args...)
82                 }
83         }
84
85         // Define default configuration
86         ctx := Context{
87                 ProgName:         cliCtx.App.Name,
88                 Cli:              cliCtx,
89                 Log:              log,
90                 LogLevelSilly:    logSilly,
91                 LogSillyf:        sillyFunc,
92                 lockXdsSrvUpdate: LockXdsUpdate{LockCpt: 0},
93                 Exit:             make(chan os.Signal, 1),
94         }
95
96         // register handler on SIGTERM / exit
97         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
98         go handlerSigTerm(&ctx)
99
100         return &ctx
101 }
102
103 // Run Main function called to run XDS Server
104 func (ctx *Context) Run() (int, error) {
105         var err error
106
107         // Logs redirected into a file when logfile option or logsDir config is set
108         ctx.Config.LogVerboseOut = os.Stderr
109         if ctx.Config.FileConf.LogsDir != "" {
110                 if ctx.Config.Options.LogFile != "stdout" {
111                         logFile := ctx.Config.Options.LogFile
112
113                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
114                         if err != nil {
115                                 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
116                                 return int(syscall.EPERM), fmt.Errorf(msgErr)
117                         }
118                         ctx.Log.Out = fdL
119
120                         ctx._logPrint("Logging file: %s\n", logFile)
121                 }
122
123                 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
124                 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
125                 if err != nil {
126                         msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
127                         return int(syscall.EPERM), fmt.Errorf(msgErr)
128                 }
129                 ctx.Config.LogVerboseOut = fdLH
130
131                 ctx._logPrint("Logging file for HTTP requests:  %s\n", logFileHTTPReq)
132         }
133
134         // Create events management
135         ctx.events = EventsConstructor(ctx)
136
137         // Create syncthing instance when section "syncthing" is present in server-config.json
138         if ctx.Config.FileConf.SThgConf != nil {
139                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
140         }
141
142         // Start local instance of Syncthing and Syncthing-notify
143         if ctx.SThg != nil {
144                 ctx.Log.Infof("Starting Syncthing...")
145                 ctx.SThgCmd, err = ctx.SThg.Start()
146                 if err != nil {
147                         return -4, err
148                 }
149                 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
150
151                 ctx.Log.Infof("Starting Syncthing-inotify...")
152                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
153                 if err != nil {
154                         return -4, err
155                 }
156                 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
157
158                 // Establish connection with local Syncthing (retry if connection fail)
159                 ctx._logPrint("Establishing connection with Syncthing...\n")
160                 time.Sleep(2 * time.Second)
161                 maxRetry := 30
162                 retry := maxRetry
163                 err = nil
164                 for retry > 0 {
165                         if err = ctx.SThg.Connect(); err == nil {
166                                 break
167                         }
168                         ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
169                         time.Sleep(time.Second)
170                         retry--
171                 }
172                 if err != nil || retry == 0 {
173                         return -4, err
174                 }
175
176                 // FIXME: do we still need Builder notion ? if no cleanup
177                 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
178                         return -4, err
179                 }
180                 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
181         }
182
183         // Init model folder
184         ctx.mfolders = FoldersConstructor(ctx)
185
186         // Load initial folders config from disk
187         if err := ctx.mfolders.LoadConfig(); err != nil {
188                 return -5, err
189         }
190
191         // Init cross SDKs
192         ctx.sdks, err = SDKsConstructor(ctx)
193         if err != nil {
194                 return -6, err
195         }
196
197         // Init target and terminals model
198         ctx.targets = TargetsConstructor(ctx)
199
200         // Load initial target & terminal config
201         if err := ctx.targets.LoadConfig(); err != nil {
202                 return -6, err
203         }
204
205         // Create Web Server
206         ctx.WWWServer = WebServerConstructor(ctx)
207
208         // Sessions manager
209         ctx.sessions = ClientSessionsConstructor(ctx, cookieMaxAge)
210
211         // Check if a new package version is available
212         // and monitor updates
213         MonitorUpdates(ctx)
214
215         // Run Web Server until exit requested (blocking call)
216         if err = ctx.WWWServer.Serve(); err != nil {
217                 ctx.Log.Println(err)
218                 return -7, err
219         }
220
221         return -99, fmt.Errorf("Program exited ")
222 }
223
224 // Helper function to log message on both stdout and logger
225 func (ctx *Context) _logPrint(format string, args ...interface{}) {
226         fmt.Printf(format, args...)
227         if ctx.Log.Out != os.Stdout {
228                 ctx.Log.Infof(format, args...)
229         }
230 }
231
232 // Handle exit and properly stop/close all stuff
233 func handlerSigTerm(ctx *Context) {
234         <-ctx.Exit
235         if ctx.SThg != nil {
236                 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
237                 ctx.SThg.Stop()
238                 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
239                 ctx.SThg.StopInotify()
240         }
241         if ctx.WWWServer != nil {
242                 ctx.Log.Infof("Stoping Web server...")
243                 ctx.WWWServer.Stop()
244         }
245         os.Exit(0)
246 }