2 * Copyright (C) 2017-2018 "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 XdsSupervisor *XdsSupervisor
60 // NewAgent Create a new instance of Agent
61 func NewAgent(cliCtx *cli.Context) *Context {
64 // Set logger level and formatter
65 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
67 logLevel := cliCtx.GlobalString("log")
69 logLevel = "error" // FIXME get from Config DefaultLogLevel
71 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
72 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
75 log.Formatter = &logrus.TextFormatter{}
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{}) {
82 log.Debugf("SILLY: "+format, args...)
86 // Define default configuration
88 ProgName: cliCtx.App.Name,
90 LogLevelSilly: logSilly,
92 Exit: make(chan os.Signal, 1),
95 xdsServers: make(map[string]*XdsServer),
99 // register handler on SIGTERM / exit
100 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
101 go handlerSigTerm(&ctx)
106 // Run Main function called to run agent
107 func (ctx *Context) Run() (int, error) {
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
116 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
118 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
119 return int(syscall.EPERM), msgErr
123 ctx._logPrint("Logging file: %s\n", logFile)
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)
129 msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
130 return int(syscall.EPERM), msgErr
132 ctx.Config.LogVerboseOut = fdLH
134 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
137 // Create events management
138 ctx.events = NewEvents(ctx)
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)
145 // Start local instance of Syncthing and Syncthing-notify
147 ctx.Log.Infof("Starting Syncthing...")
148 ctx.SThgCmd, err = ctx.SThg.Start()
152 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
154 ctx.Log.Infof("Starting Syncthing-inotify...")
155 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
159 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
161 // Establish connection with local Syncthing (retry if connection fail)
162 time.Sleep(3 * time.Second)
166 if err := ctx.SThg.Connect(); err == nil {
169 ctx.Log.Infof("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
170 time.Sleep(time.Second)
173 if err != nil || retry == 0 {
177 // Retrieve Syncthing config
178 id, err := ctx.SThg.IDGet()
182 ctx.Log.Infof("Local Syncthing ID: %s", id)
185 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
189 ctx.webServer = NewWebServer(ctx)
192 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
194 // Create projects management
195 ctx.projects = NewProjects(ctx, ctx.SThg)
197 // Run Web Server until exit requested (blocking call)
198 if err = ctx.webServer.Serve(); err != nil {
203 return 4, fmt.Errorf("Program exited")
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...)
214 // Handle exit and properly stop/close all stuff
215 func handlerSigTerm(ctx *Context) {
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)
223 ctx.SThg.StopInotify()
225 if ctx.webServer != nil {
226 ctx.Log.Infof("Stoping Web server...")