13 "github.com/Sirupsen/logrus"
14 "github.com/iotbzh/xds-agent/lib/syncthing"
15 "github.com/iotbzh/xds-agent/lib/xdsconfig"
16 "github.com/urfave/cli"
19 const cookieMaxAge = "3600"
21 // Context holds the Agent context structure
24 Config *xdsconfig.Config
32 xdsServers map[string]*XdsServer
40 // NewAgent Create a new instance of Agent
41 func NewAgent(cliCtx *cli.Context) *Context {
44 // Set logger level and formatter
45 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
47 logLevel := cliCtx.GlobalString("log")
49 logLevel = "error" // FIXME get from Config DefaultLogLevel
51 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
52 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
55 log.Formatter = &logrus.TextFormatter{}
57 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
59 // Define default configuration
61 ProgName: cliCtx.App.Name,
63 LogLevelSilly: (sillyLog && sillyVal == "1"),
64 Exit: make(chan os.Signal, 1),
67 xdsServers: make(map[string]*XdsServer),
71 // register handler on SIGTERM / exit
72 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
73 go handlerSigTerm(&ctx)
78 // Run Main function called to run agent
79 func (ctx *Context) Run() (int, error) {
82 // Logs redirected into a file when logfile option or logsDir config is set
83 ctx.Config.LogVerboseOut = os.Stderr
84 if ctx.Config.FileConf.LogsDir != "" {
85 if ctx.Config.Options.LogFile != "stdout" {
86 logFile := ctx.Config.Options.LogFile
88 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
90 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
91 return int(syscall.EPERM), msgErr
95 ctx._logPrint("Logging file: %s\n", logFile)
98 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-agent-verbose.log")
99 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
101 msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
102 return int(syscall.EPERM), msgErr
104 ctx.Config.LogVerboseOut = fdLH
106 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
109 // Create syncthing instance when section "syncthing" is present in config.json
110 if ctx.Config.FileConf.SThgConf != nil {
111 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
114 // Start local instance of Syncthing and Syncthing-notify
116 ctx.Log.Infof("Starting Syncthing...")
117 ctx.SThgCmd, err = ctx.SThg.Start()
121 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
123 ctx.Log.Infof("Starting Syncthing-inotify...")
124 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
128 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
130 // Establish connection with local Syncthing (retry if connection fail)
131 time.Sleep(3 * time.Second)
135 if err := ctx.SThg.Connect(); err == nil {
138 ctx.Log.Infof("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
139 time.Sleep(time.Second)
142 if err != nil || retry == 0 {
146 // Retrieve Syncthing config
147 id, err := ctx.SThg.IDGet()
151 ctx.Log.Infof("Local Syncthing ID: %s", id)
154 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
158 ctx.webServer = NewWebServer(ctx)
161 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
163 // Create events management
164 ctx.events = NewEvents(ctx)
166 // Create projects management
167 ctx.projects = NewProjects(ctx, ctx.SThg)
169 // Run Web Server until exit requested (blocking call)
170 if err = ctx.webServer.Serve(); err != nil {
175 return 4, fmt.Errorf("Program exited")
178 // Helper function to log message on both stdout and logger
179 func (ctx *Context) _logPrint(format string, args ...interface{}) {
180 fmt.Printf(format, args...)
181 if ctx.Log.Out != os.Stdout {
182 ctx.Log.Infof(format, args...)
186 // Handle exit and properly stop/close all stuff
187 func handlerSigTerm(ctx *Context) {
190 ctx.Log.Infof("Stoping Syncthing... (PID %d)",
191 ctx.SThgCmd.Process.Pid)
192 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)",
193 ctx.SThgInotCmd.Process.Pid)
195 ctx.SThg.StopInotify()
197 if ctx.webServer != nil {
198 ctx.Log.Infof("Stoping Web server...")