-
Notifications
You must be signed in to change notification settings - Fork 37
/
node.go
2046 lines (1734 loc) · 66.9 KB
/
node.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 contributors to the Hyperledger Fabric Operator project
*
* SPDX-License-Identifier: Apache-2.0
*
* 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 baseorderer
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
current "github.com/IBM-Blockchain/fabric-operator/api/v1beta1"
config "github.com/IBM-Blockchain/fabric-operator/operatorconfig"
"github.com/IBM-Blockchain/fabric-operator/pkg/action"
commonapi "github.com/IBM-Blockchain/fabric-operator/pkg/apis/common"
"github.com/IBM-Blockchain/fabric-operator/pkg/certificate"
commoninit "github.com/IBM-Blockchain/fabric-operator/pkg/initializer/common"
commonconfig "github.com/IBM-Blockchain/fabric-operator/pkg/initializer/common/config"
initializer "github.com/IBM-Blockchain/fabric-operator/pkg/initializer/orderer"
ordererconfig "github.com/IBM-Blockchain/fabric-operator/pkg/initializer/orderer/config/v1"
v2ordererconfig "github.com/IBM-Blockchain/fabric-operator/pkg/initializer/orderer/config/v2"
v24ordererconfig "github.com/IBM-Blockchain/fabric-operator/pkg/initializer/orderer/config/v24"
v25ordererconfig "github.com/IBM-Blockchain/fabric-operator/pkg/initializer/orderer/config/v25"
"github.com/IBM-Blockchain/fabric-operator/pkg/initializer/validator"
controllerclient "github.com/IBM-Blockchain/fabric-operator/pkg/k8s/controllerclient"
"github.com/IBM-Blockchain/fabric-operator/pkg/manager/resources"
resourcemanager "github.com/IBM-Blockchain/fabric-operator/pkg/manager/resources/manager"
"github.com/IBM-Blockchain/fabric-operator/pkg/offering/base/orderer/override"
"github.com/IBM-Blockchain/fabric-operator/pkg/offering/common"
"github.com/IBM-Blockchain/fabric-operator/pkg/offering/common/reconcilechecks"
"github.com/IBM-Blockchain/fabric-operator/pkg/operatorerrors"
"github.com/IBM-Blockchain/fabric-operator/pkg/restart"
"github.com/IBM-Blockchain/fabric-operator/pkg/util"
"github.com/IBM-Blockchain/fabric-operator/version"
"github.com/pkg/errors"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
k8sclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/yaml"
)
const (
NODE = "node"
DaysToSecondsConversion = int64(24 * 60 * 60)
)
type Override interface {
Deployment(v1.Object, *appsv1.Deployment, resources.Action) error
Service(v1.Object, *corev1.Service, resources.Action) error
PVC(v1.Object, *corev1.PersistentVolumeClaim, resources.Action) error
EnvCM(v1.Object, *corev1.ConfigMap, resources.Action, map[string]interface{}) error
OrdererNode(v1.Object, *current.IBPOrderer, resources.Action) error
}
//go:generate counterfeiter -o mocks/deployment_manager.go -fake-name DeploymentManager . DeploymentManager
type DeploymentManager interface {
resources.Manager
CheckForSecretChange(v1.Object, string, func(string, *appsv1.Deployment) bool) error
}
//go:generate counterfeiter -o mocks/initializeibporderer.go -fake-name InitializeIBPOrderer . InitializeIBPOrderer
type InitializeIBPOrderer interface {
GenerateSecrets(commoninit.SecretType, *current.IBPOrderer, *commonconfig.Response) error
Create(initializer.OrdererConfig, initializer.IBPOrderer, string) (*initializer.Response, error)
Update(initializer.OrdererConfig, initializer.IBPOrderer) (*initializer.Response, error)
CreateOrUpdateConfigMap(*current.IBPOrderer, initializer.OrdererConfig) error
GetConfigFromConfigMap(instance *current.IBPOrderer) (*corev1.ConfigMap, error)
MissingCrypto(*current.IBPOrderer) bool
Delete(*current.IBPOrderer) error
CheckIfAdminCertsUpdated(*current.IBPOrderer) (bool, error)
UpdateAdminSecret(*current.IBPOrderer) error
GetInitOrderer(instance *current.IBPOrderer, storagePath string) (*initializer.Orderer, error)
GetUpdatedOrderer(instance *current.IBPOrderer) (*initializer.Orderer, error)
UpdateSecrets(prefix commoninit.SecretType, instance *current.IBPOrderer, crypto *commonconfig.Response) error
GenerateSecretsFromResponse(instance *current.IBPOrderer, cryptoResponse *commonconfig.CryptoResponse) error
UpdateSecretsFromResponse(instance *current.IBPOrderer, cryptoResponse *commonconfig.CryptoResponse) error
GetCrypto(instance *current.IBPOrderer) (*commonconfig.CryptoResponse, error)
GetCoreConfigFromFile(instance *current.IBPOrderer, file string) (initializer.OrdererConfig, error)
GetCoreConfigFromBytes(instance *current.IBPOrderer, bytes []byte) (initializer.OrdererConfig, error)
}
//go:generate counterfeiter -o mocks/update.go -fake-name Update . Update
type Update interface {
SpecUpdated() bool
ConfigOverridesUpdated() bool
TLSCertUpdated() bool
EcertUpdated() bool
OrdererTagUpdated() bool
CertificateUpdated() bool
RestartNeeded() bool
EcertReenrollNeeded() bool
TLScertReenrollNeeded() bool
EcertNewKeyReenroll() bool
TLScertNewKeyReenroll() bool
DeploymentUpdated() bool
MSPUpdated() bool
EcertEnroll() bool
TLScertEnroll() bool
CertificateCreated() bool
GetCreatedCertType() commoninit.SecretType
CryptoBackupNeeded() bool
MigrateToV2() bool
MigrateToV24() bool
MigrateToV25() bool
NodeOUUpdated() bool
ImagesUpdated() bool
FabricVersionUpdated() bool
}
type IBPOrderer interface {
Initialize(instance *current.IBPOrderer, update Update) error
PreReconcileChecks(instance *current.IBPOrderer, update Update) (bool, error)
ReconcileManagers(instance *current.IBPOrderer, update Update, genesisBlock []byte) error
Reconcile(instance *current.IBPOrderer, update Update) (common.Result, error)
}
//go:generate counterfeiter -o mocks/certificate_manager.go -fake-name CertificateManager . CertificateManager
type CertificateManager interface {
CheckCertificatesForExpire(instance v1.Object, numSecondsBeforeExpire int64) (current.IBPCRStatusType, string, error)
GetSignCert(string, string) ([]byte, error)
GetDurationToNextRenewal(commoninit.SecretType, v1.Object, int64) (time.Duration, error)
RenewCert(commoninit.SecretType, certificate.Instance, *current.EnrollmentSpec, *commonapi.BCCSP, string, bool, bool) error
}
//go:generate counterfeiter -o mocks/restart_manager.go -fake-name RestartManager . RestartManager
type RestartManager interface {
ForAdminCertUpdate(instance v1.Object) error
ForCertUpdate(certType commoninit.SecretType, instance v1.Object) error
ForConfigOverride(instance v1.Object) error
ForNodeOU(instance v1.Object) error
TriggerIfNeeded(instance restart.Instance) error
ForRestartAction(instance v1.Object) error
}
type OrdererConfig interface {
MergeWith(interface{}, bool) error
ToBytes() ([]byte, error)
UsingPKCS11() bool
SetPKCS11Defaults(bool)
GetBCCSPSection() *commonapi.BCCSP
SetDefaultKeyStore()
SetBCCSPLibrary(string)
}
type Manager struct {
Client controllerclient.Client
Scheme *runtime.Scheme
Config *config.Config
}
func (m *Manager) GetNode(nodeNumber int, renewCertTimers map[string]*time.Timer, restartManager RestartManager) *Node {
return NewNode(m.Client, m.Scheme, m.Config, fmt.Sprintf("%s%d", NODE, nodeNumber), renewCertTimers, restartManager)
}
var _ IBPOrderer = &Node{}
type Node struct {
Client controllerclient.Client
Scheme *runtime.Scheme
Config *config.Config
DeploymentManager DeploymentManager
ServiceManager resources.Manager
PVCManager resources.Manager
EnvConfigMapManager resources.Manager
RoleManager resources.Manager
RoleBindingManager resources.Manager
ServiceAccountManager resources.Manager
Override Override
Initializer InitializeIBPOrderer
Name string
CertificateManager CertificateManager
RenewCertTimers map[string]*time.Timer
Restart RestartManager
}
func NewNode(client controllerclient.Client, scheme *runtime.Scheme, config *config.Config, name string, renewCertTimers map[string]*time.Timer, restartManager RestartManager) *Node {
n := &Node{
Client: client,
Scheme: scheme,
Config: config,
Override: &override.Override{
Name: name,
Client: client,
Config: config,
},
Name: name,
RenewCertTimers: renewCertTimers,
Restart: restartManager,
}
n.CreateManagers()
validator := &validator.Validator{
Client: client,
}
n.Initializer = initializer.New(client, scheme, config.OrdererInitConfig, name, validator)
n.CertificateManager = certificate.New(client, scheme)
return n
}
func NewNodeWithOverrides(client controllerclient.Client, scheme *runtime.Scheme, config *config.Config, name string, o Override, renewCertTimers map[string]*time.Timer, restartManager RestartManager) *Node {
n := &Node{
Client: client,
Scheme: scheme,
Config: config,
Override: o,
Name: name,
RenewCertTimers: renewCertTimers,
Restart: restartManager,
}
n.CreateManagers()
validator := &validator.Validator{
Client: client,
}
n.Initializer = initializer.New(client, scheme, config.OrdererInitConfig, name, validator)
n.CertificateManager = certificate.New(client, scheme)
return n
}
func (n *Node) CreateManagers() {
override := n.Override
resourceManager := resourcemanager.New(n.Client, n.Scheme)
n.DeploymentManager = resourceManager.CreateDeploymentManager("", override.Deployment, n.GetLabels, n.Config.OrdererInitConfig.DeploymentFile)
n.ServiceManager = resourceManager.CreateServiceManager("", override.Service, n.GetLabels, n.Config.OrdererInitConfig.ServiceFile)
n.PVCManager = resourceManager.CreatePVCManager("", override.PVC, n.GetLabels, n.Config.OrdererInitConfig.PVCFile)
n.EnvConfigMapManager = resourceManager.CreateConfigMapManager("env", override.EnvCM, n.GetLabels, n.Config.OrdererInitConfig.CMFile, nil)
n.RoleManager = resourceManager.CreateRoleManager("", nil, n.GetLabels, n.Config.OrdererInitConfig.RoleFile)
n.RoleBindingManager = resourceManager.CreateRoleBindingManager("", nil, n.GetLabels, n.Config.OrdererInitConfig.RoleBindingFile)
n.ServiceAccountManager = resourceManager.CreateServiceAccountManager("", nil, n.GetLabels, n.Config.OrdererInitConfig.ServiceAccountFile)
}
func (n *Node) Reconcile(instance *current.IBPOrderer, update Update) (common.Result, error) {
log.Info(fmt.Sprintf("Reconciling node instance '%s' ... update: %+v", instance.Name, update))
var err error
var status *current.CRStatus
versionSet, err := n.SetVersion(instance)
if err != nil {
return common.Result{}, errors.Wrap(err, fmt.Sprintf("failed updating CR '%s' to version '%s'", instance.Name, version.Operator))
}
if versionSet {
log.Info("Instance version updated, requeuing request...")
return common.Result{
Result: reconcile.Result{
Requeue: true,
},
}, nil
}
instanceUpdated, err := n.PreReconcileChecks(instance, update)
if err != nil {
return common.Result{}, errors.Wrap(err, "failed pre reconcile checks")
}
externalEndpointUpdated := n.UpdateExternalEndpoint(instance)
if instanceUpdated || externalEndpointUpdated {
log.Info(fmt.Sprintf("Updating instance after pre reconcile checks: %t, updating external endpoint: %t",
instanceUpdated, externalEndpointUpdated))
err = n.Client.Patch(context.TODO(), instance, nil, controllerclient.PatchOption{
Resilient: &controllerclient.ResilientPatch{
Retry: 3,
Into: ¤t.IBPOrderer{},
Strategy: k8sclient.MergeFrom,
},
})
if err != nil {
return common.Result{}, errors.Wrap(err, "failed to update instance")
}
log.Info("Instance updated, requeuing request...")
return common.Result{
Result: reconcile.Result{
Requeue: true,
},
Status: ¤t.CRStatus{
Type: current.Initializing,
Reason: "Setting default values for either zone, region, and/or external endpoint",
Message: "Operator has updated spec with defaults as part of initialization",
},
}, nil
}
err = n.Initialize(instance, update)
if err != nil {
return common.Result{}, operatorerrors.Wrap(err, operatorerrors.OrdererInitilizationFailed, "failed to initialize orderer node")
}
err = n.ReconcileManagers(instance, update, nil)
if err != nil {
return common.Result{}, errors.Wrap(err, "failed to reconcile managers")
}
err = n.UpdateConnectionProfile(instance)
if err != nil {
return common.Result{}, errors.Wrap(err, "failed to create connection profile")
}
err = n.CheckStates(instance)
if err != nil {
return common.Result{}, errors.Wrap(err, "failed to check and restore state")
}
// custom product logic can be implemented here
// No-Op atm
status, result, err := n.CustomLogic(instance, update)
if err != nil {
return common.Result{}, errors.Wrap(err, "failed to run custom offering logic")
}
if result != nil {
return *result, nil
}
if update.MSPUpdated() {
err = n.UpdateMSPCertificates(instance)
if err != nil {
if err != nil {
return common.Result{}, errors.Wrap(err, "failed to update certificates passed in MSP spec")
}
}
}
if update.EcertUpdated() {
log.Info("Ecert was updated")
// Request deployment restart for tls cert update
err = n.Restart.ForCertUpdate(commoninit.ECERT, instance)
if err != nil {
return common.Result{}, errors.Wrap(err, "failed to update restart config")
}
}
if update.TLSCertUpdated() {
log.Info("TLS cert was updated")
// Request deployment restart for ecert update
err = n.Restart.ForCertUpdate(commoninit.TLS, instance)
if err != nil {
return common.Result{}, errors.Wrap(err, "failed to update restart config")
}
}
if err := n.HandleActions(instance, update); err != nil {
return common.Result{}, errors.Wrap(err, "failed to handle actions")
}
if err := n.HandleRestart(instance, update); err != nil {
return common.Result{}, err
}
return common.Result{
Status: status,
}, nil
}
// PreReconcileChecks validate CR request before starting reconcile flow
func (n *Node) PreReconcileChecks(instance *current.IBPOrderer, update Update) (bool, error) {
var err error
imagesUpdated, err := reconcilechecks.FabricVersionHelper(instance, n.Config.Operator.Versions, update)
if err != nil {
return false, errors.Wrap(err, "failed during version and image checks")
}
if instance.Spec.HSMSet() {
err = util.ValidateHSMProxyURL(instance.Spec.HSM.PKCS11Endpoint)
if err != nil {
return false, errors.Wrapf(err, "invalid HSM endpoint for orderer instance '%s'", instance.GetName())
}
}
if !instance.Spec.DomainSet() {
return false, fmt.Errorf("domain not set for orderer instance '%s'", instance.GetName())
}
if instance.Spec.Action.Enroll.Ecert && instance.Spec.Action.Reenroll.Ecert {
return false, errors.New("both enroll and renenroll action requested for ecert, must only select one")
}
if instance.Spec.Action.Enroll.TLSCert && instance.Spec.Action.Reenroll.TLSCert {
return false, errors.New("both enroll and renenroll action requested for TLS cert, must only select one")
}
if instance.Spec.Action.Enroll.Ecert && instance.Spec.Action.Reenroll.EcertNewKey {
return false, errors.New("both enroll and renenroll with new key action requested for ecert, must only select one")
}
if instance.Spec.Action.Enroll.TLSCert && instance.Spec.Action.Reenroll.TLSCertNewKey {
return false, errors.New("both enroll and renenroll with new key action requested for TLS cert, must only select one")
}
if instance.Spec.Action.Reenroll.Ecert && instance.Spec.Action.Reenroll.EcertNewKey {
return false, errors.New("both reenroll and renenroll with new key action requested for ecert, must only select one")
}
if instance.Spec.Action.Reenroll.TLSCert && instance.Spec.Action.Reenroll.TLSCertNewKey {
return false, errors.New("both reenroll and renenroll with new key action requested for TLS cert, must only select one")
}
zoneUpdated, err := n.SelectZone(instance)
if err != nil {
return false, err
}
regionUpdated, err := n.SelectRegion(instance)
if err != nil {
return false, err
}
hsmImageUpdated := n.ReconcileHSMImages(instance)
var replicasUpdated bool
if instance.Spec.Replicas == nil {
replicas := int32(1)
instance.Spec.Replicas = &replicas
replicasUpdated = true
}
updated := zoneUpdated || regionUpdated || hsmImageUpdated || replicasUpdated || imagesUpdated
if updated {
log.Info(fmt.Sprintf("zoneUpdated %t, regionUpdated %t, hsmImageUpdated %t, replicasUpdated %t, imagesUpdated %t",
zoneUpdated, regionUpdated, hsmImageUpdated, replicasUpdated, imagesUpdated))
}
return updated, nil
}
func (n *Node) Initialize(instance *current.IBPOrderer, update Update) error {
var err error
log.Info(fmt.Sprintf("Checking if initialization needed for node: %s", instance.GetName()))
// TODO: Add checks to determine if initialization is neeeded. Split this method into
// two, one should handle initialization during the create event of a CR and the other
// should update events
// Service account is required by HSM init job
err = n.ReconcileRBAC(instance)
if err != nil {
return errors.Wrap(err, "failed RBAC reconciliation")
}
if instance.IsHSMEnabled() {
// If HSM config not found, HSM proxy is being used
if instance.UsingHSMProxy() {
err = os.Setenv("PKCS11_PROXY_SOCKET", instance.Spec.HSM.PKCS11Endpoint)
if err != nil {
return err
}
} else {
hsmConfig, err := commonconfig.ReadHSMConfig(n.Client, instance)
if err != nil {
return errors.New("using non-proxy HSM, but no HSM config defined as config map 'ibp-hsm-config'")
}
if hsmConfig.Daemon != nil {
log.Info("Using daemon based HSM, creating pvc...")
n.PVCManager.SetCustomName(instance.Spec.CustomNames.PVC.Orderer)
err = n.PVCManager.Reconcile(instance, update.SpecUpdated())
if err != nil {
return errors.Wrap(err, "failed PVC reconciliation")
}
}
}
}
initOrderer, err := n.Initializer.GetInitOrderer(instance, n.GetInitStoragePath(instance))
if err != nil {
return err
}
initOrderer.UsingHSMProxy = instance.UsingHSMProxy()
ordererConfig := n.Config.OrdererInitConfig.OrdererFile
if version.GetMajorReleaseVersion(instance.Spec.FabricVersion) == version.V2 {
currentVer := version.String(instance.Spec.FabricVersion)
if currentVer.EqualWithoutTag(version.V2_5_1) || currentVer.GreaterThan(version.V2_5_1) {
ordererConfig = n.Config.OrdererInitConfig.OrdererV25File
} else if currentVer.EqualWithoutTag(version.V2_4_1) || currentVer.GreaterThan(version.V2_4_1) {
ordererConfig = n.Config.OrdererInitConfig.OrdererV24File
} else if currentVer.LessThan(version.V2_4_1) {
ordererConfig = n.Config.OrdererInitConfig.OrdererV2File
}
}
initOrderer.Config, err = n.Initializer.GetCoreConfigFromFile(instance, ordererConfig)
if err != nil {
return err
}
updated := update.ConfigOverridesUpdated() || update.NodeOUUpdated()
if update.ConfigOverridesUpdated() {
err = n.InitializeUpdateConfigOverride(instance, initOrderer)
if err != nil {
return err
}
// Request deployment restart for config override update
if err := n.Restart.ForConfigOverride(instance); err != nil {
return err
}
}
if update.NodeOUUpdated() {
err = n.InitializeUpdateNodeOU(instance)
if err != nil {
return err
}
// Request deloyment restart for node OU update
if err = n.Restart.ForNodeOU(instance); err != nil {
return err
}
}
if !updated {
err = n.InitializeCreate(instance, initOrderer)
if err != nil {
return err
}
}
updateNeeded, err := n.Initializer.CheckIfAdminCertsUpdated(instance)
if err != nil {
return err
}
if updateNeeded {
err = n.Initializer.UpdateAdminSecret(instance)
if err != nil {
return err
}
// Request deployment restart for admin cert updates
if err = n.Restart.ForAdminCertUpdate(instance); err != nil {
return err
}
}
return nil
}
func (n *Node) InitializeCreate(instance *current.IBPOrderer, initOrderer *initializer.Orderer) error {
// TODO: Should also check for secrets not just config map
if n.ConfigExists(instance) {
log.Info(fmt.Sprintf("Config '%s-config' exists, not reinitializing node", instance.GetName()))
return nil
}
log.Info(fmt.Sprintf("Running initialization for create event on node '%s', since config '%s-config' does not exists", instance.GetName(), instance.GetName()))
configOverride, err := instance.GetConfigOverride()
if err != nil {
return err
}
resp, err := n.Initializer.Create(configOverride.(OrdererConfig), initOrderer, n.GetInitStoragePath(instance))
if err != nil {
return err
}
if resp != nil {
if resp.Crypto != nil {
if !instance.Spec.NodeOUDisabled() {
if err := resp.Crypto.VerifyCertOU("orderer"); err != nil {
return err
}
}
err = n.Initializer.GenerateSecretsFromResponse(instance, resp.Crypto)
if err != nil {
return err
}
}
if resp.Config != nil {
log.Info(fmt.Sprintf("Create config map for '%s'...", instance.GetName()))
if instance.IsHSMEnabled() && !instance.UsingHSMProxy() {
hsmConfig, err := commonconfig.ReadHSMConfig(n.Client, instance)
if err != nil {
return err
}
resp.Config.SetBCCSPLibrary(filepath.Join("/hsm/lib", filepath.Base(hsmConfig.Library.FilePath)))
}
err = n.Initializer.CreateOrUpdateConfigMap(instance, resp.Config)
if err != nil {
return err
}
}
}
return nil
}
func (n *Node) ConfigExists(instance *current.IBPOrderer) bool {
name := fmt.Sprintf("%s-config", instance.GetName())
namespacedName := types.NamespacedName{
Name: name,
Namespace: instance.Namespace,
}
cm := &corev1.ConfigMap{}
err := n.Client.Get(context.TODO(), namespacedName, cm)
if err != nil {
return false
}
return true
}
func (n *Node) InitializeUpdateConfigOverride(instance *current.IBPOrderer, initOrderer *initializer.Orderer) error {
log.Info(fmt.Sprintf("Running initialization update config override for node: %s", instance.GetName()))
if n.Initializer.MissingCrypto(instance) {
log.Info("Missing crypto for node")
// If crypto is missing, we should run the create logic
err := n.InitializeCreate(instance, initOrderer)
if err != nil {
return err
}
return nil
}
cm, err := n.Initializer.GetConfigFromConfigMap(instance)
if err != nil {
return err
}
initOrderer.Config, err = n.Initializer.GetCoreConfigFromBytes(instance, cm.BinaryData["orderer.yaml"])
if err != nil {
return err
}
configOverride, err := instance.GetConfigOverride()
if err != nil {
return err
}
resp, err := n.Initializer.Update(configOverride.(OrdererConfig), initOrderer)
if err != nil {
return err
}
if resp != nil && resp.Config != nil {
log.Info(fmt.Sprintf("Update config map for '%s'...", instance.GetName()))
err = n.Initializer.CreateOrUpdateConfigMap(instance, resp.Config)
if err != nil {
return err
}
}
return nil
}
func (n *Node) InitializeUpdateNodeOU(instance *current.IBPOrderer) error {
log.Info(fmt.Sprintf("Running initialize update node OU enabled: %t for orderer '%s", !instance.Spec.NodeOUDisabled(), instance.GetName()))
crypto, err := n.Initializer.GetCrypto(instance)
if err != nil {
return err
}
if !instance.Spec.NodeOUDisabled() {
if err := crypto.VerifyCertOU("orderer"); err != nil {
return err
}
} else {
// If nodeOUDisabled, admin certs are required
if crypto.Enrollment.AdminCerts == nil {
return errors.New("node OU disabled, admin certs are required but missing")
}
}
// Update config.yaml in config map
err = n.Initializer.CreateOrUpdateConfigMap(instance, nil)
if err != nil {
return err
}
return nil
}
func (n *Node) ReconcileManagers(instance *current.IBPOrderer, updated Update, genesisBlock []byte) error {
var err error
update := updated.SpecUpdated()
n.PVCManager.SetCustomName(instance.Spec.CustomNames.PVC.Orderer)
err = n.PVCManager.Reconcile(instance, update)
if err != nil {
return errors.Wrapf(err, "failed PVC reconciliation")
}
err = n.ServiceManager.Reconcile(instance, update)
if err != nil {
return errors.Wrap(err, "failed Service reconciliation")
}
err = n.ReconcileRBAC(instance)
if err != nil {
return errors.Wrap(err, "failed RBAC reconciliation")
}
err = n.EnvConfigMapManager.Reconcile(instance, update)
if err != nil {
return errors.Wrap(err, "failed Env ConfigMap reconciliation")
}
if instance.Spec.IsUsingChannelLess() {
log.Info("Node is in channel less mode - ending reconcile")
} else if !instance.Spec.IsPrecreateOrderer() {
log.Info("Node is not precreate - reconciling genesis secret")
err = n.ReconcileGenesisSecret(instance)
if err != nil {
return errors.Wrap(err, "failed Genesis Secret reconciliation")
}
}
err = n.DeploymentManager.Reconcile(instance, updated.DeploymentUpdated())
if err != nil {
return errors.Wrap(err, "failed Deployment reconciliation")
}
return nil
}
func (n *Node) CheckStates(instance *current.IBPOrderer) error {
// Don't need to check state if the state is being updated via CR. State needs
// to be checked if operator detects changes to a resources that was not triggered
// via CR.
if n.DeploymentManager.Exists(instance) {
err := n.DeploymentManager.CheckState(instance)
if err != nil {
log.Error(err, "unexpected state")
err = n.DeploymentManager.RestoreState(instance)
if err != nil {
return err
}
}
}
return nil
}
func (n *Node) SetVersion(instance *current.IBPOrderer) (bool, error) {
if instance.Status.Version == "" || !version.String(instance.Status.Version).Equal(version.Operator) {
log.Info("Version of Operator: ", "version", version.Operator)
log.Info(fmt.Sprintf("Version of CR '%s': %s", instance.GetName(), instance.Status.Version))
log.Info(fmt.Sprintf("Setting '%s' to version '%s'", instance.Name, version.Operator))
instance.Status.Version = version.Operator
err := n.Client.PatchStatus(context.TODO(), instance, nil, controllerclient.PatchOption{
Resilient: &controllerclient.ResilientPatch{
Retry: 3,
Into: ¤t.IBPOrderer{},
Strategy: k8sclient.MergeFrom,
},
})
if err != nil {
return false, err
}
return true, nil
}
return false, nil
}
func (n *Node) GetLabels(instance v1.Object) map[string]string {
parts := strings.Split(instance.GetName(), "node")
label := os.Getenv("OPERATOR_LABEL_PREFIX")
if label == "" {
label = "fabric"
}
if len(parts) > 1 {
ordererclustername := strings.Join(parts[:len(parts)-1], "node")
orderingnode := "node" + parts[len(parts)-1]
return map[string]string{
"app": instance.GetName(),
"creator": label,
"orderingservice": ordererclustername,
"orderingnode": orderingnode,
"parent": ordererclustername,
"app.kubernetes.io/name": label,
"app.kubernetes.io/instance": label + "orderer",
"app.kubernetes.io/managed-by": label + "-operator",
}
}
return map[string]string{
"app": instance.GetName(),
"creator": label,
"orderingservice": fmt.Sprintf("%s", instance.GetName()),
"app.kubernetes.io/name": label,
"app.kubernetes.io/instance": label + "orderer",
"app.kubernetes.io/managed-by": label + "-operator",
}
}
func (n *Node) Delete(instance *current.IBPOrderer) error {
log.Info(fmt.Sprintf("Deleting node '%s'", n.Name))
err := n.ServiceManager.Delete(instance)
if err != nil {
return errors.Wrapf(err, "failed to delete service '%s'", n.ServiceManager.GetName(instance))
}
err = n.PVCManager.Delete(instance)
if err != nil {
return errors.Wrapf(err, "failed to delete pvc '%s'", n.ServiceManager.GetName(instance))
}
err = n.EnvConfigMapManager.Delete(instance)
if err != nil {
return errors.Wrapf(err, "failed to delete config map '%s'", n.ServiceManager.GetName(instance))
}
err = n.Initializer.Delete(instance)
if err != nil {
return errors.Wrapf(err, "failed to delete secrets")
}
// Important: This must always be the last resource to be deleted
err = n.DeploymentManager.Delete(instance)
if err != nil {
return errors.Wrapf(err, "failed to delete deployment '%s'", n.DeploymentManager.GetName(instance))
}
return nil
}
func (n *Node) ReconcileGenesisSecret(instance *current.IBPOrderer) error {
namespacedName := types.NamespacedName{
Name: instance.Name + "-genesis",
Namespace: instance.Namespace,
}
secret := &corev1.Secret{}
err := n.Client.Get(context.TODO(), namespacedName, secret)
if err != nil {
if k8serrors.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
return n.CreateGenesisSecret(instance)
}
// Error reading the object - requeue the request.
return err
}
return nil
}
func (n *Node) CreateGenesisSecret(instance *current.IBPOrderer) error {
data := map[string][]byte{}
genesisBlock, err := util.Base64ToBytes(instance.Spec.GenesisBlock)
if err != nil {
return errors.Wrap(err, "failed to decode genesis block")
}
data["orderer.block"] = genesisBlock
s := &corev1.Secret{
Data: data,
}
s.Name = instance.Name + "-genesis"
s.Namespace = instance.Namespace
s.Labels = n.GetLabels(instance)
err = n.Client.CreateOrUpdate(context.TODO(), s, controllerclient.CreateOrUpdateOption{
Owner: instance,
Scheme: n.Scheme,
})
if err != nil {
return errors.Wrap(err, "failed to create genesis secret")
}
return nil
}
func (n *Node) ReconcileRBAC(instance *current.IBPOrderer) error {
var err error
err = n.RoleManager.Reconcile(instance, false)
if err != nil {
return err
}
err = n.RoleBindingManager.Reconcile(instance, false)
if err != nil {
return err
}
err = n.ServiceAccountManager.Reconcile(instance, false)
if err != nil {
return err
}
return nil
}
func (n *Node) SelectZone(instance *current.IBPOrderer) (bool, error) {
if instance.Spec.Zone == "select" {
log.Info("Selecting zone...")
zone := util.GetZone(n.Client)
log.Info(fmt.Sprintf("Zone set to: '%s'", zone))
instance.Spec.Zone = zone
return true, nil
}
if instance.Spec.Zone != "" {
err := util.ValidateZone(n.Client, instance.Spec.Zone)
if err != nil {
return false, err
}
}
return false, nil
}
func (n *Node) SelectRegion(instance *current.IBPOrderer) (bool, error) {
if instance.Spec.Region == "select" {
log.Info("Selecting region...")
region := util.GetRegion(n.Client)
log.Info(fmt.Sprintf("Region set to: '%s'", region))
instance.Spec.Region = region
return true, nil
}
if instance.Spec.Region != "" {
err := util.ValidateRegion(n.Client, instance.Spec.Region)
if err != nil {
return false, err
}
}
return false, nil
}
func (n *Node) UpdateExternalEndpoint(instance *current.IBPOrderer) bool {
if instance.Spec.ExternalAddress == "" {
instance.Spec.ExternalAddress = instance.Namespace + "-" + instance.Name + "-orderer" + "." + instance.Spec.Domain + ":443"
return true
}
return false
}
func (n *Node) UpdateConnectionProfile(instance *current.IBPOrderer) error {
var err error
endpoints := n.GetEndpoints(instance)
tlscert, err := common.GetTLSSignCertEncoded(n.Client, instance)
if err != nil {
return err
}
tlscacerts, err := common.GetTLSCACertEncoded(n.Client, instance)
if err != nil {
return err
}
tlsintercerts, err := common.GetTLSIntercertEncoded(n.Client, instance)
if err != nil {
return err
}
ecert, err := common.GetEcertSignCertEncoded(n.Client, instance)
if err != nil {
return err
}