/
config.go
110 lines (89 loc) · 2.28 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package config
import (
"fmt"
"os"
"github.com/BurntSushi/toml"
"github.com/kardianos/osext"
"github.com/sirupsen/logrus"
)
// DatastoreConf holds the config values for Datastore
type DatastoreConf struct {
Namespace string
Project string
}
// SQLConf holds the config values for SQL databases
type SQLConf struct {
Username string
PasswordFile string
Host string
Port int
Database string
DisableSSL bool
}
// Config struct holds the current configuration
type Config struct {
Server struct {
Address string
Port int
}
Logging struct {
Format string
Level string
}
Metadata map[string]string
GoogleCloudDatastore DatastoreConf
PostgreSQL SQLConf
Crawler struct {
LogPattern string
}
}
// Initialize a new Config
func Initialize(configFile string) *Config {
cfg := DefaultConfig()
ReadConfigFile(cfg, getConfigFilePath(configFile))
return cfg
}
// DefaultConfig returns a Config struct with default values
func DefaultConfig() *Config {
cfg := &Config{}
cfg.Server.Address = "0.0.0.0"
cfg.Server.Port = 7654
cfg.Logging.Format = "text"
cfg.Logging.Level = "DEBUG"
cfg.Metadata = make(map[string]string)
cfg.Metadata["owner"] = os.Getenv("USER")
cfg.Crawler.LogPattern = `.*\[([\d{4}\-\d{2}\-\d{2}T\d{2}:\d{2}:\d{2}.\d*Z]*)\].*?\s(.*)$`
return cfg
}
// getConfigFilePath returns the location of the config file in order of priority:
// 1 ) --config commandline flag
// 1 ) File in same directory as the executable
// 2 ) Global file in /etc/ale/config.toml
func getConfigFilePath(configPath string) string {
if configPath != "" {
if _, err := os.Stat(configPath); err == nil {
return configPath
}
panic(fmt.Sprintf("Unable to open %s.", configPath))
}
path, _ := osext.ExecutableFolder()
path = fmt.Sprintf("%s/config.toml", path)
if _, err := os.Open(path); err == nil {
return path
}
globalPath := "/etc/ale/config.toml"
if _, err := os.Open(globalPath); err == nil {
return globalPath
}
return ""
}
// ReadConfigFile reads the config file and merges with DefaultConfig, taking precedence
func ReadConfigFile(cfg *Config, path string) {
_, err := os.Stat(path)
if err != nil {
return
}
if _, err := toml.DecodeFile(path, cfg); err != nil {
logrus.WithError(err).Fatal("unable to read config")
}
}