Standardized XDS config file name and location.
[src/xds/xds-server.git] / lib / xdsserver / xdsserver.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 xdsserver
19
20 import (
21         "fmt"
22         "os"
23         "os/exec"
24         "os/signal"
25         "path/filepath"
26         "syscall"
27         "time"
28
29         "github.com/Sirupsen/logrus"
30         "github.com/codegangsta/cli"
31         "github.com/iotbzh/xds-server/lib/xsapiv1"
32
33         "github.com/iotbzh/xds-server/lib/syncthing"
34         "github.com/iotbzh/xds-server/lib/xdsconfig"
35 )
36
37 const cookieMaxAge = "3600"
38
39 // Context holds the XDS server context
40 type Context struct {
41         ProgName      string
42         Cli           *cli.Context
43         Config        *xdsconfig.Config
44         Log           *logrus.Logger
45         LogLevelSilly bool
46         LogSillyf     func(format string, args ...interface{})
47         SThg          *st.SyncThing
48         SThgCmd       *exec.Cmd
49         SThgInotCmd   *exec.Cmd
50         mfolders      *Folders
51         sdks          *SDKs
52         WWWServer     *WebServer
53         sessions      *Sessions
54         Exit          chan os.Signal
55 }
56
57 // NewXdsServer Create a new instance of XDS server
58 func NewXdsServer(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         // Support silly logging (printed on log.debug)
75         sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
76         logSilly := sillyLog && sillyVal == "1"
77         sillyFunc := func(format string, args ...interface{}) {
78                 if logSilly {
79                         log.Debugf("SILLY: "+format, args...)
80                 }
81         }
82
83         // Define default configuration
84         ctx := Context{
85                 ProgName:      cliCtx.App.Name,
86                 Cli:           cliCtx,
87                 Log:           log,
88                 LogLevelSilly: logSilly,
89                 LogSillyf:     sillyFunc,
90                 Exit:          make(chan os.Signal, 1),
91         }
92
93         // register handler on SIGTERM / exit
94         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
95         go handlerSigTerm(&ctx)
96
97         return &ctx
98 }
99
100 // Run Main function called to run XDS Server
101 func (ctx *Context) Run() (int, error) {
102         var err error
103
104         // Logs redirected into a file when logfile option or logsDir config is set
105         ctx.Config.LogVerboseOut = os.Stderr
106         if ctx.Config.FileConf.LogsDir != "" {
107                 if ctx.Config.Options.LogFile != "stdout" {
108                         logFile := ctx.Config.Options.LogFile
109
110                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
111                         if err != nil {
112                                 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
113                                 return int(syscall.EPERM), fmt.Errorf(msgErr)
114                         }
115                         ctx.Log.Out = fdL
116
117                         ctx._logPrint("Logging file: %s\n", logFile)
118                 }
119
120                 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
121                 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
122                 if err != nil {
123                         msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
124                         return int(syscall.EPERM), fmt.Errorf(msgErr)
125                 }
126                 ctx.Config.LogVerboseOut = fdLH
127
128                 ctx._logPrint("Logging file for HTTP requests:  %s\n", logFileHTTPReq)
129         }
130
131         // Create syncthing instance when section "syncthing" is present in server-config.json
132         if ctx.Config.FileConf.SThgConf != nil {
133                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
134         }
135
136         // Start local instance of Syncthing and Syncthing-notify
137         if ctx.SThg != nil {
138                 ctx.Log.Infof("Starting Syncthing...")
139                 ctx.SThgCmd, err = ctx.SThg.Start()
140                 if err != nil {
141                         return -4, err
142                 }
143                 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
144
145                 ctx.Log.Infof("Starting Syncthing-inotify...")
146                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
147                 if err != nil {
148                         return -4, err
149                 }
150                 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
151
152                 // Establish connection with local Syncthing (retry if connection fail)
153                 ctx._logPrint("Establishing connection with Syncthing...\n")
154                 time.Sleep(2 * time.Second)
155                 maxRetry := 30
156                 retry := maxRetry
157                 err = nil
158                 for retry > 0 {
159                         if err = ctx.SThg.Connect(); err == nil {
160                                 break
161                         }
162                         ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
163                         time.Sleep(time.Second)
164                         retry--
165                 }
166                 if err != nil || retry == 0 {
167                         return -4, err
168                 }
169
170                 // FIXME: do we still need Builder notion ? if no cleanup
171                 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
172                         return -4, err
173                 }
174                 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
175         }
176
177         // Init model folder
178         ctx.mfolders = FoldersNew(ctx)
179
180         // Load initial folders config from disk
181         if err := ctx.mfolders.LoadConfig(); err != nil {
182                 return -5, err
183         }
184
185         // Init cross SDKs
186         ctx.sdks, err = NewSDKs(ctx)
187         if err != nil {
188                 return -6, err
189         }
190
191         // Create Web Server
192         ctx.WWWServer = NewWebServer(ctx)
193
194         // Sessions manager
195         ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
196
197         // Run Web Server until exit requested (blocking call)
198         if err = ctx.WWWServer.Serve(); err != nil {
199                 ctx.Log.Println(err)
200                 return -7, err
201         }
202
203         return -99, fmt.Errorf("Program exited ")
204 }
205
206 // Helper function to log message on both stdout and logger
207 func (ctx *Context) _logPrint(format string, args ...interface{}) {
208         fmt.Printf(format, args...)
209         if ctx.Log.Out != os.Stdout {
210                 ctx.Log.Infof(format, args...)
211         }
212 }
213
214 // Handle exit and properly stop/close all stuff
215 func handlerSigTerm(ctx *Context) {
216         <-ctx.Exit
217         if ctx.SThg != nil {
218                 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
219                 ctx.SThg.Stop()
220                 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
221                 ctx.SThg.StopInotify()
222         }
223         if ctx.WWWServer != nil {
224                 ctx.Log.Infof("Stoping Web server...")
225                 ctx.WWWServer.Stop()
226         }
227         os.Exit(0)
228 }