-
Notifications
You must be signed in to change notification settings - Fork 48
/
nova_controller.go
2025 lines (1819 loc) · 68.1 KB
/
nova_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 2022.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"fmt"
"strings"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
k8s_errors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/go-logr/logr"
"github.com/openstack-k8s-operators/lib-common/modules/common"
"github.com/openstack-k8s-operators/lib-common/modules/common/condition"
"github.com/openstack-k8s-operators/lib-common/modules/common/endpoint"
"github.com/openstack-k8s-operators/lib-common/modules/common/env"
helper "github.com/openstack-k8s-operators/lib-common/modules/common/helper"
job "github.com/openstack-k8s-operators/lib-common/modules/common/job"
"github.com/openstack-k8s-operators/lib-common/modules/common/labels"
common_rbac "github.com/openstack-k8s-operators/lib-common/modules/common/rbac"
"github.com/openstack-k8s-operators/lib-common/modules/common/secret"
"github.com/openstack-k8s-operators/lib-common/modules/common/tls"
util "github.com/openstack-k8s-operators/lib-common/modules/common/util"
novav1 "github.com/openstack-k8s-operators/nova-operator/api/v1beta1"
"github.com/openstack-k8s-operators/nova-operator/pkg/nova"
"github.com/openstack-k8s-operators/nova-operator/pkg/novaapi"
memcachedv1 "github.com/openstack-k8s-operators/infra-operator/apis/memcached/v1beta1"
rabbitmqv1 "github.com/openstack-k8s-operators/infra-operator/apis/rabbitmq/v1beta1"
keystonev1 "github.com/openstack-k8s-operators/keystone-operator/api/v1beta1"
mariadbv1 "github.com/openstack-k8s-operators/mariadb-operator/api/v1beta1"
)
// NovaReconciler reconciles a Nova object
type NovaReconciler struct {
ReconcilerBase
}
// GetLogger returns a logger object with a prefix of "controller.name" and additional controller context fields
func (r *NovaReconciler) GetLogger(ctx context.Context) logr.Logger {
return log.FromContext(ctx).WithName("Controllers").WithName("Nova")
}
// +kubebuilder:rbac:groups=nova.openstack.org,resources=nova,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=nova.openstack.org,resources=nova/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=nova.openstack.org,resources=nova/finalizers,verbs=update;patch
// +kubebuilder:rbac:groups=mariadb.openstack.org,resources=mariadbdatabases,verbs=get;list;watch;create;update;patch;delete;
// +kubebuilder:rbac:groups=mariadb.openstack.org,resources=mariadbdatabases/finalizers,verbs=update;patch
// +kubebuilder:rbac:groups=mariadb.openstack.org,resources=mariadbaccounts,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=mariadb.openstack.org,resources=mariadbaccounts/finalizers,verbs=update;patch
// +kubebuilder:rbac:groups=keystone.openstack.org,resources=keystoneapis,verbs=get;list;watch;
// +kubebuilder:rbac:groups=keystone.openstack.org,resources=keystoneservices,verbs=get;list;watch;create;update;patch;delete;
// +kubebuilder:rbac:groups=keystone.openstack.org,resources=keystoneendpoints,verbs=get;list;watch;create;update;patch;delete;
// +kubebuilder:rbac:groups=rabbitmq.openstack.org,resources=transporturls,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=memcached.openstack.org,resources=memcacheds,verbs=get;list;watch;update;patch
// +kubebuilder:rbac:groups=memcached.openstack.org,resources=memcacheds/finalizers,verbs=update;patch
// service account, role, rolebinding
// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=roles,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=rolebindings,verbs=get;list;watch;create;update;patch
// service account permissions that are needed to grant permission to the above
// +kubebuilder:rbac:groups="security.openshift.io",resourceNames=anyuid,resources=securitycontextconstraints,verbs=use
// +kubebuilder:rbac:groups="",resources=pods,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups=core,resources=secrets,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 Nova 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/[email protected]/pkg/reconcile
func (r *NovaReconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, _err error) {
Log := r.GetLogger(ctx)
// Fetch the NovaAPI instance that needs to be reconciled
instance := &novav1.Nova{}
err := r.Client.Get(ctx, req.NamespacedName, instance)
if err != nil {
if k8s_errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected.
// For additional cleanup logic use finalizers. Return and don't requeue.
Log.Info("Nova instance not found, probably deleted before reconciled. Nothing to do.")
return ctrl.Result{}, nil
}
// Error reading the object - requeue the request.
Log.Error(err, "Failed to read the Nova instance.")
return ctrl.Result{}, err
}
h, err := helper.NewHelper(
instance,
r.Client,
r.Kclient,
r.Scheme,
Log,
)
if err != nil {
Log.Error(err, "Failed to create lib-common Helper")
return ctrl.Result{}, err
}
Log.Info("Reconciling")
// Save a copy of the conditions so that we can restore the LastTransitionTime
// when a condition's state doesn't change.
savedConditions := instance.Status.Conditions.DeepCopy()
// initialize status fields
if err = r.initStatus(instance); err != nil {
return ctrl.Result{}, err
}
instance.Status.ObservedGeneration = instance.Generation
// Always update the instance status when exiting this function so we can
// persist any changes happened during the current reconciliation.
defer func() {
// update the Ready condition based on the sub conditions
if allSubConditionIsTrue(instance.Status) {
instance.Status.Conditions.MarkTrue(
condition.ReadyCondition, condition.ReadyMessage)
} else {
// something is not ready so reset the Ready condition
instance.Status.Conditions.MarkUnknown(
condition.ReadyCondition, condition.InitReason, condition.ReadyInitMessage)
// and recalculate it based on the state of the rest of the conditions
instance.Status.Conditions.Set(
instance.Status.Conditions.Mirror(condition.ReadyCondition))
}
condition.RestoreLastTransitionTimes(&instance.Status.Conditions, savedConditions)
err := h.PatchInstance(ctx, instance)
if err != nil {
_err = err
return
}
}()
if !instance.DeletionTimestamp.IsZero() {
return ctrl.Result{}, r.reconcileDelete(ctx, h, instance)
}
// We create a KeystoneService CR later and that will automatically get the
// Nova finalizer. So we need a finalizer on the ourselves too so that
// during Nova CR delete we can have a chance to remove the finalizer from
// the our KeystoneService so that is also deleted.
updated := controllerutil.AddFinalizer(instance, h.GetFinalizer())
if updated {
Log.Info("Added finalizer to ourselves")
// we intentionally return immediately to force the deferred function
// to persist the Instance with the finalizer. We need to have our own
// finalizer persisted before we try to create the KeystoneService with
// our finalizer to avoid orphaning the KeystoneService.
return ctrl.Result{}, nil
}
// Service account, role, binding
rbacRules := []rbacv1.PolicyRule{
{
APIGroups: []string{"security.openshift.io"},
ResourceNames: []string{"anyuid"},
Resources: []string{"securitycontextconstraints"},
Verbs: []string{"use"},
},
{
APIGroups: []string{""},
Resources: []string{"pods"},
Verbs: []string{"create", "get", "list", "watch", "update", "patch", "delete"},
},
}
rbacResult, err := common_rbac.ReconcileRbac(ctx, h, instance, rbacRules)
if err != nil {
return rbacResult, err
} else if (rbacResult != ctrl.Result{}) {
return rbacResult, nil
}
// ensure MariaDBAccount exists. This account record may be created by
// openstack-operator or the cloud operator up front without a specific
// MariaDBDatabase configured yet. Otherwise, a MariaDBAccount CR is
// created here with a generated username as well as a secret with
// generated password. The MariaDBAccount is created without being
// yet associated with any MariaDBDatabase.
_, _, err = mariadbv1.EnsureMariaDBAccount(
ctx, h, instance.Spec.APIDatabaseAccount,
instance.Namespace, false, "nova_api",
)
if err != nil {
instance.Status.Conditions.Set(condition.FalseCondition(
mariadbv1.MariaDBAccountReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
mariadbv1.MariaDBAccountNotReadyMessage,
err.Error()))
return ctrl.Result{}, err
}
instance.Status.Conditions.MarkTrue(
mariadbv1.MariaDBAccountReadyCondition,
mariadbv1.MariaDBAccountReadyMessage,
)
// There is a webhook validation that ensures that there is always cell0 in
// the cellTemplates
cell0Template := instance.Spec.CellTemplates[novav1.Cell0Name]
expectedSelectors := []string{
instance.Spec.PasswordSelectors.Service,
instance.Spec.PasswordSelectors.MetadataSecret,
}
_, result, secret, err := ensureSecret(
ctx,
types.NamespacedName{Namespace: instance.Namespace, Name: instance.Spec.Secret},
expectedSelectors,
h.GetClient(),
&instance.Status.Conditions,
r.RequeueTimeout,
)
if (err != nil || result != ctrl.Result{}) {
return result, err
}
instance.Status.Conditions.MarkTrue(condition.InputReadyCondition, condition.InputReadyMessage)
_, err = ensureMemcached(ctx, h, instance.Namespace, instance.Spec.MemcachedInstance, &instance.Status.Conditions)
if err != nil {
return ctrl.Result{}, err
}
err = r.ensureKeystoneServiceUser(ctx, h, instance)
if err != nil {
return ctrl.Result{}, err
}
// We have to wait until our service is registered to keystone
if !instance.Status.Conditions.IsTrue(condition.KeystoneServiceReadyCondition) {
Log.Info("Waiting for the KeystoneService to become Ready")
return ctrl.Result{}, nil
}
keystoneInternalAuthURL, keystonePublicAuthURL, err := r.getKeystoneAuthURL(
ctx, h, instance)
if err != nil {
return ctrl.Result{}, err
}
// We create the API DB separately from the Cell DBs as we want to report
// its status separately and we need to pass the API DB around for Cells
// having up-call support
// NOTE(gibi): We don't return on error or if the DB is not ready yet. We
// move forward and kick off the rest of the work we can do (e.g. creating
// Cell DBs and Cells without up-call support). Eventually we rely on the
// watch to get reconciled if the status of the API DB resource changes.
apiDB, apiDBStatus, apiDBError := r.ensureAPIDB(ctx, h, instance)
switch apiDBStatus {
case nova.DBFailed:
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAPIDBReadyCondition,
condition.ErrorReason,
condition.SeverityError,
condition.DBReadyErrorMessage,
apiDBError.Error(),
))
case nova.DBCreating:
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAPIDBReadyCondition,
condition.ErrorReason,
condition.SeverityError,
condition.DBReadyRunningMessage,
))
case nova.DBCompleted:
instance.Status.Conditions.MarkTrue(novav1.NovaAPIDBReadyCondition, condition.DBReadyMessage)
default:
return ctrl.Result{}, fmt.Errorf("invalid DatabaseStatus from ensureAPIDB: %d", apiDBStatus)
}
// We need to create a list of cellNames to iterate on and as the map
// iteration order is undefined we need to make sure that cell0 is the
// first to allow dependency handling during ensureCell calls.
orderedCellNames := []string{novav1.Cell0Name}
for cellName := range instance.Spec.CellTemplates {
if cellName != novav1.Cell0Name {
orderedCellNames = append(orderedCellNames, cellName)
}
}
// Create the Cell DBs. Note that we are not returning on error or if the
// DB creation is still in progress. We move forward with whatever we can
// and relay on the watch to get reconciled if some of the resources change
// status
cellDBs := map[string]*nova.Database{}
var failedDBs []string
var creatingDBs []string
for _, cellName := range orderedCellNames {
cellTemplate := instance.Spec.CellTemplates[cellName]
cellDB, status, err := r.ensureCellDB(ctx, h, instance, cellName, cellTemplate)
switch status {
case nova.DBFailed:
failedDBs = append(failedDBs, fmt.Sprintf("%s(%v)", cellName, err.Error()))
case nova.DBCreating:
creatingDBs = append(creatingDBs, cellName)
case nova.DBCompleted:
default:
return ctrl.Result{}, fmt.Errorf("invalid DatabaseStatus from ensureCellDB: %d for cell %s", status, cellName)
}
cellDBs[cellName] = &nova.Database{Database: cellDB, Status: status}
}
if len(failedDBs) > 0 {
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAllCellsDBReadyCondition,
condition.ErrorReason,
condition.SeverityError,
novav1.NovaAllCellsDBReadyErrorMessage,
strings.Join(failedDBs, ",")))
} else if len(creatingDBs) > 0 {
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAllCellsDBReadyCondition,
condition.ErrorReason,
condition.SeverityError,
novav1.NovaAllCellsDBReadyCreatingMessage,
strings.Join(creatingDBs, ",")))
} else { // we have no DB in failed or creating status so all DB is ready
instance.Status.Conditions.MarkTrue(
novav1.NovaAllCellsDBReadyCondition, novav1.NovaAllCellsDBReadyMessage)
}
// Create TransportURLs to access the message buses of each cell. Cell0
// message bus is always the same as the top level API message bus so
// we create API MQ separately first
apiTransportURL, apiMQStatus, apiMQError := r.ensureMQ(
ctx, h, instance, instance.Name+"-api-transport", instance.Spec.APIMessageBusInstance)
switch apiMQStatus {
case nova.MQFailed:
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAPIMQReadyCondition,
condition.ErrorReason,
condition.SeverityError,
novav1.NovaAPIMQReadyErrorMessage,
apiMQError.Error(),
))
case nova.MQCreating:
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAPIMQReadyCondition,
condition.ErrorReason,
condition.SeverityError,
novav1.NovaAPIMQReadyCreatingMessage,
))
case nova.MQCompleted:
instance.Status.Conditions.MarkTrue(
novav1.NovaAPIMQReadyCondition, novav1.NovaAPIMQReadyMessage)
default:
return ctrl.Result{}, fmt.Errorf("invalid MessageBusStatus from for the API MQ: %d", apiMQStatus)
}
cellMQs := map[string]*nova.MessageBus{}
var failedMQs []string
var creatingMQs []string
for _, cellName := range orderedCellNames {
var cellTransportURL string
var status nova.MessageBusStatus
var err error
cellTemplate := instance.Spec.CellTemplates[cellName]
// cell0 does not need its own cell message bus it uses the
// API message bus instead
if cellName == novav1.Cell0Name {
cellTransportURL = apiTransportURL
status = apiMQStatus
err = apiMQError
} else {
cellTransportURL, status, err = r.ensureMQ(
ctx, h, instance, instance.Name+"-"+cellName+"-transport", cellTemplate.CellMessageBusInstance)
}
switch status {
case nova.MQFailed:
failedMQs = append(failedMQs, fmt.Sprintf("%s(%v)", cellName, err.Error()))
case nova.MQCreating:
creatingMQs = append(creatingMQs, cellName)
case nova.MQCompleted:
default:
return ctrl.Result{}, fmt.Errorf("invalid MessageBusStatus from ensureMQ: %d for cell %s", status, cellName)
}
cellMQs[cellName] = &nova.MessageBus{TransportURL: cellTransportURL, Status: status}
}
if len(failedMQs) > 0 {
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAllCellsMQReadyCondition,
condition.ErrorReason,
condition.SeverityError,
novav1.NovaAllCellsMQReadyErrorMessage,
strings.Join(failedMQs, ",")))
} else if len(creatingMQs) > 0 {
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAllCellsMQReadyCondition,
condition.ErrorReason,
condition.SeverityError,
novav1.NovaAllCellsMQReadyCreatingMessage,
strings.Join(creatingMQs, ",")))
} else { // we have no MQ in failed or creating status so all MQ is ready
instance.Status.Conditions.MarkTrue(
novav1.NovaAllCellsMQReadyCondition, novav1.NovaAllCellsMQReadyMessage)
}
// Kick of the creation of Cells. We skip over those cells where the cell
// DB or MQ is not yet created and those which needs API DB access but
// cell0 is not ready yet
failedCells := []string{}
deployingCells := []string{}
mappingCells := []string{}
discoveringCells := []string{}
skippedCells := []string{}
readyCells := []string{}
cells := map[string]*novav1.NovaCell{}
allCellsReady := true
for _, cellName := range orderedCellNames {
cellTemplate := instance.Spec.CellTemplates[cellName]
cellDB := cellDBs[cellName]
cellMQ := cellMQs[cellName]
if cellDB.Status != nova.DBCompleted {
allCellsReady = false
skippedCells = append(skippedCells, cellName)
Log.Info("Skipping NovaCell as waiting for the cell DB to be created",
"CellName", cellName)
continue
}
if cellMQ.Status != nova.MQCompleted {
allCellsReady = false
skippedCells = append(skippedCells, cellName)
Log.Info("Skipping NovaCell as waiting for the cell MQ to be created",
"CellName", cellName)
continue
}
// The cell0 is always handled first in the loop as we iterate on
// orderedCellNames. So for any other cells we can assume that if cell0
// is not in the list then cell0 is not ready
cell0Ready := (cells[novav1.Cell0Name] != nil && cells[novav1.Cell0Name].IsReady())
if cellName != novav1.Cell0Name && cellTemplate.HasAPIAccess && !cell0Ready {
allCellsReady = false
skippedCells = append(skippedCells, cellName)
Log.Info("Skip NovaCell as cell0 is not ready yet and this cell needs API DB access", "CellName", cellName)
continue
}
cell, status, err := r.ensureCell(
ctx, h, instance, cellName, cellTemplate,
cellDB.Database, apiDB, cellMQ.TransportURL,
keystoneInternalAuthURL, secret,
)
cells[cellName] = cell
switch status {
case nova.CellDeploying:
deployingCells = append(deployingCells, cellName)
case nova.CellMapping:
mappingCells = append(mappingCells, cellName)
case nova.CellComputeDiscovering:
discoveringCells = append(discoveringCells, cellName)
case nova.CellFailed, nova.CellMappingFailed, nova.CellComputeDiscoveryFailed:
failedCells = append(failedCells, fmt.Sprintf("%s(%v)", cellName, err.Error()))
case nova.CellReady:
readyCells = append(readyCells, cellName)
}
allCellsReady = allCellsReady && status == nova.CellReady
}
Log.Info("Cell statuses",
"waiting", skippedCells,
"deploying", deployingCells,
"mapping", mappingCells,
"discovering", discoveringCells,
"ready", readyCells,
"failed", failedCells,
"all cells ready", allCellsReady)
if len(failedCells) > 0 {
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAllCellsReadyCondition,
condition.ErrorReason,
condition.SeverityError,
novav1.NovaAllCellsReadyErrorMessage,
strings.Join(failedCells, ","),
))
} else if len(deployingCells)+len(mappingCells)+len(discoveringCells) > 0 {
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAllCellsReadyCondition,
condition.RequestedReason,
condition.SeverityWarning,
novav1.NovaAllCellsReadyNotReadyMessage,
strings.Join(append(deployingCells, mappingCells...), ","),
))
} else if len(skippedCells) > 0 {
instance.Status.Conditions.Set(condition.FalseCondition(
novav1.NovaAllCellsReadyCondition,
condition.InitReason,
condition.SeverityWarning,
novav1.NovaAllCellsReadyWaitingMessage,
strings.Join(skippedCells, ","),
))
}
if allCellsReady {
instance.Status.Conditions.MarkTrue(novav1.NovaAllCellsReadyCondition, novav1.NovaAllCellsReadyMessage)
}
// Don't move forward with the top level service creations like NovaAPI
// until cell0 is ready as top level services need cell0 to register in
if cell0, ok := cells[novav1.Cell0Name]; !ok || !cell0.IsReady() ||
cell0.Generation > cell0.Status.ObservedGeneration {
// we need to stop here until cell0 is ready
Log.Info("Waiting for cell0 to become Ready before creating the top level services")
return ctrl.Result{}, nil
}
topLevelSecretName, err := r.ensureTopLevelSecret(ctx, h, instance, apiTransportURL, secret)
if err != nil {
return ctrl.Result{}, err
}
result, err = r.ensureAPI(
ctx, instance, cell0Template,
cellDBs[novav1.Cell0Name].Database, apiDB,
keystoneInternalAuthURL, keystonePublicAuthURL,
topLevelSecretName,
)
if err != nil {
return result, err
}
result, err = r.ensureScheduler(
ctx, instance, cell0Template,
cellDBs[novav1.Cell0Name].Database, apiDB, keystoneInternalAuthURL,
topLevelSecretName,
)
if err != nil {
return result, err
}
if *instance.Spec.MetadataServiceTemplate.Enabled {
result, err = r.ensureMetadata(
ctx, instance, cell0Template,
cellDBs[novav1.Cell0Name].Database, apiDB, keystoneInternalAuthURL,
topLevelSecretName,
)
if err != nil {
return result, err
}
} else {
// The NovaMetadata is explicitly disable so we delete its deployment
// if exists
err = r.ensureMetadataDeleted(ctx, instance)
if err != nil {
return ctrl.Result{}, err
}
instance.Status.Conditions.Remove(novav1.NovaMetadataReadyCondition)
instance.Status.MetadataServiceReadyCount = 0
}
// remove finalizers from unused MariaDBAccount records but ONLY if
// ensureAPIDB finished
if apiDBStatus == nova.DBCompleted {
err = mariadbv1.DeleteUnusedMariaDBAccountFinalizers(ctx, h, "nova-api", instance.Spec.APIDatabaseAccount, instance.Namespace)
if err != nil {
return ctrl.Result{}, err
}
}
// We need to check and delete cells
novaCellList := &novav1.NovaCellList{}
listOpts := []client.ListOption{
client.InNamespace(instance.Namespace),
}
if err := r.Client.List(ctx, novaCellList, listOpts...); err != nil {
return ctrl.Result{}, err
}
for _, cr := range novaCellList.Items {
_, ok := instance.Spec.CellTemplates[cr.Spec.CellName]
if !ok {
err := r.ensureCellDeleted(ctx, h, instance,
cr.Spec.CellName, apiTransportURL,
secret, apiDB, cellDBs[novav1.Cell0Name].Database.GetDatabaseHostname(), cells[novav1.Cell0Name])
if err != nil {
return ctrl.Result{}, err
}
Log.Info("Cell deleted", "cell", cr.Spec.CellName)
delete(instance.Status.RegisteredCells, cr.Name)
}
}
Log.Info("Successfully reconciled")
return ctrl.Result{}, nil
}
func (r *NovaReconciler) ensureAccountDeletedIfOwned(
ctx context.Context,
h *helper.Helper,
instance *novav1.Nova,
accountName string,
) error {
Log := r.GetLogger(ctx)
account, err := mariadbv1.GetAccount(ctx, h, accountName, instance.Namespace)
if err != nil && !k8s_errors.IsNotFound(err) {
return err
}
if k8s_errors.IsNotFound(err) {
// Nothing to delete
return nil
}
// If it is not created by us, we don't clean it up
if !OwnedBy(account, instance) {
Log.Info("MariaDBAccount in not owned by Nova, not deleting", "account", account)
return nil
}
// NOTE(gibi): We need to delete the Secret first and then the Account
// otherwise we cannot retry the Secret deletion when the Account is
// gone as we will not know the name of the Secret. This logic should
// be moved to the mariadb-operator.
err = secret.DeleteSecretsWithName(ctx, h, account.Spec.Secret, instance.Namespace)
if err != nil && !k8s_errors.IsNotFound(err) {
return err
}
err = r.Client.Delete(ctx, account)
if err != nil && !k8s_errors.IsNotFound(err) {
return err
}
Log.Info("Deleted MariaDBAccount", "account", account)
return nil
}
func (r *NovaReconciler) ensureCellDeleted(
ctx context.Context,
h *helper.Helper,
instance *novav1.Nova,
cellName string,
apiTransportURL string,
topLevelSecret corev1.Secret,
apiDB *mariadbv1.Database,
APIDatabaseHostname string,
cell0 *novav1.NovaCell,
) error {
Log := r.GetLogger(ctx)
cell := &novav1.NovaCell{}
fullCellName := types.NamespacedName{
Name: getNovaCellCRName(instance.Name, cellName),
Namespace: instance.GetNamespace(),
}
err := r.Client.Get(ctx, fullCellName, cell)
if k8s_errors.IsNotFound(err) {
// We cannot do further cleanup of the MariaDBDatabase and
// MariaDBAccount as their name is only available in the NovaCell CR
// since the cell definition is removed from the Nova CR already.
return nil
}
if err != nil {
return err
}
// If it is not created by us, we don't touch it
if !OwnedBy(cell, instance) {
Log.Info("Cell isn't defined in the Nova, but there is a "+
"Cell CR not owned by us. Not deleting it.",
"cell", cell)
return nil
}
dbName, accountName := novaapi.ServiceName+"-"+cell.Spec.CellName, cell.Spec.CellDatabaseAccount
configHash, scriptName, configName, err := r.ensureNovaManageJobSecret(ctx, h, instance,
cell0, topLevelSecret, APIDatabaseHostname, apiTransportURL, apiDB)
if err != nil {
return err
}
inputHash, err := util.HashOfInputHashes(configHash)
if err != nil {
return err
}
labels := map[string]string{
common.AppSelector: NovaLabelPrefix,
}
jobDef := nova.CellDeleteJob(instance, cell, configName, scriptName, inputHash, labels)
job := job.NewJob(
jobDef, cell.Name+"-cell-delete",
instance.Spec.PreserveJobs, r.RequeueTimeout,
inputHash)
_, err = job.DoJob(ctx, h)
if err != nil {
return err
}
secretName := getNovaCellCRName(instance.Name, cellName)
err = secret.DeleteSecretsWithName(ctx, h, secretName, instance.Namespace)
if err != nil && !k8s_errors.IsNotFound(err) {
return err
}
configSecret, scriptSecret := r.getNovaManageJobSecretNames(cell)
err = secret.DeleteSecretsWithName(ctx, h, configSecret, instance.Namespace)
if err != nil && !k8s_errors.IsNotFound(err) {
return err
}
err = secret.DeleteSecretsWithName(ctx, h, scriptSecret, instance.Namespace)
if err != nil && !k8s_errors.IsNotFound(err) {
return err
}
// Delete transportURL cr
transportURL := &rabbitmqv1.TransportURL{
ObjectMeta: metav1.ObjectMeta{
Name: instance.Name + "-" + cellName + "-transport",
Namespace: instance.Namespace,
},
}
err = r.Client.Delete(ctx, transportURL)
if err != nil && !k8s_errors.IsNotFound(err) {
return err
}
err = mariadbv1.DeleteDatabaseAndAccountFinalizers(
ctx, h, dbName, accountName, instance.Namespace)
if err != nil {
return err
}
err = r.ensureAccountDeletedIfOwned(ctx, h, instance, accountName)
if err != nil {
return err
}
database := &mariadbv1.MariaDBDatabase{
ObjectMeta: metav1.ObjectMeta{
Name: dbName,
Namespace: instance.Namespace,
},
}
err = r.Client.Delete(ctx, database)
if err != nil && !k8s_errors.IsNotFound(err) {
return err
}
Log.Info("Deleted MariaDBDatabase", "database", database)
// Finally we delete the NovaCell CR. We need to do it as the last step
// otherwise we cannot retry the above cleanup as we won't have the data
// what to clean up.
err = r.Client.Delete(ctx, cell)
if err != nil && k8s_errors.IsNotFound(err) {
return err
}
Log.Info("Cell isn't defined in the Nova CR, so it is deleted", "cell", cell)
return nil
}
func (r *NovaReconciler) initStatus(
instance *novav1.Nova,
) error {
if err := r.initConditions(instance); err != nil {
return err
}
if instance.Status.RegisteredCells == nil {
instance.Status.RegisteredCells = map[string]string{}
}
if instance.Status.DiscoveredCells == nil {
instance.Status.DiscoveredCells = map[string]string{}
}
return nil
}
func (r *NovaReconciler) initConditions(
instance *novav1.Nova,
) error {
//
// initialize status
//
if instance.Status.Conditions == nil {
instance.Status.Conditions = condition.Conditions{}
}
// initialize all conditions to Unknown
cl := condition.CreateList(
// TODO(gibi): Initialize each condition the controller reports
// here to Unknown. By default only the top level Ready condition is
// created by Conditions.Init()
condition.UnknownCondition(
condition.InputReadyCondition,
condition.InitReason,
condition.InputReadyInitMessage,
),
condition.UnknownCondition(
novav1.NovaAPIDBReadyCondition,
condition.InitReason,
condition.DBReadyInitMessage,
),
condition.UnknownCondition(
novav1.NovaAPIReadyCondition,
condition.InitReason,
novav1.NovaAPIReadyInitMessage,
),
condition.UnknownCondition(
novav1.NovaAllCellsDBReadyCondition,
condition.InitReason,
condition.DBReadyInitMessage,
),
condition.UnknownCondition(
novav1.NovaAllCellsReadyCondition,
condition.InitReason,
novav1.NovaAllCellsReadyInitMessage,
),
condition.UnknownCondition(
condition.KeystoneServiceReadyCondition,
condition.InitReason,
"Service registration not started",
),
condition.UnknownCondition(
novav1.NovaAPIMQReadyCondition,
condition.InitReason,
novav1.NovaAPIMQReadyInitMessage,
),
condition.UnknownCondition(
novav1.NovaAllCellsMQReadyCondition,
condition.InitReason,
novav1.NovaAllCellsMQReadyInitMessage,
),
condition.UnknownCondition(
novav1.NovaSchedulerReadyCondition,
condition.InitReason,
novav1.NovaSchedulerReadyInitMessage,
),
condition.UnknownCondition(
novav1.NovaMetadataReadyCondition,
condition.InitReason,
novav1.NovaMetadataReadyInitMessage,
),
// service account, role, rolebinding conditions
condition.UnknownCondition(
condition.ServiceAccountReadyCondition,
condition.InitReason,
condition.ServiceAccountReadyInitMessage,
),
condition.UnknownCondition(
condition.RoleReadyCondition,
condition.InitReason,
condition.RoleReadyInitMessage,
),
condition.UnknownCondition(
condition.RoleBindingReadyCondition,
condition.InitReason,
condition.RoleBindingReadyInitMessage,
),
condition.UnknownCondition(
condition.MemcachedReadyCondition,
condition.InitReason,
condition.MemcachedReadyInitMessage,
),
)
instance.Status.Conditions.Init(&cl)
return nil
}
func (r *NovaReconciler) getNovaManageJobSecretNames(
cell *novav1.NovaCell,
) (configName string, scriptName string) {
configName = fmt.Sprintf("%s-config-data", cell.Name+"-manage")
scriptName = fmt.Sprintf("%s-scripts", cell.Name+"-manage")
return
}
func (r *NovaReconciler) ensureNovaManageJobSecret(
ctx context.Context, h *helper.Helper, instance *novav1.Nova,
cell *novav1.NovaCell,
ospSecret corev1.Secret,
apiDBHostname string,
cellTransportURL string,
cellDB *mariadbv1.Database,
) (map[string]env.Setter, string, string, error) {
configName, scriptName := r.getNovaManageJobSecretNames(cell)
cmLabels := labels.GetLabels(
instance, labels.GetGroupLabel(NovaLabelPrefix), map[string]string{},
)
var tlsCfg *tls.Service
if instance.Spec.APIServiceTemplate.TLS.Ca.CaBundleSecretName != "" {
tlsCfg = &tls.Service{}
}
extraData := map[string]string{
"my.cnf": cellDB.GetDatabaseClientConfig(tlsCfg), //(mschuppert) for now just get the default my.cnf
}
extraTemplates := map[string]string{
"01-nova.conf": "/nova.conf",
"nova-blank.conf": "/nova-blank.conf",
}
apiDatabaseAccount, apiDbSecret, err := mariadbv1.GetAccountAndSecret(ctx, h, instance.Spec.APIDatabaseAccount, instance.Namespace)
if err != nil {
return nil, "", "", err
}
cellDatabaseAccount, cellDbSecret, err := mariadbv1.GetAccountAndSecret(ctx, h, cell.Spec.CellDatabaseAccount, instance.Namespace)
if err != nil {
return nil, "", "", err
}
// We configure the Job like it runs in the env of the conductor of the given cell
// but we ensure that the config always has [api_database] section configure
// even if the cell has no API access at all.
templateParameters := map[string]interface{}{
"service_name": "nova-conductor",
"keystone_internal_url": cell.Spec.KeystoneAuthURL,
"nova_keystone_user": cell.Spec.ServiceUser,
"nova_keystone_password": string(ospSecret.Data[instance.Spec.PasswordSelectors.Service]),
// cell.Spec.APIDatabaseAccount is empty for cells without APIDB access
"api_db_name": NovaAPIDatabaseName,
"api_db_user": apiDatabaseAccount.Spec.UserName,
"api_db_password": string(apiDbSecret.Data[mariadbv1.DatabasePasswordSelector]),
// cell.Spec.APIDatabaseHostname is empty for cells without APIDB access
"api_db_address": apiDBHostname,
"api_db_port": 3306,
"cell_db_name": getCellDatabaseName(cell.Spec.CellName),
"cell_db_user": cellDatabaseAccount.Spec.UserName,
"cell_db_password": string(cellDbSecret.Data[mariadbv1.DatabasePasswordSelector]),
"cell_db_address": cell.Spec.CellDatabaseHostname,
"cell_db_port": 3306,
"openstack_cacert": "", // fixme
"openstack_region_name": "regionOne", // fixme
"default_project_domain": "Default", // fixme
"default_user_domain": "Default", // fixme
}
// NOTE(gibi): cell mapping for cell0 should not have transport_url
// configured. As the nova-manage command used to create the mapping
// uses the transport_url from the nova.conf provided to the job
// we need to make sure that transport_url is only configured for the job
// if it is mapping other than cell0.
if cell.Spec.CellName != novav1.Cell0Name {
templateParameters["transport_url"] = cellTransportURL
}
cms := []util.Template{
{
Name: scriptName,
Namespace: instance.Namespace,
Type: util.TemplateTypeScripts,
InstanceType: "nova-manage",
Labels: cmLabels,
},
{
Name: configName,
Namespace: instance.Namespace,
Type: util.TemplateTypeConfig,
InstanceType: "nova-manage",
ConfigOptions: templateParameters,
Labels: cmLabels,
CustomData: extraData,
Annotations: map[string]string{},
AdditionalTemplate: extraTemplates,
},
}
configHash := make(map[string]env.Setter)
err = secret.EnsureSecrets(ctx, h, instance, cms, &configHash)
return configHash, scriptName, configName, err
}