-
Notifications
You must be signed in to change notification settings - Fork 93
/
peer_controller.go
1459 lines (1401 loc) · 46.1 KB
/
peer_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
package peer
import (
"context"
"crypto/ecdsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/kfsoftware/hlf-operator/controllers/hlfmetrics"
"github.com/kfsoftware/hlf-operator/kubectl-hlf/cmd/helpers"
"k8s.io/apimachinery/pkg/types"
"os"
"reflect"
"strings"
"time"
"github.com/operator-framework/operator-lib/status"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"helm.sh/helm/v3/pkg/cli"
apiv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/kubernetes/pkg/api/v1/pod"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/go-logr/logr"
hlfv1alpha1 "github.com/kfsoftware/hlf-operator/api/hlf.kungfusoftware.es/v1alpha1"
"github.com/kfsoftware/hlf-operator/controllers/certs"
"github.com/kfsoftware/hlf-operator/controllers/utils"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/storage/driver"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// FabricPeerReconciler reconciles a FabricPeer object
type FabricPeerReconciler struct {
client.Client
ChartPath string
Log logr.Logger
Scheme *runtime.Scheme
Config *rest.Config
}
func (r *FabricPeerReconciler) addFinalizer(reqLogger logr.Logger, m *hlfv1alpha1.FabricPeer) error {
if len(m.GetFinalizers()) < 1 && m.GetDeletionTimestamp() == nil {
reqLogger.Info("Adding Finalizer for the Memcached")
m.SetFinalizers([]string{peerFinalizer})
// Update CR
err := r.Client.Update(context.TODO(), m)
if err != nil {
reqLogger.Error(err, "Failed to update Peer with finalizer")
return err
}
reqLogger.Info(fmt.Sprintf("Finalizer for peer %s added", m.Name))
}
return nil
}
type Status struct {
Status hlfv1alpha1.DeploymentStatus
TLSCert string
NodePort int
}
const (
deploymentRestartTriggerAnnotation = "es.kungfusoftware.hlf.deployment-restart.timestamp"
)
func restartDeployment(config *rest.Config, deployment *appsv1.Deployment) error {
clientSet, err := utils.GetClientKubeWithConf(config)
if err != nil {
return err
}
patchData := map[string]interface{}{}
patchData["spec"] = map[string]interface{}{
"template": map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]interface{}{
deploymentRestartTriggerAnnotation: time.Now().Format(time.Stamp),
},
},
},
}
encodedData, err := json.Marshal(patchData)
if err != nil {
return err
}
_, err = clientSet.AppsV1().Deployments(deployment.Namespace).Patch(context.TODO(), deployment.Name, types.MergePatchType, encodedData, v1.PatchOptions{})
if err != nil {
return err
}
return nil
}
func GetPeerDeployment(conf *action.Configuration, config *rest.Config, releaseName string, ns string) (*appsv1.Deployment, error) {
ctx := context.Background()
cmd := action.NewGet(conf)
rel, err := cmd.Run(releaseName)
if err != nil {
return nil, err
}
clientSet, err := utils.GetClientKubeWithConf(config)
if err != nil {
return nil, err
}
if ns == "" {
ns = "default"
}
objects := utils.ParseK8sYaml([]byte(rel.Manifest))
for _, object := range objects {
kind := object.GetObjectKind().GroupVersionKind().Kind
if kind == "Deployment" {
depSpec := object.(*appsv1.Deployment)
dep, err := clientSet.AppsV1().Deployments(ns).Get(ctx, depSpec.Name, v1.GetOptions{})
if err != nil {
return nil, err
}
return dep, nil
}
}
return nil, errors.Errorf("Deployment not found")
}
func GetPeerState(conf *action.Configuration, config *rest.Config, releaseName string, ns string, svc *corev1.Service) (*hlfv1alpha1.FabricPeerStatus, error) {
ctx := context.Background()
cmd := action.NewGet(conf)
rel, err := cmd.Run(releaseName)
if err != nil {
return nil, err
}
clientSet, err := utils.GetClientKubeWithConf(config)
if err != nil {
return nil, err
}
if ns == "" {
ns = "default"
}
r := &hlfv1alpha1.FabricPeerStatus{
Status: hlfv1alpha1.PendingStatus,
}
objects := utils.ParseK8sYaml([]byte(rel.Manifest))
for _, object := range objects {
kind := object.GetObjectKind().GroupVersionKind().Kind
if kind == "Deployment" {
depSpec := object.(*appsv1.Deployment)
dep, err := clientSet.AppsV1().Deployments(ns).Get(ctx, depSpec.Name, v1.GetOptions{})
if err != nil {
return nil, err
}
pods, err := clientSet.CoreV1().Pods(ns).List(ctx, v1.ListOptions{
LabelSelector: fmt.Sprintf("release=%s", releaseName),
})
if err != nil {
return nil, err
}
if len(pods.Items) > 0 {
for _, item := range pods.Items {
if pod.IsPodReadyConditionTrue(item.Status) {
r.Status = hlfv1alpha1.RunningStatus
} else {
switch item.Status.Phase {
case corev1.PodPending:
r.Status = hlfv1alpha1.PendingStatus
case corev1.PodSucceeded:
case corev1.PodRunning:
r.Status = hlfv1alpha1.RunningStatus
case corev1.PodFailed:
r.Status = hlfv1alpha1.FailedStatus
case corev1.PodUnknown:
r.Status = hlfv1alpha1.UnknownStatus
}
}
}
} else {
if dep.Status.ReadyReplicas == *depSpec.Spec.Replicas {
r.Status = hlfv1alpha1.RunningStatus
} else {
r.Status = hlfv1alpha1.PendingStatus
}
}
}
}
for _, port := range svc.Spec.Ports {
if port.Name == PeerPortName {
r.NodePort = int(port.NodePort)
}
}
tlsCrt, _, rootTlsCrt, err := getExistingTLSCrypto(clientSet, releaseName, ns)
if err != nil {
return nil, err
}
r.TlsCert = string(utils.EncodeX509Certificate(tlsCrt))
r.TlsCACert = string(utils.EncodeX509Certificate(rootTlsCrt))
hlfmetrics.UpdateCertificateExpiry(
"peer",
"tls",
tlsCrt,
releaseName,
ns,
)
signCrt, _, rootSignCrt, err := getExistingSignCrypto(clientSet, releaseName, ns)
if err != nil {
return nil, err
}
r.SignCert = string(utils.EncodeX509Certificate(signCrt))
r.SignCACert = string(utils.EncodeX509Certificate(rootSignCrt))
hlfmetrics.UpdateCertificateExpiry(
"peer",
"sign",
signCrt,
releaseName,
ns,
)
return r, nil
}
const peerFinalizer = "finalizer.peer.hlf.kungfusoftware.es"
const chartName = "hlf-peer"
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabricpeers,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabricpeers/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabricpeers/finalizers,verbs=get;update;patch
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabricorderernodes,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabricorderernodes/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabricorderernodes/finalizers,verbs=get;update;patch
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabricorderingservices,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabricorderingservices/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabricorderingservices/finalizers,verbs=get;update;patch
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabriccas,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabriccas/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=hlf.kungfusoftware.es,resources=fabriccas/finalizers,verbs=get;update;patch
// +kubebuilder:rbac:groups="",resources=nodes,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterroles,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=rbac.authorization.k8s.io,resources=clusterrolebindings,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=monitoring.coreos.com,resources=servicemonitors,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=monitoring.coreos.com,resources=podmonitors,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=replicasets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=replicasets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions,resources=replicasets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=persistentvolumeclaims,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=persistentvolumeclaims,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions,resources=persistentvolumeclaims,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=pods,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions,resources=pods,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=services,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions,resources=services,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=secrets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions,resources=secrets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=pods/log,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=pods/log,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions,resources=pods/log,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=pods/status,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=pods/status,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions,resources=pods/status,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=networking.istio.io,resources=gateways,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=networking.istio.io,resources=virtualservices,verbs=get;list;watch;create;update;patch;delete
func (r *FabricPeerReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
ctx := context.Background()
reqLogger := r.Log.WithValues("hlf", req.NamespacedName)
fabricPeer := &hlfv1alpha1.FabricPeer{}
releaseName := req.Name
ns := req.Namespace
cfg, err := newActionCfg(r.Log, r.Config, ns)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
err = r.Get(ctx, req.NamespacedName, fabricPeer)
if err != nil {
log.Debugf("Error getting the object %s error=%v", req.NamespacedName, err)
if apierrors.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
reqLogger.Info("Peer resource not found. Ignoring since object must be deleted.")
return ctrl.Result{}, nil
}
reqLogger.Error(err, "Failed to get Peer.")
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
isPeerMarkedToDelete := fabricPeer.GetDeletionTimestamp() != nil
if isPeerMarkedToDelete {
if utils.Contains(fabricPeer.GetFinalizers(), peerFinalizer) {
if err := r.finalizePeer(reqLogger, fabricPeer); err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
controllerutil.RemoveFinalizer(fabricPeer, peerFinalizer)
err := r.Update(ctx, fabricPeer)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
}
return ctrl.Result{}, nil
}
if !utils.Contains(fabricPeer.GetFinalizers(), peerFinalizer) {
if err := r.addFinalizer(reqLogger, fabricPeer); err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
}
cmdStatus := action.NewStatus(cfg)
exists := true
_, err = cmdStatus.Run(releaseName)
if err != nil {
if errors.Is(err, driver.ErrReleaseNotFound) {
exists = false
} else {
// it doesnt exist
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
}
log.Debugf("Release %s exists=%v", releaseName, exists)
clientSet, err := utils.GetClientKubeWithConf(r.Config)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
svc, err := createPeerService(
clientSet,
chartName,
fabricPeer,
)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
reqLogger.Info(fmt.Sprintf("Service %s created", svc.Name))
if exists {
// update
c, err := GetConfig(fabricPeer, clientSet, releaseName, req.Namespace, svc, false)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
err = r.upgradeChart(cfg, err, ns, releaseName, c)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
lastTimeCertsRenewed := fabricPeer.Status.LastCertificateUpdate
if fabricPeer.Status.LastCertificateUpdate != nil {
lastCertificateUpdate := fabricPeer.Status.LastCertificateUpdate.Time
if fabricPeer.Spec.UpdateCertificateTime.Time.After(lastCertificateUpdate) {
// must update the certificates and block until it's done
// scale down to zero replicas
// wait for the deployment to scale down
// update the certs
// scale up the peer
log.Infof("Trying to upgrade certs")
err := r.updateCerts(req, fabricPeer, clientSet, releaseName, svc, ctx, cfg, ns)
if err != nil {
log.Errorf("Error renewing certs: %v", err)
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
lastTimeCertsRenewed = fabricPeer.Spec.UpdateCertificateTime
}
} else if fabricPeer.Status.LastCertificateUpdate == nil && fabricPeer.Spec.UpdateCertificateTime != nil {
log.Infof("Trying to upgrade certs")
err := r.updateCerts(req, fabricPeer, clientSet, releaseName, svc, ctx, cfg, ns)
if err != nil {
log.Errorf("Error renewing certs: %v", err)
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
lastTimeCertsRenewed = fabricPeer.Spec.UpdateCertificateTime
}
s, err := GetPeerState(cfg, r.Config, releaseName, ns, svc)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
fPeer := fabricPeer.DeepCopy()
fPeer.Status.Status = s.Status
fPeer.Status.TlsCert = s.TlsCert
fPeer.Status.TlsCACert = s.TlsCACert
fPeer.Status.SignCert = s.SignCert
fPeer.Status.SignCACert = s.SignCACert
fPeer.Status.NodePort = s.NodePort
fPeer.Status.LastCertificateUpdate = lastTimeCertsRenewed
fPeer.Status.Conditions.SetCondition(status.Condition{
Type: status.ConditionType(s.Status),
Status: "True",
})
if !reflect.DeepEqual(fPeer.Status, fabricPeer.Status) {
if err := r.Status().Update(ctx, fPeer); err != nil {
log.Errorf("Error updating the status: %v", err)
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
}
log.Infof("Peer %s in %s status", fPeer.Name, string(s.Status))
switch s.Status {
case hlfv1alpha1.PendingStatus:
log.Infof("Peer %s in %s status", fPeer.Name, string(s.Status))
return ctrl.Result{
RequeueAfter: 10 * time.Second,
}, nil
case hlfv1alpha1.FailedStatus:
log.Infof("Peer %s in %s status", fPeer.Name, string(s.Status))
return ctrl.Result{
RequeueAfter: 10 * time.Second,
}, nil
case hlfv1alpha1.RunningStatus:
return ctrl.Result{}, nil
default:
return ctrl.Result{
RequeueAfter: 2 * time.Second,
}, nil
}
} else {
cmd := action.NewInstall(cfg)
name, chart, err := cmd.NameAndChart([]string{releaseName, r.ChartPath})
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
cmd.ReleaseName = name
ch, err := loader.Load(chart)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
c, err := GetConfig(
fabricPeer,
clientSet,
name,
req.Namespace,
svc,
false,
)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
var inInterface map[string]interface{}
inrec, err := json.Marshal(c)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
err = json.Unmarshal(inrec, &inInterface)
if err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
release, err := cmd.Run(ch, inInterface)
if err != nil {
reqLogger.Error(err, "Failed to install chart")
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
log.Infof("Chart installed %s", release.Name)
fabricPeer.Status.Status = hlfv1alpha1.PendingStatus
fabricPeer.Status.Conditions.SetCondition(status.Condition{
Type: "DEPLOYED",
Status: "True",
LastTransitionTime: v1.Time{},
})
if err := r.Status().Update(ctx, fabricPeer); err != nil {
r.setConditionStatus(ctx, fabricPeer, hlfv1alpha1.FailedStatus, false, err, false)
return r.updateCRStatusOrFailReconcile(ctx, r.Log, fabricPeer)
}
return ctrl.Result{
Requeue: false,
RequeueAfter: 10 * time.Second,
}, nil
}
}
func (r *FabricPeerReconciler) updateCerts(req ctrl.Request, fPeer *hlfv1alpha1.FabricPeer, clientSet *kubernetes.Clientset, releaseName string, svc *corev1.Service, ctx context.Context, cfg *action.Configuration, ns string) error {
log.Infof("Trying to upgrade certs")
r.setConditionStatus(ctx, fPeer, hlfv1alpha1.UpdatingCertificates, false, nil, false)
config, err := GetConfig(fPeer, clientSet, releaseName, req.Namespace, svc, true)
if err != nil {
log.Errorf("Error getting the config: %v", err)
return err
}
err = r.upgradeChart(cfg, err, ns, releaseName, config)
if err != nil {
return err
}
dep, err := GetPeerDeployment(
cfg,
r.Config,
releaseName,
req.Namespace,
)
if err != nil {
return err
}
err = restartDeployment(
r.Config,
dep,
)
if err != nil {
return err
}
return nil
}
func (r *FabricPeerReconciler) upgradeChart(
cfg *action.Configuration,
err error,
ns string,
releaseName string,
c *FabricPeerChart,
) error {
inrec, err := json.Marshal(c)
if err != nil {
return err
}
var inInterface map[string]interface{}
err = json.Unmarshal(inrec, &inInterface)
if err != nil {
return err
}
cmd := action.NewUpgrade(cfg)
cmd.MaxHistory = 5
err = os.Setenv("HELM_NAMESPACE", ns)
if err != nil {
return err
}
settings := cli.New()
chartPath, err := cmd.LocateChart(r.ChartPath, settings)
ch, err := loader.Load(chartPath)
if err != nil {
return err
}
cmd.Wait = true
cmd.Timeout = time.Minute * 5
release, err := cmd.Run(releaseName, ch, inInterface)
if err != nil {
return err
}
log.Infof("Chart upgraded %s", release.Name)
return nil
}
func (r *FabricPeerReconciler) setConditionStatus(ctx context.Context, p *hlfv1alpha1.FabricPeer, conditionType hlfv1alpha1.DeploymentStatus, statusFlag bool, err error, statusUnknown bool) (update bool) {
statusStr := func() corev1.ConditionStatus {
if statusUnknown {
return corev1.ConditionUnknown
}
if statusFlag {
return corev1.ConditionTrue
} else {
return corev1.ConditionFalse
}
}
if p.Status.Status != conditionType {
depCopy := client.MergeFrom(p.DeepCopy())
p.Status.Status = conditionType
err = r.Status().Patch(ctx, p, depCopy)
if err != nil {
log.Warnf("Failed to update status to %s: %v", conditionType, err)
}
}
if err != nil {
p.Status.Message = err.Error()
}
condition := func() status.Condition {
if err != nil {
return status.Condition{
Type: status.ConditionType(conditionType),
Status: statusStr(),
Reason: status.ConditionReason(err.Error()),
Message: err.Error(),
}
}
return status.Condition{
Type: status.ConditionType(conditionType),
Status: statusStr(),
}
}
return p.Status.Conditions.SetCondition(condition())
}
func getExistingTLSOPSCrypto(client *kubernetes.Clientset, chartName string, namespace string) (*x509.Certificate, *ecdsa.PrivateKey, *x509.Certificate, error) {
secretName := fmt.Sprintf("%s-tls-ops", chartName)
tlsRootSecretName := fmt.Sprintf("%s-tlsrootcert", chartName)
secret, err := client.CoreV1().Secrets(namespace).Get(context.Background(), secretName, v1.GetOptions{})
if err != nil {
return nil, nil, nil, err
}
rootCertSecret, err := client.CoreV1().Secrets(namespace).Get(context.Background(), tlsRootSecretName, v1.GetOptions{})
if err != nil {
return nil, nil, nil, err
}
// cacert.pem
tlsKeyData := secret.Data["tls.key"]
tlsCrtData := secret.Data["tls.crt"]
rootTLSCrtData := rootCertSecret.Data["cacert.pem"]
key, err := utils.ParseECDSAPrivateKey(tlsKeyData)
if err != nil {
return nil, nil, nil, err
}
crt, err := utils.ParseX509Certificate(tlsCrtData)
if err != nil {
return nil, nil, nil, err
}
rootCrt, err := utils.ParseX509Certificate(rootTLSCrtData)
if err != nil {
return nil, nil, nil, err
}
return crt, key, rootCrt, nil
}
var (
ErrClientK8s = errors.New("k8sAPIClientError")
)
func (r *FabricPeerReconciler) updateCRStatusOrFailReconcile(ctx context.Context, log logr.Logger, p *hlfv1alpha1.FabricPeer) (
reconcile.Result, error) {
if err := r.Status().Update(ctx, p); err != nil {
log.Error(err, fmt.Sprintf("%v failed to update the application status", ErrClientK8s))
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
func getExistingTLSCrypto(client *kubernetes.Clientset, chartName string, namespace string) (*x509.Certificate, *ecdsa.PrivateKey, *x509.Certificate, error) {
secretName := fmt.Sprintf("%s-tls", chartName)
tlsRootSecretName := fmt.Sprintf("%s-tlsrootcert", chartName)
secret, err := client.CoreV1().Secrets(namespace).Get(context.Background(), secretName, v1.GetOptions{})
if err != nil {
return nil, nil, nil, err
}
rootCertSecret, err := client.CoreV1().Secrets(namespace).Get(context.Background(), tlsRootSecretName, v1.GetOptions{})
if err != nil {
return nil, nil, nil, err
}
// cacert.pem
tlsKeyData := secret.Data["tls.key"]
tlsCrtData := secret.Data["tls.crt"]
rootTLSCrtData := rootCertSecret.Data["cacert.pem"]
key, err := utils.ParseECDSAPrivateKey(tlsKeyData)
if err != nil {
return nil, nil, nil, err
}
crt, err := utils.ParseX509Certificate(tlsCrtData)
if err != nil {
return nil, nil, nil, err
}
rootCrt, err := utils.ParseX509Certificate(rootTLSCrtData)
if err != nil {
return nil, nil, nil, err
}
return crt, key, rootCrt, nil
}
func getExistingSignCrypto(client *kubernetes.Clientset, chartName string, namespace string) (*x509.Certificate, *ecdsa.PrivateKey, *x509.Certificate, error) {
secretCrtName := fmt.Sprintf("%s-idcert", chartName)
secretKeyName := fmt.Sprintf("%s-idkey", chartName)
secretRootCrtName := fmt.Sprintf("%s-cacert", chartName)
secretCrt, err := client.CoreV1().Secrets(namespace).Get(context.Background(), secretCrtName, v1.GetOptions{})
if err != nil {
return nil, nil, nil, err
}
secretKey, err := client.CoreV1().Secrets(namespace).Get(context.Background(), secretKeyName, v1.GetOptions{})
if err != nil {
return nil, nil, nil, err
}
secretRootCrt, err := client.CoreV1().Secrets(namespace).Get(context.Background(), secretRootCrtName, v1.GetOptions{})
if err != nil {
return nil, nil, nil, err
}
signCrtData := secretCrt.Data["cert.pem"]
signKeyData := secretKey.Data["key.pem"]
signRootCrtData := secretRootCrt.Data["cacert.pem"]
crt, err := utils.ParseX509Certificate(signCrtData)
if err != nil {
return nil, nil, nil, err
}
rootCrt, err := utils.ParseX509Certificate(signRootCrtData)
if err != nil {
return nil, nil, nil, err
}
key, err := utils.ParseECDSAPrivateKey(signKeyData)
if err != nil {
return nil, nil, nil, err
}
return crt, key, rootCrt, nil
}
func CreateTLSCryptoMaterial(conf *hlfv1alpha1.FabricPeer, caName string, caurl string, enrollID string, enrollSecret string, tlsCertString string, hosts []string) (*x509.Certificate, *ecdsa.PrivateKey, *x509.Certificate, error) {
tlsCert, tlsKey, tlsRootCert, err := certs.EnrollUser(certs.EnrollUserRequest{
TLSCert: tlsCertString,
URL: caurl,
Name: caName,
MSPID: conf.Spec.MspID,
User: enrollID,
Secret: enrollSecret,
Hosts: hosts,
CN: "",
Profile: "tls",
Attributes: nil,
})
if err != nil {
return nil, nil, nil, err
}
return tlsCert, tlsKey, tlsRootCert, nil
}
func CreateTLSOPSCryptoMaterial(conf *hlfv1alpha1.FabricPeer, caName string, caurl string, enrollID string, enrollSecret string, tlsCertString string, hosts []string) (*x509.Certificate, *ecdsa.PrivateKey, *x509.Certificate, error) {
tlsCert, tlsKey, tlsRootCert, err := certs.EnrollUser(
certs.EnrollUserRequest{
TLSCert: tlsCertString,
URL: caurl,
Name: caName,
MSPID: conf.Spec.MspID,
User: enrollID,
Secret: enrollSecret,
Hosts: hosts,
CN: "",
Profile: "tls",
Attributes: nil,
},
)
if err != nil {
return nil, nil, nil, err
}
return tlsCert, tlsKey, tlsRootCert, nil
}
func CreateSignCryptoMaterial(conf *hlfv1alpha1.FabricPeer, caName string, caurl string, enrollID string, enrollSecret string, tlsCertString string) (*x509.Certificate, *ecdsa.PrivateKey, *x509.Certificate, error) {
tlsCert, tlsKey, tlsRootCert, err := certs.EnrollUser(certs.EnrollUserRequest{
TLSCert: tlsCertString,
URL: caurl,
Name: caName,
MSPID: conf.Spec.MspID,
User: enrollID,
Secret: enrollSecret,
})
if err != nil {
return nil, nil, nil, err
}
return tlsCert, tlsKey, tlsRootCert, nil
}
func GetConfig(
conf *hlfv1alpha1.FabricPeer,
client *kubernetes.Clientset,
chartName string,
namespace string,
svc *corev1.Service,
refreshCerts bool,
) (*FabricPeerChart, error) {
spec := conf.Spec
tlsParams := conf.Spec.Secret.Enrollment.TLS
tlsCAUrl := fmt.Sprintf("https://%s:%d", tlsParams.Cahost, tlsParams.Caport)
ingressHosts := spec.Hosts
var hosts []string
hosts = append(hosts, tlsParams.Csr.Hosts...)
hosts = append(hosts, ingressHosts...)
var tlsCert, tlsRootCert, tlsOpsCert, signCert, signRootCert *x509.Certificate
var tlsKey, tlsOpsKey, signKey *ecdsa.PrivateKey
var err error
if refreshCerts {
cacert, err := base64.StdEncoding.DecodeString(tlsParams.Catls.Cacert)
if err != nil {
return nil, err
}
tlsCert, tlsKey, tlsRootCert, err = CreateTLSCryptoMaterial(
conf,
tlsParams.Caname,
tlsCAUrl,
tlsParams.Enrollid,
tlsParams.Enrollsecret,
string(cacert),
hosts,
)
if err != nil {
return nil, err
}
} else {
tlsCert, tlsKey, tlsRootCert, err = getExistingTLSCrypto(client, chartName, namespace)
if err != nil {
cacert, err := base64.StdEncoding.DecodeString(tlsParams.Catls.Cacert)
if err != nil {
return nil, err
}
tlsCert, tlsKey, tlsRootCert, err = CreateTLSCryptoMaterial(
conf,
tlsParams.Caname,
tlsCAUrl,
tlsParams.Enrollid,
tlsParams.Enrollsecret,
string(cacert),
hosts,
)
if err != nil {
return nil, err
}
}
}
if refreshCerts {
cacert, err := base64.StdEncoding.DecodeString(tlsParams.Catls.Cacert)
if err != nil {
return nil, err
}
tlsOpsCert, tlsOpsKey, _, err = CreateTLSOPSCryptoMaterial(
conf,
tlsParams.Caname,
tlsCAUrl,
tlsParams.Enrollid,
tlsParams.Enrollsecret,
string(cacert),
hosts,
)
if err != nil {
return nil, err
}
} else {
tlsOpsCert, tlsOpsKey, _, err = getExistingTLSOPSCrypto(client, chartName, namespace)
if err != nil {
cacert, err := base64.StdEncoding.DecodeString(tlsParams.Catls.Cacert)
if err != nil {
return nil, err
}
tlsOpsCert, tlsOpsKey, _, err = CreateTLSOPSCryptoMaterial(
conf,
tlsParams.Caname,
tlsCAUrl,
tlsParams.Enrollid,
tlsParams.Enrollsecret,
string(cacert),
hosts,
)
if err != nil {
return nil, err
}
}
}
signParams := conf.Spec.Secret.Enrollment.Component
caUrl := fmt.Sprintf("https://%s:%d", signParams.Cahost, signParams.Caport)
if refreshCerts {
cacert, err := base64.StdEncoding.DecodeString(signParams.Catls.Cacert)
if err != nil {
return nil, err
}
signCert, signKey, signRootCert, err = CreateSignCryptoMaterial(
conf,
signParams.Caname,
caUrl,
signParams.Enrollid,
signParams.Enrollsecret,
string(cacert),
)
if err != nil {
return nil, err
}
} else {
signCert, signKey, signRootCert, err = getExistingSignCrypto(client, chartName, namespace)
if err != nil {
cacert, err := base64.StdEncoding.DecodeString(signParams.Catls.Cacert)
if err != nil {
return nil, err
}
signCert, signKey, signRootCert, err = CreateSignCryptoMaterial(
conf,
signParams.Caname,
caUrl,
signParams.Enrollid,
signParams.Enrollsecret,
string(cacert),
)
if err != nil {
return nil, err
}
}
}
tlsCRTEncoded := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: tlsCert.Raw,
})
tlsRootCRTEncoded := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: tlsRootCert.Raw,
})
tlsEncodedPK, err := x509.MarshalPKCS8PrivateKey(tlsKey)
if err != nil {
return nil, err
}
tlsPEMEncodedPK := pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: tlsEncodedPK,
})
tlsOpsCRTEncoded := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: tlsOpsCert.Raw,
})
tlsOpsEncodedPK, err := x509.MarshalPKCS8PrivateKey(tlsOpsKey)
if err != nil {
return nil, err
}
tlsOpsPEMEncodedPK := pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: tlsOpsEncodedPK,
})
signCRTEncoded := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: signCert.Raw,
})
signRootCRTEncoded := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: signRootCert.Raw,
})
signEncodedPK, err := x509.MarshalPKCS8PrivateKey(signKey)
if err != nil {
return nil, err
}
signPEMEncodedPK := pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: signEncodedPK,
})
var externalEndpoint string
if spec.ExternalEndpoint != "" {
externalEndpoint = spec.ExternalEndpoint
} else {
requestNodePort, err := getRequestNodePort(svc)
if err != nil {
return nil, err
}
publicIP, err := utils.GetPublicIPKubernetes(client)
if err != nil {
return nil, err
}
externalEndpoint = fmt.Sprintf("%s:%d", publicIP, requestNodePort)
}
gossipExternalEndpoint := spec.Gossip.ExternalEndpoint
if gossipExternalEndpoint == "" {
gossipExternalEndpoint = externalEndpoint
}
gossipEndpoint := spec.Gossip.Endpoint
if gossipEndpoint == "" {
gossipEndpoint = externalEndpoint
}
externalBuilders := []ExternalBuilder{}
for _, builder := range spec.ExternalBuilders {
externalBuilders = append(externalBuilders, ExternalBuilder{
Name: builder.Name,
Path: builder.Path,
PropagateEnvironment: builder.PropagateEnvironment,
})
}