This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 328
/
platform.go
2007 lines (1749 loc) · 61.5 KB
/
platform.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 k8s
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/docker/distribution/reference"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/hashicorp/go-hclog"
"github.com/mitchellh/copystructure"
"github.com/mitchellh/mapstructure"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
v1 "k8s.io/api/apps/v1"
autoscalingv1 "k8s.io/api/autoscaling/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
k8sresource "k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/wait"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"github.com/hashicorp/waypoint-plugin-sdk/component"
"github.com/hashicorp/waypoint-plugin-sdk/docs"
"github.com/hashicorp/waypoint-plugin-sdk/framework/resource"
sdk "github.com/hashicorp/waypoint-plugin-sdk/proto/gen"
"github.com/hashicorp/waypoint-plugin-sdk/terminal"
"github.com/hashicorp/waypoint/builtin/aws/utils"
"github.com/hashicorp/waypoint/builtin/docker"
)
const (
labelId = "waypoint.hashicorp.com/id"
labelNonce = "waypoint.hashicorp.com/nonce"
DefaultServicePort = 3000
)
// Platform is the Platform implementation for Kubernetes.
type Platform struct {
config Config
}
// Config implements Configurable
func (p *Platform) Config() (interface{}, error) {
return &p.config, nil
}
// DeployFunc implements component.Platform
func (p *Platform) DeployFunc() interface{} {
return p.Deploy
}
// DestroyFunc implements component.Destroyer
func (p *Platform) DestroyFunc() interface{} {
return p.Destroy
}
// ValidateAuthFunc implements component.Authenticator
func (p *Platform) ValidateAuthFunc() interface{} {
return p.ValidateAuth
}
// AuthFunc implements component.Authenticator
func (p *Platform) AuthFunc() interface{} {
return p.Auth
}
func (p *Platform) Auth() error {
return nil
}
func (p *Platform) ValidateAuth() error {
return nil
}
func (p *Platform) StatusFunc() interface{} {
return p.Status
}
// DefaultReleaserFunc implements component.PlatformReleaser
func (p *Platform) DefaultReleaserFunc() interface{} {
var rc ReleaserConfig
if err := mapstructure.Decode(p.config, &rc); err != nil {
// shouldn't happen
panic("error decoding config: " + err.Error())
}
return func() *Releaser {
return &Releaser{
config: rc,
}
}
}
// ConfigSet is called after a configuration has been decoded
// we can use this to validate the config
func (p *Platform) ConfigSet(config interface{}) error {
c, ok := config.(*Config)
if !ok {
// this should never happen
return status.Errorf(codes.FailedPrecondition, "invalid configuration, expected *k8s.Config, got %T", config)
}
if len(c.DeprecatedPorts) > 0 {
return status.Errorf(codes.InvalidArgument, "invalid kubernetes platform config - the 'ports' field has been deprecated and removed "+
"in favor of Pod.Container.Port. Refer to Port documentation here: https://www.waypointproject.io/plugins/kubernetes#port")
}
// Some fields can be specified on pod.Container and at the top level, for convenience and for
// historical reasons. Validate that both are not set at once.
if c.Pod != nil && c.Pod.Container != nil {
containerOverlayErrStr := "%s defined multiple times - in top level config and in Pod.Container"
container := c.Pod.Container
err := utils.Error(validation.ValidateStruct(c,
validation.Field(&c.Probe,
validation.Empty.When(container.Probe != nil).Error(fmt.Sprintf(containerOverlayErrStr, "Probe")),
),
validation.Field(&c.ProbePath,
validation.Empty.When(container.ProbePath != "").Error(fmt.Sprintf(containerOverlayErrStr, "ProbePath")),
),
validation.Field(&c.Resources,
validation.Empty.When(container.Resources != nil).Error(fmt.Sprintf(containerOverlayErrStr, "Resources")),
),
validation.Field(&c.CPU,
validation.Empty.When(container.CPU != nil).Error(fmt.Sprintf(containerOverlayErrStr, "CPU")),
),
validation.Field(&c.Memory,
validation.Empty.When(container.Memory != nil).Error(fmt.Sprintf(containerOverlayErrStr, "Memory")),
),
validation.Field(&c.StaticEnvVars,
validation.Empty.When(container.StaticEnvVars != nil).Error(fmt.Sprintf(containerOverlayErrStr, "StaticEnvVars")),
),
validation.Field(&c.ServicePort,
validation.Empty.When(len(container.Ports) > 0).Error("Cannot define both 'service_port' and container 'port'. Use"+
" container 'port' multiple times for configuring multiple container ports"),
),
))
if err != nil {
return status.Errorf(codes.InvalidArgument, "Invalid kubernetes platform plugin config: %s", err.Error())
}
}
return nil
}
func (p *Platform) resourceManager(log hclog.Logger, dcr *component.DeclaredResourcesResp) *resource.Manager {
return resource.NewManager(
resource.WithLogger(log.Named("resource_manager")),
resource.WithValueProvider(p.getClientset),
resource.WithDeclaredResourcesResp(dcr),
resource.WithResource(resource.NewResource(
resource.WithName(platformName),
resource.WithState(&Resource_Deployment{}),
resource.WithCreate(p.resourceDeploymentCreate),
resource.WithDestroy(p.resourceDeploymentDestroy),
resource.WithStatus(p.resourceDeploymentStatus),
resource.WithPlatform(platformName),
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_INSTANCE_MANAGER),
)),
resource.WithResource(resource.NewResource(
resource.WithName("autoscaler"),
resource.WithState(&Resource_Autoscale{}),
resource.WithCreate(p.resourceAutoscalerCreate),
resource.WithDestroy(p.resourceAutoscalerDestroy),
resource.WithStatus(p.resourceAutoscalerStatus),
resource.WithPlatform(platformName),
resource.WithCategoryDisplayHint(sdk.ResourceCategoryDisplayHint_INSTANCE_MANAGER),
)),
)
}
// getClientset is a value provider for our resource manager and provides
// the connection information used by resources to interact with Kubernetes.
func (p *Platform) getClientset() (*clientsetInfo, error) {
// Get our client
clientSet, ns, config, err := Clientset(p.config.KubeconfigPath, p.config.Context)
if err != nil {
return nil, err
}
return &clientsetInfo{
Clientset: clientSet,
Namespace: ns,
Config: config,
}, nil
}
func (p *Platform) resourceDeploymentStatus(
ctx context.Context,
sg terminal.StepGroup,
deploymentState *Resource_Deployment,
clientset *clientsetInfo,
sr *resource.StatusResponse,
) error {
s := sg.Add("Checking status of the Kubernetes deployment resource...")
defer s.Abort()
namespace := p.config.Namespace
if namespace == "" {
namespace = clientset.Namespace
}
// Get deployment status
deploymentResource := sdk.StatusReport_Resource{
Type: "deployment",
CategoryDisplayHint: sdk.ResourceCategoryDisplayHint_INSTANCE_MANAGER,
}
sr.Resources = append(sr.Resources, &deploymentResource)
deployResp, err := clientset.Clientset.AppsV1().Deployments(namespace).Get(ctx, deploymentState.Name, metav1.GetOptions{})
if deployResp == nil {
return status.Errorf(codes.FailedPrecondition, "kubernetes deployment response cannot be empty")
} else if err != nil {
if !errors.IsNotFound(err) {
return status.Errorf(codes.FailedPrecondition, "error getting kubernetes deployment %s: %s", deploymentState.Name, err)
} else {
deploymentResource.Name = deploymentState.Name
deploymentResource.Health = sdk.StatusReport_MISSING
deploymentResource.HealthMessage = sdk.StatusReport_MISSING.String()
// Continue on with getting statuses for the rest of our resources
}
} else {
// Found the deployment, and can use it to populate our resource
var mostRecentCondition v1.DeploymentCondition
for _, condition := range deployResp.Status.Conditions {
if condition.LastUpdateTime.Time.After(mostRecentCondition.LastUpdateTime.Time) {
mostRecentCondition = condition
}
}
// The most recently updated condition isn't always the most pertinent - a healthy deployment
// can have a "Progressing" most recently updated condition at steady-state.
// If the deployment exists, we'll mark it as "Ready", and rely on our pod status checks
// to give more detailed status.
deployHealth := sdk.StatusReport_READY
// Redact env vars from containers - they can contain secrets
for i := 0; i < len(deployResp.Spec.Template.Spec.Containers); i++ {
deployResp.Spec.Template.Spec.Containers[i].Env = []corev1.EnvVar{}
}
deployStateJson, err := json.Marshal(map[string]interface{}{
"deployment": deployResp,
})
if err != nil {
return status.Errorf(codes.FailedPrecondition, "failed to marshal deployment to json: %s", err)
}
deploymentResource.Name = deployResp.Name
deploymentResource.Id = fmt.Sprintf("%s", deployResp.UID)
deploymentResource.CreatedTime = timestamppb.New(deployResp.CreationTimestamp.Time)
deploymentResource.Health = deployHealth
deploymentResource.HealthMessage = fmt.Sprintf("%s: %s", mostRecentCondition.Type, mostRecentCondition.Message)
deploymentResource.StateJson = string(deployStateJson)
}
// Get pod status
podClient := clientset.Clientset.CoreV1().Pods(namespace)
podLabelId := fmt.Sprintf("app=%s", deploymentState.Name)
podList, err := podClient.List(ctx, metav1.ListOptions{LabelSelector: podLabelId})
if err != nil {
return status.Errorf(codes.FailedPrecondition, "error listing pods to determine application health: %s", err)
}
if podList == nil {
return status.Errorf(codes.FailedPrecondition, "kubernetes pod list cannot be nil")
}
for _, pod := range podList.Items {
// Redact env vars because they can contain secrets
for i := 0; i < len(pod.Spec.Containers); i++ {
pod.Spec.Containers[i].Env = []corev1.EnvVar{}
}
podJson, err := json.Marshal(map[string]interface{}{
"pod": pod,
"hostIP": pod.Status.HostIP,
"ipAddress": pod.Status.PodIP,
})
if err != nil {
return status.Errorf(codes.Internal, "failed to marshal k8s pod definition to json: %s", podJson)
}
var health sdk.StatusReport_Health
var healthMessage string
switch pod.Status.Phase {
case corev1.PodPending:
health = sdk.StatusReport_ALIVE
case corev1.PodRunning:
health = sdk.StatusReport_ALIVE
// Extra checks on the latest condition to ensure pod is reporting ready and running
for _, c := range pod.Status.Conditions {
if c.Status == corev1.ConditionTrue && c.Type == corev1.PodReady {
health = sdk.StatusReport_READY
healthMessage = fmt.Sprintf("ready")
break
}
}
case corev1.PodSucceeded:
// kind of a weird one - in our current model pods are always assumed to be long-lived. If a pod exits at all, it's Down.
health = sdk.StatusReport_DOWN
case corev1.PodFailed:
health = sdk.StatusReport_DOWN
case corev1.PodUnknown:
health = sdk.StatusReport_UNKNOWN
default:
health = sdk.StatusReport_UNKNOWN
}
// If we don't have anything better, the pod status phase is an OK health message
// NOTE(izaak): An alternative health message could be the "type" of all conditions tied for the most recent
// latestTransitionTime concatenated together.
if healthMessage == "" {
healthMessage = fmt.Sprintf("%s", pod.Status.Phase)
}
sr.Resources = append(sr.Resources, &sdk.StatusReport_Resource{
Name: pod.ObjectMeta.Name,
Id: fmt.Sprintf("%s", pod.UID),
Type: "pod",
ParentResourceId: deploymentResource.Id,
Health: health,
HealthMessage: healthMessage,
CategoryDisplayHint: sdk.ResourceCategoryDisplayHint_INSTANCE,
StateJson: string(podJson),
CreatedTime: timestamppb.New(pod.CreationTimestamp.Time),
})
}
s.Update("Finished building report for Kubernetes deployment resource")
s.Done()
return nil
}
func configureContainer(
c *Container,
image string,
envVars map[string]string,
scratchSpace []string,
volumes []corev1.Volume,
autoscaleConfig *AutoscaleConfig,
log hclog.Logger,
ui terminal.UI,
) (*corev1.Container, error) {
// If the user is using the latest tag, then don't specify an overriding pull policy.
// This by default means kubernetes will always pull so that latest is useful.
var pullPolicy corev1.PullPolicy
imageReference, err := reference.Parse(image)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "image %q is not a valid OCI reference: %q", image, err)
}
taggedImageReference, ok := imageReference.(reference.Tagged)
if !ok || taggedImageReference.Tag() == "latest" {
// If no tag is set, docker will default to "latest", and we always want to pull.
pullPolicy = corev1.PullAlways
} else {
// A tag is present, we can use k8s worker caching
pullPolicy = corev1.PullIfNotPresent
}
var k8sPorts []corev1.ContainerPort
for _, port := range c.Ports {
// Default the port protocol to TCP
if port.Protocol == "" {
port.Protocol = "TCP"
}
k8sPorts = append(k8sPorts, corev1.ContainerPort{
Name: port.Name,
ContainerPort: int32(port.Port),
HostPort: int32(port.HostPort),
HostIP: port.HostIP,
Protocol: corev1.Protocol(strings.TrimSpace(strings.ToUpper(port.Protocol))),
})
}
if envVars == nil {
envVars = make(map[string]string)
}
// assume the first port defined is the 'main' port to use
var defaultPort int
if len(k8sPorts) != 0 {
defaultPort = int(k8sPorts[0].ContainerPort)
envVars["PORT"] = fmt.Sprintf("%d", defaultPort)
}
var k8sEnvVars []corev1.EnvVar
for k, v := range envVars {
k8sEnvVars = append(k8sEnvVars, corev1.EnvVar{Name: k, Value: v})
}
initialDelaySeconds := int32(5)
timeoutSeconds := int32(5)
failureThreshold := int32(30)
if c.Probe != nil {
if c.Probe.InitialDelaySeconds != 0 {
initialDelaySeconds = int32(c.Probe.InitialDelaySeconds)
}
if c.Probe.TimeoutSeconds != 0 {
timeoutSeconds = int32(c.Probe.TimeoutSeconds)
}
if c.Probe.FailureThreshold != 0 {
failureThreshold = int32(c.Probe.FailureThreshold)
}
}
// Get container resource limits and requests
resourceLimits := make(map[corev1.ResourceName]k8sresource.Quantity)
resourceRequests := make(map[corev1.ResourceName]k8sresource.Quantity)
if c.CPU != nil {
if c.CPU.Request != "" {
q, err := k8sresource.ParseQuantity(c.CPU.Request)
if err != nil {
return nil,
status.Errorf(codes.InvalidArgument, "failed to parse cpu request %s to k8s quantity: %s", c.CPU.Request, err)
}
resourceRequests[corev1.ResourceCPU] = q
}
if c.CPU.Limit != "" {
q, err := k8sresource.ParseQuantity(c.CPU.Limit)
if err != nil {
return nil,
status.Errorf(codes.InvalidArgument, "failed to parse cpu limit %s to k8s quantity: %s", c.CPU.Limit, err)
}
resourceLimits[corev1.ResourceCPU] = q
}
}
if c.Memory != nil {
if c.Memory.Request != "" {
q, err := k8sresource.ParseQuantity(c.Memory.Request)
if err != nil {
return nil,
status.Errorf(codes.InvalidArgument, "failed to parse memory requested %s to k8s quantity: %s", c.Memory.Request, err)
}
resourceRequests[corev1.ResourceMemory] = q
}
if c.Memory.Limit != "" {
q, err := k8sresource.ParseQuantity(c.Memory.Limit)
if err != nil {
return nil,
status.Errorf(codes.InvalidArgument, "failed to parse memory limit %s to k8s quantity: %s", c.Memory.Limit, err)
}
resourceLimits[corev1.ResourceMemory] = q
}
}
for k, v := range c.Resources {
if strings.HasPrefix(k, "limits_") {
limitKey := strings.Split(k, "_")
resourceName := corev1.ResourceName(limitKey[1])
q, err := k8sresource.ParseQuantity(v)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to parse resource %s to k8s quantity: %s", v, err)
}
resourceLimits[resourceName] = q
} else if strings.HasPrefix(k, "requests_") {
reqKey := strings.Split(k, "_")
resourceName := corev1.ResourceName(reqKey[1])
q, err := k8sresource.ParseQuantity(v)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to parse resource %s to k8s quantity: %s", v, err)
}
resourceRequests[resourceName] = q
} else {
log.Warn("ignoring unrecognized k8s resources key", "key", k)
}
}
_, cpuLimit := resourceLimits[corev1.ResourceCPU]
_, cpuRequest := resourceRequests[corev1.ResourceCPU]
// Check autoscaling
if autoscaleConfig != nil && !(cpuLimit || cpuRequest) {
ui.Output("For autoscaling in Kubernetes to work, a deployment must specify "+
"cpu resource limits and requests. Otherwise the metrics-server will not properly be able "+
"to scale your deployment.", terminal.WithWarningStyle())
}
resourceRequirements := corev1.ResourceRequirements{
Limits: resourceLimits,
Requests: resourceRequests,
}
var volumeMounts []corev1.VolumeMount
for idx, scratchSpaceLocation := range scratchSpace {
volumeMounts = append(
volumeMounts,
corev1.VolumeMount{
// We know all the volumes are identical
Name: volumes[idx].Name,
MountPath: scratchSpaceLocation,
},
)
}
container := corev1.Container{
Name: c.Name,
Image: image,
ImagePullPolicy: pullPolicy,
Env: k8sEnvVars,
Resources: resourceRequirements,
VolumeMounts: volumeMounts,
}
if len(k8sPorts) > 0 {
container.Ports = k8sPorts
}
if c.Command != nil {
container.Command = *c.Command
}
if c.Args != nil {
container.Args = *c.Args
}
// Only define liveliness & readiness checks if container binds to a port
if defaultPort > 0 {
var handler corev1.ProbeHandler
if c.ProbePath != "" {
handler = corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: c.ProbePath,
Port: intstr.FromInt(defaultPort),
},
}
} else {
// If no probe path is defined, assume app will bind to default TCP port
// TODO: handle apps that aren't socket listeners
handler = corev1.ProbeHandler{
TCPSocket: &corev1.TCPSocketAction{
Port: intstr.FromInt(defaultPort),
},
}
}
container.LivenessProbe = &corev1.Probe{
ProbeHandler: handler,
InitialDelaySeconds: initialDelaySeconds,
TimeoutSeconds: timeoutSeconds,
FailureThreshold: failureThreshold,
}
container.ReadinessProbe = &corev1.Probe{
ProbeHandler: handler,
InitialDelaySeconds: initialDelaySeconds,
TimeoutSeconds: timeoutSeconds,
FailureThreshold: failureThreshold,
}
}
return &container, nil
}
// resourceDeploymentCreate creates the Kubernetes deployment.
func (p *Platform) resourceDeploymentCreate(
ctx context.Context,
log hclog.Logger,
src *component.Source,
img *docker.Image,
deployConfig *component.DeploymentConfig,
ui terminal.UI,
result *Deployment,
state *Resource_Deployment,
csinfo *clientsetInfo,
sg terminal.StepGroup,
) error {
// Prepare our namespace and override if set.
ns := csinfo.Namespace
if p.config.Namespace != "" {
ns = p.config.Namespace
}
step := sg.Add("")
defer func() { step.Abort() }()
step.Update("Kubernetes client connected to %s with namespace %s", csinfo.Config.Host, ns)
step.Done()
step = sg.Add("Preparing deployment...")
clientSet := csinfo.Clientset
deployClient := clientSet.AppsV1().Deployments(ns)
// Determine if we have a deployment that we manage already
create := false
deployment, err := deployClient.Get(ctx, result.Name, metav1.GetOptions{})
if errors.IsNotFound(err) {
deployment = result.newDeployment(result.Name)
create = true
err = nil
}
if err != nil {
return err
}
var overlayTarget *Container
if p.config.Pod != nil && p.config.Pod.Container != nil {
overlayTarget = p.config.Pod.Container
} else {
overlayTarget = &Container{}
}
appContainerSpec, err := overlayTopLevelProperties(p.config, overlayTarget)
if err != nil {
return status.Errorf(codes.InvalidArgument, "Failed to parse container config: %s", err)
}
// App container must have some kind of port
if len(appContainerSpec.Ports) == 0 {
log.Warn("No ports defined in waypoint.hcl - defaulting to http on port", "port", DefaultServicePort)
appContainerSpec.Ports = append(appContainerSpec.Ports, &Port{Port: DefaultServicePort, Name: "http"})
}
portStep := sg.Add("")
defer func() { portStep.Abort() }()
// we dont use %q to save us convering a uint Port to a string and handling the error
portStep.Update("Expected %q port \"%d\" for app %q",
appContainerSpec.Ports[0].Name,
appContainerSpec.Ports[0].Port,
result.Name)
portStep.Done()
envVars := make(map[string]string)
// Add deploy config environment to container env vars
for k, v := range p.config.StaticEnvVars {
envVars[k] = v
}
if p.config.Pod != nil && p.config.Pod.Container != nil {
for k, v := range p.config.Pod.Container.StaticEnvVars {
envVars[k] = v
}
}
for k, v := range deployConfig.Env() {
envVars[k] = v
}
// Create scratch space volumes
var volumes []corev1.Volume
for idx := range p.config.ScratchSpace {
scratchName := fmt.Sprintf("scratch-%d", idx)
volumes = append(volumes,
corev1.Volume{
Name: scratchName,
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
)
}
appImage := fmt.Sprintf("%s:%s", img.Image, img.Tag)
appContainerSpec.Name = src.App
appContainer, err := configureContainer(
appContainerSpec,
appImage,
envVars,
p.config.ScratchSpace,
volumes,
p.config.AutoscaleConfig,
log,
ui,
)
if err != nil {
return status.Errorf(status.Code(err),
"Failed to define app container: %s", err)
}
var sidecarContainers []corev1.Container
if p.config.Pod != nil {
for _, sidecarConfig := range p.config.Pod.Sidecars {
envVars := make(map[string]string)
// Add deploy config environment to container env vars
for k, v := range sidecarConfig.Container.StaticEnvVars {
envVars[k] = v
}
for k, v := range deployConfig.Env() {
envVars[k] = v
}
sidecarContainer, err := configureContainer(
sidecarConfig.Container,
sidecarConfig.Image,
envVars,
p.config.ScratchSpace,
volumes,
p.config.AutoscaleConfig,
log,
ui,
)
if err != nil {
return status.Errorf(status.Code(err),
"Failed to define sidecar container %s: %s", sidecarConfig.Container.Name, err)
}
sidecarContainers = append(sidecarContainers, *sidecarContainer)
}
}
// Update the deployment with our spec
containers := []corev1.Container{*appContainer}
deployment.Spec.Template.Spec = corev1.PodSpec{
Containers: append(containers, sidecarContainers...),
Volumes: volumes,
}
// If no count is specified, presume that the user is managing the replica
// count some other way (perhaps manual scaling, perhaps a pod autoscaler).
// Either way if they don't specify a count, we should be sure we don't send one.
if p.config.Count > 0 {
deployment.Spec.Replicas = &p.config.Count
}
// Set our ID on the label. We use this ID so that we can have a key
// to route to multiple versions during release management.
deployment.Spec.Template.Labels[labelId] = result.Id
// Version label duplicates "labelId" to support services like Istio that
// expect pods to be labeled with 'version'
deployment.Spec.Template.Labels["version"] = result.Id
// Apply user defined labels
for k, v := range p.config.Labels {
deployment.Spec.Template.Labels[k] = v
}
if p.config.Pod != nil {
// Configure Pod
podConfig := p.config.Pod
if podConfig.SecurityContext != nil {
secCtx := podConfig.SecurityContext
// Configure Pod Security Context
deployment.Spec.Template.Spec.SecurityContext = &corev1.PodSecurityContext{
RunAsUser: secCtx.RunAsUser,
RunAsNonRoot: secCtx.RunAsNonRoot,
FSGroup: secCtx.FsGroup,
}
}
}
if p.config.ImageSecret != "" {
deployment.Spec.Template.Spec.ImagePullSecrets = []corev1.LocalObjectReference{{
Name: p.config.ImageSecret,
}}
}
if deployment.Spec.Template.Annotations == nil {
deployment.Spec.Template.Annotations = make(map[string]string)
}
deployment.Spec.Template.Annotations[labelNonce] =
time.Now().UTC().Format(time.RFC3339Nano)
if deployment.Spec.Template.ObjectMeta.Annotations == nil {
deployment.Spec.Template.Annotations = make(map[string]string)
}
deployment.Spec.Template.Annotations = p.config.Annotations
if p.config.ServiceAccount != "" {
deployment.Spec.Template.Spec.ServiceAccountName = p.config.ServiceAccount
// Determine if we need to make a service account
saClient := clientSet.CoreV1().ServiceAccounts(ns)
saCreate := false
serviceAccount, err := saClient.Get(ctx, p.config.ServiceAccount, metav1.GetOptions{})
if errors.IsNotFound(err) {
serviceAccount = newServiceAccount(p.config.ServiceAccount)
saCreate = true
err = nil
}
if err != nil {
return err
}
if saCreate {
serviceAccount, err = saClient.Create(ctx, serviceAccount, metav1.CreateOptions{})
if err != nil {
return err
}
}
}
dc := clientSet.AppsV1().Deployments(ns)
// Create/update
if create {
log.Debug("no existing deployment, creating a new one")
step.Update("Creating deployment...")
deployment, err = dc.Create(ctx, deployment, metav1.CreateOptions{})
} else {
log.Debug("updating deployment")
step.Update("Updating deployment...")
deployment, err = dc.Update(ctx, deployment, metav1.UpdateOptions{})
}
if err != nil {
return status.Errorf(codes.Internal, "failed to create or update deployment: %s", err)
}
ev := clientSet.CoreV1().Events(ns)
// We successfully created or updated, so set the name on our state so
// that if we error, we'll partially clean up properly. THIS IS IMPORTANT.
state.Name = result.Name
step.Done()
step = sg.Add("Waiting for deployment...")
ps := clientSet.CoreV1().Pods(ns)
podLabelId := fmt.Sprintf("%s=%s", labelId, result.Id)
var (
lastStatus time.Time
detectedError string
k8error string
reportedError bool
)
var timeoutSeconds int
var failureThreshold int
var initialDelaySeconds int
for _, container := range deployment.Spec.Template.Spec.Containers {
if int(container.ReadinessProbe.TimeoutSeconds) > timeoutSeconds {
timeoutSeconds = int(container.ReadinessProbe.TimeoutSeconds)
}
if int(container.ReadinessProbe.FailureThreshold) > failureThreshold {
failureThreshold = int(container.ReadinessProbe.FailureThreshold)
}
if int(container.ReadinessProbe.TimeoutSeconds) > initialDelaySeconds {
initialDelaySeconds = int(container.ReadinessProbe.InitialDelaySeconds)
}
}
// We wait the maximum amount of time that the deployment controller would wait for a pod
// to start before exiting. We double the time to allow for various Kubernetes based
// delays in startup, detection, and reporting.
timeout := time.Duration((timeoutSeconds*failureThreshold)+initialDelaySeconds) * 2 * time.Second
podsSeen := make(map[types.UID]string)
// Wait on the Pod to start
err = wait.PollImmediate(time.Second, timeout, func() (bool, error) {
dep, err := dc.Get(ctx, result.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
if time.Since(lastStatus) > 10*time.Second {
step.Update(fmt.Sprintf(
"Waiting on deployment to become available: requested=%d running=%d ready=%d",
*dep.Spec.Replicas,
dep.Status.UnavailableReplicas+dep.Status.AvailableReplicas,
dep.Status.AvailableReplicas,
))
lastStatus = time.Now()
}
if dep.Status.AvailableReplicas > 0 {
return true, nil
}
pods, err := ps.List(ctx, metav1.ListOptions{
LabelSelector: podLabelId,
})
if err != nil {
return false, nil
}
for _, p := range pods.Items {
podsSeen[p.UID] = p.Name
for _, cs := range p.Status.ContainerStatuses {
if cs.Ready {
continue
}
if cs.State.Waiting != nil {
// TODO: handle other pod failures here
if cs.State.Waiting.Reason == "ImagePullBackOff" ||
cs.State.Waiting.Reason == "ErrImagePull" {
detectedError = "Pod unable to access Docker image"
k8error = cs.State.Waiting.Message
}
}
}
}
if detectedError != "" && !reportedError {
// we use ui output here instead of a step group, otherwise the warning
// gets swallowed up on the next poll iteration
ui.Output("Detected pods having an issue starting - %s: %s",
detectedError, k8error, terminal.WithWarningStyle())
reportedError = true
// force a faster rerender
lastStatus = time.Time{}
}
return false, nil
})
if err != nil {
step.Update("Error detected waiting for Deployment to start.")
step.Status(terminal.StatusError)
step.Abort()
ui.Output("The following is events for pods observed while attempting to start the Deployment", terminal.WithWarningStyle())
for uid, name := range podsSeen {
sel := ev.GetFieldSelector(nil, nil, nil, (*string)(&uid))
events, err := ev.List(ctx, metav1.ListOptions{
FieldSelector: sel.String(),
})
if err == nil {
ui.Output("Events for %s", name, terminal.WithHeaderStyle())
for _, ev := range events.Items {
if ev.Type == "Normal" {
continue
}
ui.Output(" %s: %s (%s)", ev.Type, ev.Message, ev.Reason)
}
}
}
if err == wait.ErrWaitTimeout {
err = fmt.Errorf("Deployment was not able to start pods after %s", timeout)
}
return err
}
step.Update("Deployment successfully rolled out!")
step.Done()
return nil
}
var deleteGrace = int64(120)
// Destroy deletes the K8S deployment.
func (p *Platform) resourceDeploymentDestroy(
ctx context.Context,
state *Resource_Deployment,
sg terminal.StepGroup,
csinfo *clientsetInfo,
) error {
// Prepare our namespace and override if set.
ns := csinfo.Namespace
if p.config.Namespace != "" {
ns = p.config.Namespace
}
step := sg.Add("")
defer func() { step.Abort() }()
step.Update("Kubernetes client connected to %s with namespace %s", csinfo.Config.Host, ns)
step.Done()
step = sg.Add("Deleting deployment...")
del := metav1.DeletePropagationBackground
msg := "Deployment deleted"
deployclient := csinfo.Clientset.AppsV1().Deployments(ns)
if err := deployclient.Delete(ctx, state.Name, metav1.DeleteOptions{
GracePeriodSeconds: &deleteGrace,
PropagationPolicy: &del,
}); err != nil {
if !errors.IsNotFound(err) {
return err
}
msg = fmt.Sprintf("Deployment (%s) not found, continuing..", state.Name)
}
step.Update(msg)
step.Done()
return nil
}
// resourceAutoscalerCreate creates the Kubernetes deployment.
func (p *Platform) resourceAutoscalerCreate(
ctx context.Context,
log hclog.Logger,
src *component.Source,
img *docker.Image,