forked from movio/bramble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
303 lines (265 loc) · 8.29 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
package bramble
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/fsnotify/fsnotify"
log "github.com/sirupsen/logrus"
)
var Version = "dev"
// PluginConfig contains the configuration for the named plugin
type PluginConfig struct {
Name string
Config json.RawMessage
}
// Config contains the gateway configuration
type Config struct {
IdFieldName string `json:"id-field-name"`
GatewayListenAddress string `json:"gateway-address"`
DisableIntrospection bool `json:"disable-introspection"`
MetricsListenAddress string `json:"metrics-address"`
PrivateListenAddress string `json:"private-address"`
GatewayPort int `json:"gateway-port"`
MetricsPort int `json:"metrics-port"`
PrivatePort int `json:"private-port"`
Services []string `json:"services"`
LogLevel log.Level `json:"loglevel"`
PollInterval string `json:"poll-interval"`
PollIntervalDuration time.Duration
MaxRequestsPerQuery int64 `json:"max-requests-per-query"`
MaxServiceResponseSize int64 `json:"max-service-response-size"`
Plugins []PluginConfig
// Config extensions that can be shared among plugins
Extensions map[string]json.RawMessage
// HTTP client to customize for downstream services query
QueryHTTPClient *http.Client
plugins []Plugin
executableSchema *ExecutableSchema
watcher *fsnotify.Watcher
configFiles []string
linkedFiles []string
}
func (c *Config) addrOrPort(addr string, port int) string {
if addr != "" {
return addr
}
return fmt.Sprintf(":%d", port)
}
// GatewayAddress returns the host:port string of the gateway
func (c *Config) GatewayAddress() string {
return c.addrOrPort(c.GatewayListenAddress, c.GatewayPort)
}
// PrivateAddress returns the address for private port
func (c *Config) PrivateAddress() string {
return c.addrOrPort(c.PrivateListenAddress, c.PrivatePort)
}
func (c *Config) PrivateHttpAddress(path string) string {
if c.PrivateListenAddress == "" {
return fmt.Sprintf("http://localhost:%d/%s", c.PrivatePort, path)
}
return fmt.Sprintf("http://%s/%s", c.PrivateListenAddress, path)
}
// MetricAddress returns the address for the metric port
func (c *Config) MetricAddress() string {
return c.addrOrPort(c.MetricsListenAddress, c.MetricsPort)
}
// Load loads or reloads all the config files.
func (c *Config) Load() error {
c.Extensions = nil
// concatenate plugins from all the config files
var plugins []PluginConfig
for _, configFile := range c.configFiles {
c.Plugins = nil
f, err := os.Open(configFile)
if err != nil {
return err
}
defer f.Close()
if err := json.NewDecoder(f).Decode(&c); err != nil {
return fmt.Errorf("error decoding config file %q: %w", configFile, err)
}
plugins = append(plugins, c.Plugins...)
}
c.Plugins = plugins
if strings.TrimSpace(c.IdFieldName) != "" {
IdFieldName = c.IdFieldName
}
logLevel := os.Getenv("BRAMBLE_LOG_LEVEL")
if level, err := log.ParseLevel(logLevel); err == nil {
c.LogLevel = level
} else if logLevel != "" {
log.WithField("loglevel", logLevel).Warn("invalid loglevel")
}
log.SetLevel(c.LogLevel)
var err error
c.PollIntervalDuration, err = time.ParseDuration(c.PollInterval)
if err != nil {
return fmt.Errorf("invalid poll interval: %w", err)
}
services, err := c.buildServiceList()
if err != nil {
return err
}
c.Services = services
c.plugins = c.ConfigurePlugins()
return nil
}
func (c *Config) buildServiceList() ([]string, error) {
serviceSet := map[string]bool{}
for _, service := range c.Services {
serviceSet[service] = true
}
for _, service := range strings.Fields(os.Getenv("BRAMBLE_SERVICE_LIST")) {
serviceSet[service] = true
}
for _, plugin := range c.plugins {
ok, path := plugin.GraphqlQueryPath()
if ok {
service := c.PrivateHttpAddress(path)
serviceSet[service] = true
}
}
services := []string{}
for service := range serviceSet {
services = append(services, service)
}
if len(services) == 0 {
return nil, fmt.Errorf("no services found in BRAMBLE_SERVICE_LIST or %s", c.configFiles)
}
return services, nil
}
// Watch starts watching the config files for change.
func (c *Config) Watch() {
for {
select {
case err := <-c.watcher.Errors:
log.WithError(err).Error("config watch error")
case e := <-c.watcher.Events:
log.WithFields(log.Fields{"event": e, "files": c.configFiles, "links": c.linkedFiles}).Debug("received config file event")
shouldUpdate := false
for i := range c.configFiles {
// we want to reload the config if:
// - the config file was updated, or
// - the config file is a symlink and was changed (k8s config map update)
if filepath.Clean(e.Name) == c.configFiles[i] && (e.Op == fsnotify.Write || e.Op == fsnotify.Create) {
shouldUpdate = true
break
}
currentFile, _ := filepath.EvalSymlinks(c.configFiles[i])
if c.linkedFiles[i] != "" && c.linkedFiles[i] != currentFile {
c.linkedFiles[i] = currentFile
shouldUpdate = true
break
}
}
if !shouldUpdate {
log.Debug("nothing to update")
continue
}
if e.Op != fsnotify.Write && e.Op != fsnotify.Create {
log.Debug("ignoring non write/create event")
continue
}
err := c.Load()
if err != nil {
log.WithError(err).Error("error reloading config")
}
log.WithField("services", c.Services).Info("config file updated")
err = c.executableSchema.UpdateServiceList(c.Services)
if err != nil {
log.WithError(err).Error("error updating services")
}
log.WithField("services", c.Services).Info("updated services")
}
}
}
// GetConfig returns operational config for the gateway
func GetConfig(configFiles []string) (*Config, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, fmt.Errorf("could not create watcher: %w", err)
}
var linkedFiles []string
for _, configFile := range configFiles {
// watch the directory, else we'll lose the watch if the file is relinked
err = watcher.Add(filepath.Dir(configFile))
if err != nil {
return nil, fmt.Errorf("error add file to watcher: %w", err)
}
linkedFile, _ := filepath.EvalSymlinks(configFile)
linkedFiles = append(linkedFiles, linkedFile)
}
cfg := Config{
GatewayPort: 8082,
PrivatePort: 8083,
MetricsPort: 9009,
LogLevel: log.DebugLevel,
PollInterval: "10s",
MaxRequestsPerQuery: 50,
MaxServiceResponseSize: 1024 * 1024,
watcher: watcher,
configFiles: configFiles,
linkedFiles: linkedFiles,
}
err = cfg.Load()
return &cfg, err
}
// ConfigurePlugins calls the Configure method on each plugin.
func (c *Config) ConfigurePlugins() []Plugin {
var enabledPlugins []Plugin
for _, pl := range c.Plugins {
p, ok := RegisteredPlugins()[pl.Name]
if !ok {
log.Warnf("plugin %q not found", pl.Name)
continue
}
err := p.Configure(c, pl.Config)
if err != nil {
log.WithError(err).Fatalf("error unmarshalling config for plugin %q: %s", pl.Name, err)
}
enabledPlugins = append(enabledPlugins, p)
}
return enabledPlugins
}
// Init initializes the config and does an initial fetch of the services.
func (c *Config) Init() error {
var err error
c.Services, err = c.buildServiceList()
if err != nil {
return fmt.Errorf("error building service list: %w", err)
}
var services []*Service
for _, s := range c.Services {
services = append(services, NewService(s))
}
queryClientOptions := []ClientOpt{WithMaxResponseSize(c.MaxServiceResponseSize), WithUserAgent(GenerateUserAgent("query"))}
if c.QueryHTTPClient != nil {
queryClientOptions = append(queryClientOptions, WithHTTPClient(c.QueryHTTPClient))
}
queryClient := NewClientWithPlugins(c.plugins, queryClientOptions...)
es := NewExecutableSchema(c.plugins, c.MaxRequestsPerQuery, queryClient, services...)
err = es.UpdateSchema(true)
if err != nil {
return err
}
c.executableSchema = es
var pluginsNames []string
for _, plugin := range c.plugins {
plugin.Init(c.executableSchema)
pluginsNames = append(pluginsNames, plugin.ID())
}
log.Infof("enabled plugins: %v", pluginsNames)
return nil
}
type arrayFlags []string
func (a *arrayFlags) String() string {
return strings.Join(*a, ",")
}
func (a *arrayFlags) Set(value string) error {
*a = append(*a, value)
return nil
}