2 * Copyright (C) 2017-2018 "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.
29 st "gerrit.automotivelinux.org/gerrit/src/xds/xds-server/lib/syncthing"
30 "gerrit.automotivelinux.org/gerrit/src/xds/xds-server/lib/xdsconfig"
31 "gerrit.automotivelinux.org/gerrit/src/xds/xds-server/lib/xsapiv1"
32 "github.com/Sirupsen/logrus"
33 "github.com/codegangsta/cli"
36 const cookieMaxAge = "3600"
38 // Context holds the XDS server context
42 Config *xdsconfig.Config
45 LogSillyf func(format string, args ...interface{})
57 // NewXdsServer Create a new instance of XDS server
58 func NewXdsServer(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 // 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{}) {
79 log.Debugf("SILLY: "+format, args...)
83 // Define default configuration
85 ProgName: cliCtx.App.Name,
88 LogLevelSilly: logSilly,
90 Exit: make(chan os.Signal, 1),
93 // register handler on SIGTERM / exit
94 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
95 go handlerSigTerm(&ctx)
100 // Run Main function called to run XDS Server
101 func (ctx *Context) Run() (int, error) {
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
110 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
112 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
113 return int(syscall.EPERM), fmt.Errorf(msgErr)
117 ctx._logPrint("Logging file: %s\n", logFile)
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)
123 msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
124 return int(syscall.EPERM), fmt.Errorf(msgErr)
126 ctx.Config.LogVerboseOut = fdLH
128 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
131 // Create events management
132 ctx.events = NewEvents(ctx)
134 // Create syncthing instance when section "syncthing" is present in server-config.json
135 if ctx.Config.FileConf.SThgConf != nil {
136 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
139 // Start local instance of Syncthing and Syncthing-notify
141 ctx.Log.Infof("Starting Syncthing...")
142 ctx.SThgCmd, err = ctx.SThg.Start()
146 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
148 ctx.Log.Infof("Starting Syncthing-inotify...")
149 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
153 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
155 // Establish connection with local Syncthing (retry if connection fail)
156 ctx._logPrint("Establishing connection with Syncthing...\n")
157 time.Sleep(2 * time.Second)
162 if err = ctx.SThg.Connect(); err == nil {
165 ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
166 time.Sleep(time.Second)
169 if err != nil || retry == 0 {
173 // FIXME: do we still need Builder notion ? if no cleanup
174 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
177 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
181 ctx.mfolders = FoldersNew(ctx)
183 // Load initial folders config from disk
184 if err := ctx.mfolders.LoadConfig(); err != nil {
189 ctx.sdks, err = NewSDKs(ctx)
195 ctx.WWWServer = NewWebServer(ctx)
198 ctx.sessions = NewClientSessions(ctx, cookieMaxAge)
200 // Run Web Server until exit requested (blocking call)
201 if err = ctx.WWWServer.Serve(); err != nil {
206 return -99, fmt.Errorf("Program exited ")
209 // Helper function to log message on both stdout and logger
210 func (ctx *Context) _logPrint(format string, args ...interface{}) {
211 fmt.Printf(format, args...)
212 if ctx.Log.Out != os.Stdout {
213 ctx.Log.Infof(format, args...)
217 // Handle exit and properly stop/close all stuff
218 func handlerSigTerm(ctx *Context) {
221 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
223 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
224 ctx.SThg.StopInotify()
226 if ctx.WWWServer != nil {
227 ctx.Log.Infof("Stoping Web server...")