2 * Copyright (C) 2017 "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.
25 common "github.com/iotbzh/xds-common/golib"
28 type SyncThingConf struct {
29 BinDir string `json:"binDir"`
30 Home string `json:"home"`
31 GuiAddress string `json:"gui-address"`
32 GuiAPIKey string `json:"gui-apikey"`
35 type XDSServerConf struct {
36 URL string `json:"url"`
37 ConnRetry int `json:"connRetry"`
39 // private/not exported fields
41 APIBaseURL string `json:"-"`
42 APIPartialURL string `json:"-"`
45 type FileConfig struct {
46 HTTPPort string `json:"httpPort"`
47 WebAppDir string `json:"webAppDir"`
48 LogsDir string `json:"logsDir"`
49 XDSAPIKey string `json:"xds-apikey"`
50 ServersConf []XDSServerConf `json:"xdsServers"`
51 SThgConf *SyncThingConf `json:"syncthing"`
54 // readGlobalConfig reads configuration from a config file.
55 // Order to determine which config file is used:
56 // 1/ from command line option: "--config myConfig.json"
57 // 2/ $HOME/.xds/agent/agent-config.json file
58 // 3/ /etc/xds-agent/config.json file
60 func readGlobalConfig(c *Config, confFile string) error {
62 searchIn := make([]string, 0, 3)
64 searchIn = append(searchIn, confFile)
66 if homeDir := common.GetUserHome(); homeDir != "" {
67 searchIn = append(searchIn, path.Join(homeDir, ".xds", "agent", "agent-config.json"))
70 searchIn = append(searchIn, "/etc/xds-agent/agent-config.json")
73 for _, p := range searchIn {
74 if _, err := os.Stat(p); err == nil {
80 c.Log.Infof("No config file found")
84 c.Log.Infof("Use config file: %s", *cFile)
86 // TODO move on viper package to support comments in JSON and also
87 // bind with flags (command line options)
88 // see https://github.com/spf13/viper#working-with-flags
90 fd, _ := os.Open(*cFile)
93 // Decode config file content and save it in a first variable
95 if err := json.NewDecoder(fd).Decode(&fCfg); err != nil {
99 // Decode config file content and overwrite default settings
101 json.NewDecoder(fd).Decode(&c.FileConf)
103 // Disable Syncthing support when there is no syncthing field in config
104 if fCfg.SThgConf == nil {
105 c.FileConf.SThgConf = nil
108 // Support environment variables (IOW ${MY_ENV_VAR} syntax) in agent-config.json
111 &c.FileConf.WebAppDir,
113 if c.FileConf.SThgConf != nil {
114 vars = append(vars, &c.FileConf.SThgConf.Home,
115 &c.FileConf.SThgConf.BinDir)
117 for _, field := range vars {
119 *field, err = common.ResolveEnvVar(*field)