Migration to AGL gerrit (update go import)
[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 )
60
61 // Init loads the configuration on start-up
62 func Init(cliCtx *cli.Context, log *logrus.Logger) (*Config, error) {
63         var err error
64
65         dfltShareDir := DefaultShareDir
66         dfltSTHomeDir := DefaultSTHomeDir
67         if resDir, err := common.ResolveEnvVar(DefaultShareDir); err == nil {
68                 dfltShareDir = resDir
69         }
70         if resDir, err := common.ResolveEnvVar(DefaultSTHomeDir); err == nil {
71                 dfltSTHomeDir = resDir
72         }
73
74         // Retrieve Server ID (or create one the first time)
75         uuid, err := ServerIDGet()
76         if err != nil {
77                 return nil, err
78         }
79
80         // Define default configuration
81         c := Config{
82                 APIConfig: xsapiv1.APIConfig{
83                         ServerUID:        uuid,
84                         Version:          cliCtx.App.Metadata["version"].(string),
85                         APIVersion:       DefaultAPIVersion,
86                         VersionGitTag:    cliCtx.App.Metadata["git-tag"].(string),
87                         Builder:          xsapiv1.BuilderConfig{},
88                         SupportedSharing: map[string]bool{ /*FIXME USE folder.TypePathMap*/ "PathMap": true},
89                 },
90
91                 Options: Options{
92                         ConfigFile:     cliCtx.GlobalString("config"),
93                         LogLevel:       cliCtx.GlobalString("log"),
94                         LogFile:        cliCtx.GlobalString("logfile"),
95                         NoFolderConfig: cliCtx.GlobalBool("no-folderconfig"),
96                 },
97                 FileConf: FileConfig{
98                         WebAppDir:     "webapp/dist",
99                         ShareRootDir:  dfltShareDir,
100                         SdkScriptsDir: DefaultSdkScriptsDir,
101                         HTTPPort:      DefaultPort,
102                         SThgConf:      &SyncThingConf{Home: dfltSTHomeDir},
103                         LogsDir:       "",
104                 },
105                 Log: log,
106         }
107
108         c.Log.Infoln("Server UUID:          ", uuid)
109
110         // config file settings overwrite default config
111         err = readGlobalConfig(&c, c.Options.ConfigFile)
112         if err != nil {
113                 return nil, err
114         }
115
116         // Update location of shared dir if needed
117         if !common.Exists(c.FileConf.ShareRootDir) {
118                 if err := os.MkdirAll(c.FileConf.ShareRootDir, 0770); err != nil {
119                         return nil, fmt.Errorf("No valid shared directory found: %v", err)
120                 }
121         }
122         c.Log.Infoln("Share root directory: ", c.FileConf.ShareRootDir)
123
124         // Where Logs are redirected:
125         //  default 'stdout' (logfile option default value)
126         //  else use file (or filepath) set by --logfile option
127         //  that may be overwritten by LogsDir field of config file
128         logF := c.Options.LogFile
129         logD := c.FileConf.LogsDir
130         if logF != "stdout" {
131                 if logD != "" {
132                         lf := filepath.Base(logF)
133                         if lf == "" || lf == "." {
134                                 lf = "xds-server.log"
135                         }
136                         logF = filepath.Join(logD, lf)
137                 } else {
138                         logD = filepath.Dir(logF)
139                 }
140         }
141         if logD == "" || logD == "." {
142                 logD = "/tmp/xds/logs"
143         }
144         c.Options.LogFile = logF
145         c.FileConf.LogsDir = logD
146
147         if c.FileConf.LogsDir != "" && !common.Exists(c.FileConf.LogsDir) {
148                 if err := os.MkdirAll(c.FileConf.LogsDir, 0770); err != nil {
149                         return nil, fmt.Errorf("Cannot create logs dir: %v", err)
150                 }
151         }
152
153         c.Log.Infoln("Logs file:            ", c.Options.LogFile)
154         c.Log.Infoln("Logs directory:       ", c.FileConf.LogsDir)
155
156         return &c, nil
157 }