Improved silly logging.
[src/xds/xds-agent.git] / lib / agent / agent.go
1 /*
2  * Copyright (C) 2017 "IoT.bzh"
3  * Author Sebastien Douheret <sebastien@iot.bzh>
4  *
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
8  *
9  *   http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 package agent
19
20 import (
21         "fmt"
22         "log"
23         "os"
24         "os/exec"
25         "os/signal"
26         "path/filepath"
27         "syscall"
28         "time"
29
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"
34 )
35
36 const cookieMaxAge = "3600"
37
38 // Context holds the Agent context structure
39 type Context struct {
40         ProgName      string
41         Config        *xdsconfig.Config
42         Log           *logrus.Logger
43         LogLevelSilly bool
44         LogSillyf     func(format string, args ...interface{})
45         SThg          *st.SyncThing
46         SThgCmd       *exec.Cmd
47         SThgInotCmd   *exec.Cmd
48
49         webServer  *WebServer
50         xdsServers map[string]*XdsServer
51         sessions   *Sessions
52         events     *Events
53         projects   *Projects
54
55         Exit chan os.Signal
56 }
57
58 // NewAgent Create a new instance of Agent
59 func NewAgent(cliCtx *cli.Context) *Context {
60         var err error
61
62         // Set logger level and formatter
63         log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
64
65         logLevel := cliCtx.GlobalString("log")
66         if logLevel == "" {
67                 logLevel = "error" // FIXME get from Config DefaultLogLevel
68         }
69         if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
70                 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
71                 os.Exit(1)
72         }
73         log.Formatter = &logrus.TextFormatter{}
74
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{}) {
79                 if logSilly {
80                         log.Debugf("SILLY: "+format, args...)
81                 }
82         }
83
84         // Define default configuration
85         ctx := Context{
86                 ProgName:      cliCtx.App.Name,
87                 Log:           log,
88                 LogLevelSilly: logSilly,
89                 LogSillyf:     sillyFunc,
90                 Exit:          make(chan os.Signal, 1),
91
92                 webServer:  nil,
93                 xdsServers: make(map[string]*XdsServer),
94                 events:     nil,
95         }
96
97         // register handler on SIGTERM / exit
98         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
99         go handlerSigTerm(&ctx)
100
101         return &ctx
102 }
103
104 // Run Main function called to run agent
105 func (ctx *Context) Run() (int, error) {
106         var err error
107
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
113
114                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
115                         if err != nil {
116                                 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
117                                 return int(syscall.EPERM), msgErr
118                         }
119                         ctx.Log.Out = fdL
120
121                         ctx._logPrint("Logging file: %s\n", logFile)
122                 }
123
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)
126                 if err != nil {
127                         msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
128                         return int(syscall.EPERM), msgErr
129                 }
130                 ctx.Config.LogVerboseOut = fdLH
131
132                 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
133         }
134
135         // Create syncthing instance when section "syncthing" is present in config.json
136         if ctx.Config.FileConf.SThgConf != nil {
137                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
138         }
139
140         // Start local instance of Syncthing and Syncthing-notify
141         if ctx.SThg != nil {
142                 ctx.Log.Infof("Starting Syncthing...")
143                 ctx.SThgCmd, err = ctx.SThg.Start()
144                 if err != nil {
145                         return 2, err
146                 }
147                 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
148
149                 ctx.Log.Infof("Starting Syncthing-inotify...")
150                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
151                 if err != nil {
152                         return 2, err
153                 }
154                 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
155
156                 // Establish connection with local Syncthing (retry if connection fail)
157                 time.Sleep(3 * time.Second)
158                 maxRetry := 30
159                 retry := maxRetry
160                 for retry > 0 {
161                         if err := ctx.SThg.Connect(); err == nil {
162                                 break
163                         }
164                         ctx.Log.Infof("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
165                         time.Sleep(time.Second)
166                         retry--
167                 }
168                 if err != nil || retry == 0 {
169                         return 2, err
170                 }
171
172                 // Retrieve Syncthing config
173                 id, err := ctx.SThg.IDGet()
174                 if err != nil {
175                         return 2, err
176                 }
177                 ctx.Log.Infof("Local Syncthing ID: %s", id)
178
179         } else {
180                 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
181         }
182
183         // Create Web Server
184         ctx.webServer = NewWebServer(ctx)
185
186         // Sessions manager
187         ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
188
189         // Create events management
190         ctx.events = NewEvents(ctx)
191
192         // Create projects management
193         ctx.projects = NewProjects(ctx, ctx.SThg)
194
195         // Run Web Server until exit requested (blocking call)
196         if err = ctx.webServer.Serve(); err != nil {
197                 log.Println(err)
198                 return 3, err
199         }
200
201         return 4, fmt.Errorf("Program exited")
202 }
203
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...)
209         }
210 }
211
212 // Handle exit and properly stop/close all stuff
213 func handlerSigTerm(ctx *Context) {
214         <-ctx.Exit
215         if ctx.SThg != nil {
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)
220                 ctx.SThg.Stop()
221                 ctx.SThg.StopInotify()
222         }
223         if ctx.webServer != nil {
224                 ctx.Log.Infof("Stoping Web server...")
225                 ctx.webServer.Stop()
226         }
227         os.Exit(1)
228 }