-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
340 lines (281 loc) · 9.37 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package config
import (
"errors"
"fmt"
cc "github.com/ContainX/go-springcloud/config"
"github.com/ContainX/go-utils/encoding"
"github.com/ContainX/go-utils/logger"
"github.com/kelseyhightower/envconfig"
_ "github.com/kelseyhightower/envconfig"
"github.com/spf13/cobra"
"os"
"regexp"
)
const (
EnvErrorFmt = "Error creating config from env: %s"
DefaultNginxTemplatePath = "/etc/nginx/nginx.template"
DefaultNginxConfPath = "/etc/nginx/nginx.conf"
MarathonScheduler SchedulerType = 1
SwarmScheduler SchedulerType = 2
)
type SchedulerType int
var log = logger.GetLogger("beethoven.config")
// Config provides configuration information for Marathon streams and the proxy
type Config struct {
// Scheduler type to use (0 for Marathon, 1 for Swarm)
// Only applicable if both Swarm and Marathon are configured
SchedulerType SchedulerType `json:"scheduler_type"`
// Docker/Swarm configuration
Swarm *SwarmConfig `json:"swarm"`
// Marathon configuration options
Marathon *MarathonConfig `json:"marathon"`
// Deprecated - Please use Marathon
MarthonUrls []string `json:"marthon_urls" envconfig:"-"`
// Deprecated - Use Marathon.Username
Username string `json:"username" envconfig:"-"`
// Deprecated - Use Marathon.Password
Password string `json:"password" envconfig:"-"`
// Optional regex filter to only reload based on certain apps that match
// ex. ^.*something.* would match all /apps/something app identifiers
// Enivronment variable: BT_FILTER_REGEX
FilterRegExStr string `json:"filter_regex" envconfig:"filter_regex"`
// Resolved Filter regex
filterRegEx *regexp.Regexp
// Port to listen to HTTP requests. Default 7777
Port int `json:"port"`
// Scheme we are listening to (http | https)
Scheme string `json:"scheme"`
// Location to nginx.conf template - default: /etc/nginx/nginx.template
Template string `json:"template"`
// Location of the nginx.conf - default: /etc/nginx/nginx.conf
NginxConfig string `json:"nginx_config"`
// User defined configuration data that can be used as part of the template parsing
// if Beethoven is launched with --root-apps=false .
Data map[string]interface{}
/* Internal */
Version string `json:"-"`
context *reloadContext `json:"-"`
}
type SwarmConfig struct {
// Target connection string for Swarm
Endpoint string `json:"endpoint"`
// Network is the name of the network Beethoven should proxy internal requests to. This is only used
// if RouteToNode is set to false (the default)
Network string `json:"network"`
// RouteToNode will instruct beethoven to route requests to the public address of the Swarm node. This
// can be used in scenarios where Beethoven is running outside of the Swarm cluster
RouteToNode bool
// Interval to watch for Swarm topology changes
WatchIntervalSecs int `json:"watch_interval_secs"`
// TLS Certificate file
TLSCert string `json:"tls_cert"`
// TLS Certificate key
TLSKey string `json:"tls_key"`
// TLS CA Certificate
TLSCACert string `json:"tlsca_cert"`
// Verify TLS
TLSVerify bool `json:"tls_verify"`
}
type MarathonConfig struct {
// The URL to Marathon: ex. http://host:8080
// Enivronment variable: BT_MARATHON_URLS
Endpoints []string `json:"endpoints" envconfig:"marathon_urls"`
// The Marathon ID for Beethoven (optional). If set,
// will allow for reloading new configuration changes (if using user Data below).
ServiceId string `json:"service_id"`
// The basic auth username - if applicable
// Enivronment variable: BT_USERNAME
Username string `json:"username" envconfig:"username"`
// The basic auth password - if applicable
// Enivronment variable: BT_PASSWORD
Password string `json:"password" envconfig:"password"`
}
type reloadContext struct {
server string
name string
label string
profile string
filename string
}
var (
FileNotFound = errors.New("Cannot find the specified config file")
dryRun = false
rootedApps = true
)
// AddFlags is a hook to add additional CLI Flags
func AddFlags(cmd *cobra.Command) {
cmd.Flags().StringP("config", "c", "", "Path and filename of local configuration file. ex: config.yml")
cmd.Flags().BoolP("remote", "r", false, "Use remote configuraion server")
cmd.Flags().StringP("server", "s", "", "Remote: URI to remote config server. ex: http://server:8888, env: CONFIG_SERVER")
cmd.Flags().String("name", "beethoven", "Remote: The name of the app, env: CONFIG_NAME")
cmd.Flags().String("label", "master", "Remote: The branch to fetch the config from, env: CONFIG_LABEL")
cmd.Flags().String("profile", "default", "Remote: The profile to use, env: CONFIG_PROFILE")
cmd.Flags().Bool("dryrun", false, "Bypass NGINX validation/reload -- used for debugging logs")
cmd.Flags().Bool("root-apps", true, "True by defaults, template context is all apps from marathon. False, apps is a field in the template as well as config")
}
func LoadConfigFromCommand(cmd *cobra.Command) (*Config, error) {
remote, _ := cmd.Flags().GetBool("remote")
config, _ := cmd.Flags().GetString("config")
dryRun, _ = cmd.Flags().GetBool("dryrun")
rootedApps, _ = cmd.Flags().GetBool("root-apps")
if remote {
server := os.Getenv("CONFIG_SERVER")
name := os.Getenv("CONFIG_NAME")
label := os.Getenv("CONFIG_LABEL")
profile := os.Getenv("CONFIG_PROFILE")
if server == "" {
server, _ = cmd.Flags().GetString("server")
}
if name == "" {
name, _ = cmd.Flags().GetString("name")
}
if label == "" {
label, _ = cmd.Flags().GetString("label")
}
if profile == "" {
profile, _ = cmd.Flags().GetString("profile")
}
return loadFromRemote(server, name, label, profile)
}
if config != "" {
return loadFromFile(config)
}
cfg := new(Config)
if err := envconfig.Process("bt", cfg); err != nil {
return nil, fmt.Errorf(EnvErrorFmt, err.Error())
}
if len(cfg.MarthonUrls) == 0 {
return nil, fmt.Errorf(EnvErrorFmt, "BT_MARATHON_URLS not defined")
}
return cfg.loadDefaults(), nil
}
// loadFromFile loads the config from a file and returns the config
func loadFromFile(configFile string) (*Config, error) {
if configFile == "" {
return nil, FileNotFound
}
encoder, err := encoding.NewEncoderFromFileExt(configFile)
if err != nil {
return nil, err
}
cfg := new(Config)
if err := encoder.UnMarshalFile(configFile, cfg); err != nil {
return nil, err
}
cfg.context = &reloadContext{filename: configFile}
return cfg.loadDefaults(), nil
}
// loadFromRemote loads the config from a remote configuration server, specifically
// spring cloud config
func loadFromRemote(server, appName, label, profile string) (*Config, error) {
client, err := cc.New(cc.Bootstrap{
URI: server,
Label: label,
Name: appName,
Profile: profile,
})
if err != nil {
return nil, err
}
cfg := new(Config)
if err := client.Fetch(cfg); err != nil {
return nil, err
}
cfg.context = &reloadContext{
server: server,
name: appName,
label: label,
profile: profile,
}
return cfg.loadDefaults(), nil
}
/* Config receivers */
// Reload will re-fetch/load the a subset of the configuration and apply it.
// The data applied is "Data" and "FilterRegExStr" values
func (c *Config) Reload() bool {
newCfg, err := loadConfigFromContext(c.context)
if err != nil {
log.Errorf("Error reloading configuration: %s", err.Error())
return false
}
c.Data = newCfg.Data
if c.FilterRegExStr != newCfg.FilterRegExStr {
c.FilterRegExStr = newCfg.FilterRegExStr
c.ParseRegEx()
}
log.Info("Configuration successfully reloaded")
return true
}
func loadConfigFromContext(c *reloadContext) (*Config, error) {
if c.filename != "" {
return loadFromFile(c.filename)
}
return loadFromRemote(c.server, c.name, c.label, c.profile)
}
// HttpPort is the port we serve the API with
// default 7777 if config port is undefined
func (c *Config) HttpPort() int {
if c.Port == 0 {
return 7777
}
return c.Port
}
func (c *Config) loadDefaults() *Config {
if c.NginxConfig == "" {
c.NginxConfig = DefaultNginxConfPath
}
if c.Template == "" {
c.Template = DefaultNginxTemplatePath
}
if c.Scheme == "" {
c.Scheme = "http"
}
if c.Marathon == nil && (c.MarthonUrls != nil && len(c.MarthonUrls) > 0) {
c.Marathon = &MarathonConfig{
Endpoints: c.MarthonUrls,
Username: c.Username,
Password: c.Password,
}
if c.SchedulerType == 0 {
c.SchedulerType = MarathonScheduler
}
} else if c.Marathon != nil && c.SchedulerType == 0 {
c.SchedulerType = MarathonScheduler
}
if c.Swarm != nil {
if c.Swarm.Endpoint == "" {
c.Swarm.Endpoint = "unix:///var/run/docker.sock"
}
if c.SchedulerType == 0 {
c.SchedulerType = SwarmScheduler
}
}
c.ParseRegEx()
return c
}
// ParseRegEx validates and parses that the regex is valid. If the FilterRegExpStr is invalid
// the value is emptied and an Error is logged
func (c *Config) ParseRegEx() {
if c.FilterRegExStr != "" {
if rx, err := regexp.Compile(c.FilterRegExStr); err != nil {
log.Error("Error: ignoring user regex filter: %s", err.Error())
c.FilterRegExStr = ""
} else {
c.filterRegEx = rx
}
}
}
func (c *Config) IsFilterDefined() bool {
return c.filterRegEx != nil
}
func (c *Config) Filter() *regexp.Regexp {
return c.filterRegEx
}
func (c *Config) DryRun() bool {
return dryRun
}
// IsTemplatedAppRooted means that application from marathon are the actual object during
// template parsing. If false then applications are a sub-element.
func (c *Config) IsTemplatedAppRooted() bool {
return rootedApps
}