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/lib/syncthing"
32 "gerrit.automotivelinux.org/gerrit/src/xds/xds-agent/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
59 // NewAgent Create a new instance of Agent
60 func NewAgent(cliCtx *cli.Context) *Context {
63 // Set logger level and formatter
64 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
66 logLevel := cliCtx.GlobalString("log")
68 logLevel = "error" // FIXME get from Config DefaultLogLevel
70 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
71 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
74 log.Formatter = &logrus.TextFormatter{}
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{}) {
81 log.Debugf("SILLY: "+format, args...)
85 // Define default configuration
87 ProgName: cliCtx.App.Name,
89 LogLevelSilly: logSilly,
91 Exit: make(chan os.Signal, 1),
94 xdsServers: make(map[string]*XdsServer),
98 // register handler on SIGTERM / exit
99 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
100 go handlerSigTerm(&ctx)
105 // Run Main function called to run agent
106 func (ctx *Context) Run() (int, error) {
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
115 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
117 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
118 return int(syscall.EPERM), msgErr
122 ctx._logPrint("Logging file: %s\n", logFile)
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)
128 msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
129 return int(syscall.EPERM), msgErr
131 ctx.Config.LogVerboseOut = fdLH
133 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
136 // Create events management
137 ctx.events = NewEvents(ctx)
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)
144 // Start local instance of Syncthing and Syncthing-notify
146 ctx.Log.Infof("Starting Syncthing...")
147 ctx.SThgCmd, err = ctx.SThg.Start()
151 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
153 ctx.Log.Infof("Starting Syncthing-inotify...")
154 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
158 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
160 // Establish connection with local Syncthing (retry if connection fail)
161 time.Sleep(3 * time.Second)
165 if err := ctx.SThg.Connect(); err == nil {
168 ctx.Log.Infof("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
169 time.Sleep(time.Second)
172 if err != nil || retry == 0 {
176 // Retrieve Syncthing config
177 id, err := ctx.SThg.IDGet()
181 ctx.Log.Infof("Local Syncthing ID: %s", id)
184 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
188 ctx.webServer = NewWebServer(ctx)
191 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
193 // Create projects management
194 ctx.projects = NewProjects(ctx, ctx.SThg)
196 // Run Web Server until exit requested (blocking call)
197 if err = ctx.webServer.Serve(); err != nil {
202 return 4, fmt.Errorf("Program exited")
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...)
213 // Handle exit and properly stop/close all stuff
214 func handlerSigTerm(ctx *Context) {
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)
222 ctx.SThg.StopInotify()
224 if ctx.webServer != nil {
225 ctx.Log.Infof("Stoping Web server...")