-
Notifications
You must be signed in to change notification settings - Fork 22
/
config.go
498 lines (414 loc) · 12.9 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package config
import (
"encoding/json"
"fmt"
"net/url"
"os"
"strconv"
"time"
"code.cloudfoundry.org/multierror"
)
type MessageBusServerSchema struct {
Host string `json:"host"`
User string `json:"user"`
Password string `json:"password"`
}
type RoutingAPISchema struct {
APIURL string `json:"api_url"`
OAuthURL string `json:"oauth_url"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
CACerts string `json:"ca_certs"`
SkipSSLValidation bool `json:"skip_ssl_validation"`
ClientCertificatePath string `json:"client_cert_path"`
ClientPrivateKeyPath string `json:"client_private_key_path"`
ServerCACertificatePath string `json:"server_ca_cert_path"`
MaxTTL string `json:"max_ttl,omitempty"`
}
type HealthCheckSchema struct {
Name string `json:"name"`
ScriptPath string `json:"script_path"`
Timeout string `json:"timeout"`
}
type ConfigSchema struct {
MessageBusServers []MessageBusServerSchema `json:"message_bus_servers"`
RoutingAPI RoutingAPISchema `json:"routing_api"`
Routes []RouteSchema `json:"routes"`
NATSmTLSConfig ClientTLSConfigSchema `json:"nats_mtls_config"`
Host string `json:"host"`
AvailabilityZone string `json:"availability_zone"`
UnregistrationMessageLimit *int `json:"unregistration_message_limit,omitempty"`
}
type RouteSchema struct {
Type string `json:"type"`
Name string `json:"name"`
Port *int `json:"port"`
Protocol string `json:"protocol"`
SniPort *int `json:"sni_port"`
TLSPort *int `json:"tls_port"`
Tags map[string]string `json:"tags"`
URIs []string `json:"uris"`
RouterGroup string `json:"router_group"`
ExternalPort *int `json:"external_port,omitempty"`
RouteServiceUrl string `json:"route_service_url"`
RegistrationInterval string `json:"registration_interval,omitempty"`
HealthCheck *HealthCheckSchema `json:"health_check,omitempty"`
ServerCertDomainSAN string `json:"server_cert_domain_san,omitempty"`
SniRoutableSan string `json:"sni_routable_san,omitempty"`
Options *Options `json:"options,omitempty"`
}
type Options struct {
LoadBalancingAlgorithm LoadBalancingAlgorithm `json:"lb_algo,omitempty"`
}
type LoadBalancingAlgorithm string
var supportedLoadBalancingAlgorithms = []LoadBalancingAlgorithm{RoundRobin, LeastConns}
const (
RoundRobin LoadBalancingAlgorithm = "round-robin"
LeastConns LoadBalancingAlgorithm = "least-connection"
)
type ClientTLSConfigSchema struct {
Enabled bool `json:"enabled"`
CertPath string `json:"cert_path"`
KeyPath string `json:"key_path"`
CAPath string `json:"ca_path"`
}
type MessageBusServer struct {
Host string
User string
Password string
}
type RoutingAPI struct {
APIURL string
OAuthURL string
ClientID string
ClientSecret string
CACerts string
SkipSSLValidation bool
ClientCertificatePath string
ClientPrivateKeyPath string
ServerCACertificatePath string
MaxTTL time.Duration
}
type HealthCheck struct {
Name string
ScriptPath string
Timeout time.Duration
}
type Config struct {
MessageBusServers []MessageBusServer
RoutingAPI RoutingAPI
Routes []Route
NATSmTLSConfig ClientTLSConfig
Host string
AvailabilityZone string `json:"availability_zone"`
UnregistrationMessageLimit int
}
type ClientTLSConfig struct {
Enabled bool
CertPath string
KeyPath string
CAPath string
}
type Route struct {
Type string
Name string
Port *int
Protocol string
TLSPort *int
Tags map[string]string
URIs []string
RouterGroup string
Host string
ExternalPort *int
RouteServiceUrl string
RegistrationInterval time.Duration
HealthCheck *HealthCheck
ServerCertDomainSAN string
Options *Options
}
func NewConfigSchemaFromFile(configFile string) (ConfigSchema, error) {
var config ConfigSchema
c, err := os.ReadFile(configFile)
if err != nil {
return ConfigSchema{}, err
}
err = json.Unmarshal(c, &config)
if err != nil {
return ConfigSchema{}, err
}
return config, nil
}
func (c ConfigSchema) ParseSchemaAndSetDefaultsToConfig() (*Config, error) {
errors := multierror.NewMultiError("config")
if c.UnregistrationMessageLimit == nil {
defaultUnregistrationLimit := 5
c.UnregistrationMessageLimit = &defaultUnregistrationLimit
}
if *c.UnregistrationMessageLimit <= 0 {
errors.Add(fmt.Errorf("unregistration_message_limit must be a positive integer"))
}
if c.Host == "" {
errors.Add(fmt.Errorf("host required"))
}
tcp_routes := 0
routes := []Route{}
for index, r := range c.Routes {
route, err := routeFromSchema(r, index)
if err != nil {
errors.Add(err)
continue
}
if route.Type == "tcp" {
tcp_routes++
route.Host = c.Host
}
routes = append(routes, *route)
}
messageBusServers, err := messageBusServersFromSchema(c.MessageBusServers)
if err != nil && (len(routes)-tcp_routes > 0) {
errors.Add(err)
}
routingAPI, err := routingAPIFromSchema(c.RoutingAPI)
if err != nil && tcp_routes > 0 {
errors.Add(err)
}
if errors.Length() > 0 {
return nil, errors
}
natsTLSConfig := clientTLSConfigFromSchema(c.NATSmTLSConfig)
config := Config{
Host: c.Host,
AvailabilityZone: c.AvailabilityZone,
UnregistrationMessageLimit: *c.UnregistrationMessageLimit,
MessageBusServers: messageBusServers,
Routes: routes,
NATSmTLSConfig: natsTLSConfig,
}
if routingAPI != nil {
config.RoutingAPI = *routingAPI
}
return &config, nil
}
func nameOrIndex(r RouteSchema, index int) string {
if r.Name != "" {
return fmt.Sprintf(`"%s"`, r.Name)
}
return strconv.Itoa(index)
}
func parseRegistrationInterval(registrationInterval string) (time.Duration, error) {
var duration time.Duration
if registrationInterval == "" {
return duration, fmt.Errorf("no registration_interval")
}
var err error
duration, err = time.ParseDuration(registrationInterval)
if err != nil {
return duration, fmt.Errorf("invalid registration_interval: %s", err.Error())
}
if duration <= 0 {
return duration, fmt.Errorf("invalid registration_interval: interval must be greater than 0")
}
return duration, nil
}
func routeFromSchema(r RouteSchema, index int) (*Route, error) {
errors := multierror.NewMultiError(fmt.Sprintf("route %s", nameOrIndex(r, index)))
if r.Type != "tcp" && r.Type != "sni" && r.Name == "" {
errors.Add(fmt.Errorf("no name"))
}
if r.Port == nil && r.TLSPort == nil && r.SniPort == nil {
errors.Add(fmt.Errorf("no port"))
}
if r.Port != nil && *r.Port <= 0 {
errors.Add(fmt.Errorf("invalid port: %d", *r.Port))
}
if r.TLSPort != nil && *r.TLSPort <= 0 {
errors.Add(fmt.Errorf("invalid tls_port: %d", *r.TLSPort))
}
if r.Type != "tcp" && r.Type != "sni" {
if len(r.URIs) == 0 {
errors.Add(fmt.Errorf("no URIs"))
}
for _, u := range r.URIs {
if u == "" {
errors.Add(fmt.Errorf("empty URIs"))
break
}
}
_, err := url.Parse(r.RouteServiceUrl)
if err != nil {
errors.Add(err)
}
} else {
if r.RouterGroup == "" {
errors.Add(fmt.Errorf("missing router_group"))
}
if r.ExternalPort != nil && *r.ExternalPort <= 0 {
errors.Add(fmt.Errorf("invalid port: %d", *r.ExternalPort))
}
}
if r.Protocol != "" && r.Protocol != "http1" && r.Protocol != "http2" {
errors.Add(fmt.Errorf("unknown protocol: %s", r.Protocol))
}
if r.Options != nil {
if r.Options.LoadBalancingAlgorithm != "" {
err := validatePerRouteLoadBalancingAlgorithm(r.Options.LoadBalancingAlgorithm)
if err != nil {
errors.Add(err)
}
}
}
registrationInterval, err := parseRegistrationInterval(r.RegistrationInterval)
if err != nil {
errors.Add(err)
}
var healthCheck *HealthCheck
if r.HealthCheck != nil {
healthCheck, err = healthCheckFromSchema(r.HealthCheck, registrationInterval)
if err != nil {
errors.Add(err)
}
}
if errors.Length() > 0 {
return nil, errors
}
route := Route{
Type: r.Type,
Name: r.Name,
Port: r.Port,
Protocol: r.Protocol,
TLSPort: r.TLSPort,
Tags: r.Tags,
URIs: r.URIs,
RouterGroup: r.RouterGroup,
ExternalPort: r.ExternalPort,
RouteServiceUrl: r.RouteServiceUrl,
ServerCertDomainSAN: r.ServerCertDomainSAN,
RegistrationInterval: registrationInterval,
HealthCheck: healthCheck,
Options: r.Options,
}
if r.Type == "sni" {
route.Port = r.SniPort
route.ServerCertDomainSAN = r.SniRoutableSan
route.Type = "tcp"
}
return &route, nil
}
func validatePerRouteLoadBalancingAlgorithm(loadBalancingAlgo LoadBalancingAlgorithm) error {
for _, lbAlgo := range supportedLoadBalancingAlgorithms {
if loadBalancingAlgo == lbAlgo {
return nil
}
}
return fmt.Errorf("unknown load balancing algorithm: %s. Allowed values: %s", loadBalancingAlgo, supportedLoadBalancingAlgorithms)
}
func healthCheckFromSchema(
healthCheckSchema *HealthCheckSchema,
registrationInterval time.Duration,
) (*HealthCheck, error) {
errors := multierror.NewMultiError("healthcheck")
healthCheck := &HealthCheck{
Name: healthCheckSchema.Name,
ScriptPath: healthCheckSchema.ScriptPath,
}
if healthCheck.Name == "" {
errors.Add(fmt.Errorf("no name"))
}
if healthCheck.ScriptPath == "" {
errors.Add(fmt.Errorf("no script_path"))
}
if healthCheckSchema.Timeout == "" && registrationInterval > 0 {
if errors.Length() > 0 {
return nil, errors
}
healthCheck.Timeout = registrationInterval / 2
return healthCheck, nil
}
var err error
healthCheck.Timeout, err = time.ParseDuration(healthCheckSchema.Timeout)
if err != nil {
errors.Add(fmt.Errorf("invalid healthcheck timeout: %s", err.Error()))
return nil, errors
}
if healthCheck.Timeout <= 0 {
errors.Add(fmt.Errorf("invalid healthcheck timeout: %s", healthCheck.Timeout))
return nil, errors
}
if healthCheck.Timeout >= registrationInterval && registrationInterval > 0 {
errors.Add(fmt.Errorf(
"invalid healthcheck timeout: %v must be less than the registration interval: %v",
healthCheck.Timeout,
registrationInterval,
))
return nil, errors
}
if errors.Length() > 0 {
return nil, errors
}
return healthCheck, nil
}
func messageBusServersFromSchema(servers []MessageBusServerSchema) ([]MessageBusServer, error) {
messageBusServers := []MessageBusServer{}
if len(servers) < 1 {
return nil, fmt.Errorf("message_bus_servers must have at least one entry")
}
for _, m := range servers {
messageBusServers = append(
messageBusServers,
MessageBusServer(m),
)
}
return messageBusServers, nil
}
func parseMaxTTL(max_ttl string) time.Duration {
ttl, _ := time.ParseDuration(max_ttl)
if ttl <= 0 {
ttl = 2 * time.Minute
}
return ttl
}
func routingAPIFromSchema(api RoutingAPISchema) (*RoutingAPI, error) {
if api.APIURL == "" {
return nil, fmt.Errorf("routing_api must have an api_url")
}
apiURL, err := url.Parse(api.APIURL)
if err != nil {
return nil, fmt.Errorf("routing_api must a vaid URL")
}
if api.OAuthURL == "" {
return nil, fmt.Errorf("routing_api must have an oauth_url")
}
if api.ClientID == "" {
return nil, fmt.Errorf("routing_api must have a client_id")
}
if api.ClientSecret == "" {
return nil, fmt.Errorf("routing_api must have a client_secret")
}
if apiURL.Scheme == "https" {
if api.ClientCertificatePath == "" {
return nil, fmt.Errorf("routing_api must have a client_certificate_path")
}
if api.ClientPrivateKeyPath == "" {
return nil, fmt.Errorf("routing_api must have a client_private_key_path")
}
if api.ServerCACertificatePath == "" {
return nil, fmt.Errorf("routing_api must have a server_ca_cert_path")
}
}
maxTTL := parseMaxTTL(api.MaxTTL)
return &RoutingAPI{
APIURL: api.APIURL,
OAuthURL: api.OAuthURL,
ClientID: api.ClientID,
ClientSecret: api.ClientSecret,
CACerts: api.CACerts,
SkipSSLValidation: api.SkipSSLValidation,
ClientCertificatePath: api.ClientCertificatePath,
ClientPrivateKeyPath: api.ClientPrivateKeyPath,
ServerCACertificatePath: api.ServerCACertificatePath,
MaxTTL: maxTTL,
}, nil
}
func clientTLSConfigFromSchema(clientTLSConfigSchema ClientTLSConfigSchema) ClientTLSConfig {
return ClientTLSConfig(clientTLSConfigSchema)
}