forked from oracle/oracle-database-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshardingdatabase_controller.go
1783 lines (1600 loc) · 67.5 KB
/
shardingdatabase_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) 2022 Oracle and/or its affiliates.
**
** The Universal Permissive License (UPL), Version 1.0
**
** Subject to the condition set forth below, permission is hereby granted to any
** person obtaining a copy of this software, associated documentation and/or data
** (collectively the "Software"), free of charge and under any and all copyright
** rights in the Software, and any and all patent rights owned or freely
** licensable by each licensor hereunder covering either (i) the unmodified
** Software as contributed to or provided by such licensor, or (ii) the Larger
** Works (as defined below), to deal in both
**
** (a) the Software, and
** (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
** one is included with the Software (each a "Larger Work" to which the Software
** is contributed by such licensors),
**
** without restriction, including without limitation the rights to copy, create
** derivative works of, display, perform, and distribute the Software and make,
** use, sell, offer for sale, import, export, have made, and have sold the
** Software and the Larger Work(s), and to sublicense the foregoing rights on
** either these or other terms.
**
** This license is subject to the following condition:
** The above copyright notice and either this complete permission notice or at
** a minimum a reference to the UPL must be included in all copies or
** substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
*/
package controllers
import (
"context"
"encoding/json"
"fmt"
"reflect"
"strconv"
"time"
"github.com/go-logr/logr"
"github.com/oracle/oci-go-sdk/v65/common"
"github.com/oracle/oci-go-sdk/v65/ons"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
databasev1alpha1 "github.com/oracle/oracle-database-operator/apis/database/v1alpha1"
shardingv1 "github.com/oracle/oracle-database-operator/commons/sharding"
)
//Sharding Topology
type ShardingTopology struct {
topicid string
Instance *databasev1alpha1.ShardingDatabase
deltopology bool
onsProvider common.ConfigurationProvider
onsProviderFlag bool
rclient ons.NotificationDataPlaneClient
}
// ShardingDatabaseReconciler reconciles a ShardingDatabase object
type ShardingDatabaseReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
kubeClient kubernetes.Interface
kubeConfig clientcmd.ClientConfig
Recorder record.EventRecorder
osh []*ShardingTopology
}
// +kubebuilder:rbac:groups=database.oracle.com,resources=shardingdatabases,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=database.oracle.com,resources=shardingdatabases/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=database.oracle.com,resources=shardingdatabases/finalizers,verbs=get;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=pods;pods/log;pods/exec;secrets;services;events;nodes;configmaps;persistentvolumeclaims;namespaces,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=pods/exec,verbs=create
// +kubebuilder:rbac:groups=apps,resources=statefulsets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups='',resources=statefulsets/finalizers,verbs=get;list;watch;create;update;patch;delete
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the ShardingDatabase object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.6.4/pkg/reconcile
func (r *ShardingDatabaseReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
//ctx := context.Background()
//_ = r.Log.WithValues("shardingdatabase", req.NamespacedName)
// your logic here
var i int32
//var ShardImageLatest []databasev1alpha1.ShardSpec
var OraCatalogSpex databasev1alpha1.CatalogSpec
var OraShardSpex databasev1alpha1.ShardSpec
var OraGsmSpex databasev1alpha1.GsmSpec
var result ctrl.Result
var isShardTopologyDeleteTrue bool = false
//var msg string
var err error
var idx int
var stateType string
resultNq := ctrl.Result{Requeue: false}
resultQ := ctrl.Result{Requeue: true, RequeueAfter: 30 * time.Second}
var nilErr error = nil
// On every reconcile, we will call setCrdLifeCycleState
// To understand this, please refer https://sdk.operatorframework.io/docs/building-operators/golang/advanced-topics/
// https://github.com/kubernetes/apimachinery/blob/master/pkg/api/meta/conditions.go
// Kube Client Config Setup
if r.kubeConfig == nil && r.kubeClient == nil {
r.kubeConfig, r.kubeClient, err = shardingv1.GetK8sClientConfig(r.Client)
if err != nil {
return ctrl.Result{}, err
}
}
// Fetch the ProvShard instance
instance := &databasev1alpha1.ShardingDatabase{}
err = r.Client.Get(context.TODO(), req.NamespacedName, instance)
if err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile req.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
return ctrl.Result{}, nil
}
// Error reading the object - requeue the req.
return ctrl.Result{}, err
}
_, instFlag := r.checkProvInstance(instance)
// assinging osh instance
if !instFlag {
// Sharding Topolgy Struct Assignment
// ======================================
osh := &ShardingTopology{}
osh.Instance = instance
r.osh = append(r.osh, osh)
}
defer r.setCrdLifeCycleState(instance, &result, &err, &stateType)
// =============================== Check Deletion TimeStamp========
// Check if the ProvOShard instance is marked to be deleted, which is
// // indicated by the deletion timestamp being set.
err, isShardTopologyDeleteTrue = r.finalizerShardingDatabaseInstance(instance)
if err != nil {
//r.setCrdLifeCycleState(instance, &result, &err, stateType)
result = resultNq
if isShardTopologyDeleteTrue == true {
err = nilErr
return result, err
} else {
return result, err
}
}
// ======== Setting the flag and Index to be used later in this function ========
idx, instFlag = r.checkProvInstance(instance)
if !instFlag {
//r.setCrdLifeCycleState(instance, &result, &err, stateType)
result = resultNq
return result, fmt.Errorf("DId not fid the instance in checkProvInstance")
}
// ================================ OCI Notification Provider ===========
r.getOnsConfigProvider(instance, idx)
// =============================== Checking Namespace ==============
if instance.Spec.Namespace != "" {
err = shardingv1.AddNamespace(instance, r.Client, r.Log)
if err != nil {
//r.setCrdLifeCycleState(instance, &result, &err, stateType)
result = resultNq
return result, err
}
} else {
instance.Spec.Namespace = "default"
}
// ======================== Validate Specs ==============
err = r.validateSpex(instance, idx)
if err != nil {
//r.setCrdLifeCycleState(instance, &result, &err, stateType)
result = resultNq
return result, err
}
// ========================= Service Setup For Catalog===================
// Following check and loop will make sure to create the service
for i = 0; i < int32(len(instance.Spec.Catalog)); i++ {
OraCatalogSpex = instance.Spec.Catalog[i]
result, err = r.createService(instance, shardingv1.BuildServiceDefForCatalog(instance, 0, OraCatalogSpex, "local"))
if err != nil {
result = resultNq
return result, err
}
if instance.Spec.IsExternalSvc {
result, err = r.createService(instance, shardingv1.BuildServiceDefForCatalog(instance, 0, OraCatalogSpex, "external"))
if err != nil {
result = resultNq
return result, err
}
}
}
// ================================ Catalog Setup ===================
if len(instance.Spec.Catalog) > 0 {
for i = 0; i < int32(len(instance.Spec.Catalog)); i++ {
OraCatalogSpex = instance.Spec.Catalog[i]
// See if StatefulSets already exists and create if it doesn't
result, err = r.deployStatefulSet(instance, shardingv1.BuildStatefulSetForCatalog(instance, OraCatalogSpex), "CATALOG")
if err != nil {
result = resultNq
return result, err
}
}
}
// ========================= Service Setup For Gsm===================
// Following check and loop will make sure if we need service per replica pod or on a single pod
// if user set replicasize greater than 1 but also set instance.Spec.OraDbPvcName then only one service will be created and one pod
for i = 0; i < int32(len(instance.Spec.Gsm)); i++ {
OraGsmSpex = instance.Spec.Gsm[i]
result, err = r.createService(instance, shardingv1.BuildServiceDefForGsm(instance, 0, OraGsmSpex, "local"))
if err != nil {
result = resultNq
return result, err
}
if instance.Spec.IsExternalSvc {
result, err = r.createService(instance, shardingv1.BuildServiceDefForGsm(instance, 0, OraGsmSpex, "external"))
if err != nil {
result = resultNq
return result, err
}
}
}
// ========================= Service Setup For Gsm===================
// Following check and loop will make sure if we need service per replica pod or on a single pod
// if user set replicasize greater than 1 but also set instance.Spec.OraDbPvcName then only one service will be created and one pod
// ================================ Gsm Setup ===================
if len(instance.Spec.Gsm) > 0 {
// for _, OraGsmSpex := range instance.Spec.Gsm
for i = 0; i < int32(len(instance.Spec.Gsm)); i++ {
OraGsmSpex = instance.Spec.Gsm[i]
result, err = r.deployStatefulSet(instance, shardingv1.BuildStatefulSetForGsm(instance, OraGsmSpex), "GSM")
if err != nil {
result = resultNq
return result, err
}
}
}
// ========================= Service Setup For Shard===================
// Following check and loop will make sure if we need service per replica pod or on a single pod
// if user set replicasize greater than 1 but also set instance.Spec.OraDbPvcName then only one service will be created and one pod
for i = 0; i < int32(len(instance.Spec.Shard)); i++ {
OraShardSpex = instance.Spec.Shard[i]
if OraShardSpex.IsDelete != true {
result, err = r.createService(instance, shardingv1.BuildServiceDefForShard(instance, 0, OraShardSpex, "local"))
if err != nil {
result = resultNq
return result, err
}
if instance.Spec.IsExternalSvc {
result, err = r.createService(instance, shardingv1.BuildServiceDefForShard(instance, 0, OraShardSpex, "external"))
if err != nil {
result = resultNq
return result, err
}
}
}
}
// ================================ Shard Setup ===================
if len(instance.Spec.Shard) > 0 {
for i = 0; i < int32(len(instance.Spec.Shard)); i++ {
OraShardSpex = instance.Spec.Shard[i]
if OraShardSpex.IsDelete != true {
result, err = r.deployStatefulSet(instance, shardingv1.BuildStatefulSetForShard(instance, OraShardSpex), "SHARD")
if err != nil {
result = resultNq
return result, err
}
}
}
}
//================ Validate the GSM and Catalog before procedding for Shard Setup ==============
// If the GSM and Catalog is not configured then Requeue the loop unless it returns nil
// Until GSM and Catalog is configured, the topology state remain provisioning
err = r.validateGsmnCatalog(instance)
if err != nil {
// r.setCrdLifeCycleState(instance, &result, &err, stateType)
// time.Sleep(30 * time.Second)
err = nilErr
result = resultQ
return result, err
}
//set the Waiting state for Reconcile loop
// Loop will be requeued only if Shard Statefulset is not ready or not configured.
// Till that time Reconcilation loop will remain in blocked state
// if the err is return because of Shard is not ready then blocked state is rmeoved and reconcilation state is set
err = r.addPrimaryShards(instance, idx)
if err != nil {
// time.Sleep(30 * time.Second)
err = nilErr
result = resultQ
return result, err
}
// Loop will be requeued only if Standby Shard Statefulset is not ready or not configured.
// Till that time Reconcilation loop will remain in blocked state
// if the err is return because of Shard is not ready then blocked state is rmeoved and reconcilation state is
err = r.addStandbyShards(instance, idx)
if err != nil {
// time.Sleep(30 * time.Second)
err = nilErr
result = resultQ
return result, err
}
// we don't need to run the requeue loop but still putting this condition to address any unkown situation
// delShard function set the state to blocked and we do not allow any other operationn while delete is going on
err = r.delGsmShard(instance, idx)
if err != nil {
// time.Sleep(30 * time.Second)
err = nilErr
result = resultQ
return result, err
}
// ====================== Update Setup for Catalog ==============================
for i = 0; i < int32(len(instance.Spec.Catalog)); i++ {
OraCatalogSpex = instance.Spec.Catalog[i]
sfSet, catalogPod, err := r.validateInvidualCatalog(instance, OraCatalogSpex, int(i))
if err != nil {
shardingv1.LogMessages("INFO", "Catalog "+sfSet.Name+" is not in available state.", nil, instance, r.Log)
result = resultNq
return result, err
}
result, err = shardingv1.UpdateProvForCatalog(instance, OraCatalogSpex, r.Client, sfSet, catalogPod, r.Log)
if err != nil {
shardingv1.LogMessages("INFO", "Error Occurred during catalog update operation.", nil, instance, r.Log)
result = resultNq
return result, err
}
}
// ====================== Update Setup for Shard ==============================
for i = 0; i < int32(len(instance.Spec.Shard)); i++ {
OraShardSpex = instance.Spec.Shard[i]
if OraShardSpex.IsDelete != true {
sfSet, shardPod, err := r.validateShard(instance, OraShardSpex, int(i))
if err != nil {
shardingv1.LogMessages("INFO", "Shard "+sfSet.Name+" is not in available state.", nil, instance, r.Log)
result = resultNq
return result, err
}
result, err = shardingv1.UpdateProvForShard(instance, OraShardSpex, r.Client, sfSet, shardPod, r.Log)
if err != nil {
shardingv1.LogMessages("INFO", "Error Occurred during shard update operation..", nil, instance, r.Log)
result = resultNq
return result, err
}
}
}
// ====================== Update Setup for Gsm ==============================
for i = 0; i < int32(len(instance.Spec.Gsm)); i++ {
OraGsmSpex = instance.Spec.Gsm[i]
sfSet, gsmPod, err := r.validateInvidualGsm(instance, OraGsmSpex, int(i))
if err != nil {
shardingv1.LogMessages("INFO", "Gsm "+sfSet.Name+" is not in available state.", nil, instance, r.Log)
result = resultNq
return result, err
}
result, err = shardingv1.UpdateProvForGsm(instance, OraGsmSpex, r.Client, sfSet, gsmPod, r.Log)
if err != nil {
shardingv1.LogMessages("INFO", "Error Occurred during GSM update operation.", nil, instance, r.Log)
result = resultNq
return result, err
}
}
// Calling updateShardTopology to update the entire sharding topology
// This is required because we just executed updateShard,updateCatalog and UpdateGsm
// If some state has changed it will update the topology
err = r.updateShardTopologyStatus(instance)
if err != nil {
// time.Sleep(30 * time.Second)
result = resultQ
err = nilErr
return result, err
}
stateType = string(databasev1alpha1.CrdReconcileCompeleteState)
// r.setCrdLifeCycleState(instance, &result, &err, stateType)
// Set error to ni to avoid reconcilation state reconcilation error as we are passing err to setCrdLifeCycleState
shardingv1.LogMessages("INFO", "Completed the Sharding topology setup reconcilation loop.", nil, instance, r.Log)
result = resultNq
err = nilErr
return result, err
}
// SetupWithManager sets up the controller with the Manager.
// The default concurrent reconcilation loop is 1
// Check https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/controller#Options to under MaxConcurrentReconciles
func (r *ShardingDatabaseReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&databasev1alpha1.ShardingDatabase{}).
Owns(&appsv1.StatefulSet{}).
Owns(&corev1.Service{}).
Owns(&corev1.Pod{}).
WithEventFilter(r.eventFilterPredicate()).
WithOptions(controller.Options{MaxConcurrentReconciles: 50}). //MaxConcurrentReconciles is the maximum number of concurrent Reconciles which can be run. Defaults to 1
Complete(r)
}
// ###################### Event Filter Predicate ######################
func (r *ShardingDatabaseReconciler) eventFilterPredicate() predicate.Predicate {
return predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool {
return true
},
UpdateFunc: func(e event.UpdateEvent) bool {
return true
},
DeleteFunc: func(e event.DeleteEvent) bool {
_, podOk := e.Object.GetLabels()["statefulset.kubernetes.io/pod-name"]
for i := 0; i < len(r.osh); i++ {
if r.osh[i] != nil {
oshInst := r.osh[i]
if oshInst.deltopology == true {
break
}
if e.Object.GetLabels()[string(databasev1alpha1.ShardingDelLabelKey)] == string(databasev1alpha1.ShardingDelLabelTrueValue) {
break
}
if podOk {
delObj := e.Object.(*corev1.Pod)
if e.Object.GetLabels()["type"] == "Shard" && e.Object.GetLabels()["app"] == "OracleSharding" && e.Object.GetLabels()["oralabel"] == oshInst.Instance.Name {
if delObj.DeletionTimestamp != nil {
go r.gsmInvitedNodeOp(oshInst.Instance, delObj.Name)
}
}
if e.Object.GetLabels()["type"] == "Catalog" && e.Object.GetLabels()["app"] == "OracleSharding" && e.Object.GetLabels()["oralabel"] == oshInst.Instance.Name {
if delObj.DeletionTimestamp != nil {
go r.gsmInvitedNodeOp(oshInst.Instance, delObj.Name)
}
}
}
}
}
return true
},
}
}
// ================== Function to get the Notification controller ==============
func (r *ShardingDatabaseReconciler) getOnsConfigProvider(instance *databasev1alpha1.ShardingDatabase, idx int,
) {
var err error
if instance.Spec.NsConfigMap != "" && instance.Spec.NsSecret != "" && r.osh[idx].onsProviderFlag != true {
cmName := instance.Spec.NsConfigMap
secName := instance.Spec.NsSecret
shardingv1.LogMessages("DEBUG", "Received parameters are "+shardingv1.GetFmtStr(cmName)+","+shardingv1.GetFmtStr(secName), nil, instance, r.Log)
region, user, tenancy, passphrase, fingerprint, topicid := shardingv1.ReadConfigMap(cmName, instance, r.Client, r.Log)
privatekey := shardingv1.ReadSecret(secName, instance, r.Client, r.Log)
r.osh[idx].topicid = topicid
r.osh[idx].onsProvider = common.NewRawConfigurationProvider(tenancy, user, region, fingerprint, privatekey, &passphrase)
r.osh[idx].rclient, err = ons.NewNotificationDataPlaneClientWithConfigurationProvider(r.osh[idx].onsProvider)
if err != nil {
msg := "Error occurred in getting the OCI notification service based client."
r.osh[idx].onsProviderFlag = false
r.Log.Error(err, msg)
shardingv1.LogMessages("Error", msg, nil, instance, r.Log)
} else {
r.osh[idx].onsProviderFlag = true
}
}
}
// ================== Function the Message ==============
func (r *ShardingDatabaseReconciler) sendMessage(instance *databasev1alpha1.ShardingDatabase, title string, body string) {
idx, instFlag := r.checkProvInstance(instance)
if instFlag {
if r.osh[idx].onsProviderFlag {
shardingv1.SendNotification(title, body, instance, r.osh[idx].topicid, r.osh[idx].rclient, r.Log)
}
}
}
func (r *ShardingDatabaseReconciler) publishEvents(instance *databasev1alpha1.ShardingDatabase, eventMsg string, state string) {
if state == string(databasev1alpha1.AvailableState) || state == string(databasev1alpha1.AddingShardState) || state == string(databasev1alpha1.ShardOnlineState) || state == string(databasev1alpha1.ProvisionState) || state == string(databasev1alpha1.DeletingState) || state == string(databasev1alpha1.Terminated) {
r.Recorder.Eventf(instance, corev1.EventTypeNormal, "State Change", eventMsg)
} else {
r.Recorder.Eventf(instance, corev1.EventTypeWarning, "State Change", eventMsg)
}
}
// ================== Function to check insytance deletion timestamp and activate the finalizer code ========
func (r *ShardingDatabaseReconciler) finalizerShardingDatabaseInstance(instance *databasev1alpha1.ShardingDatabase,
) (error, bool) {
isProvOShardToBeDeleted := instance.GetDeletionTimestamp() != nil
if isProvOShardToBeDeleted {
if controllerutil.ContainsFinalizer(instance, shardingv1.ShardingDatabaseFinalizer) {
// Run finalization logic for finalizer. If the
// finalization logic fails, don't remove the finalizer so
// that we can retry during the next reconciliation.
if err := r.finalizeShardingDatabase(instance); err != nil {
return err, false
}
// Remove finalizer. Once all finalizers have been
// removed, the object will be deleted.
controllerutil.RemoveFinalizer(instance, shardingv1.ShardingDatabaseFinalizer)
err := r.Client.Update(context.TODO(), instance)
if err != nil {
return err, false
}
}
// Send true because delete is in progress and it is a custom delete message
// We don't need to print custom err stack as we are deleting the topology
return fmt.Errorf("delete of the sharding topology is in progress"), true
}
// Add finalizer for this CR
if instance.DeletionTimestamp == nil {
if !controllerutil.ContainsFinalizer(instance, shardingv1.ShardingDatabaseFinalizer) {
if err := r.addFinalizer(instance); err != nil {
return err, false
}
}
}
return nil, false
}
// ========================== FInalizer Section ===================
func (r *ShardingDatabaseReconciler) addFinalizer(instance *databasev1alpha1.ShardingDatabase) error {
reqLogger := r.Log.WithValues("instance.Spec.Namespace", instance.Spec.Namespace, "instance.Name", instance.Name)
controllerutil.AddFinalizer(instance, shardingv1.ShardingDatabaseFinalizer)
// Update CR
err := r.Client.Update(context.TODO(), instance)
if err != nil {
reqLogger.Error(err, "Failed to update Sharding Database with finalizer")
return err
}
return nil
}
func (r *ShardingDatabaseReconciler) finalizeShardingDatabase(instance *databasev1alpha1.ShardingDatabase) error {
// TODO(user): Add the cleanup steps that the operator needs to do before the CR
// can be deleted. Examples of finalizers include performing backups and deleting
// resources that are not owned by this CR, like a PVC.
var i int32
var err error
var pvcName string
idx, _ := r.checkProvInstance(instance)
sfSetFound := &appsv1.StatefulSet{}
svcFound := &corev1.Service{}
r.osh[idx].deltopology = true
if len(instance.Spec.Shard) > 0 {
for i = 0; i < int32(len(instance.Spec.Shard)); i++ {
OraShardSpex := instance.Spec.Shard[i]
sfSetFound, err = shardingv1.CheckSfset(OraShardSpex.Name, instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), sfSetFound)
if err != nil {
return err
}
if instance.Spec.IsDeleteOraPvc && len(instance.Spec.StorageClass) > 0 {
pvcName = OraShardSpex.Name + "-oradata-vol4-" + OraShardSpex.Name + "-0"
err = shardingv1.DelPvc(pvcName, instance, r.Client, r.Log)
if err != nil {
return err
}
}
}
}
}
if len(instance.Spec.Gsm) > 0 {
for i = 0; i < int32(len(instance.Spec.Gsm)); i++ {
OraGsmSpex := instance.Spec.Gsm[i]
sfSetFound, err = shardingv1.CheckSfset(OraGsmSpex.Name, instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), sfSetFound)
if err != nil {
return err
}
if instance.Spec.IsDeleteOraPvc && len(instance.Spec.StorageClass) > 0 {
pvcName = OraGsmSpex.Name + "-oradata-vol4-" + OraGsmSpex.Name + "-0"
err = shardingv1.DelPvc(pvcName, instance, r.Client, r.Log)
if err != nil {
return err
}
}
}
}
}
if len(instance.Spec.Catalog) > 0 {
for i = 0; i < int32(len(instance.Spec.Catalog)); i++ {
OraCatalogSpex := instance.Spec.Catalog[i]
// See if StatefulSets already exists and create if it doesn't
sfSetFound, err = shardingv1.CheckSfset(OraCatalogSpex.Name, instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), sfSetFound)
if err != nil {
return err
}
if instance.Spec.IsDeleteOraPvc && len(instance.Spec.StorageClass) > 0 {
pvcName = OraCatalogSpex.Name + "-oradata-vol4-" + OraCatalogSpex.Name + "-0"
err = shardingv1.DelPvc(pvcName, instance, r.Client, r.Log)
if err != nil {
return err
}
}
}
}
}
if len(instance.Spec.Shard) > 0 {
for i = 0; i < int32(len(instance.Spec.Shard)); i++ {
if instance.Spec.IsExternalSvc {
svcFound, err = shardingv1.CheckSvc(instance.Spec.Shard[i].Name+strconv.FormatInt(int64(0), 10)+"-svc", instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), svcFound)
if err != nil {
return err
}
}
}
svcFound, err = shardingv1.CheckSvc(instance.Spec.Shard[i].Name, instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), svcFound)
if err != nil {
return err
}
}
}
}
if len(instance.Spec.Catalog) > 0 {
for i = 0; i < int32(len(instance.Spec.Catalog)); i++ {
if instance.Spec.IsExternalSvc {
svcFound, err = shardingv1.CheckSvc(instance.Spec.Catalog[i].Name+strconv.FormatInt(int64(0), 10)+"-svc", instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), svcFound)
if err != nil {
return err
}
}
}
svcFound, err = shardingv1.CheckSvc(instance.Spec.Catalog[i].Name, instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), svcFound)
if err != nil {
return err
}
}
}
}
if len(instance.Spec.Gsm) > 0 {
for i = 0; i < int32(len(instance.Spec.Gsm)); i++ {
// See if StatefulSets already exists and create if it doesn't
if len(instance.Spec.Gsm[i].PvcName) == 0 {
if instance.Spec.IsExternalSvc {
svcFound, err = shardingv1.CheckSvc(instance.Spec.Gsm[i].Name+strconv.FormatInt(int64(i), 10)+"-svc", instance, r.Client)
if err == nil {
// See if StatefulSets already exists and delete if it doesn't
err = r.Client.Delete(context.Background(), svcFound)
if err != nil {
return err
}
}
}
svcFound, err = shardingv1.CheckSvc(instance.Spec.Gsm[i].Name, instance, r.Client)
if err == nil {
// See if StatefulSets already exists and delete if it doesn't
err = r.Client.Delete(context.Background(), svcFound)
if err != nil {
return err
}
}
if instance.Spec.IsExternalSvc {
svcFound, err = shardingv1.CheckSvc(instance.Spec.Gsm[i].Name+strconv.FormatInt(int64(0), 10)+"-svc", instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), svcFound)
if err != nil {
return err
}
}
}
} else {
if instance.Spec.IsExternalSvc {
svcFound, err = shardingv1.CheckSvc(instance.Spec.Gsm[i].Name+strconv.FormatInt(int64(0), 10)+"-svc", instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), svcFound)
if err != nil {
return err
}
}
}
svcFound, err = shardingv1.CheckSvc(instance.Spec.Gsm[i].Name, instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), svcFound)
if err != nil {
return err
}
}
}
}
}
// List the stateful for this instance's statefulset and delete the all the stateful set which belong to this instance as a left over
sfList := &appsv1.StatefulSetList{}
listOpts := []client.ListOption{
client.InNamespace(instance.Namespace),
client.MatchingLabels(shardingv1.LabelsForProvShardKind(instance, "shard")),
}
err = r.Client.List(context.TODO(), sfList, listOpts...)
if err == nil {
for _, sset := range sfList.Items {
sfSetFound, err = shardingv1.CheckSfset(sset.Name, instance, r.Client)
if err == nil {
// See if StatefulSets already exists and create if it doesn't
err = r.Client.Delete(context.Background(), sfSetFound)
if err != nil {
return err
}
}
}
}
r.osh[idx].deltopology = false
//r.osh[idx].addSem.Release(1)
//r.osh[idx].delSem.Release(1)
//instance1 := &shardingv1alpha1.ProvShard{}
r.osh[idx].Instance = &databasev1alpha1.ShardingDatabase{}
//r.osh[idx] = nil
return nil
}
//==============
// Get the current instance
func (r *ShardingDatabaseReconciler) checkProvInstance(instance *databasev1alpha1.ShardingDatabase,
) (int, bool) {
var status bool = false
var idx int
for i := 0; i < len(r.osh); i++ {
idx = i
if r.osh[i] != nil {
if !r.osh[i].deltopology {
if r.osh[i].Instance.Name == instance.Name {
status = true
break
}
}
}
}
return idx, status
}
// =========== validate Specs ============
func (r *ShardingDatabaseReconciler) validateSpex(instance *databasev1alpha1.ShardingDatabase, idx int) error {
var eventMsg string
var eventErr string = "Spec Error"
lastSuccSpec, err := instance.GetLastSuccessfulSpec()
if err != nil {
return nil
}
// Check if last Successful update nil or not
if lastSuccSpec == nil {
// Logic to check if inital Spec is good or not
// Once the initial Spec is been validated then update the last Sucessful Spec
err = instance.UpdateLastSuccessfulSpec(r.Client)
if err != nil {
return err
}
} else {
// if the last sucessful spec is not nil
// check the parameters which cannot be changed
if lastSuccSpec.Namespace != instance.Spec.Namespace {
eventMsg = "ShardingDatabase CRD resource " + shardingv1.GetFmtStr(instance.Name) + " namespace changed from " + shardingv1.GetFmtStr(lastSuccSpec.Namespace) + " to " + shardingv1.GetFmtStr(instance.Spec.Namespace) + ". This change is not allowed."
r.Recorder.Eventf(instance, corev1.EventTypeWarning, eventErr, eventMsg)
return fmt.Errorf("instance spec has changed and namespace change is not supported")
}
if lastSuccSpec.DbImage != instance.Spec.DbImage {
eventMsg = "ShardingDatabase CRD resource " + shardingv1.GetFmtStr(instance.Name) + " DBImage changed from " + shardingv1.GetFmtStr(lastSuccSpec.DbImage) + " to " + shardingv1.GetFmtStr(instance.Spec.DbImage) + ". This change is not allowed."
r.Recorder.Eventf(instance, corev1.EventTypeWarning, eventErr, eventMsg)
return fmt.Errorf("instance spec has changed and DbImage change is not supported")
}
if lastSuccSpec.GsmImage != instance.Spec.GsmImage {
eventMsg = "ShardingDatabase CRD resource " + shardingv1.GetFmtStr(instance.Name) + " GsmImage changed from " + shardingv1.GetFmtStr(lastSuccSpec.GsmImage) + " to " + shardingv1.GetFmtStr(instance.Spec.GsmImage) + ". This change is not allowed."
r.Recorder.Eventf(instance, corev1.EventTypeWarning, eventErr, eventMsg)
return fmt.Errorf("instance spec has changed and GsmImage change is not supported")
}
if lastSuccSpec.StorageClass != instance.Spec.StorageClass {
eventMsg = "ShardingDatabase CRD resource " + shardingv1.GetFmtStr(instance.Name) + " StorageClass changed from " + shardingv1.GetFmtStr(lastSuccSpec.StorageClass) + " to " + shardingv1.GetFmtStr(instance.Spec.StorageClass) + ". This change is not allowed."
r.Recorder.Eventf(instance, corev1.EventTypeWarning, eventErr, eventMsg)
return fmt.Errorf("instance spec has changed and StorageClass change is not supported")
}
// Compare Env variables for shard begins here
if !r.comapreShardEnvVariables(instance, lastSuccSpec) {
return fmt.Errorf("change of Shard env variables are not")
}
// Compare Env variables for catalog begins here
if !r.comapreCatalogEnvVariables(instance, lastSuccSpec) {
return fmt.Errorf("change of Catalog env variables are not")
}
// Compare env variable for Catalog ends here
if !r.comapreGsmEnvVariables(instance, lastSuccSpec) {
return fmt.Errorf("change of GSM env variables are not")
}
}
return nil
}
// Compare GSM Env Variables
func (r *ShardingDatabaseReconciler) comapreGsmEnvVariables(instance *databasev1alpha1.ShardingDatabase, lastSuccSpec *databasev1alpha1.ShardingDatabaseSpec) bool {
var eventMsg string
var eventErr string = "Spec Error"
var i, j int32
if len(instance.Spec.Gsm) > 0 {
for i = 0; i < int32(len(instance.Spec.Gsm)); i++ {
OraGsmSpex := instance.Spec.Gsm[i]
for j = 0; j < int32(len(lastSuccSpec.Gsm)); j++ {
if OraGsmSpex.Name == lastSuccSpec.Gsm[j].Name {
if !reflect.DeepEqual(OraGsmSpex.EnvVars, lastSuccSpec.Gsm[j].EnvVars) {
eventMsg = "ShardingDatabase CRD resource " + shardingv1.GetFmtStr(instance.Name) + " env vairable changes are not supported."
r.Recorder.Eventf(instance, corev1.EventTypeWarning, eventErr, eventMsg)
return false
}
}
// child for loop ens here
}
//Main For loop ends here
}
}
return true
}
func (r *ShardingDatabaseReconciler) comapreCatalogEnvVariables(instance *databasev1alpha1.ShardingDatabase, lastSuccSpec *databasev1alpha1.ShardingDatabaseSpec) bool {
var eventMsg string
var eventErr string = "Spec Error"
var i, j int32
if len(instance.Spec.Catalog) > 0 {
for i = 0; i < int32(len(instance.Spec.Catalog)); i++ {
OraCatalogSpex := instance.Spec.Catalog[i]
for j = 0; j < int32(len(lastSuccSpec.Catalog)); j++ {
if OraCatalogSpex.Name == lastSuccSpec.Catalog[j].Name {
if !reflect.DeepEqual(OraCatalogSpex.EnvVars, lastSuccSpec.Catalog[j].EnvVars) {
eventMsg = "ShardingDatabase CRD resource " + shardingv1.GetFmtStr(instance.Name) + " env vairable changes are not supported."
r.Recorder.Eventf(instance, corev1.EventTypeWarning, eventErr, eventMsg)
return false
}
}
// child for loop ens here
}
//Main For loop ends here
}
}
return true
}
func (r *ShardingDatabaseReconciler) comapreShardEnvVariables(instance *databasev1alpha1.ShardingDatabase, lastSuccSpec *databasev1alpha1.ShardingDatabaseSpec) bool {
var eventMsg string
var eventErr string = "Spec Error"
var i, j int32
if len(instance.Spec.Shard) > 0 {
for i = 0; i < int32(len(instance.Spec.Shard)); i++ {
OraShardSpex := instance.Spec.Shard[i]
for j = 0; j < int32(len(lastSuccSpec.Shard)); j++ {
if OraShardSpex.Name == lastSuccSpec.Shard[j].Name {
if !reflect.DeepEqual(OraShardSpex.EnvVars, lastSuccSpec.Shard[j].EnvVars) {
eventMsg = "ShardingDatabase CRD resource " + shardingv1.GetFmtStr(instance.Name) + " env vairable changes are not supported."
r.Recorder.Eventf(instance, corev1.EventTypeWarning, eventErr, eventMsg)
return false
}
}
// child for loop ens here
}
//Main For loop ends here
}
}
return true
}
//===== Set the CRD resource life cycle state ========
func (r *ShardingDatabaseReconciler) setCrdLifeCycleState(instance *databasev1alpha1.ShardingDatabase, result *ctrl.Result, err *error, stateType *string) {
var metaCondition metav1.Condition
var updateFlag = false
if *stateType == "ReconcileWaiting" {
metaCondition = shardingv1.GetMetaCondition(instance, result, err, *stateType, string(databasev1alpha1.CrdReconcileWaitingReason))
updateFlag = true
} else if *stateType == "ReconcileComplete" {
metaCondition = shardingv1.GetMetaCondition(instance, result, err, *stateType, string(databasev1alpha1.CrdReconcileCompleteReason))
updateFlag = true
} else if result.Requeue {
metaCondition = shardingv1.GetMetaCondition(instance, result, err, string(databasev1alpha1.CrdReconcileQueuedState), string(databasev1alpha1.CrdReconcileQueuedReason))
updateFlag = true
} else if *err != nil {
metaCondition = shardingv1.GetMetaCondition(instance, result, err, string(databasev1alpha1.CrdReconcileErrorState), string(databasev1alpha1.CrdReconcileErrorReason))
updateFlag = true
} else {
}
if updateFlag == true {
if len(instance.Status.CrdStatus) > 0 {
//meta.SetStatusCondition()
meta.RemoveStatusCondition(&instance.Status.CrdStatus, metaCondition.Type)
}
meta.SetStatusCondition(&instance.Status.CrdStatus, metaCondition)
// Always refresh status before a reconcile
r.Client.Status().Update(context.TODO(), instance)
}