-
Notifications
You must be signed in to change notification settings - Fork 208
/
clustermesh.go
1664 lines (1448 loc) · 53.4 KB
/
clustermesh.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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2020 Authors of Cilium
package clustermesh
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/cilium/cilium/api/v1/models"
ciliumv2 "github.com/cilium/cilium/pkg/k8s/apis/cilium.io/v2"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"github.com/cilium/cilium-cli/defaults"
"github.com/cilium/cilium-cli/internal/certs"
"github.com/cilium/cilium-cli/internal/utils"
"github.com/cilium/cilium-cli/k8s"
"github.com/cilium/cilium-cli/status"
)
const (
configNameClusterID = "cluster-id"
configNameClusterName = "cluster-name"
configNameTunnel = "tunnel"
caSuffix = ".etcd-client-ca.crt"
keySuffix = ".etcd-client.key"
certSuffix = ".etcd-client.crt"
)
var (
replicas = int32(1)
deploymentMaxSurge = intstr.FromInt(1)
deploymentMaxUnavailable = intstr.FromInt(1)
secretDefaultMode = int32(0400)
)
var clusterRole = &rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: defaults.ClusterMeshClusterRoleName,
},
Rules: []rbacv1.PolicyRule{
{
APIGroups: []string{"discovery.k8s.io"},
Resources: []string{"endpointslices"},
Verbs: []string{"get", "list", "watch"},
},
{
APIGroups: []string{""},
Resources: []string{"namespaces", "services", "endpoints"},
Verbs: []string{"get", "list", "watch"},
},
{
APIGroups: []string{"apiextensions.k8s.io"},
Resources: []string{"customresourcedefinitions"},
Verbs: []string{"list"},
},
{
APIGroups: []string{"cilium.io"},
Resources: []string{
"ciliumnodes",
"ciliumnodes/status",
"ciliumexternalworkloads",
"ciliumexternalworkloads/status",
"ciliumidentities",
"ciliumidentities/status",
"ciliumendpoints",
"ciliumendpoints/status",
},
Verbs: []string{"*"},
},
},
}
func (k *K8sClusterMesh) generateService() (*corev1.Service, error) {
svc := &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: defaults.ClusterMeshServiceName,
Labels: defaults.ClusterMeshDeploymentLabels,
Annotations: map[string]string{},
},
Spec: corev1.ServiceSpec{
Type: corev1.ServiceTypeClusterIP,
Ports: []corev1.ServicePort{
{Port: int32(2379)},
},
Selector: defaults.ClusterMeshDeploymentLabels,
},
}
if k.params.ServiceType != "" {
if k.params.ServiceType == "NodePort" {
k.Log("⚠️ Using service type NodePort may fail when nodes are removed from the cluster!")
}
svc.Spec.Type = corev1.ServiceType(k.params.ServiceType)
} else {
switch k.flavor.Kind {
case k8s.KindGKE:
k.Log("🔮 Auto-exposing service within GCP VPC (cloud.google.com/load-balancer-type=Internal)")
svc.Spec.Type = corev1.ServiceTypeLoadBalancer
svc.ObjectMeta.Annotations["cloud.google.com/load-balancer-type"] = "Internal"
// if all the clusters are in the same region the next annotation can be removed
svc.ObjectMeta.Annotations["networking.gke.io/internal-load-balancer-allow-global-access"] = "true"
case k8s.KindAKS:
k.Log("🔮 Auto-exposing service within Azure VPC (service.beta.kubernetes.io/azure-load-balancer-internal)")
svc.Spec.Type = corev1.ServiceTypeLoadBalancer
svc.ObjectMeta.Annotations["service.beta.kubernetes.io/azure-load-balancer-internal"] = "true"
case k8s.KindEKS:
k.Log("🔮 Auto-exposing service within AWS VPC (service.beta.kubernetes.io/aws-load-balancer-internal: 0.0.0.0/0")
svc.Spec.Type = corev1.ServiceTypeLoadBalancer
svc.ObjectMeta.Annotations["service.beta.kubernetes.io/aws-load-balancer-internal"] = "0.0.0.0/0"
default:
return nil, fmt.Errorf("cannot auto-detect service type, please specify using '--service-type' option")
}
}
return svc, nil
}
var initContainerArgs = []string{`rm -rf /var/run/etcd/*;
export ETCDCTL_API=3;
/usr/local/bin/etcd --data-dir=/var/run/etcd --name=clustermesh-apiserver --listen-client-urls=http://127.0.0.1:2379 --advertise-client-urls=http://127.0.0.1:2379 --initial-cluster-token=clustermesh-apiserver --initial-cluster-state=new --auto-compaction-retention=1 &
export rootpw="$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 16)";
echo $rootpw | etcdctl --interactive=false user add root;
etcdctl user grant-role root root;
export vmpw="$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 16)";
echo $vmpw | etcdctl --interactive=false user add externalworkload;
etcdctl role add externalworkload;
etcdctl role grant-permission externalworkload --from-key read '';
etcdctl role grant-permission externalworkload readwrite --prefix cilium/state/noderegister/v1/;
etcdctl role grant-permission externalworkload readwrite --prefix cilium/.initlock/;
etcdctl user grant-role externalworkload externalworkload;
export remotepw="$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 16)";
echo $remotepw | etcdctl --interactive=false user add remote;
etcdctl role add remote;
etcdctl role grant-permission remote --from-key read '';
etcdctl user grant-role remote remote;
etcdctl auth enable;
exit`}
func (k *K8sClusterMesh) apiserverImage(imagePathMode utils.ImagePathMode) string {
return utils.BuildImagePath(k.params.ApiserverImage, k.params.ApiserverVersion, defaults.ClusterMeshApiserverImage, k.imageVersion, imagePathMode)
}
func (k *K8sClusterMesh) etcdImage() string {
etcdVersion := "v3.4.13"
if k.clusterArch == "amd64" {
return "quay.io/coreos/etcd:" + etcdVersion
}
return "quay.io/coreos/etcd:" + etcdVersion + "-" + k.clusterArch
}
func (k *K8sClusterMesh) etcdEnvs() []corev1.EnvVar {
envs := []corev1.EnvVar{
{
Name: "ETCDCTL_API",
Value: "3",
},
{
Name: "HOSTNAME_IP",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
FieldPath: "status.podIP",
},
},
},
}
if k.clusterArch == "arm64" {
envs = append(envs, corev1.EnvVar{
Name: "ETCD_UNSUPPORTED_ARCH",
Value: "arm64",
})
}
return envs
}
func (k *K8sClusterMesh) generateDeployment(clustermeshApiserverArgs []string) *appsv1.Deployment {
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: defaults.ClusterMeshDeploymentName,
Labels: defaults.ClusterMeshDeploymentLabels,
},
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{
MatchLabels: defaults.ClusterMeshDeploymentLabels,
},
Strategy: appsv1.DeploymentStrategy{
Type: appsv1.RollingUpdateDeploymentStrategyType,
RollingUpdate: &appsv1.RollingUpdateDeployment{
MaxUnavailable: &deploymentMaxUnavailable,
MaxSurge: &deploymentMaxSurge,
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Name: defaults.ClusterMeshDeploymentName,
Labels: defaults.ClusterMeshDeploymentLabels,
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyAlways,
ServiceAccountName: defaults.ClusterMeshServiceAccountName,
Containers: []corev1.Container{
{
Name: "etcd",
Command: []string{"/usr/local/bin/etcd"},
Args: []string{
"--data-dir=/var/run/etcd",
"--name=clustermesh-apiserver",
"--client-cert-auth",
"--trusted-ca-file=/var/lib/etcd-secrets/ca.crt",
"--cert-file=/var/lib/etcd-secrets/tls.crt",
"--key-file=/var/lib/etcd-secrets/tls.key",
"--listen-client-urls=https://127.0.0.1:2379,https://$(HOSTNAME_IP):2379",
"--advertise-client-urls=https://$(HOSTNAME_IP):2379",
"--initial-cluster-token=clustermesh-apiserver",
"--auto-compaction-retention=1",
},
Image: k.etcdImage(),
ImagePullPolicy: corev1.PullIfNotPresent,
Env: k.etcdEnvs(),
VolumeMounts: []corev1.VolumeMount{
{
Name: "etcd-server-secrets",
MountPath: "/var/lib/etcd-secrets",
ReadOnly: true,
},
{
Name: "etcd-data-dir",
MountPath: "/var/run/etcd",
},
},
},
{
Name: "apiserver",
Command: []string{"/usr/bin/clustermesh-apiserver"},
Args: append(clustermeshApiserverArgs,
"--cluster-name="+k.clusterName,
"--cluster-id="+k.clusterID,
"--kvstore-opt",
"etcd.config=/var/lib/cilium/etcd-config.yaml",
),
Image: k.apiserverImage(utils.ImagePathIncludeDigest),
ImagePullPolicy: corev1.PullIfNotPresent,
Env: []corev1.EnvVar{
{
Name: "CILIUM_CLUSTER_NAME",
ValueFrom: &corev1.EnvVarSource{
ConfigMapKeyRef: &corev1.ConfigMapKeySelector{
LocalObjectReference: corev1.LocalObjectReference{
Name: defaults.ConfigMapName,
},
Key: configNameClusterName,
},
},
},
{
Name: "CILIUM_CLUSTER_ID",
ValueFrom: &corev1.EnvVarSource{
ConfigMapKeyRef: &corev1.ConfigMapKeySelector{
LocalObjectReference: corev1.LocalObjectReference{
Name: defaults.ConfigMapName,
},
Key: configNameClusterID,
},
},
},
{
Name: "CILIUM_IDENTITY_ALLOCATION_MODE",
ValueFrom: &corev1.EnvVarSource{
ConfigMapKeyRef: &corev1.ConfigMapKeySelector{
LocalObjectReference: corev1.LocalObjectReference{
Name: defaults.ConfigMapName,
},
Key: "identity-allocation-mode",
},
},
},
},
VolumeMounts: []corev1.VolumeMount{
{
Name: "etcd-admin-client",
MountPath: "/var/lib/cilium/etcd-secrets",
ReadOnly: true,
},
},
},
},
InitContainers: []corev1.Container{
{
Name: "etcd-init",
Command: []string{"/bin/sh", "-c"},
Args: initContainerArgs,
Image: k.etcdImage(),
ImagePullPolicy: corev1.PullIfNotPresent,
Env: k.etcdEnvs(),
VolumeMounts: []corev1.VolumeMount{
{
Name: "etcd-data-dir",
MountPath: "etcd-data-dir",
},
},
},
},
Volumes: []corev1.Volume{
{
Name: "etcd-data-dir",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
{
Name: "etcd-server-secrets",
VolumeSource: corev1.VolumeSource{
Projected: &corev1.ProjectedVolumeSource{
DefaultMode: &secretDefaultMode,
Sources: []corev1.VolumeProjection{
{
Secret: &corev1.SecretProjection{
LocalObjectReference: corev1.LocalObjectReference{
Name: defaults.CASecretName,
},
Items: []corev1.KeyToPath{
{
Key: defaults.CASecretCertName,
Path: "ca.crt",
},
},
},
},
{
Secret: &corev1.SecretProjection{
LocalObjectReference: corev1.LocalObjectReference{
Name: defaults.ClusterMeshServerSecretName,
},
},
},
},
},
},
},
{
Name: "etcd-admin-client",
VolumeSource: corev1.VolumeSource{
Projected: &corev1.ProjectedVolumeSource{
DefaultMode: &secretDefaultMode,
Sources: []corev1.VolumeProjection{
{
Secret: &corev1.SecretProjection{
LocalObjectReference: corev1.LocalObjectReference{
Name: defaults.CASecretName,
},
Items: []corev1.KeyToPath{
{
Key: defaults.CASecretCertName,
Path: "ca.crt",
},
},
},
},
{
Secret: &corev1.SecretProjection{
LocalObjectReference: corev1.LocalObjectReference{
Name: defaults.ClusterMeshAdminSecretName,
},
},
},
},
},
},
},
},
},
},
},
}
return deployment
}
type k8sClusterMeshImplementation interface {
CreateSecret(ctx context.Context, namespace string, secret *corev1.Secret, opts metav1.CreateOptions) (*corev1.Secret, error)
PatchSecret(ctx context.Context, namespace, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions) (*corev1.Secret, error)
DeleteSecret(ctx context.Context, namespace, name string, opts metav1.DeleteOptions) error
GetSecret(ctx context.Context, namespace, name string, opts metav1.GetOptions) (*corev1.Secret, error)
CreateServiceAccount(ctx context.Context, namespace string, account *corev1.ServiceAccount, opts metav1.CreateOptions) (*corev1.ServiceAccount, error)
DeleteServiceAccount(ctx context.Context, namespace, name string, opts metav1.DeleteOptions) error
CreateClusterRole(ctx context.Context, role *rbacv1.ClusterRole, opts metav1.CreateOptions) (*rbacv1.ClusterRole, error)
DeleteClusterRole(ctx context.Context, name string, opts metav1.DeleteOptions) error
CreateClusterRoleBinding(ctx context.Context, role *rbacv1.ClusterRoleBinding, opts metav1.CreateOptions) (*rbacv1.ClusterRoleBinding, error)
DeleteClusterRoleBinding(ctx context.Context, name string, opts metav1.DeleteOptions) error
GetConfigMap(ctx context.Context, namespace, name string, opts metav1.GetOptions) (*corev1.ConfigMap, error)
CreateDeployment(ctx context.Context, namespace string, deployment *appsv1.Deployment, opts metav1.CreateOptions) (*appsv1.Deployment, error)
GetDeployment(ctx context.Context, namespace, name string, opts metav1.GetOptions) (*appsv1.Deployment, error)
DeleteDeployment(ctx context.Context, namespace, name string, opts metav1.DeleteOptions) error
CheckDeploymentStatus(ctx context.Context, namespace, deployment string) error
CreateService(ctx context.Context, namespace string, service *corev1.Service, opts metav1.CreateOptions) (*corev1.Service, error)
DeleteService(ctx context.Context, namespace, name string, opts metav1.DeleteOptions) error
GetService(ctx context.Context, namespace, name string, opts metav1.GetOptions) (*corev1.Service, error)
PatchDaemonSet(ctx context.Context, namespace, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions) (*appsv1.DaemonSet, error)
GetDaemonSet(ctx context.Context, namespace, name string, options metav1.GetOptions) (*appsv1.DaemonSet, error)
ListNodes(ctx context.Context, options metav1.ListOptions) (*corev1.NodeList, error)
ListPods(ctx context.Context, namespace string, options metav1.ListOptions) (*corev1.PodList, error)
AutodetectFlavor(ctx context.Context) k8s.Flavor
CiliumStatus(ctx context.Context, namespace, pod string) (*models.StatusResponse, error)
ClusterName() string
ListCiliumExternalWorkloads(ctx context.Context, opts metav1.ListOptions) (*ciliumv2.CiliumExternalWorkloadList, error)
GetCiliumExternalWorkload(ctx context.Context, name string, opts metav1.GetOptions) (*ciliumv2.CiliumExternalWorkload, error)
CreateCiliumExternalWorkload(ctx context.Context, cew *ciliumv2.CiliumExternalWorkload, opts metav1.CreateOptions) (*ciliumv2.CiliumExternalWorkload, error)
DeleteCiliumExternalWorkload(ctx context.Context, name string, opts metav1.DeleteOptions) error
GetRunningCiliumVersion(ctx context.Context, namespace string) (string, error)
ListCiliumEndpoints(ctx context.Context, namespace string, options metav1.ListOptions) (*ciliumv2.CiliumEndpointList, error)
GetPlatform(ctx context.Context) (*k8s.Platform, error)
}
type K8sClusterMesh struct {
client k8sClusterMeshImplementation
certManager *certs.CertManager
statusCollector *status.K8sStatusCollector
flavor k8s.Flavor
params Parameters
clusterName string
clusterID string
imageVersion string
clusterArch string
}
type Parameters struct {
Namespace string
ServiceType string
DestinationContext string
Wait bool
WaitDuration time.Duration
DestinationEndpoints []string
SourceEndpoints []string
SkipServiceCheck bool
ApiserverImage string
ApiserverVersion string
CreateCA bool
Writer io.Writer
Labels map[string]string
IPv4AllocCIDR string
IPv6AllocCIDR string
All bool
ConfigOverwrites []string
Retries int
}
func (p Parameters) validateParams() error {
if p.ApiserverImage != defaults.ClusterMeshApiserverImage {
return nil
} else if !utils.CheckVersion(p.ApiserverVersion) && p.ApiserverVersion != "" {
return fmt.Errorf("invalid syntax %q for image tag", p.ApiserverVersion)
}
return nil
}
func (p Parameters) waitTimeout() time.Duration {
if p.WaitDuration != time.Duration(0) {
return p.WaitDuration
}
return time.Minute * 15
}
func NewK8sClusterMesh(client k8sClusterMeshImplementation, p Parameters) *K8sClusterMesh {
return &K8sClusterMesh{
client: client,
params: p,
certManager: certs.NewCertManager(client, certs.Parameters{Namespace: p.Namespace}),
}
}
func (k *K8sClusterMesh) Log(format string, a ...interface{}) {
fmt.Fprintf(k.params.Writer, format+"\n", a...)
}
func (k *K8sClusterMesh) GetClusterConfig(ctx context.Context) error {
k.flavor = k.client.AutodetectFlavor(ctx)
cm, err := k.client.GetConfigMap(ctx, k.params.Namespace, defaults.ConfigMapName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("unable to retrieve ConfigMap %q: %w", defaults.ConfigMapName, err)
}
clusterID := cm.Data[configNameClusterID]
if clusterID == "" {
clusterID = "0"
}
k.clusterID = clusterID
clusterName := cm.Data[configNameClusterName]
if clusterName == "" {
clusterName = "default"
}
k.clusterName = clusterName
if clusterID == "0" || clusterName == "default" {
k.Log("⚠️ Cluster not configured for clustermesh, use '--cluster-id' and '--cluster-name' with 'cilium install'. External workloads may still be configured.")
}
return nil
}
func (k *K8sClusterMesh) Disable(ctx context.Context) error {
k.Log("🔥 Deleting clustermesh-apiserver...")
k.client.DeleteService(ctx, k.params.Namespace, defaults.ClusterMeshServiceName, metav1.DeleteOptions{})
k.client.DeleteDeployment(ctx, k.params.Namespace, defaults.ClusterMeshDeploymentName, metav1.DeleteOptions{})
k.client.DeleteClusterRoleBinding(ctx, defaults.ClusterMeshClusterRoleName, metav1.DeleteOptions{})
k.client.DeleteClusterRole(ctx, defaults.ClusterMeshClusterRoleName, metav1.DeleteOptions{})
k.client.DeleteServiceAccount(ctx, k.params.Namespace, defaults.ClusterMeshServiceAccountName, metav1.DeleteOptions{})
k.client.DeleteSecret(ctx, k.params.Namespace, defaults.ClusterMeshSecretName, metav1.DeleteOptions{})
k.deleteCertificates(ctx)
k.Log("✅ ClusterMesh disabled.")
return nil
}
func (p Parameters) validateForEnable() error {
switch corev1.ServiceType(p.ServiceType) {
case corev1.ServiceTypeClusterIP:
case corev1.ServiceTypeNodePort:
case corev1.ServiceTypeLoadBalancer:
case corev1.ServiceTypeExternalName:
case "":
default:
return fmt.Errorf("unknown service type %q", p.ServiceType)
}
return nil
}
func (k *K8sClusterMesh) Enable(ctx context.Context) error {
if err := k.params.validateParams(); err != nil {
return err
}
if err := k.params.validateForEnable(); err != nil {
return err
}
if err := k.GetClusterConfig(ctx); err != nil {
return err
}
var err error
k.imageVersion, err = k.client.GetRunningCiliumVersion(ctx, k.params.Namespace)
if err != nil {
return err
}
p, err := k.client.GetPlatform(ctx)
if err != nil {
return err
}
k.clusterArch = p.Arch
svc, err := k.generateService()
if err != nil {
return err
}
_, err = k.client.GetDeployment(ctx, k.params.Namespace, defaults.ClusterMeshDeploymentName, metav1.GetOptions{})
if err == nil {
k.Log("✅ ClusterMesh is already enabled")
return nil
}
if err := k.installCertificates(ctx); err != nil {
return err
}
k.Log("✨ Deploying clustermesh-apiserver from %s...", k.apiserverImage(utils.ImagePathExcludeDigest))
if _, err := k.client.CreateServiceAccount(ctx, k.params.Namespace, k8s.NewServiceAccount(defaults.ClusterMeshServiceAccountName), metav1.CreateOptions{}); err != nil {
return err
}
if _, err := k.client.CreateClusterRole(ctx, clusterRole, metav1.CreateOptions{}); err != nil {
return err
}
if _, err := k.client.CreateClusterRoleBinding(ctx, k8s.NewClusterRoleBinding(defaults.ClusterMeshClusterRoleName, k.params.Namespace, defaults.ClusterMeshServiceAccountName), metav1.CreateOptions{}); err != nil {
return err
}
for i, opt := range k.params.ConfigOverwrites {
if !strings.HasPrefix(opt, "--") {
k.params.ConfigOverwrites[i] = "--" + opt
}
}
if _, err := k.client.CreateDeployment(ctx, k.params.Namespace, k.generateDeployment(k.params.ConfigOverwrites), metav1.CreateOptions{}); err != nil {
return err
}
if _, err := k.client.CreateService(ctx, k.params.Namespace, svc, metav1.CreateOptions{}); err != nil {
return err
}
k.Log("✅ ClusterMesh enabled!")
return nil
}
type accessInformation struct {
ServiceIPs []string
ServicePort int
ClusterID string
ClusterName string
CA []byte
ClientCert []byte
ClientKey []byte
ExternalWorkloadCert []byte
ExternalWorkloadKey []byte
Tunnel string
}
func (ai *accessInformation) etcdConfiguration() string {
cfg := "endpoints:\n"
cfg += "- https://" + ai.ClusterName + ".mesh.cilium.io:" + fmt.Sprintf("%d", ai.ServicePort) + "\n"
cfg += "trusted-ca-file: /var/lib/cilium/clustermesh/" + ai.ClusterName + caSuffix + "\n"
cfg += "key-file: /var/lib/cilium/clustermesh/" + ai.ClusterName + keySuffix + "\n"
cfg += "cert-file: /var/lib/cilium/clustermesh/" + ai.ClusterName + certSuffix + "\n"
return cfg
}
func (ai *accessInformation) validate() bool {
return ai.ClusterName != "" &&
ai.ClusterName != "default" &&
ai.ClusterID != "" &&
ai.ClusterID != "0"
}
func (k *K8sClusterMesh) extractAccessInformation(ctx context.Context, client k8sClusterMeshImplementation, endpoints []string, verbose bool) (*accessInformation, error) {
cm, err := client.GetConfigMap(ctx, k.params.Namespace, defaults.ConfigMapName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("unable to retrieve ConfigMap %q: %w", defaults.ConfigMapName, err)
}
if _, ok := cm.Data[configNameClusterName]; !ok {
return nil, fmt.Errorf("%s is not set in ConfigMap %q", configNameClusterName, defaults.ConfigMapName)
}
clusterID := cm.Data[configNameClusterID]
clusterName := cm.Data[configNameClusterName]
if verbose {
k.Log("✨ Extracting access information of cluster %s...", clusterName)
}
svc, err := client.GetService(ctx, k.params.Namespace, defaults.ClusterMeshServiceName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("unable to get clustermesh service %q: %w", defaults.ClusterMeshServiceName, err)
}
if verbose {
k.Log("🔑 Extracting secrets from cluster %s...", clusterName)
}
caSecret, err := client.GetSecret(ctx, k.params.Namespace, defaults.CASecretName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("unable to get secret %q to retrieve CA: %s", defaults.CASecretName, err)
}
caCert, ok := caSecret.Data[defaults.CASecretCertName]
if !ok {
return nil, fmt.Errorf("secret %q does not contain CA cert %q", defaults.CASecretName, defaults.CASecretCertName)
}
meshSecret, err := client.GetSecret(ctx, k.params.Namespace, defaults.ClusterMeshClientSecretName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("unable to get secret %q to access clustermesh service: %s", defaults.ClusterMeshClientSecretName, err)
}
clientKey, ok := meshSecret.Data[corev1.TLSPrivateKeyKey]
if !ok {
return nil, fmt.Errorf("secret %q does not contain key %q", defaults.ClusterMeshClientSecretName, corev1.TLSPrivateKeyKey)
}
clientCert, ok := meshSecret.Data[corev1.TLSCertKey]
if !ok {
return nil, fmt.Errorf("secret %q does not contain key %q", defaults.ClusterMeshClientSecretName, corev1.TLSCertKey)
}
externalWorkloadSecret, err := client.GetSecret(ctx, k.params.Namespace, defaults.ClusterMeshExternalWorkloadSecretName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("unable to get secret %q to access clustermesh service: %s", defaults.ClusterMeshExternalWorkloadSecretName, err)
}
externalWorkloadKey, ok := externalWorkloadSecret.Data[corev1.TLSPrivateKeyKey]
if !ok {
return nil, fmt.Errorf("secret %q does not contain key %q", defaults.ClusterMeshExternalWorkloadSecretName, corev1.TLSPrivateKeyKey)
}
externalWorkloadCert, ok := externalWorkloadSecret.Data[corev1.TLSCertKey]
if !ok {
return nil, fmt.Errorf("secret %q does not contain key %q", defaults.ClusterMeshExternalWorkloadSecretName, corev1.TLSCertKey)
}
ai := &accessInformation{
ClusterID: clusterID,
ClusterName: clusterName,
CA: caCert,
ClientKey: clientKey,
ClientCert: clientCert,
ExternalWorkloadKey: externalWorkloadKey,
ExternalWorkloadCert: externalWorkloadCert,
ServiceIPs: []string{},
Tunnel: cm.Data[configNameTunnel],
}
switch {
case len(endpoints) > 0:
for _, endpoint := range endpoints {
ip, port, err := net.SplitHostPort(endpoint)
if err != nil {
return nil, fmt.Errorf("invalid endpoint %q, must be IP:PORT: %w", endpoint, err)
}
intPort, err := strconv.Atoi(port)
if err != nil {
return nil, fmt.Errorf("invalid port %q: %w", port, err)
}
if ai.ServicePort == 0 {
ai.ServicePort = intPort
} else if ai.ServicePort != intPort {
return nil, fmt.Errorf("port mismatch (%d != %d), all endpoints must use the same port number", ai.ServicePort, intPort)
}
ai.ServiceIPs = append(ai.ServiceIPs, ip)
}
case svc.Spec.Type == corev1.ServiceTypeClusterIP:
if len(svc.Spec.Ports) == 0 {
return nil, fmt.Errorf("port of service could not be derived, service has no ports")
}
if svc.Spec.Ports[0].Port == 0 {
return nil, fmt.Errorf("port is not set in service")
}
ai.ServicePort = int(svc.Spec.Ports[0].Port)
if svc.Spec.ClusterIP == "" {
return nil, fmt.Errorf("IP of service could not be derived, service has no ClusterIP")
}
ai.ServiceIPs = append(ai.ServiceIPs, svc.Spec.ClusterIP)
case svc.Spec.Type == corev1.ServiceTypeNodePort:
if len(svc.Spec.Ports) == 0 {
return nil, fmt.Errorf("port of service could not be derived, service has no ports")
}
if svc.Spec.Ports[0].NodePort == 0 {
return nil, fmt.Errorf("nodeport is not set in service")
}
ai.ServicePort = int(svc.Spec.Ports[0].NodePort)
nodes, err := client.ListNodes(ctx, metav1.ListOptions{})
if err != nil {
return nil, fmt.Errorf("unable to list nodes in cluster: %w", err)
}
for _, node := range nodes.Items {
nodeIP := ""
for _, address := range node.Status.Addresses {
switch address.Type {
case corev1.NodeExternalIP:
nodeIP = address.Address
case corev1.NodeInternalIP:
if nodeIP == "" {
nodeIP = address.Address
}
}
}
if nodeIP != "" {
ai.ServiceIPs = append(ai.ServiceIPs, nodeIP)
// We can't really support multiple nodes as
// the NodePort will be different and the
// current use of hostAliases will lead to
// DNS-style RR requiring all endpoints to use
// the same port
break
}
}
k.Log("⚠️ Service type NodePort detected! Service may fail when nodes are removed from the cluster!")
case svc.Spec.Type == corev1.ServiceTypeLoadBalancer:
if len(svc.Spec.Ports) == 0 {
return nil, fmt.Errorf("port of service could not be derived, service has no ports")
}
ai.ServicePort = int(svc.Spec.Ports[0].Port)
for _, ingressStatus := range svc.Status.LoadBalancer.Ingress {
if ingressStatus.Hostname == "" {
ai.ServiceIPs = append(ai.ServiceIPs, ingressStatus.IP)
} else {
k.Log("Hostname based ingress detected, trying to resolve it")
ips, err := net.LookupHost(ingressStatus.Hostname)
if err != nil {
k.Log(fmt.Sprintf("Could not resolve the hostname of the ingress, falling back to the static IP. Error: %v", err))
ai.ServiceIPs = append(ai.ServiceIPs, ingressStatus.IP)
} else {
k.Log("Hostname resolved, using the found ip(s)")
ai.ServiceIPs = append(ai.ServiceIPs, ips...)
}
}
}
}
switch {
case len(ai.ServiceIPs) > 0:
if verbose {
k.Log("ℹ️ Found ClusterMesh service IPs: %s", ai.ServiceIPs)
}
default:
return nil, fmt.Errorf("unable to derive service IPs automatically")
}
return ai, nil
}
func (k *K8sClusterMesh) patchConfig(ctx context.Context, client k8sClusterMeshImplementation, ai *accessInformation) error {
_, err := client.GetSecret(ctx, k.params.Namespace, defaults.ClusterMeshSecretName, metav1.GetOptions{})
if err != nil {
k.Log("🔑 Secret %s does not exist yet, creating it...", defaults.ClusterMeshSecretName)
_, err = client.CreateSecret(ctx, k.params.Namespace, k8s.NewSecret(defaults.ClusterMeshSecretName, k.params.Namespace, map[string][]byte{}), metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("unable to create secret: %w", err)
}
}
k.Log("🔑 Patching existing secret %s...", defaults.ClusterMeshSecretName)
etcdBase64 := `"` + ai.ClusterName + `": "` + base64.StdEncoding.EncodeToString([]byte(ai.etcdConfiguration())) + `"`
caBase64 := `"` + ai.ClusterName + caSuffix + `": "` + base64.StdEncoding.EncodeToString(ai.CA) + `"`
keyBase64 := `"` + ai.ClusterName + keySuffix + `": "` + base64.StdEncoding.EncodeToString(ai.ClientKey) + `"`
certBase64 := `"` + ai.ClusterName + certSuffix + `": "` + base64.StdEncoding.EncodeToString(ai.ClientCert) + `"`
patch := []byte(`{"data":{` + etcdBase64 + `,` + caBase64 + `,` + keyBase64 + `,` + certBase64 + `}}`)
_, err = client.PatchSecret(ctx, k.params.Namespace, defaults.ClusterMeshSecretName, types.StrategicMergePatchType, patch, metav1.PatchOptions{})
if err != nil {
return fmt.Errorf("unable to patch secret %s with patch %q: %w", defaults.ClusterMeshSecretName, patch, err)
}
var aliases []string
for _, ip := range ai.ServiceIPs {
aliases = append(aliases, `{"ip":"`+ip+`", "hostnames":["`+ai.ClusterName+`.mesh.cilium.io"]}`)
}
patch = []byte(`{"spec":{"template":{"spec":{"hostAliases":[` + strings.Join(aliases, ",") + `]}}}}`)
k.Log("✨ Patching DaemonSet with IP aliases %s...", defaults.ClusterMeshSecretName)
_, err = client.PatchDaemonSet(ctx, k.params.Namespace, defaults.AgentDaemonSetName, types.StrategicMergePatchType, patch, metav1.PatchOptions{})
if err != nil {
return fmt.Errorf("unable to patch DaemonSet %s with patch %q: %w", defaults.AgentDaemonSetName, patch, err)
}
return nil
}
func (k *K8sClusterMesh) Connect(ctx context.Context) error {
remoteCluster, err := k8s.NewClient(k.params.DestinationContext, "")
if err != nil {
return fmt.Errorf("unable to create Kubernetes client to access remote cluster %q: %w", k.params.DestinationContext, err)
}
aiRemote, err := k.extractAccessInformation(ctx, remoteCluster, k.params.DestinationEndpoints, true)
if err != nil {
k.Log("❌ Unable to retrieve access information of remote cluster %q: %s", remoteCluster.ClusterName(), err)
return err
}
if !aiRemote.validate() {
return fmt.Errorf("remote cluster has non-unique name (%s) and/or ID (%s)", aiRemote.ClusterName, aiRemote.ClusterID)
}
aiLocal, err := k.extractAccessInformation(ctx, k.client, k.params.SourceEndpoints, true)
if err != nil {
k.Log("❌ Unable to retrieve access information of local cluster %q: %s", k.client.ClusterName(), err)
return err
}
if !aiLocal.validate() {
return fmt.Errorf("local cluster has non-unique name (%s) and/or ID (%s)", aiLocal.ClusterName, aiLocal.ClusterID)
}
if aiRemote.ClusterName == aiLocal.ClusterName {
return fmt.Errorf("remote and local cluster have the same, non-unique name: %s", aiLocal.ClusterName)
}
if aiRemote.ClusterID == aiLocal.ClusterID {
return fmt.Errorf("remote and local cluster have the same, non-unique ID: %s", aiLocal.ClusterID)
}
k.Log("✨ Connecting cluster %s -> %s...", k.client.ClusterName(), remoteCluster.ClusterName())
if err := k.patchConfig(ctx, k.client, aiRemote); err != nil {
return err
}
k.Log("✨ Connecting cluster %s -> %s...", remoteCluster.ClusterName(), k.client.ClusterName())
if err := k.patchConfig(ctx, remoteCluster, aiLocal); err != nil {
return err
}
k.Log("✅ Connected cluster %s and %s!", k.client.ClusterName(), remoteCluster.ClusterName())
return nil
}
func (k *K8sClusterMesh) disconnectCluster(ctx context.Context, src, dst k8sClusterMeshImplementation) error {
cm, err := dst.GetConfigMap(ctx, k.params.Namespace, defaults.ConfigMapName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("unable to retrieve ConfigMap %q: %w", defaults.ConfigMapName, err)
}
if _, ok := cm.Data[configNameClusterName]; !ok {
return fmt.Errorf("%s is not set in ConfigMap %q", configNameClusterName, defaults.ConfigMapName)
}
clusterName := cm.Data[configNameClusterName]
k.Log("🔑 Patching existing secret %s...", defaults.ClusterMeshSecretName)
meshSecret, err := src.GetSecret(ctx, k.params.Namespace, defaults.ClusterMeshSecretName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("clustermesh configuration secret %s does not exist", defaults.ClusterMeshSecretName)
}
for _, suffix := range []string{"", caSuffix, keySuffix, certSuffix} {
if _, ok := meshSecret.Data[clusterName+suffix]; !ok {
k.Log("⚠️ Key %q does not exist in secret. Cluster already disconnected?", clusterName+suffix)
continue
}
patch := []byte(`[{"op": "remove", "path": "/data/` + clusterName + suffix + `"}]`)
_, err = src.PatchSecret(ctx, k.params.Namespace, defaults.ClusterMeshSecretName, types.JSONPatchType, patch, metav1.PatchOptions{})
if err != nil {
k.Log("❌ Warning: Unable to patch secret %s with path %q: %s", defaults.ClusterMeshSecretName, patch, err)
}
}
return nil
}
func (k *K8sClusterMesh) Disconnect(ctx context.Context) error {
remoteCluster, err := k8s.NewClient(k.params.DestinationContext, "")
if err != nil {
return fmt.Errorf("unable to create Kubernetes client to access remote cluster %q: %w", k.params.DestinationContext, err)
}
if err := k.disconnectCluster(ctx, k.client, remoteCluster); err != nil {
return err
}
if err := k.disconnectCluster(ctx, remoteCluster, k.client); err != nil {
return err
}
k.Log("✅ Disconnected cluster %s and %s.", k.client.ClusterName(), remoteCluster.ClusterName())
return nil
}
type Status struct {
AccessInformation *accessInformation
Service *corev1.Service
Connectivity *ConnectivityStatus
}
func (k *K8sClusterMesh) statusAccessInformation(ctx context.Context, log bool) (*accessInformation, error) {
w := utils.NewWaitObserver(ctx, utils.WaitParameters{Log: func(err error, wait string) {
if log {
k.Log("⌛ Waiting (%s) for access information: %s", wait, err)
}
}})
defer w.Cancel()
retry:
ai, err := k.extractAccessInformation(ctx, k.client, []string{}, false)
if err != nil && k.params.Wait {
if err := w.Retry(err); err != nil {
return nil, err