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{})
58 // NewXdsServer Create a new instance of XDS server
59 func NewXdsServer(cliCtx *cli.Context) *Context {
62 // Set logger level and formatter
63 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
65 logLevel := cliCtx.GlobalString("log")
67 logLevel = "error" // FIXME get from Config DefaultLogLevel
69 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
70 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
73 log.Formatter = &logrus.TextFormatter{}
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{}) {
80 log.Debugf("SILLY: "+format, args...)
84 // Define default configuration
86 ProgName: cliCtx.App.Name,
89 LogLevelSilly: logSilly,
91 Exit: make(chan os.Signal, 1),
94 // register handler on SIGTERM / exit
95 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
96 go handlerSigTerm(&ctx)
101 // Run Main function called to run XDS Server
102 func (ctx *Context) Run() (int, error) {
105 // Logs redirected into a file when logfile option or logsDir config is set
106 ctx.Config.LogVerboseOut = os.Stderr
107 if ctx.Config.FileConf.LogsDir != "" {
108 if ctx.Config.Options.LogFile != "stdout" {
109 logFile := ctx.Config.Options.LogFile
111 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
113 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
114 return int(syscall.EPERM), fmt.Errorf(msgErr)
118 ctx._logPrint("Logging file: %s\n", logFile)
121 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
122 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
124 msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
125 return int(syscall.EPERM), fmt.Errorf(msgErr)
127 ctx.Config.LogVerboseOut = fdLH
129 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
132 // Create events management
133 ctx.events = EventsConstructor(ctx)
135 // Create syncthing instance when section "syncthing" is present in server-config.json
136 if ctx.Config.FileConf.SThgConf != nil {
137 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
140 // Start local instance of Syncthing and Syncthing-notify
142 ctx.Log.Infof("Starting Syncthing...")
143 ctx.SThgCmd, err = ctx.SThg.Start()
147 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
149 ctx.Log.Infof("Starting Syncthing-inotify...")
150 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
154 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
156 // Establish connection with local Syncthing (retry if connection fail)
157 ctx._logPrint("Establishing connection with Syncthing...\n")
158 time.Sleep(2 * time.Second)
163 if err = ctx.SThg.Connect(); err == nil {
166 ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
167 time.Sleep(time.Second)
170 if err != nil || retry == 0 {
174 // FIXME: do we still need Builder notion ? if no cleanup
175 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
178 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
182 ctx.mfolders = FoldersConstructor(ctx)
184 // Load initial folders config from disk
185 if err := ctx.mfolders.LoadConfig(); err != nil {
190 ctx.sdks, err = SDKsConstructor(ctx)
195 // Init target and terminals model
196 ctx.targets = TargetsConstructor(ctx)
198 // Load initial target & terminal config
199 if err := ctx.targets.LoadConfig(); err != nil {
204 ctx.WWWServer = WebServerConstructor(ctx)
207 ctx.sessions = ClientSessionsConstructor(ctx, cookieMaxAge)
209 // Run Web Server until exit requested (blocking call)
210 if err = ctx.WWWServer.Serve(); err != nil {
215 return -99, fmt.Errorf("Program exited ")
218 // Helper function to log message on both stdout and logger
219 func (ctx *Context) _logPrint(format string, args ...interface{}) {
220 fmt.Printf(format, args...)
221 if ctx.Log.Out != os.Stdout {
222 ctx.Log.Infof(format, args...)
226 // Handle exit and properly stop/close all stuff
227 func handlerSigTerm(ctx *Context) {
230 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
232 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
233 ctx.SThg.StopInotify()
235 if ctx.WWWServer != nil {
236 ctx.Log.Infof("Stoping Web server...")