github.com/cilium/cilium@v1.16.2/operator/pkg/controller-runtime/cell.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package controllerruntime 5 6 import ( 7 "context" 8 "fmt" 9 10 "github.com/bombsimon/logrusr/v4" 11 "github.com/cilium/hive/cell" 12 "github.com/cilium/hive/job" 13 "github.com/sirupsen/logrus" 14 "google.golang.org/protobuf/proto" 15 "k8s.io/apimachinery/pkg/api/equality" 16 "k8s.io/apimachinery/pkg/runtime" 17 clientgoscheme "k8s.io/client-go/kubernetes/scheme" 18 ctrlRuntime "sigs.k8s.io/controller-runtime" 19 metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" 20 21 ciliumv2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2" 22 "github.com/cilium/cilium/pkg/k8s/client" 23 ) 24 25 // Cell integrates the components of the controller-runtime library into Hive. 26 // The Kubernetes controller-runtime Project is a set of go libraries for building Controllers. 27 // See https://github.com/kubernetes-sigs/controller-runtime for further information. 28 var Cell = cell.Module( 29 "controller-runtime", 30 "Manages the controller-runtime integration and its components", 31 32 cell.Provide(newScheme), 33 cell.Provide(newManager), 34 ) 35 36 func newScheme() (*runtime.Scheme, error) { 37 scheme := clientgoscheme.Scheme 38 39 for gv, f := range map[fmt.Stringer]func(s *runtime.Scheme) error{ 40 ciliumv2.SchemeGroupVersion: ciliumv2.AddToScheme, 41 } { 42 if err := f(scheme); err != nil { 43 return nil, fmt.Errorf("failed to add types from %s to scheme: %w", gv, err) 44 } 45 } 46 47 return scheme, nil 48 } 49 50 type managerParams struct { 51 cell.In 52 53 Logger logrus.FieldLogger 54 Lifecycle cell.Lifecycle 55 JobGroup job.Group 56 Health cell.Health 57 58 K8sClient client.Clientset 59 Scheme *runtime.Scheme 60 } 61 62 func newManager(params managerParams) (ctrlRuntime.Manager, error) { 63 if !params.K8sClient.IsEnabled() { 64 return nil, nil 65 } 66 67 // Register special comparison function for proto resource to support 68 // internal comparison of types depending on type (e.g. CiliumEnvoyConfig). 69 equality.Semantic.AddFunc(func(xdsResource1, xdsResource2 ciliumv2.XDSResource) bool { 70 return proto.Equal(xdsResource1.Any, xdsResource2.Any) 71 }) 72 73 ctrlRuntime.SetLogger(logrusr.New(params.Logger)) 74 75 mgr, err := ctrlRuntime.NewManager(params.K8sClient.RestConfig(), ctrlRuntime.Options{ 76 Scheme: params.Scheme, 77 // Disable controller metrics server in favour of cilium's metrics server. 78 Metrics: metricsserver.Options{ 79 BindAddress: "0", 80 }, 81 Logger: logrusr.New(params.Logger), 82 }) 83 if err != nil { 84 return nil, fmt.Errorf("failed to create new controller-runtime manager: %w", err) 85 } 86 87 params.JobGroup.Add(job.OneShot("manager", func(ctx context.Context, health cell.Health) error { 88 return mgr.Start(ctx) 89 })) 90 91 return mgr, nil 92 }