d1a3d05a30fcb4d51e739416cdad432a0d5429e7
[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         SThg          *st.SyncThing
45         SThgCmd       *exec.Cmd
46         SThgInotCmd   *exec.Cmd
47
48         webServer  *WebServer
49         xdsServers map[string]*XdsServer
50         sessions   *Sessions
51         events     *Events
52         projects   *Projects
53
54         Exit chan os.Signal
55 }
56
57 // NewAgent Create a new instance of Agent
58 func NewAgent(cliCtx *cli.Context) *Context {
59         var err error
60
61         // Set logger level and formatter
62         log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
63
64         logLevel := cliCtx.GlobalString("log")
65         if logLevel == "" {
66                 logLevel = "error" // FIXME get from Config DefaultLogLevel
67         }
68         if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
69                 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
70                 os.Exit(1)
71         }
72         log.Formatter = &logrus.TextFormatter{}
73
74         sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
75
76         // Define default configuration
77         ctx := Context{
78                 ProgName:      cliCtx.App.Name,
79                 Log:           log,
80                 LogLevelSilly: (sillyLog && sillyVal == "1"),
81                 Exit:          make(chan os.Signal, 1),
82
83                 webServer:  nil,
84                 xdsServers: make(map[string]*XdsServer),
85                 events:     nil,
86         }
87
88         // register handler on SIGTERM / exit
89         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
90         go handlerSigTerm(&ctx)
91
92         return &ctx
93 }
94
95 // Run Main function called to run agent
96 func (ctx *Context) Run() (int, error) {
97         var err error
98
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
104
105                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
106                         if err != nil {
107                                 msgErr := fmt.Errorf("Cannot create log file %s", logFile)
108                                 return int(syscall.EPERM), msgErr
109                         }
110                         ctx.Log.Out = fdL
111
112                         ctx._logPrint("Logging file: %s\n", logFile)
113                 }
114
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)
117                 if err != nil {
118                         msgErr := fmt.Errorf("Cannot create log file %s", logFileHTTPReq)
119                         return int(syscall.EPERM), msgErr
120                 }
121                 ctx.Config.LogVerboseOut = fdLH
122
123                 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
124         }
125
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)
129         }
130
131         // Start local instance of Syncthing and Syncthing-notify
132         if ctx.SThg != nil {
133                 ctx.Log.Infof("Starting Syncthing...")
134                 ctx.SThgCmd, err = ctx.SThg.Start()
135                 if err != nil {
136                         return 2, err
137                 }
138                 fmt.Printf("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
139
140                 ctx.Log.Infof("Starting Syncthing-inotify...")
141                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
142                 if err != nil {
143                         return 2, err
144                 }
145                 fmt.Printf("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
146
147                 // Establish connection with local Syncthing (retry if connection fail)
148                 time.Sleep(3 * time.Second)
149                 maxRetry := 30
150                 retry := maxRetry
151                 for retry > 0 {
152                         if err := ctx.SThg.Connect(); err == nil {
153                                 break
154                         }
155                         ctx.Log.Infof("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
156                         time.Sleep(time.Second)
157                         retry--
158                 }
159                 if err != nil || retry == 0 {
160                         return 2, err
161                 }
162
163                 // Retrieve Syncthing config
164                 id, err := ctx.SThg.IDGet()
165                 if err != nil {
166                         return 2, err
167                 }
168                 ctx.Log.Infof("Local Syncthing ID: %s", id)
169
170         } else {
171                 ctx.Log.Infof("Cloud Sync / Syncthing not supported")
172         }
173
174         // Create Web Server
175         ctx.webServer = NewWebServer(ctx)
176
177         // Sessions manager
178         ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
179
180         // Create events management
181         ctx.events = NewEvents(ctx)
182
183         // Create projects management
184         ctx.projects = NewProjects(ctx, ctx.SThg)
185
186         // Run Web Server until exit requested (blocking call)
187         if err = ctx.webServer.Serve(); err != nil {
188                 log.Println(err)
189                 return 3, err
190         }
191
192         return 4, fmt.Errorf("Program exited")
193 }
194
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...)
200         }
201 }
202
203 // Handle exit and properly stop/close all stuff
204 func handlerSigTerm(ctx *Context) {
205         <-ctx.Exit
206         if ctx.SThg != nil {
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)
211                 ctx.SThg.Stop()
212                 ctx.SThg.StopInotify()
213         }
214         if ctx.webServer != nil {
215                 ctx.Log.Infof("Stoping Web server...")
216                 ctx.webServer.Stop()
217         }
218         os.Exit(1)
219 }