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
49 xdsServers map[string]*XdsServer
57 // NewAgent Create a new instance of Agent
58 func NewAgent(cliCtx *cli.Context) *Context {
61 // Set logger level and formatter
62 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
64 logLevel := cliCtx.GlobalString("log")
66 logLevel = "error" // FIXME get from Config DefaultLogLevel
68 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
69 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
72 log.Formatter = &logrus.TextFormatter{}
74 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
76 // Define default configuration
78 ProgName: cliCtx.App.Name,
80 LogLevelSilly: (sillyLog && sillyVal == "1"),
81 Exit: make(chan os.Signal, 1),
84 xdsServers: make(map[string]*XdsServer),
88 // register handler on SIGTERM / exit
89 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
90 go handlerSigTerm(&ctx)
95 // Run Main function called to run agent
96 func (ctx *Context) Run() (int, error) {
99 // Logs redirected into a file when logfile option or logsDir config is set
100 ctx.Config.LogVerboseOut = os.Stderr
101 if ctx.Config.FileConf.LogsDir != "" {
102 if ctx.Config.Options.LogFile != "stdout" {
103 logFile := ctx.Config.Options.LogFile
105 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
107 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
108 return int(syscall.EPERM), msgErr
112 ctx._logPrint("Logging file: %s\n", logFile)
115 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-agent-verbose.log")
116 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
118 msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
119 return int(syscall.EPERM), msgErr
121 ctx.Config.LogVerboseOut = fdLH
123 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
126 // Create syncthing instance when section "syncthing" is present in config.json
127 if ctx.Config.FileConf.SThgConf != nil {
128 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
131 // Start local instance of Syncthing and Syncthing-notify
133 ctx.Log.Infof("Starting Syncthing...")
134 ctx.SThgCmd, err = ctx.SThg.Start()
138 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
140 ctx.Log.Infof("Starting Syncthing-inotify...")
141 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
145 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
147 // Establish connection with local Syncthing (retry if connection fail)
148 time.Sleep(3 * time.Second)
152 if err := ctx.SThg.Connect(); err == nil {
155 ctx.Log.Infof("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
156 time.Sleep(time.Second)
159 if err != nil || retry == 0 {
163 // Retrieve Syncthing config
164 id, err := ctx.SThg.IDGet()
168 ctx.Log.Infof("Local Syncthing ID: %s", id)
171 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
175 ctx.webServer = NewWebServer(ctx)
178 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
180 // Create events management
181 ctx.events = NewEvents(ctx)
183 // Create projects management
184 ctx.projects = NewProjects(ctx, ctx.SThg)
186 // Run Web Server until exit requested (blocking call)
187 if err = ctx.webServer.Serve(); err != nil {
192 return 4, fmt.Errorf("Program exited")
195 // Helper function to log message on both stdout and logger
196 func (ctx *Context) _logPrint(format string, args ...interface{}) {
197 fmt.Printf(format, args...)
198 if ctx.Log.Out != os.Stdout {
199 ctx.Log.Infof(format, args...)
203 // Handle exit and properly stop/close all stuff
204 func handlerSigTerm(ctx *Context) {
207 ctx.Log.Infof("Stoping Syncthing... (PID %d)",
208 ctx.SThgCmd.Process.Pid)
209 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)",
210 ctx.SThgInotCmd.Process.Pid)
212 ctx.SThg.StopInotify()
214 if ctx.webServer != nil {
215 ctx.Log.Infof("Stoping Web server...")