2 * Copyright (C) 2017 "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 "github.com/Sirupsen/logrus"
31 "github.com/iotbzh/xds-agent/lib/syncthing"
32 "github.com/iotbzh/xds-agent/lib/xdsconfig"
33 "github.com/urfave/cli"
36 const cookieMaxAge = "3600"
38 // Context holds the Agent context structure
41 Config *xdsconfig.Config
44 LogSillyf func(format string, args ...interface{})
50 xdsServers map[string]*XdsServer
58 // NewAgent Create a new instance of Agent
59 func NewAgent(cliCtx *cli.Context) *Context {
62 // Set logger level and formatter
63 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
65 logLevel := cliCtx.GlobalString("log")
67 logLevel = "error" // FIXME get from Config DefaultLogLevel
69 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
70 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
73 log.Formatter = &logrus.TextFormatter{}
75 // Support silly logging (printed on log.debug)
76 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
77 logSilly := sillyLog && sillyVal == "1"
78 sillyFunc := func(format string, args ...interface{}) {
80 log.Debugf("SILLY: "+format, args...)
84 // Define default configuration
86 ProgName: cliCtx.App.Name,
88 LogLevelSilly: logSilly,
90 Exit: make(chan os.Signal, 1),
93 xdsServers: make(map[string]*XdsServer),
97 // register handler on SIGTERM / exit
98 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
99 go handlerSigTerm(&ctx)
104 // Run Main function called to run agent
105 func (ctx *Context) Run() (int, error) {
108 // Logs redirected into a file when logfile option or logsDir config is set
109 ctx.Config.LogVerboseOut = os.Stderr
110 if ctx.Config.FileConf.LogsDir != "" {
111 if ctx.Config.Options.LogFile != "stdout" {
112 logFile := ctx.Config.Options.LogFile
114 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
116 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
117 return int(syscall.EPERM), msgErr
121 ctx._logPrint("Logging file: %s\n", logFile)
124 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-agent-verbose.log")
125 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
127 msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
128 return int(syscall.EPERM), msgErr
130 ctx.Config.LogVerboseOut = fdLH
132 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
135 // Create syncthing instance when section "syncthing" is present in agent-config.json
136 if ctx.Config.FileConf.SThgConf != nil {
137 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
140 // Start local instance of Syncthing and Syncthing-notify
142 ctx.Log.Infof("Starting Syncthing...")
143 ctx.SThgCmd, err = ctx.SThg.Start()
147 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
149 ctx.Log.Infof("Starting Syncthing-inotify...")
150 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
154 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
156 // Establish connection with local Syncthing (retry if connection fail)
157 time.Sleep(3 * time.Second)
161 if err := ctx.SThg.Connect(); err == nil {
164 ctx.Log.Infof("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
165 time.Sleep(time.Second)
168 if err != nil || retry == 0 {
172 // Retrieve Syncthing config
173 id, err := ctx.SThg.IDGet()
177 ctx.Log.Infof("Local Syncthing ID: %s", id)
180 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
184 ctx.webServer = NewWebServer(ctx)
187 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
189 // Create events management
190 ctx.events = NewEvents(ctx)
192 // Create projects management
193 ctx.projects = NewProjects(ctx, ctx.SThg)
195 // Run Web Server until exit requested (blocking call)
196 if err = ctx.webServer.Serve(); err != nil {
201 return 4, fmt.Errorf("Program exited")
204 // Helper function to log message on both stdout and logger
205 func (ctx *Context) _logPrint(format string, args ...interface{}) {
206 fmt.Printf(format, args...)
207 if ctx.Log.Out != os.Stdout {
208 ctx.Log.Infof(format, args...)
212 // Handle exit and properly stop/close all stuff
213 func handlerSigTerm(ctx *Context) {
216 ctx.Log.Infof("Stoping Syncthing... (PID %d)",
217 ctx.SThgCmd.Process.Pid)
218 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)",
219 ctx.SThgInotCmd.Process.Pid)
221 ctx.SThg.StopInotify()
223 if ctx.webServer != nil {
224 ctx.Log.Infof("Stoping Web server...")