-
Notifications
You must be signed in to change notification settings - Fork 55
/
stage.go
1007 lines (869 loc) · 30.8 KB
/
stage.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 © 2021 - 2023 SUSE LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package application
import (
"context"
"fmt"
"path/filepath"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"github.com/spf13/viper"
batchv1 "k8s.io/api/batch/v1"
"k8s.io/utils/ptr"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"github.com/epinio/epinio/helpers/cahash"
"github.com/epinio/epinio/helpers/kubernetes"
"github.com/epinio/epinio/helpers/randstr"
"github.com/epinio/epinio/internal/api/v1/response"
"github.com/epinio/epinio/internal/application"
"github.com/epinio/epinio/internal/cli/server/requestctx"
"github.com/epinio/epinio/internal/duration"
"github.com/epinio/epinio/internal/helmchart"
"github.com/epinio/epinio/internal/names"
"github.com/epinio/epinio/internal/registry"
"github.com/epinio/epinio/internal/s3manager"
apierror "github.com/epinio/epinio/pkg/api/core/v1/errors"
"github.com/epinio/epinio/pkg/api/core/v1/models"
"golang.org/x/exp/slices"
)
type stageParam struct {
models.AppRef
BlobUID string
BuilderImage string
DownloadImage string
UnpackImage string
ServiceAccountName string
CPURequest string
MemoryRequest string
Environment models.EnvVariableList
Owner metav1.OwnerReference
RegistryURL string
S3ConnectionDetails s3manager.ConnectionDetails
Stage models.StageRef
Username string
PreviousStageID string
RegistryCASecret string
RegistryCAHash string
UserID int64
GroupID int64
Scripts string
}
// ImageURL returns the URL of the container image to be, using the
// ImageID. The ImageURL is later used in app.yml and to send in the
// stage response.
func (app *stageParam) ImageURL(registryURL string) string {
return fmt.Sprintf("%s/%s-%s:%s", registryURL, app.Namespace, app.Name, app.Stage.ID)
}
// ensurePVC creates a PVC for the application if one doesn't already exist.
// This PVC is used to store the application source blobs (as they are uploaded
// on the "upload" endpoint). It is also mounted in the staging pod, as the
// "source" workspace.
// The same PVC stores the application's build cache (on a separate directory).
func ensurePVC(ctx context.Context, cluster *kubernetes.Cluster, ar models.AppRef, diskRequest string) error {
_, err := cluster.Kubectl.CoreV1().PersistentVolumeClaims(helmchart.Namespace()).
Get(ctx, ar.MakePVCName(), metav1.GetOptions{})
if err != nil && !apierrors.IsNotFound(err) { // Unknown error, irrelevant to non-existence
return err
}
if err == nil { // pvc already exists
return nil
}
// Insert a default of last resort. See also note below.
if diskRequest == "" {
diskRequest = "1Gi"
}
// From here on, only if the PVC is missing
_, err = cluster.Kubectl.CoreV1().PersistentVolumeClaims(helmchart.Namespace()).
Create(ctx, &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: ar.MakePVCName(),
Namespace: helmchart.Namespace(),
},
Spec: corev1.PersistentVolumeClaimSpec{
AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce},
Resources: corev1.ResourceRequirements{
Requests: map[corev1.ResourceName]resource.Quantity{
// NOTE: Using `MustParse` is ok here, despite
// panicking on bad values. The server startup code
// (See internal/cli/server.go, CmdServer.RunE)
// already verified that any non-empty values are
// valid. Invalid values cause the server to not
// start.
corev1.ResourceStorage: resource.MustParse(diskRequest),
},
},
},
}, metav1.CreateOptions{})
return err
}
// Stage handles the API endpoint /namespaces/:namespace/applications/:app/stage
// It creates a Job resource to stage the app
func Stage(c *gin.Context) apierror.APIErrors {
ctx := c.Request.Context()
log := requestctx.Logger(ctx)
namespace := c.Param("namespace")
name := c.Param("app")
username := requestctx.User(ctx).Username
req := models.StageRequest{}
if err := c.BindJSON(&req); err != nil {
return apierror.NewBadRequestError(err.Error()).WithDetails("failed to unmarshal app stage request")
}
if name != req.App.Name {
return apierror.NewBadRequestError("name parameter from URL does not match name param in body")
}
if namespace != req.App.Namespace {
return apierror.NewBadRequestError("namespace parameter from URL does not match namespace param in body")
}
cluster, err := kubernetes.GetCluster(ctx)
if err != nil {
return apierror.InternalError(err, "failed to get access to a kube client")
}
// check application resource
app, err := application.Get(ctx, cluster, req.App)
if err != nil {
if apierrors.IsNotFound(err) {
return apierror.AppIsNotKnown("cannot stage app, application resource is missing")
}
return apierror.InternalError(err, "failed to get the application resource")
}
// get builder image from either request, application, or default as final fallback
builderImage, builderErr := getBuilderImage(req, app)
if builderErr != nil {
return builderErr
}
if builderImage == "" {
builderImage = viper.GetString("default-builder-image")
}
// Find staging script spec based on the builder image and what images are supported by each spec
// This also resolves a `base` reference, if present.
config, err := DetermineStagingScripts(ctx, log, cluster, helmchart.Namespace(), builderImage)
if err != nil {
return apierror.InternalError(err, "failed to retrieve staging configuration")
}
log.Info("staging app", "scripts", config.Name)
log.Info("staging app", "builder", builderImage)
log.Info("staging app", "download", config.DownloadImage)
log.Info("staging app", "unpack", config.UnpackImage)
log.Info("staging app", "userid", config.UserID)
log.Info("staging app", "groupid", config.GroupID)
log.Info("staging app", "namespace", namespace, "app", req)
staging, err := application.IsCurrentlyStaging(ctx, cluster, req.App.Namespace, req.App.Name)
if err != nil {
return apierror.InternalError(err)
}
if staging {
return apierror.NewBadRequestError("staging job for image ID still running")
}
s3ConnectionDetails, err := s3manager.GetConnectionDetails(ctx, cluster,
helmchart.Namespace(), helmchart.S3ConnectionDetailsSecretName)
if err != nil {
return apierror.InternalError(err, "failed to fetch the S3 connection details")
}
blobUID, blobErr := getBlobUID(ctx, s3ConnectionDetails, req, app)
if blobErr != nil {
return blobErr
}
// Create uid identifying the staging job to be
uid, err := randstr.Hex16()
if err != nil {
return apierror.InternalError(err, "failed to generate a uid")
}
environment, err := application.Environment(ctx, cluster, req.App)
if err != nil {
return apierror.InternalError(err, "failed to access application runtime environment")
}
owner := metav1.OwnerReference{
APIVersion: app.GetAPIVersion(),
Kind: app.GetKind(),
Name: app.GetName(),
UID: app.GetUID(),
}
// Determine stage id of currently running deployment. Fallback to itself when no such exists.
// From the view of the new build we are about to create this is the previous id.
previousID, err := application.StageID(app)
if err != nil {
return apierror.InternalError(err, "failed to determine application stage id")
}
if previousID == "" {
previousID = uid
}
registryPublicURL, err := getRegistryURL(ctx, cluster)
if err != nil {
return apierror.InternalError(err, "getting the Epinio registry public URL")
}
registryCertificateSecret := viper.GetString("registry-certificate-secret")
registryCertificateHash := ""
if registryCertificateSecret != "" {
registryCertificateHash, err = getRegistryCertificateHash(ctx, cluster, helmchart.Namespace(), registryCertificateSecret)
if err != nil {
return apierror.InternalError(err, "cannot calculate Certificate hash")
}
}
serviceAccountName := viper.GetString("staging-service-account-name")
cpuRequest := viper.GetString("staging-resource-cpu")
memoryRequest := viper.GetString("staging-resource-memory")
diskRequest := viper.GetString("staging-resource-disk")
params := stageParam{
AppRef: req.App,
BuilderImage: builderImage,
DownloadImage: config.DownloadImage,
UnpackImage: config.UnpackImage,
ServiceAccountName: serviceAccountName,
CPURequest: cpuRequest,
MemoryRequest: memoryRequest,
BlobUID: blobUID,
Environment: environment.List(),
Owner: owner,
RegistryURL: registryPublicURL,
S3ConnectionDetails: s3ConnectionDetails,
Stage: models.NewStage(uid),
PreviousStageID: previousID,
Username: username,
RegistryCAHash: registryCertificateHash,
RegistryCASecret: registryCertificateSecret,
UserID: config.UserID,
GroupID: config.GroupID,
Scripts: config.Name,
}
err = ensurePVC(ctx, cluster, req.App, diskRequest)
if err != nil {
return apierror.InternalError(err, "failed to ensure a PersistentVolumeClaim for the application source and cache")
}
job, jobenv := newJobRun(params)
// Note: The secret is deleted with the job in function `Unstage()`.
err = cluster.CreateSecret(ctx, helmchart.Namespace(), *jobenv)
if err != nil {
return apierror.InternalError(err, fmt.Sprintf("failed to create job env: %#v", jobenv))
}
err = cluster.CreateJob(ctx, helmchart.Namespace(), job)
if err != nil {
return apierror.InternalError(err, fmt.Sprintf("failed to create job run: %#v", job))
}
if err := updateApp(ctx, cluster, app, params); err != nil {
return apierror.InternalError(err, "updating application CR with staging information")
}
imageURL := params.ImageURL(params.RegistryURL)
log.Info("staged app", "namespace", helmchart.Namespace(), "app", params.AppRef, "uid", uid, "image", imageURL)
response.OKReturn(c, models.StageResponse{
Stage: models.NewStage(uid),
ImageURL: imageURL,
})
return nil
}
// Staged handles the API endpoint /namespaces/:namespace/staging/:stage_id/complete
// It waits for the Job resource staging the app to complete
func Staged(c *gin.Context) apierror.APIErrors {
ctx := c.Request.Context()
namespace := c.Param("namespace")
id := c.Param("stage_id")
cluster, err := kubernetes.GetCluster(ctx)
if err != nil {
return apierror.InternalError(err)
}
// Wait for the staging to be done, then check if it ended in failure.
// Select the job for this stage `id`.
selector := fmt.Sprintf("app.kubernetes.io/component=staging,app.kubernetes.io/part-of=%s,epinio.io/stage-id=%s",
namespace, id)
jobList, err := cluster.ListJobs(ctx, helmchart.Namespace(), selector)
if err != nil {
return apierror.InternalError(err)
}
if len(jobList.Items) == 0 {
return apierror.InternalError(fmt.Errorf("no jobs in %s with selector %s", namespace, selector))
}
for _, job := range jobList.Items {
// Wait for job to be done
err = cluster.WaitForJobDone(ctx, helmchart.Namespace(), job.Name, duration.ToAppBuilt())
if err != nil {
return apierror.InternalError(err)
}
// Check job for failure
failed, err := cluster.IsJobFailed(ctx, job.Name, helmchart.Namespace())
if err != nil {
return apierror.InternalError(err)
}
if failed {
return apierror.NewInternalError("Failed to stage",
fmt.Sprintf("stage-id = %s", id))
}
}
response.OK(c)
return nil
}
func validateBlob(ctx context.Context, blobUID string, app models.AppRef, s3ConnectionDetails s3manager.ConnectionDetails) apierror.APIErrors {
manager, err := s3manager.New(s3ConnectionDetails)
if err != nil {
return apierror.InternalError(err, "creating an S3 manager")
}
blobMeta, err := manager.Meta(ctx, blobUID)
if err != nil {
return apierror.InternalError(err, "querying blob id meta-data")
}
blobApp, ok := blobMeta["App"]
if !ok {
return apierror.NewInternalError("blob has no app name meta data")
}
if blobApp != app.Name {
return apierror.NewBadRequestError("blob app mismatch").
WithDetailsf("expected: [%s], found: [%s]", app.Name, blobApp)
}
blobNamespace, ok := blobMeta["Namespace"]
if !ok {
return apierror.NewInternalError("blob has no namespace meta data")
}
if blobNamespace != app.Namespace {
return apierror.NewBadRequestError("blob namespace mismatch").
WithDetailsf("expected: [%s], found: [%s]", app.Namespace, blobNamespace)
}
return nil
}
// newJobRun is a helper which creates the Job related resources from
// the given staging params. That is the job itself, and a secret
// holding the job's environment. Which is a copy of the app
// environment + standard variables.
func newJobRun(app stageParam) (*batchv1.Job, *corev1.Secret) {
jobName := names.GenerateResourceName("stage", app.Namespace, app.Name, app.Stage.ID)
// fake stage params of the previous to pull the old image url from.
previous := app
previous.Stage = models.NewStage(app.PreviousStageID)
// TODO: Simplify env setup -- https://github.com/epinio/epinio/issues/1176
// Note: `source` is required because the mounted files are not executable.
// runtime: AWSCLIImage
awsScript := fmt.Sprintf("source /stage-support/%s", helmchart.EpinioStageDownload)
// runtime: BashImage
unpackScript := fmt.Sprintf(`source /stage-support/%s`, helmchart.EpinioStageUnpack)
// runtime: app.BuilderImage
buildpackScript := fmt.Sprintf(`source /stage-support/%s`, helmchart.EpinioStageBuild)
// build configuration
// - shared between all the phases, even if each phase uses only part of the set
stageEnv := assembleStageEnv(app, previous)
volumeMounts := []corev1.VolumeMount{
{
Name: "source",
SubPath: "source",
MountPath: "/workspace/source",
},
{
Name: "cache",
SubPath: "cache",
MountPath: "/workspace/cache",
},
{
Name: "registry-creds",
MountPath: "/home/cnb/.docker/",
ReadOnly: true,
},
{
Name: "staging",
MountPath: "/stage-support",
},
{
Name: "app-environment",
MountPath: "/workspace/source/appenv",
ReadOnly: true,
},
}
// mount AWS credentials secret only if the credentials are provided
if app.S3ConnectionDetails.AccessKeyID != "" && app.S3ConnectionDetails.SecretAccessKey != "" {
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: "s3-creds",
MountPath: "/root/.aws",
ReadOnly: true,
})
}
volumes := []corev1.Volume{
{
Name: "staging",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: app.Scripts,
},
DefaultMode: ptr.To[int32](420),
},
},
},
{
// See `jobenv` for the Secret providing the information.
Name: "app-environment",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: jobName,
DefaultMode: ptr.To[int32](420),
},
},
},
{
Name: "cache",
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: app.MakePVCName(),
ReadOnly: false,
},
},
},
{
Name: "source",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
{
Name: "s3-creds",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: helmchart.S3ConnectionDetailsSecretName,
DefaultMode: ptr.To[int32](420),
},
},
},
{
Name: "registry-creds",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: registry.CredentialsSecretName,
DefaultMode: ptr.To[int32](420),
Items: []corev1.KeyToPath{
{
Key: ".dockerconfigjson",
Path: "config.json",
},
},
},
},
},
}
volumes, volumeMounts = mountS3Certs(volumes, volumeMounts)
volumes, volumeMounts = mountRegistryCerts(app, volumes, volumeMounts)
// Create job environment as a copy of the app environment, plus standard variable.
env := make(map[string][]byte)
env["CNB_PLATFORM_API"] = []byte("0.4")
for _, ev := range app.Environment {
env[ev.Name] = []byte(ev.Value)
}
jobenv := &corev1.Secret{
Data: env,
ObjectMeta: metav1.ObjectMeta{
Name: jobName,
Labels: map[string]string{
"app.kubernetes.io/name": app.Name,
"app.kubernetes.io/part-of": app.Namespace,
models.EpinioStageIDLabel: app.Stage.ID,
models.EpinioStageIDPrevious: app.PreviousStageID,
models.EpinioStageBlobUIDLabel: app.BlobUID,
"app.kubernetes.io/managed-by": "epinio",
"app.kubernetes.io/component": "staging",
},
Annotations: map[string]string{
models.EpinioCreatedByAnnotation: app.Username,
},
},
}
job := &batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
Name: jobName,
Labels: map[string]string{
"app.kubernetes.io/name": app.Name,
"app.kubernetes.io/part-of": app.Namespace,
models.EpinioStageIDLabel: app.Stage.ID,
models.EpinioStageIDPrevious: app.PreviousStageID,
models.EpinioStageBlobUIDLabel: app.BlobUID,
"app.kubernetes.io/managed-by": "epinio",
"app.kubernetes.io/component": "staging",
},
Annotations: map[string]string{
models.EpinioCreatedByAnnotation: app.Username,
},
},
Spec: batchv1.JobSpec{
BackoffLimit: ptr.To[int32](0),
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app.kubernetes.io/name": app.Name,
"app.kubernetes.io/part-of": app.Namespace,
models.EpinioStageIDLabel: app.Stage.ID,
models.EpinioStageIDPrevious: app.PreviousStageID,
models.EpinioStageBlobUIDLabel: app.BlobUID,
"app.kubernetes.io/managed-by": "epinio",
"app.kubernetes.io/component": "staging",
},
Annotations: map[string]string{
// Allow communication with the Registry even before the proxy is ready
"config.linkerd.io/skip-outbound-ports": "443",
models.EpinioCreatedByAnnotation: app.Username,
},
},
Spec: corev1.PodSpec{
ServiceAccountName: app.ServiceAccountName,
InitContainers: []corev1.Container{
{
Name: "download-s3-blob",
Image: app.DownloadImage,
VolumeMounts: volumeMounts,
Command: []string{"/bin/bash"},
Args: []string{
"-c",
awsScript,
},
Env: stageEnv,
},
{
Name: "unpack-blob",
Image: app.UnpackImage,
VolumeMounts: volumeMounts,
Command: []string{"bash"},
Args: []string{
"-c",
unpackScript,
},
Env: stageEnv,
},
},
Containers: []corev1.Container{
{
Name: "buildpack",
Image: app.BuilderImage,
Command: []string{"/bin/bash"},
Args: []string{
"-c",
buildpackScript,
},
Env: stageEnv,
VolumeMounts: volumeMounts,
SecurityContext: &corev1.SecurityContext{
RunAsUser: ptr.To[int64](app.UserID),
RunAsGroup: ptr.To[int64](app.GroupID),
},
},
},
RestartPolicy: corev1.RestartPolicyNever,
Volumes: volumes,
},
},
},
}
addResourceRequests(job, app)
return job, jobenv
}
func assembleStageEnv(app, previous stageParam) []corev1.EnvVar {
stageEnv := []corev1.EnvVar{}
protocol := "http"
if app.S3ConnectionDetails.UseSSL {
protocol = "https"
}
stageEnv = appendEnvVar(stageEnv, "PROTOCOL", protocol)
stageEnv = appendEnvVar(stageEnv, "ENDPOINT", app.S3ConnectionDetails.Endpoint)
stageEnv = appendEnvVar(stageEnv, "BUCKET", app.S3ConnectionDetails.Bucket)
stageEnv = appendEnvVar(stageEnv, "BLOBID", app.BlobUID)
stageEnv = appendEnvVar(stageEnv, "PREIMAGE", previous.ImageURL(previous.RegistryURL))
stageEnv = appendEnvVar(stageEnv, "APPIMAGE", app.ImageURL(app.RegistryURL))
stageEnv = appendEnvVar(stageEnv, "USERID", strconv.FormatInt(app.UserID, 10))
stageEnv = appendEnvVar(stageEnv, "GROUPID", strconv.FormatInt(app.GroupID, 10))
return stageEnv
}
func addResourceRequests(job *batchv1.Job, app stageParam) {
cpu := app.CPURequest
memory := app.MemoryRequest
if cpu == "" && memory == "" {
return
}
rr := corev1.ResourceRequirements{
Requests: corev1.ResourceList{},
}
// NOTE: Using `MustParse` is ok here, despite panicking on bad values. The server startup
// code (See internal/cli/server.go, CmdServer.RunE) already verified that any non-empty
// values are valid. Invalid values cause the server to not start.
if cpu != "" {
rr.Requests[corev1.ResourceCPU] = resource.MustParse(cpu)
}
if memory != "" {
rr.Requests[corev1.ResourceMemory] = resource.MustParse(memory)
}
job.Spec.Template.Spec.Containers[0].Resources = rr
}
func getRegistryURL(ctx context.Context, cluster *kubernetes.Cluster) (string, error) {
cd, err := registry.GetConnectionDetails(ctx, cluster, helmchart.Namespace(), registry.CredentialsSecretName)
if err != nil {
return "", err
}
registryPublicURL, err := cd.PublicRegistryURL()
if err != nil {
return "", err
}
if registryPublicURL == "" {
return "", errors.New("no public registry URL found")
}
return fmt.Sprintf("%s/%s", registryPublicURL, cd.Namespace), nil
}
// The equivalent of:
// kubectl get secret -n (helmchart.Namespace()) epinio-registry-tls -o json | jq -r '.["data"]["tls.crt"]' | base64 -d | openssl x509 -hash -noout
// written in golang.
func getRegistryCertificateHash(ctx context.Context, c *kubernetes.Cluster, namespace string, name string) (string, error) {
secret, err := c.Kubectl.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
return "", err
}
// cert-manager doesn't add the CA for ACME certificates:
// https://github.com/jetstack/cert-manager/issues/2111
if _, found := secret.Data["tls.crt"]; !found {
return "", nil
}
hash, err := cahash.GenerateHash(secret.Data["tls.crt"])
if err != nil {
return "", err
}
return hash, nil
}
// getBuilderImage returns the builder image defined on the request. If that
// one is not defined, it tries to find the builder image previously used on the
// Application CR. If one is not found, it returns an error.
func getBuilderImage(req models.StageRequest, app *unstructured.Unstructured) (string, apierror.APIErrors) {
var returnErr apierror.APIErrors
if req.BuilderImage != "" {
return req.BuilderImage, nil
}
builderImage, _, err := unstructured.NestedString(app.UnstructuredContent(), "spec", "builderimage")
if err != nil {
returnErr = apierror.InternalError(err, "builderimage should be a string!")
return "", returnErr
}
return builderImage, nil
}
func getBlobUID(ctx context.Context, s3ConnectionDetails s3manager.ConnectionDetails, req models.StageRequest, app *unstructured.Unstructured) (string, apierror.APIErrors) {
var blobUID string
var err error
var returnErr apierror.APIErrors
if req.BlobUID != "" {
blobUID = req.BlobUID
} else {
blobUID, err = findPreviousBlobUID(app)
if err != nil {
returnErr = apierror.InternalError(err, "looking up the previous blod UID")
return "", returnErr
}
}
if blobUID == "" {
returnErr = apierror.NewBadRequestError("request didn't provide a blobUID and a previous one doesn't exist")
return "", returnErr
}
// Validate incoming blob id before attempting to stage
apierr := validateBlob(ctx, blobUID, req.App, s3ConnectionDetails)
if apierr != nil {
return "", apierr
}
return blobUID, nil
}
func findPreviousBlobUID(app *unstructured.Unstructured) (string, error) {
blobUID, _, err := unstructured.NestedString(app.UnstructuredContent(), "spec", "blobuid")
if err != nil {
return "", errors.New("blobuid should be string")
}
return blobUID, nil
}
func updateApp(ctx context.Context, cluster *kubernetes.Cluster, app *unstructured.Unstructured, params stageParam) error {
if err := unstructured.SetNestedField(app.Object, params.BlobUID, "spec", "blobuid"); err != nil {
return err
}
if err := unstructured.SetNestedField(app.Object, params.Stage.ID, "spec", "stageid"); err != nil {
return err
}
if err := unstructured.SetNestedField(app.Object, params.BuilderImage, "spec", "builderimage"); err != nil {
return err
}
client, err := cluster.ClientApp()
if err != nil {
return err
}
namespace, _, err := unstructured.NestedString(app.UnstructuredContent(), "metadata", "namespace")
if err != nil {
return err
}
_, err = client.Namespace(namespace).Update(ctx, app, metav1.UpdateOptions{})
return err
}
func mountS3Certs(volumes []corev1.Volume, volumeMounts []corev1.VolumeMount) ([]corev1.Volume, []corev1.VolumeMount) {
if s3CertificateSecret := viper.GetString("s3-certificate-secret"); s3CertificateSecret != "" {
volumes = append(volumes, corev1.Volume{
Name: "s3-certs",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: s3CertificateSecret,
DefaultMode: ptr.To[int32](420),
},
},
})
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: "s3-certs",
MountPath: "/certs",
ReadOnly: true,
})
}
return volumes, volumeMounts
}
func mountRegistryCerts(app stageParam, volumes []corev1.Volume, volumeMounts []corev1.VolumeMount) ([]corev1.Volume, []corev1.VolumeMount) {
// If there is a certificate to trust
if app.RegistryCASecret != "" && app.RegistryCAHash != "" {
volumes = append(volumes, corev1.Volume{
Name: "registry-certs",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: app.RegistryCASecret,
DefaultMode: ptr.To[int32](420),
},
},
})
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: "registry-certs",
MountPath: fmt.Sprintf("/etc/ssl/certs/%s", app.RegistryCAHash),
SubPath: "tls.crt",
ReadOnly: true,
})
}
return volumes, volumeMounts
}
func appendEnvVar(envs []corev1.EnvVar, name, value string) []corev1.EnvVar {
return append(envs, corev1.EnvVar{Name: name, Value: value})
}
type StagingScriptConfig struct {
Name string // config name. Needed to mount the resource in the pod
Builder string // glob pattern for builders supported by this resource
UserID int64 // user id to run the build phase with (`cnb` user)
GroupID int64 // group id to run the build hase with
Base string // optional, name of resource to pull the other parts from
DownloadImage string // image to run the download phase with
UnpackImage string // image to run the unpack phase with
}
func DetermineStagingScripts(ctx context.Context,
logger logr.Logger,
cluster *kubernetes.Cluster,
namespace, builder string) (*StagingScriptConfig, error) {
logger.Info("locate staging scripts", "namespace", namespace)
logger.Info("locate staging scripts", "builder", builder)
configmapSelector := labels.Set(map[string]string{
"app.kubernetes.io/component": "epinio-staging",
}).AsSelector().String()
configmapList, err := cluster.Kubectl.CoreV1().ConfigMaps(namespace).List(ctx,
metav1.ListOptions{
LabelSelector: configmapSelector,
})
if err != nil {
return nil, err
}
logger.Info("locate staging scripts", "possibles", len(configmapList.Items))
var candidates []*StagingScriptConfig
for _, configmap := range configmapList.Items {
config, err := NewStagingScriptConfig(configmap)
if err != nil {
return nil, err
}
candidates = append(candidates, config)
}
// Sort the candidates by name to have a deterministic search order
slices.SortFunc(candidates, SortByName)
var fallback *StagingScriptConfig
// Show the entire ordered list (except fallbacks), also save fallbacks, and show last. NOTE
// that this loop excises the fallbacks from the regular list to avoid having to check for
// them again when matching.
var matchable []*StagingScriptConfig
for _, config := range candidates {
pattern := config.Builder
if pattern == "*" || pattern == "" {
fallback = config
continue
}
logger.Info("locate staging scripts - found",
"name", config.Name, "match", pattern)
matchable = append(matchable, config)
}
if fallback != nil {
logger.Info("locate staging scripts - fallback",
"name", fallback.Name, "match", fallback.Builder)
}
// match by pattern
for _, config := range matchable {
pattern := config.Builder
logger.Info("locate staging scripts - checking",
"name", config.Name, "match", pattern)
matched, err := filepath.Match(pattern, builder)
if err != nil {
return nil, err
}
if matched {
logger.Info("locate staging scripts - match",
"name", config.Name, "match", pattern, "builder", builder)
err := StagingScriptConfigResolve(ctx, logger, cluster, config)
if err != nil {
return nil, err
}
return config, nil
}
}
if fallback != nil {
logger.Info("locate staging scripts - using fallback", "name", fallback.Name)
err := StagingScriptConfigResolve(ctx, logger, cluster, fallback)
if err != nil {
return nil, err
}
return fallback, nil
}
return nil, fmt.Errorf("no matches, no fallback")
}
func StagingScriptConfigResolve(ctx context.Context, logger logr.Logger, cluster *kubernetes.Cluster, config *StagingScriptConfig) error {
if config.Base == "" {
// nothing to do without a base
return nil
}
logger.Info("locate staging scripts - inherit", "base", config.Base)
base, err := cluster.GetConfigMap(ctx, helmchart.Namespace(), config.Base)
if err != nil {
return apierror.InternalError(err, "failed to retrieve staging base")
}
// Fill config from the base.
// BEWARE: Keep user/group data of the incoming config.
config.Name = base.Name
config.DownloadImage = base.Data["downloadImage"]
config.UnpackImage = base.Data["unpackImage"]
return nil
}
func NewStagingScriptConfig(config v1.ConfigMap) (*StagingScriptConfig, error) {
stagingScript := &StagingScriptConfig{
Name: config.Name,
Builder: config.Data["builder"],
Base: config.Data["base"],
DownloadImage: config.Data["downloadImage"],
UnpackImage: config.Data["unpackImage"],
// user, group id, see below.
}
userID, err := strconv.ParseInt(config.Data["userID"], 10, 64)
if err != nil {
return nil, apierror.InternalError(err)
}
groupID, err := strconv.ParseInt(config.Data["groupID"], 10, 64)
if err != nil {
return nil, err
}
stagingScript.GroupID = groupID
stagingScript.UserID = userID