-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathmain.go
843 lines (704 loc) · 32.5 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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
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/k8s/secrets"
"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"
nginxCollector "github.com/nginxinc/nginx-prometheus-exporter/collector"
"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"
util_version "k8s.io/apimachinery/pkg/util/version"
"k8s.io/client-go/dynamic"
"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")
appProtect = flag.Bool("enable-app-protect", false, "Enable support for NGINX App Protect. Requires -nginx-plus.")
ingressClass = flag.String("ingress-class", "nginx",
`A class of the Ingress controller.
For Kubernetes >= 1.18, a corresponding IngressClass resource with the name equal to the class must be deployed. Otherwise,
the Ingress Controller will fail to start.
The Ingress controller only processes resources that belong to its class - i.e. have the "ingressClassName" field resource equal to the class.
For Kubernetes < 1.18, the Ingress Controller only processes resources that belong to its class
- i.e have the annotation "kubernetes.io/ingress.class" equal to the class.
Additionally, the Ingress Controller processes resources that do not have the class set,
which can be disabled by setting the "-use-ingress-class-only" flag
The Ingress Controller processes all the VirtualServer/VirtualServerRoute resources that do not have the "ingressClassName" field for all versions of kubernetes.`)
useIngressClassOnly = flag.Bool("use-ingress-class-only", false,
`For kubernetes versions >= 1.18 this flag will be IGNORED.
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", true,
"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 (default true). 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. [1024 - 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.")
nginxReloadTimeout = flag.Int("nginx-reload-timeout", 0,
`The timeout in milliseconds which the Ingress Controller will wait for a successful NGINX reload after a change or at the initial start.
The default is 4000 (or 20000 if -enable-app-protect is true). If set to 0, the default value will be used`)
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. [1024 - 65535]")
enableCustomResources = flag.Bool("enable-custom-resources", true,
"Enable custom resources")
enableSnippets = flag.Bool("enable-snippets", false,
"Enable custom NGINX configuration snippets in VirtualServer and VirtualServerRoute 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. Requires -nginx-plus and is 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.`)
enableInternalRoutes = flag.Bool("enable-internal-routes", false,
`Enable support for internal routes with NGINX Service Mesh. Requires -spire-agent-address and -nginx-plus. Is for use with NGINX Service Mesh only.`)
readyStatus = flag.Bool("ready-status", true, "Enables the readiness endpoint '/nginx-ready'. The endpoint returns a success code when NGINX has loaded all the config after the startup")
readyStatusPort = flag.Int("ready-status-port", 8081, "Set the port where the readiness endpoint is exposed. [1024 - 65535]")
enableLatencyMetrics = flag.Bool("enable-latency-metrics", false,
"Enable collection of latency metrics for upstreams. Requires -enable-prometheus-metrics")
)
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)
}
readyStatusPortValidationError := validatePort(*readyStatusPort)
if readyStatusPortValidationError != nil {
glog.Fatalf("Invalid value for ready-status-port: %v", readyStatusPortValidationError)
}
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")
}
if *appProtect && !*nginxPlus {
glog.Fatal("NGINX App Protect support is for NGINX Plus only")
}
if *spireAgentAddress != "" && !*nginxPlus {
glog.Fatal("spire-agent-address support is for NGINX Plus only")
}
if *enableInternalRoutes && *spireAgentAddress == "" {
glog.Fatal("enable-internal-routes flag requires spire-agent-address")
}
if *enableLatencyMetrics && !*enablePrometheusMetrics {
glog.Warning("enable-latency-metrics flag requires enable-prometheus-metrics, latency metrics will not be collected")
*enableLatencyMetrics = false
}
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)
}
k8sVersion, err := k8s.GetK8sVersion(kubeClient)
if err != nil {
glog.Fatalf("error retrieving k8s version: %v", err)
}
minK8sVersion := minVersion("1.14.0")
if !k8sVersion.AtLeast(minK8sVersion) {
glog.Fatalf("Versions of Kubernetes < %v are not supported, please refer to the documentation for details on supported versions.", minK8sVersion)
}
// Ingress V1 is only available from k8s > 1.18
ingressV1Version := minVersion("1.18.0")
if k8sVersion.AtLeast(ingressV1Version) {
*useIngressClassOnly = true
glog.Warningln("The '-use-ingress-class-only' flag will be deprecated and has no effect on versions of kubernetes >= 1.18.0. Processing ONLY resources that have the 'ingressClassName' field in Ingress equal to the class.")
ingressClassRes, err := kubeClient.NetworkingV1beta1().IngressClasses().Get(context.TODO(), *ingressClass, meta_v1.GetOptions{})
if err != nil {
glog.Fatalf("Error when getting IngressClass %v: %v", *ingressClass, err)
}
if ingressClassRes.Spec.Controller != k8s.IngressControllerName {
glog.Fatalf("IngressClass with name %v has an invalid Spec.Controller %v", ingressClassRes.Name, ingressClassRes.Spec.Controller)
}
}
var dynClient dynamic.Interface
if *appProtect {
dynClient, err = dynamic.NewForConfig(config)
if err != nil {
glog.Fatalf("Failed to create dynamic 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
var latencyCollector collectors.LatencyCollector
constLabels := map[string]string{"class": *ingressClass}
managerCollector = collectors.NewManagerFakeCollector()
controllerCollector = collectors.NewControllerFakeCollector()
latencyCollector = collectors.NewLatencyFakeCollector()
if *enablePrometheusMetrics {
registry = prometheus.NewRegistry()
managerCollector = collectors.NewLocalManagerMetricsCollector(constLabels)
controllerCollector = collectors.NewControllerMetricsCollector(*enableCustomResources, constLabels)
processCollector := collectors.NewNginxProcessesMetricsCollector(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)
}
err = processCollector.Register(registry)
if err != nil {
glog.Errorf("Error registering NginxProcess 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, parseReloadTimeout(*appProtect, *nginxReloadTimeout))
}
var aPPluginDone chan error
var aPAgentDone chan error
if *appProtect {
aPPluginDone = make(chan error, 1)
aPAgentDone = make(chan error, 1)
nginxManager.AppProtectAgentStart(aPAgentDone, *nginxDebug)
nginxManager.AppProtectPluginStart(aPPluginDone)
}
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, *appProtect)
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,
EnableSnippets: *enableSnippets,
NginxServiceMesh: *spireAgentAddress != "",
MainAppProtectLoadModule: *appProtect,
EnableLatencyMetrics: *enableLatencyMetrics,
}
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)
}
var plusCollector *nginxCollector.NginxPlusCollector
var syslogListener metrics.SyslogListener
syslogListener = metrics.NewSyslogFakeServer()
if *enablePrometheusMetrics {
upstreamServerVariableLabels := []string{"service", "resource_type", "resource_name", "resource_namespace"}
upstreamServerPeerVariableLabelNames := []string{"pod_name"}
if staticCfgParams.NginxServiceMesh {
upstreamServerPeerVariableLabelNames = append(upstreamServerPeerVariableLabelNames, "pod_owner")
}
if *nginxPlus {
serverZoneVariableLabels := []string{"resource_type", "resource_name", "resource_namespace"}
variableLabelNames := nginxCollector.NewVariableLabelNames(upstreamServerVariableLabels, serverZoneVariableLabels, upstreamServerPeerVariableLabelNames)
plusCollector = nginxCollector.NewNginxPlusCollector(plusClient, "nginx_ingress_nginxplus", variableLabelNames, constLabels)
go metrics.RunPrometheusListenerForNginxPlus(*prometheusMetricsListenPort, plusCollector, registry)
} 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)
}
if *enableLatencyMetrics {
latencyCollector = collectors.NewLatencyMetricsCollector(constLabels, upstreamServerVariableLabels, upstreamServerPeerVariableLabelNames)
if err := latencyCollector.Register(registry); err != nil {
glog.Errorf("Error registering Latency Prometheus metrics: %v", err)
}
syslogListener = metrics.NewLatencyMetricsListener("/var/lib/nginx/nginx-syslog.sock", latencyCollector)
go syslogListener.Run()
}
}
isWildcardEnabled := *wildcardTLSSecret != ""
cnf := configs.NewConfigurator(nginxManager, staticCfgParams, cfgParams, globalCfgParams, templateExecutor,
templateExecutorV2, *nginxPlus, isWildcardEnabled, plusCollector, *enablePrometheusMetrics, latencyCollector, *enableLatencyMetrics)
controllerNamespace := os.Getenv("POD_NAMESPACE")
transportServerValidator := cr_validation.NewTransportServerValidator(*enableTLSPassthrough)
virtualServerValidator := cr_validation.NewVirtualServerValidator(*nginxPlus)
lbcInput := k8s.NewLoadBalancerControllerInput{
KubeClient: kubeClient,
ConfClient: confClient,
DynClient: dynClient,
ResyncPeriod: 30 * time.Second,
Namespace: *watchNamespace,
NginxConfigurator: cnf,
DefaultServerSecret: *defaultServerSecret,
AppProtectEnabled: *appProtect,
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,
VirtualServerValidator: virtualServerValidator,
SpireAgentAddress: *spireAgentAddress,
InternalRoutesEnabled: *enableInternalRoutes,
IsLatencyMetricsEnabled: *enableLatencyMetrics,
}
lbc := k8s.NewLoadBalancerController(lbcInput)
if *readyStatus {
go func() {
port := fmt.Sprintf(":%v", *readyStatusPort)
s := http.NewServeMux()
s.HandleFunc("/nginx-ready", ready(lbc))
glog.Fatal(http.ListenAndServe(port, s))
}()
}
if *appProtect {
go handleTerminationWithAppProtect(lbc, nginxManager, syslogListener, nginxDone, aPAgentDone, aPPluginDone)
} else {
go handleTermination(lbc, nginxManager, syslogListener, 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, listener metrics.SyslogListener, 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.Info("Received SIGTERM, shutting down")
}
glog.Info("Shutting down the controller")
lbc.Stop()
if !exited {
glog.Info("Shutting down NGINX")
nginxManager.Quit()
<-nginxDone
}
listener.Stop()
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 < 1024 || port > 65535 {
return fmt.Errorf("port outside of valid port range [1024 - 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 = secrets.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
}
func handleTerminationWithAppProtect(lbc *k8s.LoadBalancerController, nginxManager nginx.Manager, listener metrics.SyslogListener, nginxDone, agentDone, pluginDone chan error) {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM)
select {
case err := <-nginxDone:
glog.Fatalf("nginx command exited unexpectedly with status: %v", err)
case err := <-pluginDone:
glog.Fatalf("AppProtectPlugin command exited unexpectedly with status: %v", err)
case err := <-agentDone:
glog.Fatalf("AppProtectAgent command exited unexpectedly with status: %v", err)
case <-signalChan:
glog.Infof("Received SIGTERM, shutting down")
lbc.Stop()
nginxManager.Quit()
<-nginxDone
nginxManager.AppProtectPluginQuit()
<-pluginDone
nginxManager.AppProtectAgentQuit()
<-agentDone
listener.Stop()
}
glog.Info("Exiting successfully")
os.Exit(0)
}
func parseReloadTimeout(appProtectEnabled bool, timeout int) int {
const defaultTimeout = 4000
const defaultTimeoutAppProtect = 20000
if timeout != 0 {
return timeout
}
if appProtectEnabled {
return defaultTimeoutAppProtect
}
return defaultTimeout
}
func ready(lbc *k8s.LoadBalancerController) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
if !lbc.IsNginxReady() {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "Ready")
}
}
func minVersion(min string) (v *util_version.Version) {
minVer, err := util_version.ParseGeneric(min)
if err != nil {
glog.Fatalf("unexpected error parsing minimum supported version: %v", err)
}
return minVer
}