-
Notifications
You must be signed in to change notification settings - Fork 459
/
main-controller.go
1508 lines (1363 loc) · 55.9 KB
/
main-controller.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2020-2023 MinIO, Inc.
//
// This code is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License, version 3,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License, version 3,
// along with this program. If not, see <http://www.gnu.org/licenses/>
package controller
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/minio/operator/pkg/utils"
"github.com/minio/madmin-go/v3"
"github.com/minio/operator/pkg/common"
xcerts "github.com/minio/pkg/certs"
"github.com/minio/minio-go/v7/pkg/set"
"github.com/minio/operator/pkg/controller/certificates"
"github.com/minio/pkg/env"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/klog/v2"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
miniov1 "github.com/minio/operator/pkg/apis/minio.min.io/v1"
"golang.org/x/time/rate"
// Workaround for auth import issues refer https://github.com/minio/operator/issues/283
_ "k8s.io/client-go/plugin/pkg/client/auth"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
appsinformers "k8s.io/client-go/informers/apps/v1"
coreinformers "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
appslisters "k8s.io/client-go/listers/apps/v1"
corelisters "k8s.io/client-go/listers/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
promclientset "github.com/prometheus-operator/prometheus-operator/pkg/client/versioned"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
queue "k8s.io/client-go/util/workqueue"
miniov2 "github.com/minio/operator/pkg/apis/minio.min.io/v2"
clientset "github.com/minio/operator/pkg/client/clientset/versioned"
minioscheme "github.com/minio/operator/pkg/client/clientset/versioned/scheme"
jobinformers "github.com/minio/operator/pkg/client/informers/externalversions/job.min.io/v1alpha1"
informers "github.com/minio/operator/pkg/client/informers/externalversions/minio.min.io/v2"
stsInformers "github.com/minio/operator/pkg/client/informers/externalversions/sts.min.io/v1alpha1"
"github.com/minio/operator/pkg/resources/statefulsets"
)
const (
controllerAgentName = "minio-operator"
// ErrResourceExists is used as part of the Event 'reason' when a Tenant fails
// to sync due to a StatefulSet of the same name already existing.
ErrResourceExists = "ErrResourceExists"
// MessageResourceExists is the message used for Events when a Tenant
// fails to sync due to a StatefulSet already existing
MessageResourceExists = "Resource %q already exists and is not managed by MinIO Operator"
)
// Standard Status messages for Tenant
const (
StatusInitialized = "Initialized"
StatusProvisioningCIService = "Provisioning MinIO Cluster IP Service"
StatusProvisioningHLService = "Provisioning MinIO Headless Service"
StatusProvisioningStatefulSet = "Provisioning MinIO Statefulset"
StatusProvisioningConsoleService = "Provisioning Console Service"
StatusProvisioningKESStatefulSet = "Provisioning KES StatefulSet"
StatusProvisioningInitialUsers = "Provisioning initial users"
StatusProvisioningDefaultBuckets = "Provisioning default buckets"
StatusWaitingMinIOCert = "Waiting for MinIO TLS Certificate"
StatusWaitingMinIOClientCert = "Waiting for MinIO TLS Client Certificate"
StatusWaitingKESCert = "Waiting for KES TLS Certificate"
StatusUpdatingMinIOVersion = "Updating MinIO Version"
StatusUpdatingKES = "Updating KES"
StatusNotOwned = "Statefulset not controlled by operator"
StatusFailedAlreadyExists = "Another MinIO Tenant already exists in the namespace"
StatusTenantCredentialsNotSet = "Tenant credentials are not set properly"
StatusInconsistentMinIOVersions = "Different versions across MinIO Pools"
StatusRestartingMinIO = "Restarting MinIO"
StatusDecommissioningNotAllowed = "Pool Decommissioning Not Allowed"
)
// ErrMinIONotReady is the error returned when MinIO is not Ready
var ErrMinIONotReady = fmt.Errorf("MinIO is not ready")
// ErrMinIORestarting is the error returned when MinIO is restarting
var ErrMinIORestarting = fmt.Errorf("MinIO is restarting")
// Controller struct watches the Kubernetes API for changes to Tenant resources
type Controller struct {
// podName is the identifier of this instance
podName string
// namespacesToWatch restricts the action of the opreator to a list of namespaces
namespacesToWatch set.StringSet
// k8sClient is a kubernetes client
k8sClient client.Client
// kubeClientSet is a standard kubernetes clientset
kubeClientSet kubernetes.Interface
// minioClientSet is a clientset for our own API group
minioClientSet clientset.Interface
// promClient is a clientset for Prometheus service monitor
promClient promclientset.Interface
// statefulSetLister is able to list/get StatefulSets from a shared
// informer's store.
statefulSetLister appslisters.StatefulSetLister
// statefulSetListerSynced returns true if the StatefulSet shared informer
// has synced at least once.
statefulSetListerSynced cache.InformerSynced
// deploymentLister is able to list/get Deployments from a shared
// informer's store.
deploymentLister appslisters.DeploymentLister
// deploymentListerSynced returns true if the Deployment shared informer
// has synced at least once.
deploymentListerSynced cache.InformerSynced
// tenantsSynced returns true if the StatefulSet shared informer
// has synced at least once.
tenantsSynced cache.InformerSynced
// serviceLister is able to list/get Services from a shared informer's
// store.
serviceLister corelisters.ServiceLister
// serviceListerSynced returns true if the Service shared informer
// has synced at least once.
serviceListerSynced cache.InformerSynced
// queue is a rate limited work queue. This is used to queue work to be
// processed instead of performing it as soon as a change happens. This
// means we can ensure we only process a fixed amount of resources at a
// time, and makes it easy to ensure we are never processing the same item
// simultaneously in two different workers.
workqueue queue.RateLimitingInterface
// recorder is an event recorder for recording Event resources to the
// Kubernetes API.
recorder record.EventRecorder
// Use a go template to render the hosts string
hostsTemplate string
// currently running operator version
operatorVersion string
// HTTP Upgrade server instance
us *http.Server
// STS API server instance
sts *http.Server
// Client transport
transport *http.Transport
// monitor pods in the cluster to update the health information
podInformer cache.SharedIndexInformer
// healthCheckQueue is a rate limited work queue. This is used to queue work to be
// processed instead of performing it as soon as a change happens. This
// means we can ensure we only process a fixed amount of resources at a
// time, and makes it easy to ensure we are never processing the same item
// simultaneously in two different workers.
healthCheckQueue queue.RateLimitingInterface
// image being used in the operator deployment
operatorImage string
// policyBindingListerSynced returns true if the PolicyBinding shared informer
// has synced at least once.
policyBindingListerSynced cache.InformerSynced
// controllers denotes the list of components controlled
// by the controller. Each component is itself
// a controller. This handle is for supporting the abstraction.
controllers []*JobController
}
// EventType is Event type to handle
type EventType int
// Possible values of EventType
const (
STSServerNotification EventType = iota
LeaderElection
)
// EventNotification - structure to send messages through a channel regarding a error event to be handled
type EventNotification struct {
// Err the error to handle if any, null when is just a message
Err error
// Type the event type to handle
Type EventType
}
// NewController returns a new Operator Controller
func NewController(
podName string,
namespacesToWatch set.StringSet,
kubeClientSet kubernetes.Interface,
k8sClient client.Client,
minioClientSet clientset.Interface,
promClient promclientset.Interface,
statefulSetInformer appsinformers.StatefulSetInformer,
deploymentInformer appsinformers.DeploymentInformer,
podInformer coreinformers.PodInformer,
tenantInformer informers.TenantInformer,
policyBindingInformer stsInformers.PolicyBindingInformer,
serviceInformer coreinformers.ServiceInformer,
hostsTemplate,
operatorVersion string,
jobinformer jobinformers.MinIOJobInformer,
) *Controller {
// Create event broadcaster
// Add minio-controller types to the default Kubernetes Scheme so Events can be
// logged for minio-controller types.
minioscheme.AddToScheme(scheme.Scheme) //nolint:errcheck
klog.V(4).Info("Creating event broadcaster")
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartLogging(klog.Infof)
eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeClientSet.CoreV1().Events("")})
recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName})
// get operator deployment name
ns := miniov2.GetNSFromFile()
ctx := context.Background()
oprImg := DefaultOperatorImage
oprDep, err := kubeClientSet.AppsV1().Deployments(ns).Get(ctx, getOperatorDeploymentName(), metav1.GetOptions{})
if err == nil && oprDep != nil {
// assume we are the first container, just in case they changed the default name
if len(oprDep.Spec.Template.Spec.Containers) > 0 {
oprImg = oprDep.Spec.Template.Spec.Containers[0].Image
}
// attempt to iterate in case there's multiple containers
for _, c := range oprDep.Spec.Template.Spec.Containers {
if c.Name == "minio-operator" || c.Name == "operator" {
oprImg = c.Image
}
}
}
oprImg = env.Get(DefaultOperatorImageEnv, oprImg)
//controllerConfig := controllerConfig{
// serviceLister: serviceInformer.Lister(),
// kubeClientSet: kubeClientSet,
// statefulSetLister: statefulSetInformer.Lister(),
// deploymentLister: deploymentInformer.Lister(),
// recorder: recorder,
//}
controller := &Controller{
podName: podName,
namespacesToWatch: namespacesToWatch,
kubeClientSet: kubeClientSet,
k8sClient: k8sClient,
minioClientSet: minioClientSet,
promClient: promClient,
statefulSetLister: statefulSetInformer.Lister(),
statefulSetListerSynced: statefulSetInformer.Informer().HasSynced,
podInformer: podInformer.Informer(),
deploymentLister: deploymentInformer.Lister(),
deploymentListerSynced: deploymentInformer.Informer().HasSynced,
tenantsSynced: tenantInformer.Informer().HasSynced,
serviceLister: serviceInformer.Lister(),
serviceListerSynced: serviceInformer.Informer().HasSynced,
workqueue: queue.NewNamedRateLimitingQueue(MinIOControllerRateLimiter(), "Tenants"),
healthCheckQueue: queue.NewNamedRateLimitingQueue(MinIOControllerRateLimiter(), "TenantsHealth"),
recorder: recorder,
hostsTemplate: hostsTemplate,
operatorVersion: operatorVersion,
policyBindingListerSynced: policyBindingInformer.Informer().HasSynced,
operatorImage: oprImg,
controllers: []*JobController{
NewJobController(
jobinformer,
namespacesToWatch,
jobinformer.Lister(),
jobinformer.Informer().HasSynced,
kubeClientSet,
statefulSetInformer.Lister(),
recorder,
queue.NewNamedRateLimitingQueue(MinIOControllerRateLimiter(), "Tenants"),
minioClientSet,
),
},
}
// Initialize operator HTTP upgrade server handlers
controller.us = configureHTTPUpgradeServer()
// Initialize STS API server handlers
controller.sts = configureSTSServer(controller)
klog.Info("Setting up event handlers")
// Set up an event handler for when Tenant resources change
tenantInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: controller.enqueueTenant,
UpdateFunc: func(old, new interface{}) {
oldTenant := old.(*miniov2.Tenant)
newTenant := new.(*miniov2.Tenant)
if newTenant.ResourceVersion == oldTenant.ResourceVersion {
// Periodic resync will send update events for all known Tenants.
// Two different versions of the same Tenant will always have different RVs.
return
}
controller.enqueueTenant(new)
},
})
// Set up an event handler for when StatefulSet resources change. This
// handler will lookup the owner of the given StatefulSet, and if it is
// owned by a Tenant resource will enqueue that Tenant resource for
// processing. This way, we don't need to implement custom logic for
// handling StatefulSet resources. More info on this pattern:
// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-api-machinery/controllers.md
statefulSetInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: controller.handleObject,
UpdateFunc: func(old, new interface{}) {
newDepl := new.(*appsv1.StatefulSet)
oldDepl := old.(*appsv1.StatefulSet)
if newDepl.ResourceVersion == oldDepl.ResourceVersion {
// Periodic resync will send update events for all known StatefulSet.
// Two different versions of the same StatefulSet will always have different RVs.
return
}
controller.handleObject(new)
},
DeleteFunc: controller.handleObject,
})
deploymentInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: controller.handleObject,
UpdateFunc: func(old, new interface{}) {
newDepl := new.(*appsv1.Deployment)
oldDepl := old.(*appsv1.Deployment)
if newDepl.ResourceVersion == oldDepl.ResourceVersion {
// Periodic resync will send update events for all known Deployments.
// Two different versions of the same Deployments will always have different RVs.
return
}
controller.handleObject(new)
},
DeleteFunc: controller.handleObject,
})
podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: controller.handlePodChange,
UpdateFunc: func(old, new interface{}) {
newDepl := new.(*corev1.Pod)
oldDepl := old.(*corev1.Pod)
if newDepl.ResourceVersion == oldDepl.ResourceVersion {
// Periodic resync will send update events for all known Deployments.
// Two different versions of the same Deployments will always have different RVs.
return
}
controller.handlePodChange(new)
},
DeleteFunc: controller.handlePodChange,
})
return controller
}
// startUpgradeServer Starts the Upgrade tenant API server and notifies the start and stop via notificationChannel returned
func (c *Controller) startUpgradeServer(ctx context.Context) <-chan error {
notificationChannel := make(chan error)
go func() {
defer close(notificationChannel)
klog.Infof("Starting HTTP Upgrade Tenant Image server")
if err := c.us.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
// only notify on server failure, on http.ErrServerClosed the channel should be already closed
notificationChannel <- err
}
}()
return notificationChannel
}
// startUpgradeServer Starts the Upgrade tenant API server and notifies the start and stop via notificationChannel
func (c *Controller) startSTSAPIServer(ctx context.Context, notificationChannel chan<- *EventNotification) {
klog.Infof("Starting STS API server")
publicCertPath := miniov2.GetPublicCertFilePath("sts")
privateKeyPath := miniov2.GetPrivateKeyFilePath("sts")
if utils.GetOperatorRuntime() != common.OperatorRuntimeOpenshift {
publicCertPath, privateKeyPath = c.waitSTSTLSCert()
}
certsManager, err := xcerts.NewManager(ctx, publicCertPath, privateKeyPath, LoadX509KeyPair)
if err != nil {
klog.Errorf("HTTPS STS API server failed to load CA certificate: %v", err)
notificationChannel <- &EventNotification{
Type: STSServerNotification,
Err: err,
}
}
serverCertsManager = certsManager
c.sts.TLSConfig = c.createTLSConfig(serverCertsManager)
if err := c.sts.ListenAndServeTLS("", ""); !errors.Is(err, http.ErrServerClosed) {
// only notify on server failure, on http.ErrServerClosed the channel should be already closed
notificationChannel <- &EventNotification{
Type: STSServerNotification,
Err: err,
}
}
}
// leaderRun start the Controller and the API's
// When a new leader is elected this function is ran in the pod
func leaderRun(ctx context.Context, c *Controller, threadiness int, stopCh <-chan struct{}) {
// we declate the channel to communicate on servers errors
var upgradeServerChannel <-chan error
klog.Info("Waiting for Upgrade Server to start")
upgradeServerChannel = c.startUpgradeServer(ctx)
// Start the informer factories to begin populating the informer caches
klog.Info("Starting Tenant controller")
// Wait for the caches to be synced before starting workers
klog.Info("Waiting for informer caches to sync")
if ok := cache.WaitForCacheSync(stopCh, c.statefulSetListerSynced, c.deploymentListerSynced, c.tenantsSynced, c.policyBindingListerSynced); !ok {
panic("failed to wait for caches to sync")
}
klog.Info("Starting workers")
// Launch two workers to process Tenant resources
for i := 0; i < threadiness; i++ {
go wait.Until(c.runWorker, time.Second, stopCh)
}
klog.Info("Starting Job workers")
JobController := c.controllers[0]
// fmt.Println(controller.SyncHandler())
// Launch two workers to process Job resources
for i := 0; i < threadiness; i++ {
go wait.Until(JobController.runJobWorker, time.Second, stopCh)
go wait.Until(c.runWorker, time.Second, stopCh)
}
// Launch a single worker for Health Check reacting to Pod Changes
go wait.Until(c.runHealthCheckWorker, time.Second, stopCh)
// Launch a goroutine to monitor all Tenants
go c.recurrentTenantStatusMonitor(stopCh)
// 1) we need to make sure we have console TLS certificates (if enabled)
if isOperatorConsoleTLS() {
klog.Info("Waiting for Console TLS")
go func() {
if utils.GetOperatorRuntime() == common.OperatorRuntimeOpenshift {
klog.Infof("Console TLS is enabled, skipping TLS certificate generation on Openshift deployment")
} else {
klog.Infof("Console TLS is enabled, starting console TLS certificate setup")
err := c.recreateOperatorConsoleCertsIfRequired(ctx)
if err != nil {
panic(err)
}
klog.Infof("Restarting Console pods")
err = c.rolloutRestartDeployment(getConsoleDeploymentName())
if err != nil {
klog.Errorf("Console deployment didn't restart: %s", err)
}
}
}()
} else {
klog.Infof("Console TLS is not enabled")
}
// 2) we need to make sure we have STS API certificates (if enabled)
if IsSTSEnabled() {
go func() {
if utils.GetOperatorRuntime() == common.OperatorRuntimeOpenshift {
klog.Infof("STS is enabled, skipping TLS certificate generation on Openshift deployment")
} else {
klog.Infof("STS is enabled, starting API certificate setup")
c.generateSTSTLSCert()
}
}()
}
for {
select {
case err := <-upgradeServerChannel:
if err != http.ErrServerClosed {
klog.Errorf("Upgrade Server stopped: %v, going to restart", err)
upgradeServerChannel = c.startUpgradeServer(ctx)
}
// webserver was instructed to stop, do not attempt to restart
continue
case <-stopCh:
return
}
}
}
// Start will set up the event handlers for types we are interested in, as well
// as syncing informer caches and starting workers. It will block until stopCh
// is closed, at which point it will shutdown the workqueue and wait for
// workers to finish processing their current work items.
func (c *Controller) Start(threadiness int, stopCh <-chan struct{}) error {
// use a Go context so we can tell the leaderelection code when we
// want to step down
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// listen for interrupts or the Linux SIGTERM signal and cancel
// our context, which the leader election code will observe and
// step down
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
go func() {
<-ch
klog.Info("Received termination, signaling shutdown")
cancel()
}()
leaseLockName := "minio-operator-lock"
leaseLockNamespace := miniov2.GetNSFromFile()
// notificationChannel is a channel to notify errors or events
notificationChannel := make(chan *EventNotification)
defer close(notificationChannel)
// Request kubernetes version from Kube ApiServer
apiCsrVersion := certificates.GetCertificatesAPIVersion(c.kubeClientSet)
klog.Infof("Using Kubernetes CSR Version: %s", apiCsrVersion)
// we use the Lease lock type since edits to Leases are less common
// and fewer objects in the cluster watch "all Leases".
lock := &resourcelock.LeaseLock{
LeaseMeta: metav1.ObjectMeta{
Name: leaseLockName,
Namespace: leaseLockNamespace,
},
Client: c.kubeClientSet.CoordinationV1(),
LockConfig: resourcelock.ResourceLockConfig{
Identity: c.podName,
},
}
if IsSTSEnabled() {
// runSTS starts the STS API even if the pod is not the leader
klog.Info("Waiting for STS API to start")
go c.startSTSAPIServer(ctx, notificationChannel)
} else {
klog.Info("STS Api server is not enabled, not starting")
}
go func() {
// start the leader election code loop
leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
Lock: lock,
// IMPORTANT: you MUST ensure that any code you have that
// is protected by the lease must terminate **before**
// you call cancel. Otherwise, you could have a background
// loop still running and another process could
// get elected before your background loop finished, violating
// the stated goal of the lease.
ReleaseOnCancel: true,
LeaseDuration: 60 * time.Second,
RenewDeadline: 15 * time.Second,
RetryPeriod: 5 * time.Second,
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: func(ctx context.Context) {
// start the controller + API code
leaderRun(ctx, c, threadiness, stopCh)
},
OnStoppedLeading: func() {
// we can do cleanup here
klog.Infof("leader lost: %s", c.podName)
},
OnNewLeader: func(identity string) {
// we're notified when new leader elected
if identity == c.podName {
klog.Infof("%s: I am the leader, applying leader labels on myself", c.podName)
// Patch this pod so the main service uses it
p := []patchAnnotation{{
Op: "add",
Path: "/metadata/labels/operator",
Value: "leader",
}}
payloadBytes, err := json.Marshal(p)
if err != nil {
klog.Errorf("failed to marshal patch: %#v", err)
} else {
_, err = c.kubeClientSet.CoreV1().Pods(leaseLockNamespace).Patch(ctx, c.podName, types.JSONPatchType, payloadBytes, metav1.PatchOptions{})
if err != nil {
klog.Errorf("failed to patch operator leader pod: %+v", err)
}
}
} else {
klog.Infof("%s: is the leader, removing any leader labels that I '%s' might have", identity, c.podName)
// Patch this pod so the main service uses it
p := []patchAnnotation{{
Op: "remove",
Path: "/metadata/labels/operator",
}}
payloadBytes, err := json.Marshal(p)
if err != nil {
klog.Errorf("failed to marshal patch: %#v", err)
} else {
c.kubeClientSet.CoreV1().Pods(leaseLockNamespace).Patch(ctx, c.podName, types.JSONPatchType, payloadBytes, metav1.PatchOptions{})
}
}
},
},
})
notificationChannel <- &EventNotification{
Type: LeaderElection,
Err: nil,
}
}()
for {
select {
case oerr := <-notificationChannel:
switch oerr.Type {
case STSServerNotification:
if !errors.Is(oerr.Err, http.ErrServerClosed) {
klog.Errorf("STS API Server stopped: %v, going to restart", oerr.Err)
go c.startSTSAPIServer(ctx, notificationChannel)
}
case LeaderElection:
return nil
}
case <-stopCh:
return nil
}
}
}
// Stop is called to shutdown the controller
func (c *Controller) Stop() {
klog.Info("Stopping the minio controller webservers")
// Wait upto 5 secs and terminate all connections.
tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_ = c.us.Shutdown(tctx)
_ = c.sts.Shutdown(tctx)
cancel()
klog.Info("Stopping the minio controller")
c.workqueue.ShutDown()
c.healthCheckQueue.ShutDown()
}
// runWorker is a long-running function that will continually call the
// processNextWorkItem function in order to read and process a message on the
// workqueue.
func (c *Controller) runWorker() {
defer runtime.HandleCrash()
for c.processNextWorkItem() {
}
}
// runHealthCheckWorker is a long-running function that will continually call the
// processNextWorkItem function in order to read and process a message on the
// healthCheckQueue.
func (c *Controller) runHealthCheckWorker() {
defer runtime.HandleCrash()
for c.processNextHealthCheckItem() {
}
}
// processNextWorkItem will read a single work item off the workqueue and
// attempt to process it, by calling the syncHandler.
func (c *Controller) processNextWorkItem() bool {
obj, shutdown := c.workqueue.Get()
if shutdown {
return false
}
// We wrap this block in a func so we can defer c.workqueue.Done.
processItem := func(obj interface{}) error {
// We call Done here so the workqueue knows we have finished
// processing this item. We also must remember to call Forget if we
// do not want this work item being re-queued. For example, we do
// not call Forget if a transient error occurs, instead the item is
// put back on the workqueue and attempted again after a back-off
// period.
defer c.workqueue.Done(obj)
var key string
var ok bool
// We expect strings to come off the workqueue. These are of the
// form namespace/name. We do this as the delayed nature of the
// workqueue means the items in the informer cache may actually be
// more up to date that when the item was initially put onto the
// workqueue.
if key, ok = obj.(string); !ok {
// As the item in the workqueue is actually invalid, we call
// Forget here else we'd go into a loop of attempting to
// process a work item that is invalid.
c.workqueue.Forget(obj)
runtime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
klog.V(2).Infof("Key from workqueue: %s", key)
result, err := c.syncHandler(key)
switch {
case err != nil:
c.workqueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s", key, err.Error())
case result.RequeueAfter > 0:
// The result.RequeueAfter request will be lost, if it is returned
// along with a non-nil error. But this is intended as
// We need to drive to stable reconcile loops before queuing due
// to result.RequestAfter
c.workqueue.Forget(obj)
c.workqueue.AddAfter(key, result.RequeueAfter)
case result.Requeue:
c.workqueue.AddRateLimited(key)
default:
// Finally, if no error occurs we Forget this item so it does not
// get queued again until another change happens.
c.workqueue.Forget(obj)
klog.V(4).Infof("Successfully synced '%s'", key)
}
return nil
}
if err := processItem(obj); err != nil {
runtime.HandleError(err)
return true
}
return true
}
const slashSeparator = "/"
func key2NamespaceName(key string) (namespace, name string) {
key = strings.TrimPrefix(key, slashSeparator)
m := strings.Index(key, slashSeparator)
if m < 0 {
return "", key
}
return key[:m], key[m+len(slashSeparator):]
}
// syncHandler compares the actual state with the desired, and attempts to
// converge the two. It then updates the Status block of the Tenant resource
// with the current status of the resource.
func (c *Controller) syncHandler(key string) (Result, error) {
ctx := context.Background()
cOpts := metav1.CreateOptions{}
uOpts := metav1.UpdateOptions{}
// Convert the namespace/name string into a distinct namespace and name
if key == "" {
runtime.HandleError(fmt.Errorf("Invalid resource key: %s", key))
return WrapResult(Result{}, nil)
}
namespace, tenantName := key2NamespaceName(key)
if utils.GetOperatorRuntime() == common.OperatorRuntimeOpenshift {
err := c.checkOpenshiftSignerCACertInOperatorNamespace(ctx)
if err != nil {
klog.Errorf("Error checking openshift-csr-signer-ca secret, %#v", err)
}
}
// Get the Tenant resource with this namespace/name
tenant, err := c.minioClientSet.MinioV2().Tenants(namespace).Get(context.Background(), tenantName, metav1.GetOptions{})
if err != nil {
// The Tenant resource may no longer exist, in which case we stop processing.
if k8serrors.IsNotFound(err) {
runtime.HandleError(fmt.Errorf("Tenant '%s' in work queue no longer exists", key))
// Try to delete PrometheusConfig.
// Can't use the tenant. That's nil for sure
err = c.deletePrometheusAddlConfig(ctx, &miniov2.Tenant{
ObjectMeta: metav1.ObjectMeta{
Name: tenantName,
Namespace: namespace,
},
})
if err != nil {
// Just output the error. Will not retry.
runtime.HandleError(fmt.Errorf("DeletePrometheusAddlConfig '%s/%s' error:%s", namespace, tenantName, err.Error()))
}
// try to delete pvc if set ReclaimStorageLabel:true
pvcList := corev1.PersistentVolumeClaimList{}
listOpt := client.ListOptions{
Namespace: namespace,
}
client.MatchingLabels{
"v1.min.io/tenant": tenantName,
}.ApplyToList(&listOpt)
err := c.k8sClient.List(ctx, &pvcList, &listOpt)
if err != nil {
runtime.HandleError(fmt.Errorf("PersistentVolumeClaimList '%s/%s' error:%s", namespace, tenantName, err.Error()))
}
for _, pvc := range pvcList.Items {
if pvc.Labels[statefulsets.ReclaimStorageLabel] == "true" {
err := c.k8sClient.Delete(ctx, &pvc)
if err != nil {
runtime.HandleError(fmt.Errorf("Delete PersistentVolumeClaim '%s/%s/%s' error:%s", namespace, tenantName, pvc.Name, err.Error()))
}
}
}
return WrapResult(Result{}, nil)
}
// will retry after 5sec
return WrapResult(Result{RequeueAfter: time.Second * 5}, nil)
}
// Check the Sync Version to see if the tenant needs upgrade
if tenant, err = c.checkForUpgrades(ctx, tenant); err != nil {
return WrapResult(Result{}, err)
}
// Set any required default values and init Global variables
nsName := types.NamespacedName{Namespace: namespace, Name: tenantName}
// get combined configurations (tenant.env, tenant.credsSecret and tenant.Configuration) for tenant
tenantConfiguration, err := c.getTenantCredentials(ctx, tenant)
if err != nil {
if errors.Is(err, ErrEmptyRootCredentials) {
if _, err2 := c.updateTenantStatus(ctx, tenant, err.Error(), 0); err2 != nil {
klog.V(2).Infof(err2.Error())
}
c.recorder.Event(tenant, corev1.EventTypeWarning, "MissingCreds", "Tenant is missing root credentials")
return WrapResult(Result{}, nil)
}
return WrapResult(Result{}, err)
}
// get existing configuration from config.env
skipEnvVars, err := c.getTenantConfiguration(ctx, tenant)
if err != nil {
return WrapResult(Result{}, err)
}
// Check if we are decommissioning a pool before we ensure defaults, as that would populate a defaulted pool name
tenant, err = c.checkForPoolDecommission(ctx, key, tenant, tenantConfiguration)
if err != nil {
return WrapResult(Result{}, err)
}
tenant.EnsureDefaults()
// Validate the MinIO Tenant
if err = tenant.Validate(); err != nil {
klog.V(2).Infof(err.Error())
var err2 error
if _, err2 = c.updateTenantStatus(ctx, tenant, err.Error(), 0); err2 != nil {
klog.V(2).Infof(err2.Error())
}
// return nil so we don't re-queue this work item
return WrapResult(Result{}, nil)
}
// AutoCertEnabled verification is used to manage the tenant migration between v1 and v2
// Previous behavior was that AutoCert is disabled by default if RequestAutoCert is nil
// New behavior is that AutoCert is enabled by default if RequestAutoCert is nil
// In the future this support will be dropped
if tenant.Status.Certificates.AutoCertEnabled == nil {
autoCertEnabled := true
if tenant.Spec.RequestAutoCert == nil && tenant.APIVersion != "" {
// If we get certificate signing requests for MinIO is safe to assume the Tenant v1 was deployed using AutoCert
// otherwise AutoCert will be false
if certificates.GetCertificatesAPIVersion(c.kubeClientSet) == certificates.CSRV1 {
tenantCSR, err := c.kubeClientSet.CertificatesV1().CertificateSigningRequests().Get(ctx, tenant.MinIOCSRName(), metav1.GetOptions{})
if err != nil || tenantCSR == nil {
autoCertEnabled = false
}
} else {
tenantCSR, err := c.kubeClientSet.CertificatesV1beta1().CertificateSigningRequests().Get(ctx, tenant.MinIOCSRName(), metav1.GetOptions{})
if err != nil || tenantCSR == nil {
autoCertEnabled = false
}
}
} else {
autoCertEnabled = tenant.AutoCert()
}
if tenant, err = c.updateCertificatesStatus(ctx, tenant, autoCertEnabled); err != nil {
klog.V(2).Infof(err.Error())
}
}
// Custom certificates
if customCertificates, err := c.getCustomCertificates(ctx, tenant); err == nil {
if newTenant, err := c.updateCustomCertificatesStatus(ctx, tenant, customCertificates); err != nil {
klog.V(2).Infof(err.Error())
} else {
// Only change tenant if there was no error, otherwise tenant is being deleted
tenant = newTenant
}
} else {
klog.V(2).Infof(err.Error())
}
// validate the minio certificates
err = c.checkMinIOCertificatesStatus(ctx, tenant, nsName)
if err != nil {
klog.V(2).Infof("Error when consolidating tenant service: %v", err)
// will retry after 5sec
return WrapResult(Result{RequeueAfter: time.Second * 5}, nil)
}
// validate services
// Check MinIO S3 Endpoint Service
err = c.checkMinIOSvc(ctx, tenant, nsName)
if err != nil {
klog.V(2).Infof("error consolidating minio service: %s", err.Error())
return WrapResult(Result{}, err)
}
// Check Console Endpoint Service
err = c.checkConsoleSvc(ctx, tenant, nsName)
if err != nil {
klog.V(2).Infof("error consolidating console service: %s", err.Error())
return WrapResult(Result{}, err)
}
// Check MinIO Headless Service used for internode communication
err = c.checkMinIOHLSvc(ctx, tenant, nsName)
if err != nil {
klog.V(2).Infof("error consolidating headless service: %s", err.Error())
return WrapResult(Result{}, err)
}
// List all MinIO Tenants in this namespace.
li, err := c.minioClientSet.MinioV2().Tenants(tenant.Namespace).List(context.Background(), metav1.ListOptions{})
if err != nil {
return WrapResult(Result{}, err)
}
// Only 1 minio tenant per namespace allowed.
if len(li.Items) > 1 {
for _, t := range li.Items {
if t.Status.CurrentState != StatusInitialized {
if _, err = c.updateTenantStatus(ctx, &t, StatusFailedAlreadyExists, 0); err != nil {
return WrapResult(Result{}, err)
}
// return nil so we don't re-queue this work item
return WrapResult(Result{}, err)
}
}
}
// Create Tenant Services Accoutns for Tenant
err = c.checkAndCreateServiceAccount(ctx, tenant)
if err != nil {
return WrapResult(Result{}, err)
}
adminClnt, err := tenant.NewMinIOAdmin(tenantConfiguration, c.getTransport())
if err != nil {
if _, uerr := c.updateTenantStatus(ctx, tenant, StatusTenantCredentialsNotSet, 0); uerr != nil {
return WrapResult(Result{}, uerr)
}
klog.Errorf("Error initializing minio admin client: %v", err)
return WrapResult(Result{}, err)
}
// For each pool check if there is a stateful set
var totalAvailableReplicas int32
var images []string
err = c.checkKESStatus(ctx, tenant, totalAvailableReplicas, cOpts, uOpts, nsName)
if err != nil {
klog.V(2).Infof("Error checking KES state %v", err)
return WrapResult(Result{}, err)
}
// check if operator-ca-tls has to be updated or re-created in the tenant namespace
operatorCATLSExists, err := c.checkOperatorCAForTenant(ctx, tenant)
if err != nil {
// Don't return here as we get stuck when recreating the stateful set
klog.Infof("There was an error while updating the certificate %s", err)
}