Use go module as dependency tool instead of glide
[src/xds/xds-agent.git] / lib / agent / agent.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 agent
19
20 import (
21         "fmt"
22         "log"
23         "os"
24         "os/exec"
25         "os/signal"
26         "path/filepath"
27         "syscall"
28         "time"
29
30         st "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/syncthing"
31
32         "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/xdsconfig"
33         "github.com/Sirupsen/logrus"
34         "github.com/urfave/cli"
35 )
36
37 const cookieMaxAge = "3600"
38
39 // Context holds the Agent context structure
40 type Context struct {
41         ProgName      string
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
50         webServer     *WebServer
51         xdsServers    map[string]*XdsServer
52         XdsSupervisor *XdsSupervisor
53         sessions      *Sessions
54         events        *Events
55         projects      *Projects
56
57         Exit chan os.Signal
58 }
59
60 // NewAgent Create a new instance of Agent
61 func NewAgent(cliCtx *cli.Context) *Context {
62         var err error
63
64         // Set logger level and formatter
65         log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
66
67         logLevel := cliCtx.GlobalString("log")
68         if logLevel == "" {
69                 logLevel = "error" // FIXME get from Config DefaultLogLevel
70         }
71         if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
72                 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
73                 os.Exit(1)
74         }
75         log.Formatter = &logrus.TextFormatter{}
76
77         // Support silly logging (printed on log.debug)
78         sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
79         logSilly := sillyLog && sillyVal == "1"
80         sillyFunc := func(format string, args ...interface{}) {
81                 if logSilly {
82                         log.Debugf("SILLY: "+format, args...)
83                 }
84         }
85
86         // Define default configuration
87         ctx := Context{
88                 ProgName:      cliCtx.App.Name,
89                 Log:           log,
90                 LogLevelSilly: logSilly,
91                 LogSillyf:     sillyFunc,
92                 Exit:          make(chan os.Signal, 1),
93
94                 webServer:  nil,
95                 xdsServers: make(map[string]*XdsServer),
96                 events:     nil,
97         }
98
99         // register handler on SIGTERM / exit
100         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
101         go handlerSigTerm(&ctx)
102
103         return &ctx
104 }
105
106 // Run Main function called to run agent
107 func (ctx *Context) Run() (int, error) {
108         var err error
109
110         // Logs redirected into a file when logfile option or logsDir config is set
111         ctx.Config.LogVerboseOut = os.Stderr
112         if ctx.Config.FileConf.LogsDir != "" {
113                 if ctx.Config.Options.LogFile != "stdout" {
114                         logFile := ctx.Config.Options.LogFile
115
116                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
117                         if err != nil {
118                                 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
119                                 return int(syscall.EPERM), msgErr
120                         }
121                         ctx.Log.Out = fdL
122
123                         ctx._logPrint("Logging file: %s\n", logFile)
124                 }
125
126                 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-agent-verbose.log")
127                 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
128                 if err != nil {
129                         msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
130                         return int(syscall.EPERM), msgErr
131                 }
132                 ctx.Config.LogVerboseOut = fdLH
133
134                 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
135         }
136
137         // Create events management
138         ctx.events = NewEvents(ctx)
139
140         // Create syncthing instance when section "syncthing" is present in agent-config.json
141         if ctx.Config.FileConf.SThgConf != nil {
142                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
143         }
144
145         // Start local instance of Syncthing and Syncthing-notify
146         if ctx.SThg != nil {
147                 ctx.Log.Infof("Starting Syncthing...")
148                 ctx.SThgCmd, err = ctx.SThg.Start()
149                 if err != nil {
150                         return 2, err
151                 }
152                 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
153
154                 ctx.Log.Infof("Starting Syncthing-inotify...")
155                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
156                 if err != nil {
157                         return 2, err
158                 }
159                 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
160
161                 // Establish connection with local Syncthing (retry if connection fail)
162                 time.Sleep(3 * time.Second)
163                 maxRetry := 30
164                 retry := maxRetry
165                 for retry > 0 {
166                         if err := ctx.SThg.Connect(); err == nil {
167                                 break
168                         }
169                         ctx.Log.Infof("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
170                         time.Sleep(time.Second)
171                         retry--
172                 }
173                 if err != nil || retry == 0 {
174                         return 2, err
175                 }
176
177                 // Retrieve Syncthing config
178                 id, err := ctx.SThg.IDGet()
179                 if err != nil {
180                         return 2, err
181                 }
182                 ctx.Log.Infof("Local Syncthing ID: %s", id)
183
184         } else {
185                 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
186         }
187
188         // Create Web Server
189         ctx.webServer = NewWebServer(ctx)
190
191         // Sessions manager
192         ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
193
194         // Create projects management
195         ctx.projects = NewProjects(ctx, ctx.SThg)
196
197         // Run Web Server until exit requested (blocking call)
198         if err = ctx.webServer.Serve(); err != nil {
199                 log.Println(err)
200                 return 3, err
201         }
202
203         return 4, fmt.Errorf("Program exited")
204 }
205
206 // Helper function to log message on both stdout and logger
207 func (ctx *Context) _logPrint(format string, args ...interface{}) {
208         fmt.Printf(format, args...)
209         if ctx.Log.Out != os.Stdout {
210                 ctx.Log.Infof(format, args...)
211         }
212 }
213
214 // Handle exit and properly stop/close all stuff
215 func handlerSigTerm(ctx *Context) {
216         <-ctx.Exit
217         if ctx.SThg != nil {
218                 ctx.Log.Infof("Stoping Syncthing... (PID %d)",
219                         ctx.SThgCmd.Process.Pid)
220                 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)",
221                         ctx.SThgInotCmd.Process.Pid)
222                 ctx.SThg.Stop()
223                 ctx.SThg.StopInotify()
224         }
225         if ctx.webServer != nil {
226                 ctx.Log.Infof("Stoping Web server...")
227                 ctx.webServer.Stop()
228         }
229         os.Exit(1)
230 }