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{})
59 // NewXdsServer Create a new instance of XDS server
60 func NewXdsServer(cliCtx *cli.Context) *Context {
63 // Set logger level and formatter
64 log := cliCtx.App.Metadata["logger"].(*logrus.Logger)
66 logLevel := cliCtx.GlobalString("log")
68 logLevel = "error" // FIXME get from Config DefaultLogLevel
70 if log.Level, err = logrus.ParseLevel(logLevel); err != nil {
71 fmt.Printf("Invalid log level : \"%v\"\n", logLevel)
74 log.Formatter = &logrus.TextFormatter{}
76 // Support silly logging (printed on log.debug)
77 sillyVal, sillyLog := os.LookupEnv("XDS_LOG_SILLY")
78 logSilly := sillyLog && sillyVal == "1"
79 sillyFunc := func(format string, args ...interface{}) {
81 log.Debugf("SILLY: "+format, args...)
85 // Define default configuration
87 ProgName: cliCtx.App.Name,
90 LogLevelSilly: logSilly,
92 lock: Lock{LockCpt: 0},
93 Exit: make(chan os.Signal, 1),
96 // register handler on SIGTERM / exit
97 signal.Notify(ctx.Exit, os.Interrupt, syscall.SIGTERM)
98 go handlerSigTerm(&ctx)
103 // Run Main function called to run XDS Server
104 func (ctx *Context) Run() (int, error) {
107 // Logs redirected into a file when logfile option or logsDir config is set
108 ctx.Config.LogVerboseOut = os.Stderr
109 if ctx.Config.FileConf.LogsDir != "" {
110 if ctx.Config.Options.LogFile != "stdout" {
111 logFile := ctx.Config.Options.LogFile
113 fdL, err := os.OpenFile(logFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
115 msgErr := fmt.Sprintf("Cannot create log file %s", logFile)
116 return int(syscall.EPERM), fmt.Errorf(msgErr)
120 ctx._logPrint("Logging file: %s\n", logFile)
123 logFileHTTPReq := filepath.Join(ctx.Config.FileConf.LogsDir, "xds-server-verbose.log")
124 fdLH, err := os.OpenFile(logFileHTTPReq, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
126 msgErr := fmt.Sprintf("Cannot create log file %s", logFileHTTPReq)
127 return int(syscall.EPERM), fmt.Errorf(msgErr)
129 ctx.Config.LogVerboseOut = fdLH
131 ctx._logPrint("Logging file for HTTP requests: %s\n", logFileHTTPReq)
134 // Create events management
135 ctx.events = EventsConstructor(ctx)
137 // Create syncthing instance when section "syncthing" is present in server-config.json
138 if ctx.Config.FileConf.SThgConf != nil {
139 ctx.SThg = st.NewSyncThing(ctx.Config, ctx.Log)
142 // Start local instance of Syncthing and Syncthing-notify
144 ctx.Log.Infof("Starting Syncthing...")
145 ctx.SThgCmd, err = ctx.SThg.Start()
149 ctx._logPrint("Syncthing started (PID %d)\n", ctx.SThgCmd.Process.Pid)
151 ctx.Log.Infof("Starting Syncthing-inotify...")
152 ctx.SThgInotCmd, err = ctx.SThg.StartInotify()
156 ctx._logPrint("Syncthing-inotify started (PID %d)\n", ctx.SThgInotCmd.Process.Pid)
158 // Establish connection with local Syncthing (retry if connection fail)
159 ctx._logPrint("Establishing connection with Syncthing...\n")
160 time.Sleep(2 * time.Second)
165 if err = ctx.SThg.Connect(); err == nil {
168 ctx.Log.Warningf("Establishing connection to Syncthing (retry %d/%d)", retry, maxRetry)
169 time.Sleep(time.Second)
172 if err != nil || retry == 0 {
176 // FIXME: do we still need Builder notion ? if no cleanup
177 if ctx.Config.Builder, err = xdsconfig.NewBuilderConfig(ctx.SThg.MyID); err != nil {
180 ctx.Config.SupportedSharing[xsapiv1.TypeCloudSync] = true
184 ctx.mfolders = FoldersConstructor(ctx)
186 // Load initial folders config from disk
187 if err := ctx.mfolders.LoadConfig(); err != nil {
192 ctx.sdks, err = SDKsConstructor(ctx)
197 // Init target and terminals model
198 ctx.targets = TargetsConstructor(ctx)
200 // Load initial target & terminal config
201 if err := ctx.targets.LoadConfig(); err != nil {
206 ctx.WWWServer = WebServerConstructor(ctx)
209 ctx.sessions = ClientSessionsConstructor(ctx, cookieMaxAge)
211 // Check if a new package version is available
212 // and monitor updates
215 // Run Web Server until exit requested (blocking call)
216 if err = ctx.WWWServer.Serve(); err != nil {
221 return -99, fmt.Errorf("Program exited ")
224 // Helper function to log message on both stdout and logger
225 func (ctx *Context) _logPrint(format string, args ...interface{}) {
226 fmt.Printf(format, args...)
227 if ctx.Log.Out != os.Stdout {
228 ctx.Log.Infof(format, args...)
232 // Handle exit and properly stop/close all stuff
233 func handlerSigTerm(ctx *Context) {
236 ctx.Log.Infof("Stoping Syncthing... (PID %d)", ctx.SThgCmd.Process.Pid)
238 ctx.Log.Infof("Stoping Syncthing-inotify... (PID %d)", ctx.SThgInotCmd.Process.Pid)
239 ctx.SThg.StopInotify()
241 if ctx.WWWServer != nil {
242 ctx.Log.Infof("Stoping Web server...")