main.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /*
  2. Copyright 2026 LocoStack.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package main
  14. import (
  15. "crypto/tls"
  16. "flag"
  17. "os"
  18. // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
  19. // to ensure that exec-entrypoint and run can make use of them.
  20. _ "k8s.io/client-go/plugin/pkg/client/auth"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  23. clientgoscheme "k8s.io/client-go/kubernetes/scheme"
  24. ctrl "sigs.k8s.io/controller-runtime"
  25. "sigs.k8s.io/controller-runtime/pkg/healthz"
  26. "sigs.k8s.io/controller-runtime/pkg/log/zap"
  27. "sigs.k8s.io/controller-runtime/pkg/metrics/filters"
  28. metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
  29. "sigs.k8s.io/controller-runtime/pkg/webhook"
  30. // +kubebuilder:scaffold:imports
  31. )
  32. var (
  33. scheme = runtime.NewScheme()
  34. setupLog = ctrl.Log.WithName("setup")
  35. )
  36. func init() {
  37. utilruntime.Must(clientgoscheme.AddToScheme(scheme))
  38. // +kubebuilder:scaffold:scheme
  39. }
  40. // nolint:gocyclo
  41. func main() {
  42. var metricsAddr string
  43. var metricsCertPath, metricsCertName, metricsCertKey string
  44. var webhookCertPath, webhookCertName, webhookCertKey string
  45. var enableLeaderElection bool
  46. var probeAddr string
  47. var secureMetrics bool
  48. var enableHTTP2 bool
  49. var tlsOpts []func(*tls.Config)
  50. flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+
  51. "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.")
  52. flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
  53. flag.BoolVar(&enableLeaderElection, "leader-elect", false,
  54. "Enable leader election for controller manager. "+
  55. "Enabling this will ensure there is only one active controller manager.")
  56. flag.BoolVar(&secureMetrics, "metrics-secure", true,
  57. "If set, the metrics endpoint is served securely via HTTPS. Use --metrics-secure=false to use HTTP instead.")
  58. flag.StringVar(&webhookCertPath, "webhook-cert-path", "", "The directory that contains the webhook certificate.")
  59. flag.StringVar(&webhookCertName, "webhook-cert-name", "tls.crt", "The name of the webhook certificate file.")
  60. flag.StringVar(&webhookCertKey, "webhook-cert-key", "tls.key", "The name of the webhook key file.")
  61. flag.StringVar(&metricsCertPath, "metrics-cert-path", "",
  62. "The directory that contains the metrics server certificate.")
  63. flag.StringVar(&metricsCertName, "metrics-cert-name", "tls.crt", "The name of the metrics server certificate file.")
  64. flag.StringVar(&metricsCertKey, "metrics-cert-key", "tls.key", "The name of the metrics server key file.")
  65. flag.BoolVar(&enableHTTP2, "enable-http2", false,
  66. "If set, HTTP/2 will be enabled for the metrics and webhook servers")
  67. opts := zap.Options{
  68. Development: true,
  69. }
  70. opts.BindFlags(flag.CommandLine)
  71. flag.Parse()
  72. ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))
  73. // if the enable-http2 flag is false (the default), http/2 should be disabled
  74. // due to its vulnerabilities. More specifically, disabling http/2 will
  75. // prevent from being vulnerable to the HTTP/2 Stream Cancellation and
  76. // Rapid Reset CVEs. For more information see:
  77. // - https://github.com/advisories/GHSA-qppj-fm5r-hxr3
  78. // - https://github.com/advisories/GHSA-4374-p667-p6c8
  79. disableHTTP2 := func(c *tls.Config) {
  80. setupLog.Info("Disabling HTTP/2")
  81. c.NextProtos = []string{"http/1.1"}
  82. }
  83. if !enableHTTP2 {
  84. tlsOpts = append(tlsOpts, disableHTTP2)
  85. }
  86. // Initial webhook TLS options
  87. webhookTLSOpts := tlsOpts
  88. webhookServerOptions := webhook.Options{
  89. TLSOpts: webhookTLSOpts,
  90. }
  91. if len(webhookCertPath) > 0 {
  92. setupLog.Info("Initializing webhook certificate watcher using provided certificates",
  93. "webhook-cert-path", webhookCertPath, "webhook-cert-name", webhookCertName, "webhook-cert-key", webhookCertKey)
  94. webhookServerOptions.CertDir = webhookCertPath
  95. webhookServerOptions.CertName = webhookCertName
  96. webhookServerOptions.KeyName = webhookCertKey
  97. }
  98. webhookServer := webhook.NewServer(webhookServerOptions)
  99. // Metrics endpoint is enabled in 'config/default/kustomization.yaml'. The Metrics options configure the server.
  100. // More info:
  101. // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.23.3/pkg/metrics/server
  102. // - https://book.kubebuilder.io/reference/metrics.html
  103. metricsServerOptions := metricsserver.Options{
  104. BindAddress: metricsAddr,
  105. SecureServing: secureMetrics,
  106. TLSOpts: tlsOpts,
  107. }
  108. if secureMetrics {
  109. // FilterProvider is used to protect the metrics endpoint with authn/authz.
  110. // These configurations ensure that only authorized users and service accounts
  111. // can access the metrics endpoint. The RBAC are configured in 'config/rbac/kustomization.yaml'. More info:
  112. // https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.23.3/pkg/metrics/filters#WithAuthenticationAndAuthorization
  113. metricsServerOptions.FilterProvider = filters.WithAuthenticationAndAuthorization
  114. }
  115. // If the certificate is not specified, controller-runtime will automatically
  116. // generate self-signed certificates for the metrics server. While convenient for development and testing,
  117. // this setup is not recommended for production.
  118. //
  119. // TODO(user): If you enable certManager, uncomment the following lines:
  120. // - [METRICS-WITH-CERTS] at config/default/kustomization.yaml to generate and use certificates
  121. // managed by cert-manager for the metrics server.
  122. // - [PROMETHEUS-WITH-CERTS] at config/prometheus/kustomization.yaml for TLS certification.
  123. if len(metricsCertPath) > 0 {
  124. setupLog.Info("Initializing metrics certificate watcher using provided certificates",
  125. "metrics-cert-path", metricsCertPath, "metrics-cert-name", metricsCertName, "metrics-cert-key", metricsCertKey)
  126. metricsServerOptions.CertDir = metricsCertPath
  127. metricsServerOptions.CertName = metricsCertName
  128. metricsServerOptions.KeyName = metricsCertKey
  129. }
  130. mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
  131. Scheme: scheme,
  132. Metrics: metricsServerOptions,
  133. WebhookServer: webhookServer,
  134. HealthProbeBindAddress: probeAddr,
  135. LeaderElection: enableLeaderElection,
  136. LeaderElectionID: "3fcced06.locostack.com",
  137. // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
  138. // when the Manager ends. This requires the binary to immediately end when the
  139. // Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
  140. // speeds up voluntary leader transitions as the new leader don't have to wait
  141. // LeaseDuration time first.
  142. //
  143. // In the default scaffold provided, the program ends immediately after
  144. // the manager stops, so would be fine to enable this option. However,
  145. // if you are doing or is intended to do any operation such as perform cleanups
  146. // after the manager stops then its usage might be unsafe.
  147. // LeaderElectionReleaseOnCancel: true,
  148. })
  149. if err != nil {
  150. setupLog.Error(err, "Failed to start manager")
  151. os.Exit(1)
  152. }
  153. // +kubebuilder:scaffold:builder
  154. if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
  155. setupLog.Error(err, "Failed to set up health check")
  156. os.Exit(1)
  157. }
  158. if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
  159. setupLog.Error(err, "Failed to set up ready check")
  160. os.Exit(1)
  161. }
  162. setupLog.Info("Starting manager")
  163. if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
  164. setupLog.Error(err, "Failed to run manager")
  165. os.Exit(1)
  166. }
  167. }