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