-
Notifications
You must be signed in to change notification settings - Fork 491
/
application.go
2026 lines (1885 loc) · 63.1 KB
/
application.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 2020 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package application
import (
"context"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/juju/clock"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/featureflag"
"github.com/juju/loggo"
"github.com/juju/version/v2"
"github.com/kr/pretty"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
storagev1 "k8s.io/api/storage/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/pointer"
"github.com/juju/juju/caas"
"github.com/juju/juju/caas/kubernetes/provider/constants"
"github.com/juju/juju/caas/kubernetes/provider/pebble"
"github.com/juju/juju/caas/kubernetes/provider/resources"
"github.com/juju/juju/caas/kubernetes/provider/storage"
"github.com/juju/juju/caas/kubernetes/provider/utils"
k8swatcher "github.com/juju/juju/caas/kubernetes/provider/watcher"
"github.com/juju/juju/cloudconfig/podcfg"
"github.com/juju/juju/core/annotations"
"github.com/juju/juju/core/paths"
"github.com/juju/juju/core/status"
"github.com/juju/juju/core/watcher"
"github.com/juju/juju/juju/osenv"
jujustorage "github.com/juju/juju/storage"
)
var logger = loggo.GetLogger("juju.kubernetes.provider.application")
const (
containerAgentPebblePort = "38812"
// containerProbeInitialDelay is the initial delay in seconds before the probe starts.
containerProbeInitialDelay = 30
// containerProbeTimeout is the timeout for the probe to complete in seconds.
containerProbeTimeout = 1
// containerProbePeriod is the number of seconds between each probe.
containerProbePeriod = 5
// containerProbeSuccess is the number of successful probes to mark the check as healthy.
containerProbeSuccess = 1
// containerLivenessProbeFailure is the number of failed liveness probes to mark the check as unhealthy.
containerLivenessProbeFailure = 3
// containerReadinessProbeFailure = 1 is the number of failed readiness probes to mark the check as unhealthy.
containerReadinessProbeFailure = 1
// containerStartupProbeFailure is the number of failed startup probes to mark the check as unhealthy.
containerStartupProbeFailure = 1
)
var (
containerAgentPebbleVersion = version.MustParse("2.9.37")
profileDirVersion = version.MustParse("3.5-beta1")
pebbleCopyOnceVersion = version.MustParse("3.5-beta1")
)
type app struct {
name string
namespace string
modelUUID string
modelName string
legacyLabels bool
deploymentType caas.DeploymentType
client kubernetes.Interface
newWatcher k8swatcher.NewK8sWatcherFunc
clock clock.Clock
// randomPrefix generates an annotation for stateful sets.
randomPrefix utils.RandomPrefixFunc
newApplier func() resources.Applier
}
// NewApplication returns an application.
func NewApplication(
name string,
namespace string,
modelUUID string,
modelName string,
legacyLabels bool,
deploymentType caas.DeploymentType,
client kubernetes.Interface,
newWatcher k8swatcher.NewK8sWatcherFunc,
clock clock.Clock,
randomPrefix utils.RandomPrefixFunc,
) caas.Application {
return newApplication(
name,
namespace,
modelUUID,
modelName,
legacyLabels,
deploymentType,
client,
newWatcher,
clock,
randomPrefix,
resources.NewApplier,
)
}
func newApplication(
name string,
namespace string,
modelUUID string,
modelName string,
legacyLabels bool,
deploymentType caas.DeploymentType,
client kubernetes.Interface,
newWatcher k8swatcher.NewK8sWatcherFunc,
clock clock.Clock,
randomPrefix utils.RandomPrefixFunc,
newApplier func() resources.Applier,
) *app {
return &app{
name: name,
namespace: namespace,
modelUUID: modelUUID,
modelName: modelName,
legacyLabels: legacyLabels,
deploymentType: deploymentType,
client: client,
newWatcher: newWatcher,
clock: clock,
randomPrefix: randomPrefix,
newApplier: newApplier,
}
}
// Ensure creates or updates an application pod with the given application
// name, agent path, and application config.
func (a *app) Ensure(config caas.ApplicationConfig) (err error) {
// TODO: add support `numUnits`, `Constraints` and `Devices`.
// TODO: storage handling for deployment/daemonset enhancement.
defer func() {
if err != nil {
logger.Errorf("Ensure %s", err)
}
}()
logger.Debugf("creating/updating %s application", a.name)
applier := a.newApplier()
err = a.applyServiceAccountAndSecrets(applier, config)
if err != nil {
return errors.Annotatef(err, "applying service account and secrets")
}
if err := a.configureDefaultService(a.annotations(config)); err != nil {
return errors.Annotatef(err, "ensuring the default service %q", a.name)
}
// Set up the parameters for creating charm storage (if required).
podSpec, err := a.ApplicationPodSpec(config)
if err != nil {
return errors.Annotate(err, "generating application podspec")
}
var handleVolume handleVolumeFunc = func(v corev1.Volume, mountPath string, readOnly bool) (*corev1.VolumeMount, error) {
if err := storage.PushUniqueVolume(podSpec, v, false); err != nil {
return nil, errors.Trace(err)
}
return &corev1.VolumeMount{
Name: v.Name,
ReadOnly: readOnly,
MountPath: mountPath,
}, nil
}
var handleVolumeMount handleVolumeMountFunc = func(storageName string, m corev1.VolumeMount) error {
for i := range podSpec.Containers {
name := podSpec.Containers[i].Name
if name == constants.ApplicationCharmContainer {
podSpec.Containers[i].VolumeMounts = append(podSpec.Containers[i].VolumeMounts, m)
continue
}
for _, mount := range config.Containers[name].Mounts {
if mount.StorageName == storageName {
volumeMountCopy := m
// TODO(sidecar): volumeMountCopy.MountPath was defined in `caas.ApplicationConfig.Filesystems[*].Attachment.Path`.
// Consolidate `caas.ApplicationConfig.Filesystems[*].Attachment.Path` and `caas.ApplicationConfig.Containers[*].Mounts[*].Path`!!!
volumeMountCopy.MountPath = mount.Path
podSpec.Containers[i].VolumeMounts = append(podSpec.Containers[i].VolumeMounts, volumeMountCopy)
}
}
}
return nil
}
var handlePVCForStatelessResource handlePVCFunc = func(pvc corev1.PersistentVolumeClaim, mountPath string, readOnly bool) (*corev1.VolumeMount, error) {
// Ensure PVC.
r := resources.NewPersistentVolumeClaim(pvc.GetName(), a.namespace, &pvc)
applier.Apply(r)
// Push the volume to podspec.
vol := corev1.Volume{
Name: r.GetName(),
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: r.GetName(),
ReadOnly: readOnly,
},
},
}
return handleVolume(vol, mountPath, readOnly)
}
storageClasses, err := resources.ListStorageClass(context.Background(), a.client, metav1.ListOptions{})
if err != nil {
return errors.Trace(err)
}
var handleStorageClass = func(sc storagev1.StorageClass) error {
applier.Apply(&resources.StorageClass{StorageClass: sc})
return nil
}
var configureStorage = func(storageUniqueID string, handlePVC handlePVCFunc) error {
err := a.configureStorage(
storageUniqueID,
config.Filesystems,
storageClasses,
handleVolume, handleVolumeMount, handlePVC, handleStorageClass,
)
return errors.Trace(err)
}
switch a.deploymentType {
case caas.DeploymentStateful:
if err := a.configureHeadlessService(a.name, a.annotations(config)); err != nil {
return errors.Annotatef(err, "creating or updating headless service for %q %q", a.deploymentType, a.name)
}
exists := true
ss, getErr := a.getStatefulSet()
if errors.IsNotFound(getErr) {
exists = false
} else if getErr != nil {
return errors.Trace(getErr)
}
storageUniqueID, err := a.getStorageUniqPrefix(func() (annotationGetter, error) {
return ss, getErr
})
if err != nil {
return errors.Trace(err)
}
var numPods *int32
if !exists {
numPods = pointer.Int32(int32(config.InitialScale))
}
statefulset := resources.StatefulSet{
StatefulSet: appsv1.StatefulSet{
ObjectMeta: metav1.ObjectMeta{
Name: a.name,
Namespace: a.namespace,
Labels: a.labels(),
Annotations: a.annotations(config).
Add(utils.AnnotationKeyApplicationUUID(false), storageUniqueID),
},
Spec: appsv1.StatefulSetSpec{
Replicas: numPods,
Selector: &metav1.LabelSelector{
MatchLabels: a.selectorLabels(),
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: a.selectorLabels(),
Annotations: a.annotations(config),
},
Spec: *podSpec,
},
PodManagementPolicy: appsv1.ParallelPodManagement,
ServiceName: HeadlessServiceName(a.name),
},
},
}
if err = configureStorage(
storageUniqueID,
func(pvc corev1.PersistentVolumeClaim, mountPath string, readOnly bool) (*corev1.VolumeMount, error) {
if err := storage.PushUniqueVolumeClaimTemplate(&statefulset.Spec, pvc); err != nil {
return nil, errors.Trace(err)
}
return &corev1.VolumeMount{
Name: pvc.GetName(),
ReadOnly: readOnly,
MountPath: mountPath,
}, nil
},
); err != nil {
return errors.Trace(err)
}
applier.Apply(&statefulset)
case caas.DeploymentStateless:
exists := true
d, getErr := a.getDeployment()
if errors.IsNotFound(getErr) {
exists = false
} else if getErr != nil {
return errors.Trace(getErr)
}
storageUniqueID, err := a.getStorageUniqPrefix(func() (annotationGetter, error) {
return d, getErr
})
if err != nil {
return errors.Trace(err)
}
var numPods *int32
if !exists {
numPods = pointer.Int32(int32(config.InitialScale))
}
// Config storage to update the podspec with storage info.
if err = configureStorage(storageUniqueID, handlePVCForStatelessResource); err != nil {
return errors.Trace(err)
}
deployment := resources.Deployment{
Deployment: appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: a.name,
Namespace: a.namespace,
Labels: a.labels(),
Annotations: a.annotations(config).
Add(utils.AnnotationKeyApplicationUUID(false), storageUniqueID),
},
Spec: appsv1.DeploymentSpec{
Replicas: numPods,
Selector: &metav1.LabelSelector{
MatchLabels: a.selectorLabels(),
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: a.selectorLabels(),
Annotations: a.annotations(config),
},
Spec: *podSpec,
},
},
},
}
applier.Apply(&deployment)
case caas.DeploymentDaemon:
storageUniqueID, err := a.getStorageUniqPrefix(func() (annotationGetter, error) {
return a.getDaemonSet()
})
if err != nil {
return errors.Trace(err)
}
// Config storage to update the podspec with storage info.
if err = configureStorage(storageUniqueID, handlePVCForStatelessResource); err != nil {
return errors.Trace(err)
}
daemonset := resources.DaemonSet{
DaemonSet: appsv1.DaemonSet{
ObjectMeta: metav1.ObjectMeta{
Name: a.name,
Namespace: a.namespace,
Labels: a.labels(),
Annotations: a.annotations(config).
Add(utils.AnnotationKeyApplicationUUID(false), storageUniqueID),
},
Spec: appsv1.DaemonSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: a.selectorLabels(),
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: a.selectorLabels(),
Annotations: a.annotations(config),
},
Spec: *podSpec,
},
},
},
}
applier.Apply(&daemonset)
default:
return errors.NotSupportedf("unknown deployment type")
}
return applier.Run(context.Background(), a.client, false)
}
func (a *app) applyServiceAccountAndSecrets(applier resources.Applier, config caas.ApplicationConfig) error {
secret := resources.Secret{
Secret: corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: a.secretName(),
Namespace: a.namespace,
Labels: a.labels(),
Annotations: a.annotations(config),
},
Data: map[string][]byte{
"JUJU_K8S_APPLICATION": []byte(a.name),
"JUJU_K8S_MODEL": []byte(a.modelUUID),
"JUJU_K8S_APPLICATION_PASSWORD": []byte(config.IntroductionSecret),
"JUJU_K8S_CONTROLLER_ADDRESSES": []byte(config.ControllerAddresses),
"JUJU_K8S_CONTROLLER_CA_CERT": []byte(config.ControllerCertBundle),
},
},
}
applier.Apply(&secret)
serviceAccount := resources.ServiceAccount{
ServiceAccount: corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: a.serviceAccountName(),
Namespace: a.namespace,
Labels: a.labels(),
Annotations: a.annotations(config),
},
// Will be automounted by the pod.
AutomountServiceAccountToken: pointer.Bool(false),
},
}
applier.Apply(&serviceAccount)
role := resources.Role{
Role: rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Name: a.serviceAccountName(),
Namespace: a.namespace,
Labels: a.labels(),
Annotations: a.annotations(config),
},
Rules: a.roleRules(config.Trust),
},
}
applier.Apply(&role)
roleBinding := resources.RoleBinding{
RoleBinding: rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: a.serviceAccountName(),
Namespace: a.namespace,
Labels: a.labels(),
Annotations: a.annotations(config),
},
RoleRef: rbacv1.RoleRef{
Name: a.serviceAccountName(),
Kind: "Role",
},
Subjects: []rbacv1.Subject{
{
Kind: rbacv1.ServiceAccountKind,
Name: a.serviceAccountName(),
Namespace: a.namespace,
},
},
},
}
applier.Apply(&roleBinding)
clusterRole := resources.ClusterRole{
ClusterRole: rbacv1.ClusterRole{
ObjectMeta: metav1.ObjectMeta{
Name: a.qualifiedClusterName(),
Labels: a.labels(),
Annotations: a.annotations(config),
},
Rules: a.clusterRoleRules(config.Trust),
},
}
applier.Apply(&clusterRole)
clusterRoleBinding := resources.ClusterRoleBinding{
ClusterRoleBinding: rbacv1.ClusterRoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: a.qualifiedClusterName(),
Labels: a.labels(),
Annotations: a.annotations(config),
},
RoleRef: rbacv1.RoleRef{
Name: a.qualifiedClusterName(),
Kind: "ClusterRole",
},
Subjects: []rbacv1.Subject{
{
Kind: rbacv1.ServiceAccountKind,
Name: a.serviceAccountName(),
Namespace: a.namespace,
},
},
},
}
applier.Apply(&clusterRoleBinding)
return a.applyImagePullSecrets(applier, config)
}
// Upgrade upgrades the app to the specified version.
func (a *app) Upgrade(ver version.Number) error {
// TODO(sidecar): Unify this with Ensure
applier := a.newApplier()
if err := a.upgradeMainResource(applier, ver); err != nil {
return errors.Trace(err)
}
// TODO(sidecar): we could query the cluster for all resources with the `app.juju.is/created-by` and `app.kubernetes.io/name` labels instead
// (so longer as the resource also does have the juju version annotation already).
// Then we don't have to worry about missing anything if something is added later and not also updated here.
for _, r := range []annotationUpdater{
resources.NewSecret(a.secretName(), a.namespace, nil),
resources.NewServiceAccount(a.serviceAccountName(), a.namespace, nil),
resources.NewRole(a.serviceAccountName(), a.namespace, nil),
resources.NewRoleBinding(a.serviceAccountName(), a.namespace, nil),
resources.NewClusterRole(a.qualifiedClusterName(), nil),
resources.NewClusterRoleBinding(a.qualifiedClusterName(), nil),
resources.NewService(a.name, a.namespace, nil),
} {
if err := r.Get(context.Background(), a.client); err != nil {
return errors.Trace(err)
}
existingAnnotations := annotations.New(r.GetAnnotations())
r.SetAnnotations(a.upgradeAnnotations(existingAnnotations, ver))
applier.Apply(r)
}
return applier.Run(context.Background(), a.client, false)
}
type annotationUpdater interface {
resources.Resource
GetAnnotations() map[string]string
SetAnnotations(annotations map[string]string)
}
func (a *app) upgradeHeadlessService(applier resources.Applier, ver version.Number) error {
r := resources.NewService(HeadlessServiceName(a.name), a.namespace, nil)
if err := r.Get(context.Background(), a.client); err != nil {
return errors.Trace(err)
}
r.SetAnnotations(a.upgradeAnnotations(annotations.New(r.GetAnnotations()), ver))
applier.Apply(r)
return nil
}
func (a *app) upgradeMainResource(applier resources.Applier, ver version.Number) error {
switch a.deploymentType {
case caas.DeploymentStateful:
if err := a.upgradeHeadlessService(applier, ver); err != nil {
return errors.Trace(err)
}
ss := resources.NewStatefulSet(a.name, a.namespace, nil)
if err := ss.Get(context.Background(), a.client); err != nil {
return errors.Trace(err)
}
initContainers := ss.Spec.Template.Spec.InitContainers
if len(initContainers) != 1 {
return errors.NotValidf("init container of %q", a.name)
}
initContainer := initContainers[0]
var err error
initContainer.Image, err = podcfg.RebuildOldOperatorImagePath(initContainer.Image, ver)
if err != nil {
return errors.Trace(err)
}
ss.Spec.Template.Spec.InitContainers = []corev1.Container{initContainer}
ss.Spec.Template.SetAnnotations(a.upgradeAnnotations(annotations.New(ss.Spec.Template.GetAnnotations()), ver))
ss.SetAnnotations(a.upgradeAnnotations(annotations.New(ss.GetAnnotations()), ver))
applier.Apply(ss)
return nil
case caas.DeploymentStateless:
return errors.NotSupportedf("upgrade for deployment type %q", a.deploymentType)
case caas.DeploymentDaemon:
return errors.NotSupportedf("upgrade for deployment type %q", a.deploymentType)
default:
return errors.NotSupportedf("unknown deployment type %q", a.deploymentType)
}
}
// Exists indicates if the application for the specified
// application exists, and whether the application is terminating.
func (a *app) Exists() (caas.DeploymentState, error) {
checks := []struct {
label string
check func() (bool, bool, error)
forceTerminating bool
}{
{},
{"secret", a.secretExists, false},
{"service", a.serviceExists, false},
{"roleBinding", a.roleBindingExists, false},
{"role", a.roleExists, false},
{"clusterRoleBinding", a.clusterRoleBindingExists, false},
{"clusterRole", a.clusterRoleExists, false},
{"serviceAccount", a.serviceAccountExists, false},
}
switch a.deploymentType {
case caas.DeploymentStateful:
checks[0].label = "statefulset"
checks[0].check = a.statefulSetExists
case caas.DeploymentStateless:
checks[0].label = "deployment"
checks[0].check = a.deploymentExists
case caas.DeploymentDaemon:
checks[0].label = "daemonset"
checks[0].check = a.daemonSetExists
default:
return caas.DeploymentState{}, errors.NotSupportedf("unknown deployment type")
}
state := caas.DeploymentState{}
for _, c := range checks {
exists, terminating, err := c.check()
if err != nil {
return caas.DeploymentState{}, errors.Annotatef(err, "%s resource check", c.label)
}
if !exists {
continue
}
state.Exists = true
if terminating || c.forceTerminating {
// Terminating is always set to true regardless of whether the resource is failed as terminating
// since it's the overall state that is reported baca.
logger.Debugf("application %q exists and is terminating due to dangling %s resource(s)", a.name, c.label)
return caas.DeploymentState{Exists: true, Terminating: true}, nil
}
}
return state, nil
}
// HeadlessServiceName is an idempotent function for returning the name of the
// endpoints service juju make for applications.
func HeadlessServiceName(appName string) string {
return fmt.Sprintf("%s-endpoints", appName)
}
func (a *app) configureHeadlessService(name string, annotation annotations.Annotation) error {
svc := resources.NewService(HeadlessServiceName(name), a.namespace, &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Labels: a.labels(),
Annotations: annotation.
Add("service.alpha.kubernetes.io/tolerate-unready-endpoints", "true"),
},
Spec: corev1.ServiceSpec{
Selector: a.selectorLabels(),
Type: corev1.ServiceTypeClusterIP,
ClusterIP: "None",
PublishNotReadyAddresses: true,
},
})
return svc.Apply(context.Background(), a.client)
}
const (
placeholderPortName = "placeholder"
placeholderPort = 65535
)
// configureDefaultService configures the default service for the application.
// It's only configured once when the application was deployed in the first time.
func (a *app) configureDefaultService(annotation annotations.Annotation) (err error) {
svc := resources.NewService(a.name, a.namespace, &corev1.Service{
ObjectMeta: metav1.ObjectMeta{
Labels: a.labels(),
Annotations: annotation,
},
Spec: corev1.ServiceSpec{
Selector: a.selectorLabels(),
Type: corev1.ServiceTypeClusterIP,
Ports: []corev1.ServicePort{{
Name: placeholderPortName,
Port: placeholderPort,
}},
},
})
return svc.Apply(context.Background(), a.client)
}
// UpdateService updates the default service with specific service type and port mappings.
func (a *app) UpdateService(param caas.ServiceParam) error {
// This method will be used for juju [un]expose.
// TODO(sidecar): it might be changed later when we have proper modelling for the juju expose for the sidecar charms.
svc, err := a.getService()
if err != nil {
return errors.Annotatef(err, "getting existing service %q", a.name)
}
svc.Service.Spec.Type = corev1.ServiceType(param.Type)
svc.Service.Spec.Ports = make([]corev1.ServicePort, len(param.Ports))
for i, p := range param.Ports {
if svc.Service.Spec.Ports[i], err = convertServicePort(p); err != nil {
return errors.Trace(err)
}
}
applier := a.newApplier()
applier.Apply(svc)
if err := a.updateContainerPorts(applier, svc.Service.Spec.Ports); err != nil {
return errors.Trace(err)
}
return applier.Run(context.Background(), a.client, false)
}
func convertServicePort(port caas.ServicePort) (out corev1.ServicePort, err error) {
var protocol corev1.Protocol
switch port.Protocol {
case "TCP", "tcp":
protocol = corev1.ProtocolTCP
case "UDP", "udp":
protocol = corev1.ProtocolUDP
case "SCTP", "sctp":
protocol = corev1.ProtocolSCTP
default:
return out, errors.NotValidf("protocol %q for service %q", port.Protocol, port.Name)
}
return corev1.ServicePort{
Name: port.Name,
Port: int32(port.Port),
TargetPort: intstr.FromInt(port.TargetPort),
Protocol: protocol,
}, nil
}
func (a *app) getService() (*resources.Service, error) {
svc := resources.NewService(a.name, a.namespace, nil)
if err := svc.Get(context.Background(), a.client); err != nil {
if k8serrors.IsNotFound(err) {
return nil, errors.NotFoundf("service %q", a.name)
}
return nil, errors.Trace(err)
}
return svc, nil
}
const portNamePrefix = "juju-"
// UpdatePorts updates port mappings on the specified service.
func (a *app) UpdatePorts(ports []caas.ServicePort, updateContainerPorts bool) error {
svc, err := a.getService()
if err != nil {
return errors.Annotatef(err, "getting existing service %q", a.name)
}
var replacePortsPatchType = types.MergePatchType
// We want to replace rather than merge here.
svc.PatchType = &replacePortsPatchType
var expectedPorts []corev1.ServicePort
for _, p := range svc.Service.Spec.Ports {
if p.Name == placeholderPortName && len(ports) > 0 {
// Ignore placeholder port if there are ports supplied by the charm.
continue
}
if strings.HasPrefix(p.Name, portNamePrefix) {
// Port managed by Juju - will be replaced,
continue
}
// The ports that are not managed by Juju should be kept.
expectedPorts = append(expectedPorts, p)
}
for _, port := range ports {
sp, err := convertServicePort(port)
if err != nil {
return errors.Trace(err)
}
sp.Name = portNamePrefix + sp.Name
expectedPorts = append(expectedPorts, sp)
}
svc.Service.Spec.Ports = expectedPorts
applier := a.newApplier()
applier.Apply(svc)
if updateContainerPorts {
if err := a.updateContainerPorts(applier, svc.Service.Spec.Ports); err != nil {
return errors.Trace(err)
}
}
err = applier.Run(context.Background(), a.client, false)
return errors.Trace(err)
}
func convertContainerPort(p corev1.ServicePort) corev1.ContainerPort {
return corev1.ContainerPort{
Name: p.Name,
ContainerPort: p.TargetPort.IntVal,
Protocol: p.Protocol,
}
}
func (a *app) updateContainerPorts(applier resources.Applier, ports []corev1.ServicePort) error {
updatePodSpec := func(spec *corev1.PodSpec, containerPorts []corev1.ContainerPort) {
for i, c := range spec.Containers {
ps := containerPorts
if c.Name != constants.ApplicationCharmContainer {
spec.Containers[i].Ports = ps
}
}
}
containerPorts := make([]corev1.ContainerPort, len(ports))
for i, p := range ports {
containerPorts[i] = convertContainerPort(p)
}
switch a.deploymentType {
case caas.DeploymentStateful:
ss := resources.NewStatefulSet(a.name, a.namespace, nil)
if err := ss.Get(context.Background(), a.client); err != nil {
return errors.Trace(err)
}
updatePodSpec(&ss.StatefulSet.Spec.Template.Spec, containerPorts)
applier.Apply(ss)
case caas.DeploymentStateless:
d := resources.NewDeployment(a.name, a.namespace, nil)
if err := d.Get(context.Background(), a.client); err != nil {
return errors.Trace(err)
}
updatePodSpec(&d.Deployment.Spec.Template.Spec, containerPorts)
applier.Apply(d)
case caas.DeploymentDaemon:
d := resources.NewDaemonSet(a.name, a.namespace, nil)
if err := d.Get(context.Background(), a.client); err != nil {
return errors.Trace(err)
}
updatePodSpec(&d.DaemonSet.Spec.Template.Spec, containerPorts)
applier.Apply(d)
default:
return errors.NotSupportedf("unknown deployment type")
}
return nil
}
func (a *app) getStatefulSet() (*resources.StatefulSet, error) {
ss := resources.NewStatefulSet(a.name, a.namespace, nil)
if err := ss.Get(context.Background(), a.client); err != nil {
return nil, err
}
return ss, nil
}
func (a *app) getDeployment() (*resources.Deployment, error) {
ss := resources.NewDeployment(a.name, a.namespace, nil)
if err := ss.Get(context.Background(), a.client); err != nil {
return nil, err
}
return ss, nil
}
func (a *app) getDaemonSet() (*resources.DaemonSet, error) {
ss := resources.NewDaemonSet(a.name, a.namespace, nil)
if err := ss.Get(context.Background(), a.client); err != nil {
return nil, err
}
return ss, nil
}
func (a *app) statefulSetExists() (exists bool, terminating bool, err error) {
ss := resources.NewStatefulSet(a.name, a.namespace, nil)
err = ss.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, ss.DeletionTimestamp != nil, nil
}
func (a *app) deploymentExists() (exists bool, terminating bool, err error) {
ss := resources.NewDeployment(a.name, a.namespace, nil)
err = ss.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, ss.DeletionTimestamp != nil, nil
}
func (a *app) daemonSetExists() (exists bool, terminating bool, err error) {
ss := resources.NewDaemonSet(a.name, a.namespace, nil)
err = ss.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, ss.DeletionTimestamp != nil, nil
}
func (a *app) secretExists() (exists bool, terminating bool, err error) {
ss := resources.NewSecret(a.secretName(), a.namespace, nil)
err = ss.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, ss.DeletionTimestamp != nil, nil
}
func (a *app) serviceExists() (exists bool, terminating bool, err error) {
ss := resources.NewService(a.name, a.namespace, nil)
err = ss.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, ss.DeletionTimestamp != nil, nil
}
func (a *app) roleExists() (exists bool, terminating bool, err error) {
r := resources.NewRole(a.serviceAccountName(), a.namespace, nil)
err = r.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, r.DeletionTimestamp != nil, nil
}
func (a *app) roleBindingExists() (exists bool, terminating bool, err error) {
rb := resources.NewRoleBinding(a.serviceAccountName(), a.namespace, nil)
err = rb.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, rb.DeletionTimestamp != nil, nil
}
func (a *app) clusterRoleExists() (exists bool, terminating bool, err error) {
r := resources.NewClusterRole(a.qualifiedClusterName(), nil)
err = r.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, r.DeletionTimestamp != nil, nil
}
func (a *app) clusterRoleBindingExists() (exists bool, terminating bool, err error) {
rb := resources.NewClusterRoleBinding(a.qualifiedClusterName(), nil)
err = rb.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, rb.DeletionTimestamp != nil, nil
}
func (a *app) serviceAccountExists() (exists bool, terminating bool, err error) {
sa := resources.NewServiceAccount(a.serviceAccountName(), a.namespace, nil)
err = sa.Get(context.Background(), a.client)
if errors.IsNotFound(err) {
return false, false, nil
} else if err != nil {
return false, false, errors.Trace(err)
}
return true, sa.DeletionTimestamp != nil, nil
}
// Delete deletes the specified application.
func (a *app) Delete() error {
logger.Debugf("deleting %s application", a.name)
applier := a.newApplier()
switch a.deploymentType {
case caas.DeploymentStateful:
applier.Delete(resources.NewStatefulSet(a.name, a.namespace, nil))
applier.Delete(resources.NewService(HeadlessServiceName(a.name), a.namespace, nil))
case caas.DeploymentStateless:
applier.Delete(resources.NewDeployment(a.name, a.namespace, nil))
case caas.DeploymentDaemon:
applier.Delete(resources.NewDaemonSet(a.name, a.namespace, nil))
default:
return errors.NotSupportedf("unknown deployment type")
}
applier.Delete(resources.NewService(a.name, a.namespace, nil))
applier.Delete(resources.NewSecret(a.secretName(), a.namespace, nil))
applier.Delete(resources.NewRoleBinding(a.serviceAccountName(), a.namespace, nil))