-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathmain.go
408 lines (347 loc) · 14.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
package main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/golang/glog"
"github.com/nginxinc/kubernetes-ingress/internal/controller"
"github.com/nginxinc/kubernetes-ingress/internal/handlers"
"github.com/nginxinc/kubernetes-ingress/internal/nginx"
"github.com/nginxinc/kubernetes-ingress/internal/nginx/plus"
"github.com/nginxinc/kubernetes-ingress/internal/utils"
api_v1 "k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"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 "/nginx-health" to the default server. The location responds with the 200 status code for any request.
Useful for external health-checking of the Ingress controller`)
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")`)
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 resources. 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 resources -- only one replica will report status. See -report-ingress-status flag.")
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.`)
)
func main() {
flag.Parse()
flag.Lookup("logtostderr").Value.Set("true")
if *versionFlag {
fmt.Printf("Version=%v GitCommit=%v\n", version, gitCommit)
os.Exit(0)
}
portValidationError := validateStatusPort(*nginxStatusPort)
if portValidationError != nil {
glog.Fatalf("Invalid value for nginx-status-port: %v", portValidationError)
}
var err error
allowedCIDRs, err := parseNginxStatusAllowCIDRs(*nginxStatusAllowCIDRs)
if err != nil {
glog.Fatalf(`Invalid value for nginx-status-allow-cidrs: %v`, err)
}
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)
}
local := *proxyURL != ""
nginxConfTemplatePath := "nginx.tmpl"
nginxIngressTemplatePath := "nginx.ingress.tmpl"
if *nginxPlus {
nginxConfTemplatePath = "nginx-plus.tmpl"
nginxIngressTemplatePath = "nginx-plus.ingress.tmpl"
}
if *mainTemplatePath != "" {
nginxConfTemplatePath = *mainTemplatePath
}
if *ingressTemplatePath != "" {
nginxIngressTemplatePath = *ingressTemplatePath
}
nginxBinaryPath := "/usr/sbin/nginx"
if *nginxDebug {
nginxBinaryPath = "/usr/sbin/nginx-debug"
}
templateExecutor, err := nginx.NewTemplateExecutor(nginxConfTemplatePath, nginxIngressTemplatePath, *healthStatus, *nginxStatus, allowedCIDRs, *nginxStatusPort)
if err != nil {
glog.Fatalf("Error creating TemplateExecutor: %v", err)
}
ngxc := nginx.NewNginxController("/etc/nginx/", nginxBinaryPath, local)
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 := nginx.GenerateCertAndKeyFileContent(secret)
ngxc.AddOrUpdateSecretFile(nginx.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 := nginx.GenerateCertAndKeyFileContent(secret)
ngxc.AddOrUpdateSecretFile(nginx.WildcardSecretName, bytes, nginx.TLSSecretFileMode)
}
cfg := nginx.NewDefaultConfig()
if *nginxConfigMaps != "" {
ns, name, err := utils.ParseNamespaceName(*nginxConfigMaps)
if err != nil {
glog.Fatalf("Error parsing the nginx-configmaps argument: %v", err)
}
cfm, err := kubeClient.CoreV1().ConfigMaps(ns).Get(name, meta_v1.GetOptions{})
if err != nil {
glog.Fatalf("Error when getting %v: %v", *nginxConfigMaps, err)
}
cfg = nginx.ParseConfigMap(cfm, *nginxPlus)
if cfg.MainServerSSLDHParamFileContent != nil {
fileName, err := ngxc.AddOrUpdateDHParam(*cfg.MainServerSSLDHParamFileContent)
if err != nil {
glog.Fatalf("Configmap %s/%s: Could not update dhparams: %v", ns, name, err)
} else {
cfg.MainServerSSLDHParam = fileName
}
}
if cfg.MainTemplate != nil {
err = templateExecutor.UpdateMainTemplate(cfg.MainTemplate)
if err != nil {
glog.Fatalf("Error updating NGINX main template: %v", err)
}
}
if cfg.IngressTemplate != nil {
err = templateExecutor.UpdateIngressTemplate(cfg.IngressTemplate)
if err != nil {
glog.Fatalf("Error updating ingress template: %v", err)
}
}
}
ngxConfig := nginx.GenerateNginxMainConfig(cfg)
content, err := templateExecutor.ExecuteMainConfigTemplate(ngxConfig)
if err != nil {
glog.Fatalf("Error generating NGINX main config: %v", err)
}
ngxc.UpdateMainConfigFile(content)
ngxc.UpdateConfigVersionFile()
nginxDone := make(chan error, 1)
ngxc.Start(nginxDone)
var nginxAPI *plus.NginxAPIController
if *nginxPlus {
httpClient := getSocketClient()
nginxAPI, err = plus.NewNginxAPIController(&httpClient, "http://nginx-plus-api/api", local)
if err != nil {
glog.Fatalf("Failed to create NginxAPIController: %v", err)
}
}
isWildcardEnabled := *wildcardTLSSecret != ""
cnf := nginx.NewConfigurator(ngxc, cfg, nginxAPI, templateExecutor, isWildcardEnabled)
controllerNamespace := os.Getenv("POD_NAMESPACE")
lbcInput := controller.NewLoadBalancerControllerInput{
KubeClient: kubeClient,
ResyncPeriod: 30 * time.Second,
Namespace: *watchNamespace,
NginxConfigurator: cnf,
DefaultServerSecret: *defaultServerSecret,
IsNginxPlus: *nginxPlus,
IngressClass: *ingressClass,
UseIngressClassOnly: *useIngressClassOnly,
ExternalServiceName: *externalService,
ControllerNamespace: controllerNamespace,
ReportIngressStatus: *reportIngressStatus,
IsLeaderElectionEnabled: *leaderElectionEnabled,
WildcardTLSSecret: *wildcardTLSSecret,
}
lbc := controller.NewLoadBalancerController(lbcInput)
// create handlers for resources we care about
ingressHandlers := handlers.CreateIngressHandlers(lbc)
secretHandlers := handlers.CreateSecretHandlers(lbc)
serviceHandlers := handlers.CreateServiceHandlers(lbc)
endpointHandlers := handlers.CreateEndpointHandlers(lbc)
lbc.AddSecretHandler(secretHandlers)
lbc.AddIngressHandler(ingressHandlers)
lbc.AddServiceHandler(serviceHandlers)
lbc.AddEndpointHandler(endpointHandlers)
if *nginxConfigMaps != "" {
nginxConfigMapsNS, nginxConfigMapsName, err := utils.ParseNamespaceName(*nginxConfigMaps)
if err != nil {
glog.Warning(err)
} else {
lbc.WatchNginxConfigMaps()
configMapHandlers := handlers.CreateConfigMapHandlers(lbc, nginxConfigMapsName)
lbc.AddConfigMapHandler(configMapHandlers, nginxConfigMapsNS)
}
}
if lbcInput.ReportIngressStatus && lbcInput.IsLeaderElectionEnabled {
leaderHandler := handlers.CreateLeaderHandler(lbc)
lbc.AddLeaderHandler(leaderHandler)
}
go handleTermination(lbc, ngxc, nginxDone)
lbc.Run()
for {
glog.Info("Waiting for the controller to exit...")
time.Sleep(30 * time.Second)
}
}
func handleTermination(lbc *controller.LoadBalancerController, ngxc *nginx.Controller, 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")
ngxc.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() http.Client {
return http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", "/var/run/nginx-plus-api.sock")
},
},
}
}
func validateStatusPort(nginxStatusPort int) error {
if nginxStatusPort < 1023 || nginxStatusPort > 65535 {
return fmt.Errorf("port outside of valid port range [1023 - 65535]: %v", nginxStatusPort)
}
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 := utils.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(name, meta_v1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("could not get %v: %v", secretNsName, err)
}
err = nginx.ValidateTLSSecret(secret)
if err != nil {
return nil, fmt.Errorf("%v is invalid: %v", secretNsName, err)
}
return secret, nil
}