335c1163e63ad65c994306f240fbe004659a6b63
[src/xds/xds-server.git] / lib / xdsconfig / config.go
1 /*
2  * Copyright (C) 2017-2018 "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 xdsconfig
19
20 import (
21         "fmt"
22         "io"
23         "os"
24         "path/filepath"
25
26         common "gerrit.automotivelinux.org/gerrit/src/xds/xds-common.git/golib"
27         "gerrit.automotivelinux.org/gerrit/src/xds/xds-server/lib/xsapiv1"
28         "github.com/Sirupsen/logrus"
29         "github.com/codegangsta/cli"
30 )
31
32 // Config parameters (json format) of /config command
33 type Config struct {
34         // Public APIConfig fields
35         xsapiv1.APIConfig
36
37         // Private (un-exported fields in REST GET /config route)
38         Options       Options        `json:"-"`
39         FileConf      FileConfig     `json:"-"`
40         Log           *logrus.Logger `json:"-"`
41         LogVerboseOut io.Writer      `json:"-"`
42 }
43
44 // Options set at the command line
45 type Options struct {
46         ConfigFile     string
47         LogLevel       string
48         LogFile        string
49         NoFolderConfig bool
50 }
51
52 // Config default values
53 const (
54         DefaultAPIVersion    = "1"
55         DefaultPort          = "8000"
56         DefaultShareDir      = "${HOME}/.xds/server/projects"
57         DefaultSTHomeDir     = "${HOME}/.xds/server/syncthing-config"
58         DefaultSdkScriptsDir = "${EXEPATH}/sdks"
59         DefaultSdkDbUpdate   = "startup"
60 )
61
62 // Init loads the configuration on start-up
63 func Init(cliCtx *cli.Context, log *logrus.Logger) (*Config, error) {
64         var err error
65
66         dfltShareDir := DefaultShareDir
67         dfltSTHomeDir := DefaultSTHomeDir
68         if resDir, err := common.ResolveEnvVar(DefaultShareDir); err == nil {
69                 dfltShareDir = resDir
70         }
71         if resDir, err := common.ResolveEnvVar(DefaultSTHomeDir); err == nil {
72                 dfltSTHomeDir = resDir
73         }
74
75         // Retrieve Server ID (or create one the first time)
76         uuid, err := ServerIDGet()
77         if err != nil {
78                 return nil, err
79         }
80
81         // Define default configuration
82         c := Config{
83                 APIConfig: xsapiv1.APIConfig{
84                         ServerUID:        uuid,
85                         Version:          cliCtx.App.Metadata["version"].(string),
86                         APIVersion:       DefaultAPIVersion,
87                         VersionGitTag:    cliCtx.App.Metadata["git-tag"].(string),
88                         Builder:          xsapiv1.BuilderConfig{},
89                         SupportedSharing: map[string]bool{ /*FIXME USE folder.TypePathMap*/ "PathMap": true},
90                 },
91
92                 Options: Options{
93                         ConfigFile:     cliCtx.GlobalString("config"),
94                         LogLevel:       cliCtx.GlobalString("log"),
95                         LogFile:        cliCtx.GlobalString("logfile"),
96                         NoFolderConfig: cliCtx.GlobalBool("no-folderconfig"),
97                 },
98                 FileConf: FileConfig{
99                         WebAppDir:     "webapp/dist",
100                         ShareRootDir:  dfltShareDir,
101                         SdkScriptsDir: DefaultSdkScriptsDir,
102                         SdkDbUpdate:   DefaultSdkDbUpdate,
103                         HTTPPort:      DefaultPort,
104                         SThgConf:      &SyncThingConf{Home: dfltSTHomeDir},
105                         LogsDir:       "",
106                 },
107                 Log: log,
108         }
109
110         c.Log.Infoln("Server UUID:          ", uuid)
111
112         // config file settings overwrite default config
113         err = readGlobalConfig(&c, c.Options.ConfigFile)
114         if err != nil {
115                 return nil, err
116         }
117
118         // Update location of shared dir if needed
119         if !common.Exists(c.FileConf.ShareRootDir) {
120                 if err := os.MkdirAll(c.FileConf.ShareRootDir, 0770); err != nil {
121                         return nil, fmt.Errorf("No valid shared directory found: %v", err)
122                 }
123         }
124         c.Log.Infoln("Share root directory: ", c.FileConf.ShareRootDir)
125
126         // Where Logs are redirected:
127         //  default 'stdout' (logfile option default value)
128         //  else use file (or filepath) set by --logfile option
129         //  that may be overwritten by LogsDir field of config file
130         logF := c.Options.LogFile
131         logD := c.FileConf.LogsDir
132         if logF != "stdout" {
133                 if logD != "" {
134                         lf := filepath.Base(logF)
135                         if lf == "" || lf == "." {
136                                 lf = "xds-server.log"
137                         }
138                         logF = filepath.Join(logD, lf)
139                 } else {
140                         logD = filepath.Dir(logF)
141                 }
142         }
143         if logD == "" || logD == "." {
144                 logD = "/tmp/xds/logs"
145         }
146         c.Options.LogFile = logF
147         c.FileConf.LogsDir = logD
148
149         if c.FileConf.LogsDir != "" && !common.Exists(c.FileConf.LogsDir) {
150                 if err := os.MkdirAll(c.FileConf.LogsDir, 0770); err != nil {
151                         return nil, fmt.Errorf("Cannot create logs dir: %v", err)
152                 }
153         }
154
155         c.Log.Infoln("Logs file:            ", c.Options.LogFile)
156         c.Log.Infoln("Logs directory:       ", c.FileConf.LogsDir)
157
158         return &c, nil
159 }