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