Code refactoring for bpa operator
[icn.git] / cmd / bpa-operator / vendor / sigs.k8s.io / controller-runtime / pkg / manager / manager.go
1 /*
2 Copyright 2018 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package manager
18
19 import (
20         "fmt"
21         "net"
22         "time"
23
24         "github.com/go-logr/logr"
25
26         "k8s.io/apimachinery/pkg/api/meta"
27         "k8s.io/apimachinery/pkg/runtime"
28         "k8s.io/client-go/kubernetes/scheme"
29         "k8s.io/client-go/rest"
30         "k8s.io/client-go/tools/leaderelection/resourcelock"
31         "k8s.io/client-go/tools/record"
32         "sigs.k8s.io/controller-runtime/pkg/cache"
33         "sigs.k8s.io/controller-runtime/pkg/client"
34         "sigs.k8s.io/controller-runtime/pkg/client/apiutil"
35         internalrecorder "sigs.k8s.io/controller-runtime/pkg/internal/recorder"
36         "sigs.k8s.io/controller-runtime/pkg/leaderelection"
37         "sigs.k8s.io/controller-runtime/pkg/metrics"
38         "sigs.k8s.io/controller-runtime/pkg/recorder"
39         "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
40         "sigs.k8s.io/controller-runtime/pkg/webhook/admission/types"
41 )
42
43 // Manager initializes shared dependencies such as Caches and Clients, and provides them to Runnables.
44 // A Manager is required to create Controllers.
45 type Manager interface {
46         // Add will set reqeusted dependencies on the component, and cause the component to be
47         // started when Start is called.  Add will inject any dependencies for which the argument
48         // implements the inject interface - e.g. inject.Client
49         Add(Runnable) error
50
51         // SetFields will set any dependencies on an object for which the object has implemented the inject
52         // interface - e.g. inject.Client.
53         SetFields(interface{}) error
54
55         // Start starts all registered Controllers and blocks until the Stop channel is closed.
56         // Returns an error if there is an error starting any controller.
57         Start(<-chan struct{}) error
58
59         // GetConfig returns an initialized Config
60         GetConfig() *rest.Config
61
62         // GetScheme returns and initialized Scheme
63         GetScheme() *runtime.Scheme
64
65         // GetAdmissionDecoder returns the runtime.Decoder based on the scheme.
66         GetAdmissionDecoder() types.Decoder
67
68         // GetClient returns a client configured with the Config
69         GetClient() client.Client
70
71         // GetFieldIndexer returns a client.FieldIndexer configured with the client
72         GetFieldIndexer() client.FieldIndexer
73
74         // GetCache returns a cache.Cache
75         GetCache() cache.Cache
76
77         // GetRecorder returns a new EventRecorder for the provided name
78         GetRecorder(name string) record.EventRecorder
79
80         // GetRESTMapper returns a RESTMapper
81         GetRESTMapper() meta.RESTMapper
82 }
83
84 // Options are the arguments for creating a new Manager
85 type Options struct {
86         // Scheme is the scheme used to resolve runtime.Objects to GroupVersionKinds / Resources
87         // Defaults to the kubernetes/client-go scheme.Scheme
88         Scheme *runtime.Scheme
89
90         // MapperProvider provides the rest mapper used to map go types to Kubernetes APIs
91         MapperProvider func(c *rest.Config) (meta.RESTMapper, error)
92
93         // SyncPeriod determines the minimum frequency at which watched resources are
94         // reconciled. A lower period will correct entropy more quickly, but reduce
95         // responsiveness to change if there are many watched resources. Change this
96         // value only if you know what you are doing. Defaults to 10 hours if unset.
97         SyncPeriod *time.Duration
98
99         // LeaderElection determines whether or not to use leader election when
100         // starting the manager.
101         LeaderElection bool
102
103         // LeaderElectionNamespace determines the namespace in which the leader
104         // election configmap will be created.
105         LeaderElectionNamespace string
106
107         // LeaderElectionID determines the name of the configmap that leader election
108         // will use for holding the leader lock.
109         LeaderElectionID string
110
111         // Namespace if specified restricts the manager's cache to watch objects in the desired namespace
112         // Defaults to all namespaces
113         // Note: If a namespace is specified then controllers can still Watch for a cluster-scoped resource e.g Node
114         // For namespaced resources the cache will only hold objects from the desired namespace.
115         Namespace string
116
117         // MetricsBindAddress is the TCP address that the controller should bind to
118         // for serving prometheus metrics
119         MetricsBindAddress string
120
121         // Functions to all for a user to customize the values that will be injected.
122
123         // NewCache is the function that will create the cache to be used
124         // by the manager. If not set this will use the default new cache function.
125         NewCache NewCacheFunc
126
127         // NewClient will create the client to be used by the manager.
128         // If not set this will create the default DelegatingClient that will
129         // use the cache for reads and the client for writes.
130         NewClient NewClientFunc
131
132         // Dependency injection for testing
133         newRecorderProvider func(config *rest.Config, scheme *runtime.Scheme, logger logr.Logger) (recorder.Provider, error)
134         newResourceLock     func(config *rest.Config, recorderProvider recorder.Provider, options leaderelection.Options) (resourcelock.Interface, error)
135         newAdmissionDecoder func(scheme *runtime.Scheme) (types.Decoder, error)
136         newMetricsListener  func(addr string) (net.Listener, error)
137 }
138
139 // NewCacheFunc allows a user to define how to create a cache
140 type NewCacheFunc func(config *rest.Config, opts cache.Options) (cache.Cache, error)
141
142 // NewClientFunc allows a user to define how to create a client
143 type NewClientFunc func(cache cache.Cache, config *rest.Config, options client.Options) (client.Client, error)
144
145 // Runnable allows a component to be started.
146 type Runnable interface {
147         // Start starts running the component.  The component will stop running when the channel is closed.
148         // Start blocks until the channel is closed or an error occurs.
149         Start(<-chan struct{}) error
150 }
151
152 // RunnableFunc implements Runnable
153 type RunnableFunc func(<-chan struct{}) error
154
155 // Start implements Runnable
156 func (r RunnableFunc) Start(s <-chan struct{}) error {
157         return r(s)
158 }
159
160 // New returns a new Manager for creating Controllers.
161 func New(config *rest.Config, options Options) (Manager, error) {
162         // Initialize a rest.config if none was specified
163         if config == nil {
164                 return nil, fmt.Errorf("must specify Config")
165         }
166
167         // Set default values for options fields
168         options = setOptionsDefaults(options)
169
170         // Create the mapper provider
171         mapper, err := options.MapperProvider(config)
172         if err != nil {
173                 log.Error(err, "Failed to get API Group-Resources")
174                 return nil, err
175         }
176
177         // Create the cache for the cached read client and registering informers
178         cache, err := options.NewCache(config, cache.Options{Scheme: options.Scheme, Mapper: mapper, Resync: options.SyncPeriod, Namespace: options.Namespace})
179         if err != nil {
180                 return nil, err
181         }
182
183         writeObj, err := options.NewClient(cache, config, client.Options{Scheme: options.Scheme, Mapper: mapper})
184         if err != nil {
185                 return nil, err
186         }
187         // Create the recorder provider to inject event recorders for the components.
188         // TODO(directxman12): the log for the event provider should have a context (name, tags, etc) specific
189         // to the particular controller that it's being injected into, rather than a generic one like is here.
190         recorderProvider, err := options.newRecorderProvider(config, options.Scheme, log.WithName("events"))
191         if err != nil {
192                 return nil, err
193         }
194
195         // Create the resource lock to enable leader election)
196         resourceLock, err := options.newResourceLock(config, recorderProvider, leaderelection.Options{
197                 LeaderElection:          options.LeaderElection,
198                 LeaderElectionID:        options.LeaderElectionID,
199                 LeaderElectionNamespace: options.LeaderElectionNamespace,
200         })
201         if err != nil {
202                 return nil, err
203         }
204
205         admissionDecoder, err := options.newAdmissionDecoder(options.Scheme)
206         if err != nil {
207                 return nil, err
208         }
209
210         // Create the mertics listener. This will throw an error if the metrics bind
211         // address is invalid or already in use.
212         metricsListener, err := options.newMetricsListener(options.MetricsBindAddress)
213         if err != nil {
214                 return nil, err
215         }
216
217         stop := make(chan struct{})
218
219         return &controllerManager{
220                 config:           config,
221                 scheme:           options.Scheme,
222                 admissionDecoder: admissionDecoder,
223                 errChan:          make(chan error),
224                 cache:            cache,
225                 fieldIndexes:     cache,
226                 client:           writeObj,
227                 recorderProvider: recorderProvider,
228                 resourceLock:     resourceLock,
229                 mapper:           mapper,
230                 metricsListener:  metricsListener,
231                 internalStop:     stop,
232                 internalStopper:  stop,
233         }, nil
234 }
235
236 // defaultNewClient creates the default caching client
237 func defaultNewClient(cache cache.Cache, config *rest.Config, options client.Options) (client.Client, error) {
238         // Create the Client for Write operations.
239         c, err := client.New(config, options)
240         if err != nil {
241                 return nil, err
242         }
243
244         return &client.DelegatingClient{
245                 Reader: &client.DelegatingReader{
246                         CacheReader:  cache,
247                         ClientReader: c,
248                 },
249                 Writer:       c,
250                 StatusClient: c,
251         }, nil
252 }
253
254 // setOptionsDefaults set default values for Options fields
255 func setOptionsDefaults(options Options) Options {
256         // Use the Kubernetes client-go scheme if none is specified
257         if options.Scheme == nil {
258                 options.Scheme = scheme.Scheme
259         }
260
261         if options.MapperProvider == nil {
262                 options.MapperProvider = apiutil.NewDiscoveryRESTMapper
263         }
264
265         // Allow newClient to be mocked
266         if options.NewClient == nil {
267                 options.NewClient = defaultNewClient
268         }
269
270         // Allow newCache to be mocked
271         if options.NewCache == nil {
272                 options.NewCache = cache.New
273         }
274
275         // Allow newRecorderProvider to be mocked
276         if options.newRecorderProvider == nil {
277                 options.newRecorderProvider = internalrecorder.NewProvider
278         }
279
280         // Allow newResourceLock to be mocked
281         if options.newResourceLock == nil {
282                 options.newResourceLock = leaderelection.NewResourceLock
283         }
284
285         if options.newAdmissionDecoder == nil {
286                 options.newAdmissionDecoder = admission.NewDecoder
287         }
288
289         if options.newMetricsListener == nil {
290                 options.newMetricsListener = metrics.NewListener
291         }
292
293         return options
294 }