-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathmain.go
629 lines (528 loc) · 23.9 KB
/
main.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"regexp"
"strings"
"syscall"
"time"
"github.com/golang/glog"
"github.com/nginxinc/kubernetes-ingress/internal/configs"
"github.com/nginxinc/kubernetes-ingress/internal/configs/version1"
"github.com/nginxinc/kubernetes-ingress/internal/configs/version2"
"github.com/nginxinc/kubernetes-ingress/internal/k8s"
"github.com/nginxinc/kubernetes-ingress/internal/metrics"
"github.com/nginxinc/kubernetes-ingress/internal/metrics/collectors"
"github.com/nginxinc/kubernetes-ingress/internal/nginx"
cr_validation "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/validation"
k8s_nginx "github.com/nginxinc/kubernetes-ingress/pkg/client/clientset/versioned"
conf_scheme "github.com/nginxinc/kubernetes-ingress/pkg/client/clientset/versioned/scheme"
"github.com/nginxinc/nginx-plus-go-client/client"
"github.com/prometheus/client_golang/prometheus"
api_v1 "k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
var (
// Set during build
version string
gitCommit string
healthStatus = flag.Bool("health-status", false,
`Add a location based on the value of health-status-uri to the default server. The location responds with the 200 status code for any request.
Useful for external health-checking of the Ingress controller`)
healthStatusURI = flag.String("health-status-uri", "/nginx-health",
`Sets the URI of health status location in the default server. Requires -health-status`)
proxyURL = flag.String("proxy", "",
`Use a proxy server to connect to Kubernetes API started by "kubectl proxy" command. For testing purposes only.
The Ingress controller does not start NGINX and does not write any generated NGINX configuration files to disk`)
watchNamespace = flag.String("watch-namespace", api_v1.NamespaceAll,
`Namespace to watch for Ingress resources. By default the Ingress controller watches all namespaces`)
nginxConfigMaps = flag.String("nginx-configmaps", "",
`A ConfigMap resource for customizing NGINX configuration. If a ConfigMap is set,
but the Ingress controller is not able to fetch it from Kubernetes API, the Ingress controller will fail to start.
Format: <namespace>/<name>`)
nginxPlus = flag.Bool("nginx-plus", false, "Enable support for NGINX Plus")
ingressClass = flag.String("ingress-class", "nginx",
`A class of the Ingress controller. The Ingress controller only processes Ingress resources that belong to its class
- i.e. have the annotation "kubernetes.io/ingress.class" equal to the class. Additionally,
the Ingress controller processes Ingress resources that do not have that annotation,
which can be disabled by setting the "-use-ingress-class-only" flag`)
useIngressClassOnly = flag.Bool("use-ingress-class-only", false,
`Ignore Ingress resources without the "kubernetes.io/ingress.class" annotation`)
defaultServerSecret = flag.String("default-server-tls-secret", "",
`A Secret with a TLS certificate and key for TLS termination of the default server. Format: <namespace>/<name>.
If not set, certificate and key in the file "/etc/nginx/secrets/default" are used. If a secret is set,
but the Ingress controller is not able to fetch it from Kubernetes API or a secret is not set and
the file "/etc/nginx/secrets/default" does not exist, the Ingress controller will fail to start`)
versionFlag = flag.Bool("version", false, "Print the version and git-commit hash and exit")
mainTemplatePath = flag.String("main-template-path", "",
`Path to the main NGINX configuration template. (default for NGINX "nginx.tmpl"; default for NGINX Plus "nginx-plus.tmpl")`)
ingressTemplatePath = flag.String("ingress-template-path", "",
`Path to the ingress NGINX configuration template for an ingress resource.
(default for NGINX "nginx.ingress.tmpl"; default for NGINX Plus "nginx-plus.ingress.tmpl")`)
virtualServerTemplatePath = flag.String("virtualserver-template-path", "",
`Path to the VirtualServer NGINX configuration template for a VirtualServer resource.
(default for NGINX "nginx.virtualserver.tmpl"; default for NGINX Plus "nginx-plus.virtualserver.tmpl")`)
transportServerTemplatePath = flag.String("transportserver-template-path", "",
`Path to the TransportServer NGINX configuration template for a TransportServer resource.
(default for NGINX "nginx.transportserver.tmpl"; default for NGINX Plus "nginx-plus.transportserver.tmpl")`)
externalService = flag.String("external-service", "",
`Specifies the name of the service with the type LoadBalancer through which the Ingress controller pods are exposed externally.
The external address of the service is used when reporting the status of Ingress, VirtualServer and VirtualServerRoute resources. For Ingress resources only: Requires -report-ingress-status.`)
reportIngressStatus = flag.Bool("report-ingress-status", false,
"Update the address field in the status of Ingresses resources. Requires the -external-service flag, or the 'external-status-address' key in the ConfigMap.")
leaderElectionEnabled = flag.Bool("enable-leader-election", false,
"Enable Leader election to avoid multiple replicas of the controller reporting the status of Ingress, VirtualServer and VirtualServerRoute resources -- only one replica will report status. See -report-ingress-status flag.")
leaderElectionLockName = flag.String("leader-election-lock-name", "nginx-ingress-leader-election",
`Specifies the name of the ConfigMap, within the same namespace as the controller, used as the lock for leader election. Requires -enable-leader-election.`)
nginxStatusAllowCIDRs = flag.String("nginx-status-allow-cidrs", "127.0.0.1", `Whitelist IPv4 IP/CIDR blocks to allow access to NGINX stub_status or the NGINX Plus API. Separate multiple IP/CIDR by commas.`)
nginxStatusPort = flag.Int("nginx-status-port", 8080,
"Set the port where the NGINX stub_status or the NGINX Plus API is exposed. [1023 - 65535]")
nginxStatus = flag.Bool("nginx-status", true,
"Enable the NGINX stub_status, or the NGINX Plus API.")
nginxDebug = flag.Bool("nginx-debug", false,
"Enable debugging for NGINX. Uses the nginx-debug binary. Requires 'error-log-level: debug' in the ConfigMap.")
wildcardTLSSecret = flag.String("wildcard-tls-secret", "",
`A Secret with a TLS certificate and key for TLS termination of every Ingress host for which TLS termination is enabled but the Secret is not specified.
Format: <namespace>/<name>. If the argument is not set, for such Ingress hosts NGINX will break any attempt to establish a TLS connection.
If the argument is set, but the Ingress controller is not able to fetch the Secret from Kubernetes API, the Ingress controller will fail to start.`)
enablePrometheusMetrics = flag.Bool("enable-prometheus-metrics", false,
"Enable exposing NGINX or NGINX Plus metrics in the Prometheus format")
prometheusMetricsListenPort = flag.Int("prometheus-metrics-listen-port", 9113,
"Set the port where the Prometheus metrics are exposed. [1023 - 65535]")
enableCustomResources = flag.Bool("enable-custom-resources", true,
"Enable custom resources")
globalConfiguration = flag.String("global-configuration", "",
`A GlobalConfiguration resource for global configuration of the Ingress Controller. Requires -enable-custom-resources. If the flag is set,
but the Ingress controller is not able to fetch the corresponding resource from Kubernetes API, the Ingress Controller
will fail to start. Format: <namespace>/<name>`)
enableTLSPassthrough = flag.Bool("enable-tls-passthrough", false,
"Enable TLS Passthrough on port 443. Requires -enable-custom-resources")
spireAgentAddress = flag.String("spire-agent-address", "",
`Specifies the address of the running Spire agent. For use with NGINX Service Mesh only. If the flag is set,
but the Ingress Controller is not able to connect with the Spire Agent, the Ingress Controller will fail to start.`)
)
func main() {
flag.Parse()
err := flag.Lookup("logtostderr").Value.Set("true")
if err != nil {
glog.Fatalf("Error setting logtostderr to true: %v", err)
}
if *versionFlag {
fmt.Printf("Version=%v GitCommit=%v\n", version, gitCommit)
os.Exit(0)
}
healthStatusURIValidationError := validateLocation(*healthStatusURI)
if healthStatusURIValidationError != nil {
glog.Fatalf("Invalid value for health-status-uri: %v", healthStatusURIValidationError)
}
statusLockNameValidationError := validateResourceName(*leaderElectionLockName)
if statusLockNameValidationError != nil {
glog.Fatalf("Invalid value for leader-election-lock-name: %v", statusLockNameValidationError)
}
statusPortValidationError := validatePort(*nginxStatusPort)
if statusPortValidationError != nil {
glog.Fatalf("Invalid value for nginx-status-port: %v", statusPortValidationError)
}
metricsPortValidationError := validatePort(*prometheusMetricsListenPort)
if metricsPortValidationError != nil {
glog.Fatalf("Invalid value for prometheus-metrics-listen-port: %v", metricsPortValidationError)
}
allowedCIDRs, err := parseNginxStatusAllowCIDRs(*nginxStatusAllowCIDRs)
if err != nil {
glog.Fatalf(`Invalid value for nginx-status-allow-cidrs: %v`, err)
}
if *enableTLSPassthrough && !*enableCustomResources {
glog.Fatalf("enable-tls-passthrough flag requires -enable-custom-resources")
}
glog.Infof("Starting NGINX Ingress controller Version=%v GitCommit=%v\n", version, gitCommit)
var config *rest.Config
if *proxyURL != "" {
config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{},
&clientcmd.ConfigOverrides{
ClusterInfo: clientcmdapi.Cluster{
Server: *proxyURL,
},
}).ClientConfig()
if err != nil {
glog.Fatalf("error creating client configuration: %v", err)
}
} else {
if config, err = rest.InClusterConfig(); err != nil {
glog.Fatalf("error creating client configuration: %v", err)
}
}
kubeClient, err := kubernetes.NewForConfig(config)
if err != nil {
glog.Fatalf("Failed to create client: %v.", err)
}
var confClient k8s_nginx.Interface
if *enableCustomResources {
confClient, err = k8s_nginx.NewForConfig(config)
if err != nil {
glog.Fatalf("Failed to create a conf client: %v", err)
}
// required for emitting Events for VirtualServer
err = conf_scheme.AddToScheme(scheme.Scheme)
if err != nil {
glog.Fatalf("Failed to add configuration types to the scheme: %v", err)
}
}
nginxConfTemplatePath := "nginx.tmpl"
nginxIngressTemplatePath := "nginx.ingress.tmpl"
nginxVirtualServerTemplatePath := "nginx.virtualserver.tmpl"
nginxTransportServerTemplatePath := "nginx.transportserver.tmpl"
if *nginxPlus {
nginxConfTemplatePath = "nginx-plus.tmpl"
nginxIngressTemplatePath = "nginx-plus.ingress.tmpl"
nginxVirtualServerTemplatePath = "nginx-plus.virtualserver.tmpl"
nginxTransportServerTemplatePath = "nginx-plus.transportserver.tmpl"
}
if *mainTemplatePath != "" {
nginxConfTemplatePath = *mainTemplatePath
}
if *ingressTemplatePath != "" {
nginxIngressTemplatePath = *ingressTemplatePath
}
if *virtualServerTemplatePath != "" {
nginxVirtualServerTemplatePath = *virtualServerTemplatePath
}
if *transportServerTemplatePath != "" {
nginxTransportServerTemplatePath = *transportServerTemplatePath
}
nginxBinaryPath := "/usr/sbin/nginx"
if *nginxDebug {
nginxBinaryPath = "/usr/sbin/nginx-debug"
}
templateExecutor, err := version1.NewTemplateExecutor(nginxConfTemplatePath, nginxIngressTemplatePath)
if err != nil {
glog.Fatalf("Error creating TemplateExecutor: %v", err)
}
templateExecutorV2, err := version2.NewTemplateExecutor(nginxVirtualServerTemplatePath, nginxTransportServerTemplatePath)
if err != nil {
glog.Fatalf("Error creating TemplateExecutorV2: %v", err)
}
var registry *prometheus.Registry
var managerCollector collectors.ManagerCollector
var controllerCollector collectors.ControllerCollector
constLabels := map[string]string{"class": *ingressClass}
managerCollector = collectors.NewManagerFakeCollector()
controllerCollector = collectors.NewControllerFakeCollector()
if *enablePrometheusMetrics {
registry = prometheus.NewRegistry()
managerCollector = collectors.NewLocalManagerMetricsCollector(constLabels)
controllerCollector = collectors.NewControllerMetricsCollector(*enableCustomResources, constLabels)
err = managerCollector.Register(registry)
if err != nil {
glog.Errorf("Error registering Manager Prometheus metrics: %v", err)
}
err = controllerCollector.Register(registry)
if err != nil {
glog.Errorf("Error registering Controller Prometheus metrics: %v", err)
}
}
useFakeNginxManager := *proxyURL != ""
var nginxManager nginx.Manager
if useFakeNginxManager {
nginxManager = nginx.NewFakeManager("/etc/nginx")
} else {
nginxManager = nginx.NewLocalManager("/etc/nginx/", nginxBinaryPath, managerCollector)
}
if *defaultServerSecret != "" {
secret, err := getAndValidateSecret(kubeClient, *defaultServerSecret)
if err != nil {
glog.Fatalf("Error trying to get the default server TLS secret %v: %v", *defaultServerSecret, err)
}
bytes := configs.GenerateCertAndKeyFileContent(secret)
nginxManager.CreateSecret(configs.DefaultServerSecretName, bytes, nginx.TLSSecretFileMode)
} else {
_, err = os.Stat("/etc/nginx/secrets/default")
if os.IsNotExist(err) {
glog.Fatalf("A TLS cert and key for the default server is not found")
}
}
if *wildcardTLSSecret != "" {
secret, err := getAndValidateSecret(kubeClient, *wildcardTLSSecret)
if err != nil {
glog.Fatalf("Error trying to get the wildcard TLS secret %v: %v", *wildcardTLSSecret, err)
}
bytes := configs.GenerateCertAndKeyFileContent(secret)
nginxManager.CreateSecret(configs.WildcardSecretName, bytes, nginx.TLSSecretFileMode)
}
globalConfigurationValidator := createGlobalConfigurationValidator()
globalCfgParams := configs.NewDefaultGlobalConfigParams()
if *enableTLSPassthrough {
globalCfgParams = configs.NewGlobalConfigParamsWithTLSPassthrough()
}
if *globalConfiguration != "" {
ns, name, err := k8s.ParseNamespaceName(*globalConfiguration)
if err != nil {
glog.Fatalf("Error parsing the global-configuration argument: %v", err)
}
if !*enableCustomResources {
glog.Fatal("global-configuration flag requires -enable-custom-resources")
}
gc, err := confClient.K8sV1alpha1().GlobalConfigurations(ns).Get(context.TODO(), name, meta_v1.GetOptions{})
if err != nil {
glog.Fatalf("Error when getting %s: %v", *globalConfiguration, err)
}
err = globalConfigurationValidator.ValidateGlobalConfiguration(gc)
if err != nil {
glog.Fatalf("GlobalConfiguration %s is invalid: %v", *globalConfiguration, err)
}
globalCfgParams = configs.ParseGlobalConfiguration(gc, *enableTLSPassthrough)
}
cfgParams := configs.NewDefaultConfigParams()
if *nginxConfigMaps != "" {
ns, name, err := k8s.ParseNamespaceName(*nginxConfigMaps)
if err != nil {
glog.Fatalf("Error parsing the nginx-configmaps argument: %v", err)
}
cfm, err := kubeClient.CoreV1().ConfigMaps(ns).Get(context.TODO(), name, meta_v1.GetOptions{})
if err != nil {
glog.Fatalf("Error when getting %v: %v", *nginxConfigMaps, err)
}
cfgParams = configs.ParseConfigMap(cfm, *nginxPlus)
if cfgParams.MainServerSSLDHParamFileContent != nil {
fileName, err := nginxManager.CreateDHParam(*cfgParams.MainServerSSLDHParamFileContent)
if err != nil {
glog.Fatalf("Configmap %s/%s: Could not update dhparams: %v", ns, name, err)
} else {
cfgParams.MainServerSSLDHParam = fileName
}
}
if cfgParams.MainTemplate != nil {
err = templateExecutor.UpdateMainTemplate(cfgParams.MainTemplate)
if err != nil {
glog.Fatalf("Error updating NGINX main template: %v", err)
}
}
if cfgParams.IngressTemplate != nil {
err = templateExecutor.UpdateIngressTemplate(cfgParams.IngressTemplate)
if err != nil {
glog.Fatalf("Error updating ingress template: %v", err)
}
}
}
staticCfgParams := &configs.StaticConfigParams{
HealthStatus: *healthStatus,
HealthStatusURI: *healthStatusURI,
NginxStatus: *nginxStatus,
NginxStatusAllowCIDRs: allowedCIDRs,
NginxStatusPort: *nginxStatusPort,
StubStatusOverUnixSocketForOSS: *enablePrometheusMetrics,
TLSPassthrough: *enableTLSPassthrough,
SpiffeCerts: *spireAgentAddress != "",
}
ngxConfig := configs.GenerateNginxMainConfig(staticCfgParams, cfgParams)
content, err := templateExecutor.ExecuteMainConfigTemplate(ngxConfig)
if err != nil {
glog.Fatalf("Error generating NGINX main config: %v", err)
}
nginxManager.CreateMainConfig(content)
nginxManager.UpdateConfigVersionFile(ngxConfig.OpenTracingLoadModule)
nginxManager.SetOpenTracing(ngxConfig.OpenTracingLoadModule)
if ngxConfig.OpenTracingLoadModule {
err := nginxManager.CreateOpenTracingTracerConfig(cfgParams.MainOpenTracingTracerConfig)
if err != nil {
glog.Fatalf("Error creating OpenTracing tracer config file: %v", err)
}
}
if *enableTLSPassthrough {
var emptyFile []byte
nginxManager.CreateTLSPassthroughHostsConfig(emptyFile)
}
nginxDone := make(chan error, 1)
nginxManager.Start(nginxDone)
var plusClient *client.NginxClient
if *nginxPlus && !useFakeNginxManager {
httpClient := getSocketClient("/var/lib/nginx/nginx-plus-api.sock")
plusClient, err = client.NewNginxClient(httpClient, "http://nginx-plus-api/api")
if err != nil {
glog.Fatalf("Failed to create NginxClient for Plus: %v", err)
}
nginxManager.SetPlusClients(plusClient, httpClient)
}
if *enablePrometheusMetrics {
if *nginxPlus {
go metrics.RunPrometheusListenerForNginxPlus(*prometheusMetricsListenPort, plusClient, registry, constLabels)
} else {
httpClient := getSocketClient("/var/lib/nginx/nginx-status.sock")
client, err := metrics.NewNginxMetricsClient(httpClient)
if err != nil {
glog.Fatalf("Error creating the Nginx client for Prometheus metrics: %v", err)
}
go metrics.RunPrometheusListenerForNginx(*prometheusMetricsListenPort, client, registry, constLabels)
}
}
isWildcardEnabled := *wildcardTLSSecret != ""
cnf := configs.NewConfigurator(nginxManager, staticCfgParams, cfgParams, globalCfgParams, templateExecutor, templateExecutorV2, *nginxPlus, isWildcardEnabled)
controllerNamespace := os.Getenv("POD_NAMESPACE")
transportServerValidator := cr_validation.NewTransportServerValidator(*enableTLSPassthrough)
lbcInput := k8s.NewLoadBalancerControllerInput{
KubeClient: kubeClient,
ConfClient: confClient,
ResyncPeriod: 30 * time.Second,
Namespace: *watchNamespace,
NginxConfigurator: cnf,
DefaultServerSecret: *defaultServerSecret,
IsNginxPlus: *nginxPlus,
IngressClass: *ingressClass,
UseIngressClassOnly: *useIngressClassOnly,
ExternalServiceName: *externalService,
ControllerNamespace: controllerNamespace,
ReportIngressStatus: *reportIngressStatus,
IsLeaderElectionEnabled: *leaderElectionEnabled,
LeaderElectionLockName: *leaderElectionLockName,
WildcardTLSSecret: *wildcardTLSSecret,
ConfigMaps: *nginxConfigMaps,
GlobalConfiguration: *globalConfiguration,
AreCustomResourcesEnabled: *enableCustomResources,
MetricsCollector: controllerCollector,
GlobalConfigurationValidator: globalConfigurationValidator,
TransportServerValidator: transportServerValidator,
SpireAgentAddress: *spireAgentAddress,
}
lbc := k8s.NewLoadBalancerController(lbcInput)
go handleTermination(lbc, nginxManager, nginxDone)
lbc.Run()
for {
glog.Info("Waiting for the controller to exit...")
time.Sleep(30 * time.Second)
}
}
func createGlobalConfigurationValidator() *cr_validation.GlobalConfigurationValidator {
forbiddenListenerPorts := map[int]bool{
80: true,
443: true,
}
if *nginxStatus {
forbiddenListenerPorts[*nginxStatusPort] = true
}
if *enablePrometheusMetrics {
forbiddenListenerPorts[*prometheusMetricsListenPort] = true
}
return cr_validation.NewGlobalConfigurationValidator(forbiddenListenerPorts)
}
func handleTermination(lbc *k8s.LoadBalancerController, nginxManager nginx.Manager, nginxDone chan error) {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM)
exitStatus := 0
exited := false
select {
case err := <-nginxDone:
if err != nil {
glog.Errorf("nginx command exited with an error: %v", err)
exitStatus = 1
} else {
glog.Info("nginx command exited successfully")
}
exited = true
case <-signalChan:
glog.Infof("Received SIGTERM, shutting down")
}
glog.Infof("Shutting down the controller")
lbc.Stop()
if !exited {
glog.Infof("Shutting down NGINX")
nginxManager.Quit()
<-nginxDone
}
glog.Infof("Exiting with a status: %v", exitStatus)
os.Exit(exitStatus)
}
// getSocketClient gets an http.Client with the a unix socket transport.
func getSocketClient(sockPath string) *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", sockPath)
},
},
}
}
// validateResourceName validates the name of a resource
func validateResourceName(lock string) error {
allErrs := validation.IsDNS1123Subdomain(lock)
if len(allErrs) > 0 {
return fmt.Errorf("invalid resource name %v: %v", lock, allErrs)
}
return nil
}
// validatePort makes sure a given port is inside the valid port range for its usage
func validatePort(port int) error {
if port < 1023 || port > 65535 {
return fmt.Errorf("port outside of valid port range [1023 - 65535]: %v", port)
}
return nil
}
// parseNginxStatusAllowCIDRs converts a comma separated CIDR/IP address string into an array of CIDR/IP addresses.
// It returns an array of the valid CIDR/IP addresses or an error if given an invalid address.
func parseNginxStatusAllowCIDRs(input string) (cidrs []string, err error) {
cidrsArray := strings.Split(input, ",")
for _, cidr := range cidrsArray {
trimmedCidr := strings.TrimSpace(cidr)
err := validateCIDRorIP(trimmedCidr)
if err != nil {
return cidrs, err
}
cidrs = append(cidrs, trimmedCidr)
}
return cidrs, nil
}
// validateCIDRorIP makes sure a given string is either a valid CIDR block or IP address.
// It an error if it is not valid.
func validateCIDRorIP(cidr string) error {
if cidr == "" {
return fmt.Errorf("invalid CIDR address: an empty string is an invalid CIDR block or IP address")
}
_, _, err := net.ParseCIDR(cidr)
if err == nil {
return nil
}
ip := net.ParseIP(cidr)
if ip == nil {
return fmt.Errorf("invalid IP address: %v", cidr)
}
return nil
}
// getAndValidateSecret gets and validates a secret.
func getAndValidateSecret(kubeClient *kubernetes.Clientset, secretNsName string) (secret *api_v1.Secret, err error) {
ns, name, err := k8s.ParseNamespaceName(secretNsName)
if err != nil {
return nil, fmt.Errorf("could not parse the %v argument: %v", secretNsName, err)
}
secret, err = kubeClient.CoreV1().Secrets(ns).Get(context.TODO(), name, meta_v1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("could not get %v: %v", secretNsName, err)
}
err = k8s.ValidateTLSSecret(secret)
if err != nil {
return nil, fmt.Errorf("%v is invalid: %v", secretNsName, err)
}
return secret, nil
}
const locationFmt = `/[^\s{};]*`
const locationErrMsg = "must start with / and must not include any whitespace character, `{`, `}` or `;`"
var locationRegexp = regexp.MustCompile("^" + locationFmt + "$")
func validateLocation(location string) error {
if location == "" || location == "/" {
return fmt.Errorf("invalid location format: '%v' is an invalid location", location)
}
if !locationRegexp.MatchString(location) {
msg := validation.RegexError(locationErrMsg, locationFmt, "/path", "/path/subpath-123")
return fmt.Errorf("invalid location format: %v", msg)
}
return nil
}