Migration to AGL gerrit (update go import)
[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/lib/syncthing"
31
32         "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent/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         sessions   *Sessions
53         events     *Events
54         projects   *Projects
55
56         Exit chan os.Signal
57 }
58
59 // NewAgent Create a new instance of Agent
60 func NewAgent(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                 Log:           log,
89                 LogLevelSilly: logSilly,
90                 LogSillyf:     sillyFunc,
91                 Exit:          make(chan os.Signal, 1),
92
93                 webServer:  nil,
94                 xdsServers: make(map[string]*XdsServer),
95                 events:     nil,
96         }
97
98         // register handler on SIGTERM / exit
99         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
100         go handlerSigTerm(&ctx)
101
102         return &ctx
103 }
104
105 // Run Main function called to run agent
106 func (ctx *Context) Run() (int, error) {
107         var err error
108
109         // Logs redirected into a file when logfile option or logsDir config is set
110         ctx.Config.LogVerboseOut = os.Stderr
111         if ctx.Config.FileConf.LogsDir != "" {
112                 if ctx.Config.Options.LogFile != "stdout" {
113                         logFile := ctx.Config.Options.LogFile
114
115                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
116                         if err != nil {
117                                 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
118                                 return int(syscall.EPERM), msgErr
119                         }
120                         ctx.Log.Out = fdL
121
122                         ctx._logPrint("Logging file: %s\n", logFile)
123                 }
124
125                 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-agent-verbose.log")
126                 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
127                 if err != nil {
128                         msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
129                         return int(syscall.EPERM), msgErr
130                 }
131                 ctx.Config.LogVerboseOut = fdLH
132
133                 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
134         }
135
136         // Create events management
137         ctx.events = NewEvents(ctx)
138
139         // Create syncthing instance when section "syncthing" is present in agent-config.json
140         if ctx.Config.FileConf.SThgConf != nil {
141                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
142         }
143
144         // Start local instance of Syncthing and Syncthing-notify
145         if ctx.SThg != nil {
146                 ctx.Log.Infof("Starting Syncthing...")
147                 ctx.SThgCmd, err = ctx.SThg.Start()
148                 if err != nil {
149                         return 2, err
150                 }
151                 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
152
153                 ctx.Log.Infof("Starting Syncthing-inotify...")
154                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
155                 if err != nil {
156                         return 2, err
157                 }
158                 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
159
160                 // Establish connection with local Syncthing (retry if connection fail)
161                 time.Sleep(3 * time.Second)
162                 maxRetry := 30
163                 retry := maxRetry
164                 for retry > 0 {
165                         if err := ctx.SThg.Connect(); err == nil {
166                                 break
167                         }
168                         ctx.Log.Infof("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 2, err
174                 }
175
176                 // Retrieve Syncthing config
177                 id, err := ctx.SThg.IDGet()
178                 if err != nil {
179                         return 2, err
180                 }
181                 ctx.Log.Infof("Local Syncthing ID: %s", id)
182
183         } else {
184                 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
185         }
186
187         // Create Web Server
188         ctx.webServer = NewWebServer(ctx)
189
190         // Sessions manager
191         ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
192
193         // Create projects management
194         ctx.projects = NewProjects(ctx, ctx.SThg)
195
196         // Run Web Server until exit requested (blocking call)
197         if err = ctx.webServer.Serve(); err != nil {
198                 log.Println(err)
199                 return 3, err
200         }
201
202         return 4, fmt.Errorf("Program exited")
203 }
204
205 // Helper function to log message on both stdout and logger
206 func (ctx *Context) _logPrint(format string, args ...interface{}) {
207         fmt.Printf(format, args...)
208         if ctx.Log.Out != os.Stdout {
209                 ctx.Log.Infof(format, args...)
210         }
211 }
212
213 // Handle exit and properly stop/close all stuff
214 func handlerSigTerm(ctx *Context) {
215         <-ctx.Exit
216         if ctx.SThg != nil {
217                 ctx.Log.Infof("Stoping Syncthing... (PID %d)",
218                         ctx.SThgCmd.Process.Pid)
219                 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)",
220                         ctx.SThgInotCmd.Process.Pid)
221                 ctx.SThg.Stop()
222                 ctx.SThg.StopInotify()
223         }
224         if ctx.webServer != nil {
225                 ctx.Log.Infof("Stoping Web server...")
226                 ctx.webServer.Stop()
227         }
228         os.Exit(1)
229 }