Added Copyright header.
[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         SThg          *st.SyncThing
47         SThgCmd       *exec.Cmd
48         SThgInotCmd   *exec.Cmd
49         mfolders      *Folders
50         sdks          *SDKs
51         WWWServer     *WebServer
52         sessions      *Sessions
53         Exit          chan os.Signal
54 }
55
56 // NewXdsServer Create a new instance of XDS server
57 func NewXdsServer(cliCtx *cli.Context) *Context {
58         var err error
59
60         // Set logger level and formatter
61         log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
62
63         logLevel := cliCtx.GlobalString("log")
64         if logLevel == "" {
65                 logLevel = "error" // FIXME get from Config DefaultLogLevel
66         }
67         if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
68                 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
69                 os.Exit(1)
70         }
71         log.Formatter = &logrus.TextFormatter{}
72
73         sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
74
75         // Define default configuration
76         ctx := Context{
77                 ProgName:      cliCtx.App.Name,
78                 Cli:           cliCtx,
79                 Log:           log,
80                 LogLevelSilly: (sillyLog && sillyVal == "1"),
81                 Exit:          make(chan os.Signal, 1),
82         }
83
84         // register handler on SIGTERM / exit
85         signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
86         go handlerSigTerm(&ctx)
87
88         return &ctx
89 }
90
91 // Run Main function called to run XDS Server
92 func (ctx *Context) Run() (int, error) {
93         var err error
94
95         // Logs redirected into a file when logfile option or logsDir config is set
96         ctx.Config.LogVerboseOut = os.Stderr
97         if ctx.Config.FileConf.LogsDir != "" {
98                 if ctx.Config.Options.LogFile != "stdout" {
99                         logFile := ctx.Config.Options.LogFile
100
101                         fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
102                         if err != nil {
103                                 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
104                                 return int(syscall.EPERM), fmt.Errorf(msgErr)
105                         }
106                         ctx.Log.Out = fdL
107
108                         ctx._logPrint("Logging file: %s\n", logFile)
109                 }
110
111                 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
112                 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
113                 if err != nil {
114                         msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
115                         return int(syscall.EPERM), fmt.Errorf(msgErr)
116                 }
117                 ctx.Config.LogVerboseOut = fdLH
118
119                 ctx._logPrint("Logging file for HTTP requests:  %s\n", logFileHTTPReq)
120         }
121
122         // Create syncthing instance when section "syncthing" is present in config.json
123         if ctx.Config.FileConf.SThgConf != nil {
124                 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
125         }
126
127         // Start local instance of Syncthing and Syncthing-notify
128         if ctx.SThg != nil {
129                 ctx.Log.Infof("Starting Syncthing...")
130                 ctx.SThgCmd, err = ctx.SThg.Start()
131                 if err != nil {
132                         return -4, err
133                 }
134                 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
135
136                 ctx.Log.Infof("Starting Syncthing-inotify...")
137                 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
138                 if err != nil {
139                         return -4, err
140                 }
141                 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
142
143                 // Establish connection with local Syncthing (retry if connection fail)
144                 ctx._logPrint("Establishing connection with Syncthing...\n")
145                 time.Sleep(2 * time.Second)
146                 maxRetry := 30
147                 retry := maxRetry
148                 err = nil
149                 for retry > 0 {
150                         if err = ctx.SThg.Connect(); err == nil {
151                                 break
152                         }
153                         ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
154                         time.Sleep(time.Second)
155                         retry--
156                 }
157                 if err != nil || retry == 0 {
158                         return -4, err
159                 }
160
161                 // FIXME: do we still need Builder notion ? if no cleanup
162                 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
163                         return -4, err
164                 }
165                 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
166         }
167
168         // Init model folder
169         ctx.mfolders = FoldersNew(ctx)
170
171         // Load initial folders config from disk
172         if err := ctx.mfolders.LoadConfig(); err != nil {
173                 return -5, err
174         }
175
176         // Init cross SDKs
177         ctx.sdks, err = NewSDKs(ctx)
178         if err != nil {
179                 return -6, err
180         }
181
182         // Create Web Server
183         ctx.WWWServer = NewWebServer(ctx)
184
185         // Sessions manager
186         ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
187
188         // Run Web Server until exit requested (blocking call)
189         if err = ctx.WWWServer.Serve(); err != nil {
190                 ctx.Log.Println(err)
191                 return -7, err
192         }
193
194         return -99, fmt.Errorf("Program exited ")
195 }
196
197 // Helper function to log message on both stdout and logger
198 func (ctx *Context) _logPrint(format string, args ...interface{}) {
199         fmt.Printf(format, args...)
200         if ctx.Log.Out != os.Stdout {
201                 ctx.Log.Infof(format, args...)
202         }
203 }
204
205 // Handle exit and properly stop/close all stuff
206 func handlerSigTerm(ctx *Context) {
207         <-ctx.Exit
208         if ctx.SThg != nil {
209                 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
210                 ctx.SThg.Stop()
211                 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
212                 ctx.SThg.StopInotify()
213         }
214         if ctx.WWWServer != nil {
215                 ctx.Log.Infof("Stoping Web server...")
216                 ctx.WWWServer.Stop()
217         }
218         os.Exit(0)
219 }