2 * Copyright (C) 2017-2019 "IoT.bzh"
3 * Author Sebastien Douheret <sebastien@iot.bzh>
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
30 st "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/syncthing"
32 "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent.git/lib/xdsconfig"
33 "github.com/Sirupsen/logrus"
34 "github.com/urfave/cli"
37 const cookieMaxAge = "3600"
39 // Context holds the Agent context structure
42 Config *xdsconfig.Config
45 LogSillyf func(format string, args ...interface{})
51 xdsServers map[string]*XdsServer
52 XdsMonitoring *XdsMonitoring
53 XdsLowCollector *XdsLowCollector
61 // NewAgent Create a new instance of Agent
62 func NewAgent(cliCtx *cli.Context) *Context {
65 // Set logger level and formatter
66 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
68 logLevel := cliCtx.GlobalString("log")
70 logLevel = "error" // FIXME get from Config DefaultLogLevel
72 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
73 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
76 log.Formatter = &logrus.TextFormatter{}
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{}) {
83 log.Debugf("SILLY: "+format, args...)
87 // Define default configuration
89 ProgName: cliCtx.App.Name,
91 LogLevelSilly: logSilly,
93 Exit: make(chan os.Signal, 1),
96 xdsServers: make(map[string]*XdsServer),
100 // register handler on SIGTERM / exit
101 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
102 go handlerSigTerm(&ctx)
107 // Run Main function called to run agent
108 func (ctx *Context) Run() (int, error) {
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
117 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
119 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
120 return int(syscall.EPERM), msgErr
124 ctx._logPrint("Logging file: %s\n", logFile)
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)
130 msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
131 return int(syscall.EPERM), msgErr
133 ctx.Config.LogVerboseOut = fdLH
135 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
138 // Create events management
139 ctx.events = NewEvents(ctx)
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)
146 // Start local instance of Syncthing and Syncthing-notify
148 ctx.Log.Infof("Starting Syncthing...")
149 ctx.SThgCmd, err = ctx.SThg.Start()
153 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
155 ctx.Log.Infof("Starting Syncthing-inotify...")
156 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
160 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
162 // Establish connection with local Syncthing (retry if connection fail)
163 time.Sleep(3 * time.Second)
167 if err := ctx.SThg.Connect(); err == nil {
170 ctx.Log.Infof("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
171 time.Sleep(time.Second)
174 if err != nil || retry == 0 {
178 // Retrieve Syncthing config
179 id, err := ctx.SThg.IDGet()
183 ctx.Log.Infof("Local Syncthing ID: %s", id)
186 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
190 ctx.webServer = NewWebServer(ctx)
193 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
195 // Create projects management
196 ctx.projects = NewProjects(ctx, ctx.SThg)
198 // Run Web Server until exit requested (blocking call)
199 if err = ctx.webServer.Serve(); err != nil {
204 return 4, fmt.Errorf("Program exited")
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...)
215 // Handle exit and properly stop/close all stuff
216 func handlerSigTerm(ctx *Context) {
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)
224 ctx.SThg.StopInotify()
226 if ctx.webServer != nil {
227 ctx.Log.Infof("Stoping Web server...")