root.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. Copyright © 2022 ESO Maintainer Team
  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 cmd
  14. import (
  15. "os"
  16. "time"
  17. "github.com/spf13/cobra"
  18. "go.uber.org/zap/zapcore"
  19. v1 "k8s.io/api/core/v1"
  20. apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. clientgoscheme "k8s.io/client-go/kubernetes/scheme"
  23. // To allow using gcp auth.
  24. _ "k8s.io/client-go/plugin/pkg/client/auth"
  25. ctrl "sigs.k8s.io/controller-runtime"
  26. "sigs.k8s.io/controller-runtime/pkg/client"
  27. "sigs.k8s.io/controller-runtime/pkg/controller"
  28. "sigs.k8s.io/controller-runtime/pkg/log/zap"
  29. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  30. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  31. genv1alpha1 "github.com/external-secrets/external-secrets/apis/generators/v1alpha1"
  32. "github.com/external-secrets/external-secrets/pkg/controllers/clusterexternalsecret"
  33. "github.com/external-secrets/external-secrets/pkg/controllers/externalsecret"
  34. "github.com/external-secrets/external-secrets/pkg/controllers/pushsecret"
  35. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore"
  36. "github.com/external-secrets/external-secrets/pkg/feature"
  37. )
  38. var (
  39. scheme = runtime.NewScheme()
  40. setupLog = ctrl.Log.WithName("setup")
  41. dnsName string
  42. certDir string
  43. metricsAddr string
  44. healthzAddr string
  45. controllerClass string
  46. enableLeaderElection bool
  47. enableSecretsCache bool
  48. enableConfigMapsCache bool
  49. concurrent int
  50. port int
  51. clientQPS float32
  52. clientBurst int
  53. loglevel string
  54. zapTimeEncoding string
  55. namespace string
  56. enableClusterStoreReconciler bool
  57. enableClusterExternalSecretReconciler bool
  58. enablePushSecretReconciler bool
  59. enableFloodGate bool
  60. storeRequeueInterval time.Duration
  61. serviceName, serviceNamespace string
  62. secretName, secretNamespace string
  63. crdNames []string
  64. crdRequeueInterval time.Duration
  65. certCheckInterval time.Duration
  66. certLookaheadInterval time.Duration
  67. tlsCiphers string
  68. tlsMinVersion string
  69. )
  70. const (
  71. errCreateController = "unable to create controller"
  72. )
  73. func init() {
  74. _ = clientgoscheme.AddToScheme(scheme)
  75. _ = esv1beta1.AddToScheme(scheme)
  76. _ = esv1alpha1.AddToScheme(scheme)
  77. _ = genv1alpha1.AddToScheme(scheme)
  78. _ = apiextensionsv1.AddToScheme(scheme)
  79. }
  80. var rootCmd = &cobra.Command{
  81. Use: "external-secrets",
  82. Short: "operator that reconciles ExternalSecrets and SecretStores",
  83. Long: `For more information visit https://external-secrets.io`,
  84. Run: func(cmd *cobra.Command, args []string) {
  85. var lvl zapcore.Level
  86. var enc zapcore.TimeEncoder
  87. // the client creates a ListWatch for all resource kinds that
  88. // are requested with .Get().
  89. // We want to avoid to cache all secrets or configmaps in memory.
  90. // The ES controller uses v1.PartialObjectMetadata for the secrets
  91. // that he owns.
  92. // see #721
  93. cacheList := make([]client.Object, 0)
  94. if !enableSecretsCache {
  95. cacheList = append(cacheList, &v1.Secret{})
  96. }
  97. if !enableConfigMapsCache {
  98. cacheList = append(cacheList, &v1.ConfigMap{})
  99. }
  100. lvlErr := lvl.UnmarshalText([]byte(loglevel))
  101. if lvlErr != nil {
  102. setupLog.Error(lvlErr, "error unmarshalling loglevel")
  103. os.Exit(1)
  104. }
  105. encErr := enc.UnmarshalText([]byte(zapTimeEncoding))
  106. if encErr != nil {
  107. setupLog.Error(encErr, "error unmarshalling timeEncoding")
  108. os.Exit(1)
  109. }
  110. opts := zap.Options{
  111. Level: lvl,
  112. TimeEncoder: enc,
  113. }
  114. logger := zap.New(zap.UseFlagOptions(&opts))
  115. ctrl.SetLogger(logger)
  116. config := ctrl.GetConfigOrDie()
  117. config.QPS = clientQPS
  118. config.Burst = clientBurst
  119. mgr, err := ctrl.NewManager(config, ctrl.Options{
  120. Scheme: scheme,
  121. MetricsBindAddress: metricsAddr,
  122. Port: 9443,
  123. LeaderElection: enableLeaderElection,
  124. LeaderElectionID: "external-secrets-controller",
  125. ClientDisableCacheFor: cacheList,
  126. Namespace: namespace,
  127. })
  128. if err != nil {
  129. setupLog.Error(err, "unable to start manager")
  130. os.Exit(1)
  131. }
  132. if err = (&secretstore.StoreReconciler{
  133. Client: mgr.GetClient(),
  134. Log: ctrl.Log.WithName("controllers").WithName("SecretStore"),
  135. Scheme: mgr.GetScheme(),
  136. ControllerClass: controllerClass,
  137. RequeueInterval: storeRequeueInterval,
  138. }).SetupWithManager(mgr); err != nil {
  139. setupLog.Error(err, errCreateController, "controller", "SecretStore")
  140. os.Exit(1)
  141. }
  142. if enableClusterStoreReconciler {
  143. if err = (&secretstore.ClusterStoreReconciler{
  144. Client: mgr.GetClient(),
  145. Log: ctrl.Log.WithName("controllers").WithName("ClusterSecretStore"),
  146. Scheme: mgr.GetScheme(),
  147. ControllerClass: controllerClass,
  148. RequeueInterval: storeRequeueInterval,
  149. }).SetupWithManager(mgr); err != nil {
  150. setupLog.Error(err, errCreateController, "controller", "ClusterSecretStore")
  151. os.Exit(1)
  152. }
  153. }
  154. if err = (&externalsecret.Reconciler{
  155. Client: mgr.GetClient(),
  156. Log: ctrl.Log.WithName("controllers").WithName("ExternalSecret"),
  157. Scheme: mgr.GetScheme(),
  158. RestConfig: mgr.GetConfig(),
  159. ControllerClass: controllerClass,
  160. RequeueInterval: time.Hour,
  161. ClusterSecretStoreEnabled: enableClusterStoreReconciler,
  162. EnableFloodGate: enableFloodGate,
  163. }).SetupWithManager(mgr, controller.Options{
  164. MaxConcurrentReconciles: concurrent,
  165. }); err != nil {
  166. setupLog.Error(err, errCreateController, "controller", "ExternalSecret")
  167. os.Exit(1)
  168. }
  169. if enablePushSecretReconciler {
  170. if err = (&pushsecret.Reconciler{
  171. Client: mgr.GetClient(),
  172. Log: ctrl.Log.WithName("controllers").WithName("PushSecret"),
  173. Scheme: mgr.GetScheme(),
  174. ControllerClass: controllerClass,
  175. RequeueInterval: time.Hour,
  176. }).SetupWithManager(mgr); err != nil {
  177. setupLog.Error(err, errCreateController, "controller", "PushSecret")
  178. os.Exit(1)
  179. }
  180. }
  181. if enableClusterExternalSecretReconciler {
  182. if err = (&clusterexternalsecret.Reconciler{
  183. Client: mgr.GetClient(),
  184. Log: ctrl.Log.WithName("controllers").WithName("ClusterExternalSecret"),
  185. Scheme: mgr.GetScheme(),
  186. RequeueInterval: time.Hour,
  187. }).SetupWithManager(mgr, controller.Options{
  188. MaxConcurrentReconciles: concurrent,
  189. }); err != nil {
  190. setupLog.Error(err, errCreateController, "controller", "ClusterExternalSecret")
  191. os.Exit(1)
  192. }
  193. }
  194. fs := feature.Features()
  195. for _, f := range fs {
  196. if f.Initialize == nil {
  197. continue
  198. }
  199. f.Initialize()
  200. }
  201. setupLog.Info("starting manager")
  202. if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
  203. setupLog.Error(err, "problem running manager")
  204. os.Exit(1)
  205. }
  206. },
  207. }
  208. func Execute() {
  209. cobra.CheckErr(rootCmd.Execute())
  210. }
  211. func init() {
  212. rootCmd.Flags().StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
  213. rootCmd.Flags().StringVar(&controllerClass, "controller-class", "default", "The controller is instantiated with a specific controller name and filters ES based on this property")
  214. rootCmd.Flags().BoolVar(&enableLeaderElection, "enable-leader-election", false,
  215. "Enable leader election for controller manager. "+
  216. "Enabling this will ensure there is only one active controller manager.")
  217. rootCmd.Flags().IntVar(&concurrent, "concurrent", 1, "The number of concurrent ExternalSecret reconciles.")
  218. rootCmd.Flags().Float32Var(&clientQPS, "client-qps", 0, "QPS configuration to be passed to rest.Client")
  219. rootCmd.Flags().IntVar(&clientBurst, "client-burst", 0, "Maximum Burst allowed to be passed to rest.Client")
  220. rootCmd.Flags().StringVar(&loglevel, "loglevel", "info", "loglevel to use, one of: debug, info, warn, error, dpanic, panic, fatal")
  221. rootCmd.Flags().StringVar(&zapTimeEncoding, "zap-time-encoding", "epoch", "Zap time encoding (one of 'epoch', 'millis', 'nano', 'iso8601', 'rfc3339' or 'rfc3339nano')")
  222. rootCmd.Flags().StringVar(&namespace, "namespace", "", "watch external secrets scoped in the provided namespace only. ClusterSecretStore can be used but only work if it doesn't reference resources from other namespaces")
  223. rootCmd.Flags().BoolVar(&enableClusterStoreReconciler, "enable-cluster-store-reconciler", true, "Enable cluster store reconciler.")
  224. rootCmd.Flags().BoolVar(&enableClusterExternalSecretReconciler, "enable-cluster-external-secret-reconciler", true, "Enable cluster external secret reconciler.")
  225. rootCmd.Flags().BoolVar(&enablePushSecretReconciler, "enable-push-secret-reconciler", true, "Enable push secret reconciler.")
  226. rootCmd.Flags().BoolVar(&enableSecretsCache, "enable-secrets-caching", false, "Enable secrets caching for external-secrets pod.")
  227. rootCmd.Flags().BoolVar(&enableConfigMapsCache, "enable-configmaps-caching", false, "Enable secrets caching for external-secrets pod.")
  228. rootCmd.Flags().DurationVar(&storeRequeueInterval, "store-requeue-interval", time.Minute*5, "Default Time duration between reconciling (Cluster)SecretStores")
  229. rootCmd.Flags().BoolVar(&enableFloodGate, "enable-flood-gate", true, "Enable flood gate. External secret will be reconciled only if the ClusterStore or Store have an healthy or unknown state.")
  230. fs := feature.Features()
  231. for _, f := range fs {
  232. rootCmd.Flags().AddFlagSet(f.Flags)
  233. }
  234. }