-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
play.go
1907 lines (1666 loc) · 60 KB
/
play.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
//go:build !remote
package abi
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
buildahDefine "github.com/containers/buildah/define"
bparse "github.com/containers/buildah/pkg/parse"
"github.com/containers/common/libimage"
nettypes "github.com/containers/common/libnetwork/types"
"github.com/containers/common/pkg/config"
"github.com/containers/common/pkg/secrets"
"github.com/containers/image/v5/docker/reference"
"github.com/containers/image/v5/types"
"github.com/containers/podman/v5/cmd/podman/parse"
"github.com/containers/podman/v5/libpod"
"github.com/containers/podman/v5/libpod/define"
"github.com/containers/podman/v5/pkg/annotations"
"github.com/containers/podman/v5/pkg/domain/entities"
entitiesTypes "github.com/containers/podman/v5/pkg/domain/entities/types"
"github.com/containers/podman/v5/pkg/domain/infra/abi/internal/expansion"
v1apps "github.com/containers/podman/v5/pkg/k8s.io/api/apps/v1"
v1 "github.com/containers/podman/v5/pkg/k8s.io/api/core/v1"
metav1 "github.com/containers/podman/v5/pkg/k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/containers/podman/v5/pkg/specgen"
"github.com/containers/podman/v5/pkg/specgen/generate"
"github.com/containers/podman/v5/pkg/specgen/generate/kube"
"github.com/containers/podman/v5/pkg/specgenutil"
"github.com/containers/podman/v5/pkg/systemd/notifyproxy"
"github.com/containers/podman/v5/pkg/util"
"github.com/containers/podman/v5/utils"
"github.com/containers/storage/pkg/fileutils"
"github.com/coreos/go-systemd/v22/daemon"
"github.com/opencontainers/go-digest"
"github.com/opencontainers/selinux/go-selinux"
"github.com/sirupsen/logrus"
yamlv3 "gopkg.in/yaml.v3"
"sigs.k8s.io/yaml"
)
// sdNotifyAnnotation allows for configuring service-global and
// container-specific sd-notify modes.
const sdNotifyAnnotation = "io.containers.sdnotify"
// default network created/used by kube
const kubeDefaultNetwork = "podman-default-kube-network"
// createServiceContainer creates a container that can later on
// be associated with the pods of a K8s yaml. It will be started along with
// the first pod.
func (ic *ContainerEngine) createServiceContainer(ctx context.Context, name string, options entities.PlayKubeOptions) (*libpod.Container, error) {
// Make sure to replace the service container as well if requested by
// the user.
if options.Replace {
if _, err := ic.ContainerRm(ctx, []string{name}, entities.RmOptions{Force: true, Ignore: true}); err != nil {
return nil, fmt.Errorf("replacing service container: %w", err)
}
}
// Similar to infra containers, a service container is using the pause image.
image, err := generate.PullOrBuildInfraImage(ic.Libpod, "")
if err != nil {
return nil, fmt.Errorf("image for service container: %w", err)
}
rtc, err := ic.Libpod.GetConfigNoCopy()
if err != nil {
return nil, err
}
ctrOpts := entities.ContainerCreateOptions{
// Inherited from infra containers
IsInfra: false,
MemorySwappiness: -1,
ReadOnly: true,
ReadWriteTmpFS: false,
// No need to spin up slirp etc.
Net: &entities.NetOptions{Network: specgen.Namespace{NSMode: specgen.NoNetwork}},
StopTimeout: rtc.Engine.StopTimeout,
HealthLogDestination: define.DefaultHealthCheckLocalDestination,
HealthMaxLogCount: define.DefaultHealthMaxLogCount,
HealthMaxLogSize: define.DefaultHealthMaxLogSize,
}
// Create and fill out the runtime spec.
s := specgen.NewSpecGenerator(image, false)
if err := specgenutil.FillOutSpecGen(s, &ctrOpts, []string{}); err != nil {
return nil, fmt.Errorf("completing spec for service container: %w", err)
}
s.Name = name
expandForKube(s)
runtimeSpec, spec, opts, err := generate.MakeContainer(ctx, ic.Libpod, s, false, nil)
if err != nil {
return nil, fmt.Errorf("creating runtime spec for service container: %w", err)
}
ecp, err := define.ParseKubeExitCodePropagation(options.ExitCodePropagation)
if err != nil {
return nil, err
}
opts = append(opts, libpod.WithIsService(ecp))
// Set the sd-notify mode to "ignore". Podman is responsible for
// sending the notify messages when all containers are ready.
// The mode for individual containers or entire pods can be configured
// via the `sdNotifyAnnotation` annotation in the K8s YAML.
opts = append(opts, libpod.WithSdNotifyMode(define.SdNotifyModeIgnore))
if options.Replace {
if _, err := ic.ContainerRm(ctx, []string{spec.Name}, entities.RmOptions{Force: true, Ignore: true}); err != nil {
return nil, err
}
}
// Create a new libpod container based on the spec.
ctr, err := ic.Libpod.NewContainer(ctx, runtimeSpec, spec, false, opts...)
if err != nil {
return nil, fmt.Errorf("creating service container: %w", err)
}
return ctr, nil
}
func (ic *ContainerEngine) prepareAutomountImages(ctx context.Context, forContainer string, annotations map[string]string) ([]*specgen.ImageVolume, error) {
volMap := make(map[string]*specgen.ImageVolume)
ctrAnnotation := define.KubeImageAutomountAnnotation + "/" + forContainer
automount, ok := annotations[ctrAnnotation]
if !ok || automount == "" {
return nil, nil
}
for _, imageName := range strings.Split(automount, ";") {
img, fullName, err := ic.Libpod.LibimageRuntime().LookupImage(imageName, nil)
if err != nil {
return nil, fmt.Errorf("image %s from container %s does not exist in local storage, cannot automount: %w", imageName, forContainer, err)
}
logrus.Infof("Resolved image name %s to %s for automount into container %s", imageName, fullName, forContainer)
inspect, err := img.Inspect(ctx, nil)
if err != nil {
return nil, fmt.Errorf("cannot inspect image %s to automount into container %s: %w", fullName, forContainer, err)
}
volumes := inspect.Config.Volumes
for path := range volumes {
if oldPath, ok := volMap[path]; ok && oldPath != nil {
logrus.Warnf("Multiple volume mounts to %q requested, overriding image %q with image %s", path, oldPath.Source, fullName)
}
imgVol := new(specgen.ImageVolume)
imgVol.Source = fullName
imgVol.Destination = path
imgVol.ReadWrite = false
imgVol.SubPath = path
volMap[path] = imgVol
}
}
toReturn := make([]*specgen.ImageVolume, 0, len(volMap))
for _, vol := range volMap {
toReturn = append(toReturn, vol)
}
return toReturn, nil
}
func prepareVolumesFrom(forContainer, podName string, ctrNames, annotations map[string]string) ([]string, error) {
annotationVolsFrom := define.VolumesFromAnnotation + "/" + forContainer
volsFromCtrs, ok := annotations[annotationVolsFrom]
// No volumes-from specified
if !ok || volsFromCtrs == "" {
return nil, nil
}
// The volumes-from string is a semicolon-separated container names
// optionally with respective mount options.
volumesFrom := strings.Split(volsFromCtrs, ";")
for idx, volsFromCtr := range volumesFrom {
// Each entry is of format "container[:mount-options]"
fields := strings.Split(volsFromCtr, ":")
if len(fields) != 1 && len(fields) != 2 {
return nil, fmt.Errorf("invalid annotation %s value", annotationVolsFrom)
}
if fields[0] == "" {
return nil, fmt.Errorf("from container name cannot be empty in annotation %s", annotationVolsFrom)
}
// Source and target containers cannot be same
if fields[0] == forContainer {
return nil, fmt.Errorf("to and from container names cannot be same in annotation %s", annotationVolsFrom)
}
// Update the source container name if it belongs to the pod
// the source container must exist before the target container
// in the kube yaml. Otherwise, the source container will be
// treated as an external container. This also helps in avoiding
// cyclic dependencies between containers within the pod.
if _, ok := ctrNames[fields[0]]; ok {
volumesFrom[idx] = podName + "-" + fields[0]
if len(fields) == 2 {
volumesFrom[idx] = volumesFrom[idx] + ":" + fields[1]
}
}
}
return volumesFrom, nil
}
// Creates the name for a k8s entity based on the provided content of a
// K8s yaml file and a given suffix.
func k8sName(content []byte, suffix string) string {
// The name of the service container is the first 12
// characters of the yaml file's hash followed by the
// '-service' suffix to guarantee a predictable and
// discoverable name.
hash := digest.FromBytes(content).Encoded()
return hash[0:12] + "-" + suffix
}
func (ic *ContainerEngine) PlayKube(ctx context.Context, body io.Reader, options entities.PlayKubeOptions) (_ *entities.PlayKubeReport, finalErr error) {
if options.ServiceContainer && options.Start == types.OptionalBoolFalse { // Sanity check to be future proof
return nil, fmt.Errorf("running a service container requires starting the pod(s)")
}
report := &entities.PlayKubeReport{}
validKinds := 0
// when no network options are specified, create a common network for all the pods
if len(options.Networks) == 0 {
_, err := ic.NetworkCreate(
ctx,
nettypes.Network{
Name: kubeDefaultNetwork,
DNSEnabled: true,
},
&nettypes.NetworkCreateOptions{
IgnoreIfExists: true,
},
)
if err != nil {
return nil, err
}
}
// read yaml document
content, err := io.ReadAll(body)
if err != nil {
return nil, err
}
// split yaml document
documentList, err := splitMultiDocYAML(content)
if err != nil {
return nil, err
}
// sort kube kinds
documentList, err = sortKubeKinds(documentList)
if err != nil {
return nil, fmt.Errorf("unable to sort kube kinds: %w", err)
}
ipIndex := 0
var configMaps []v1.ConfigMap
ranContainers := false
// FIXME: both, the service container and the proxies, should ideally
// be _state_ of an object. The Kube code below is quite Spaghetti-code
// which we should refactor at some point to make it easier to extend
// (via shared state instead of passing data around) and make it more
// maintainable long term.
var serviceContainer *libpod.Container
var notifyProxies []*notifyproxy.NotifyProxy
defer func() {
// Close the notify proxy on return. At that point we know
// that a) all containers have send their READY message and
// that b) the service container has exited (and hence all
// containers).
for _, proxy := range notifyProxies {
if err := proxy.Close(); err != nil {
logrus.Errorf("Closing notify proxy %q: %v", proxy.SocketPath(), err)
}
}
}()
// create pod on each document if it is a pod or deployment
// any other kube kind will be skipped
for _, document := range documentList {
kind, err := getKubeKind(document)
if err != nil {
return nil, fmt.Errorf("unable to read kube YAML: %w", err)
}
// TODO: create constants for the various "kinds" of yaml files.
if options.ServiceContainer && serviceContainer == nil && (kind == "Pod" || kind == "Deployment") {
ctr, err := ic.createServiceContainer(ctx, k8sName(content, "service"), options)
if err != nil {
return nil, err
}
serviceContainer = ctr
// Make sure to remove the container in case something goes wrong below.
defer func() {
if finalErr == nil {
return
}
if err := ic.Libpod.RemoveContainer(ctx, ctr, true, true, nil); err != nil {
// Log this in debug mode so that we don't print out an error and confuse the user
// when the service container can't be removed because the pod still exists
// This can happen when an error happens during kube play and we are trying to
// clean up after the error. The service container will be removed as part of the
// teardown function.
logrus.Debugf("Error cleaning up service container after failure: %v", err)
}
}()
}
switch kind {
case "Pod":
var podYAML v1.Pod
var podTemplateSpec v1.PodTemplateSpec
if err := yaml.Unmarshal(document, &podYAML); err != nil {
return nil, fmt.Errorf("unable to read YAML as Kube Pod: %w", err)
}
podTemplateSpec.ObjectMeta = podYAML.ObjectMeta
podTemplateSpec.Spec = podYAML.Spec
for name, val := range options.Annotations {
if podYAML.Annotations == nil {
podYAML.Annotations = make(map[string]string)
}
podYAML.Annotations[name] = val
}
if err := annotations.ValidateAnnotations(podYAML.Annotations); err != nil {
return nil, err
}
r, proxies, err := ic.playKubePod(ctx, podTemplateSpec.ObjectMeta.Name, &podTemplateSpec, options, &ipIndex, podYAML.Annotations, configMaps, serviceContainer)
if err != nil {
return nil, err
}
notifyProxies = append(notifyProxies, proxies...)
report.Pods = append(report.Pods, r.Pods...)
validKinds++
ranContainers = true
case "DaemonSet":
var daemonSetYAML v1apps.DaemonSet
if err := yaml.Unmarshal(document, &daemonSetYAML); err != nil {
return nil, fmt.Errorf("unable to read YAML as Kube DaemonSet: %w", err)
}
r, proxies, err := ic.playKubeDaemonSet(ctx, &daemonSetYAML, options, &ipIndex, configMaps, serviceContainer)
if err != nil {
return nil, err
}
notifyProxies = append(notifyProxies, proxies...)
report.Pods = append(report.Pods, r.Pods...)
validKinds++
ranContainers = true
case "Deployment":
var deploymentYAML v1apps.Deployment
if err := yaml.Unmarshal(document, &deploymentYAML); err != nil {
return nil, fmt.Errorf("unable to read YAML as Kube Deployment: %w", err)
}
r, proxies, err := ic.playKubeDeployment(ctx, &deploymentYAML, options, &ipIndex, configMaps, serviceContainer)
if err != nil {
return nil, err
}
notifyProxies = append(notifyProxies, proxies...)
report.Pods = append(report.Pods, r.Pods...)
validKinds++
ranContainers = true
case "Job":
var jobYAML v1.Job
if err := yaml.Unmarshal(document, &jobYAML); err != nil {
return nil, fmt.Errorf("unable to read YAML as Kube Job: %w", err)
}
r, proxies, err := ic.playKubeJob(ctx, &jobYAML, options, &ipIndex, configMaps, serviceContainer)
if err != nil {
return nil, err
}
notifyProxies = append(notifyProxies, proxies...)
report.Pods = append(report.Pods, r.Pods...)
validKinds++
ranContainers = true
case "PersistentVolumeClaim":
var pvcYAML v1.PersistentVolumeClaim
if err := yaml.Unmarshal(document, &pvcYAML); err != nil {
return nil, fmt.Errorf("unable to read YAML as Kube PersistentVolumeClaim: %w", err)
}
for name, val := range options.Annotations {
if pvcYAML.Annotations == nil {
pvcYAML.Annotations = make(map[string]string)
}
pvcYAML.Annotations[name] = val
}
if options.IsRemote {
if _, ok := pvcYAML.Annotations[util.VolumeImportSourceAnnotation]; ok {
return nil, fmt.Errorf("importing volumes is not supported for remote requests")
}
}
r, err := ic.playKubePVC(ctx, "", &pvcYAML)
if err != nil {
return nil, err
}
report.Volumes = append(report.Volumes, r.Volumes...)
validKinds++
case "ConfigMap":
var configMap v1.ConfigMap
if err := yaml.Unmarshal(document, &configMap); err != nil {
return nil, fmt.Errorf("unable to read YAML as Kube ConfigMap: %w", err)
}
configMaps = append(configMaps, configMap)
case "Secret":
var secret v1.Secret
if err := yaml.Unmarshal(document, &secret); err != nil {
return nil, fmt.Errorf("unable to read YAML as kube secret: %w", err)
}
r, err := ic.playKubeSecret(&secret)
if err != nil {
return nil, err
}
report.Secrets = append(report.Secrets, entities.PlaySecret{CreateReport: r})
validKinds++
default:
logrus.Infof("Kube kind %s not supported", kind)
continue
}
}
if validKinds == 0 {
if len(configMaps) > 0 {
return nil, fmt.Errorf("ConfigMaps in podman are not a standalone object and must be used in a container")
}
return nil, fmt.Errorf("YAML document does not contain any supported kube kind")
}
// If we started containers along with a service container, we are
// running inside a systemd unit and need to set the main PID.
if options.ServiceContainer && ranContainers {
switch len(notifyProxies) {
case 0: // Optimization for containers/podman/issues/17345
// No container needs sdnotify, so we can mark the
// service container's conmon as the main PID and
// return early.
data, err := serviceContainer.Inspect(false)
if err != nil {
return nil, err
}
message := fmt.Sprintf("MAINPID=%d\n%s", data.State.ConmonPid, daemon.SdNotifyReady)
if err := notifyproxy.SendMessage("", message); err != nil {
return nil, err
}
default:
// At least one container has a custom sdnotify policy,
// so we need to let the sdnotify proxies run for the
// lifetime of the service container. That means, we
// need to wait for the service container to stop.
// Podman will hence be marked as the main PID. That
// comes at the cost of keeping Podman running.
message := fmt.Sprintf("MAINPID=%d\n%s", os.Getpid(), daemon.SdNotifyReady)
if err := notifyproxy.SendMessage("", message); err != nil {
return nil, err
}
exitCode, err := serviceContainer.Wait(ctx)
if err != nil {
return nil, fmt.Errorf("waiting for service container: %w", err)
}
report.ExitCode = &exitCode
}
report.ServiceContainerID = serviceContainer.ID()
}
return report, nil
}
func (ic *ContainerEngine) playKubeDaemonSet(ctx context.Context, daemonSetYAML *v1apps.DaemonSet, options entities.PlayKubeOptions, ipIndex *int, configMaps []v1.ConfigMap, serviceContainer *libpod.Container) (*entities.PlayKubeReport, []*notifyproxy.NotifyProxy, error) {
var (
daemonSetName string
podSpec v1.PodTemplateSpec
report entities.PlayKubeReport
)
daemonSetName = daemonSetYAML.ObjectMeta.Name
if daemonSetName == "" {
return nil, nil, errors.New("daemonSet does not have a name")
}
podSpec = daemonSetYAML.Spec.Template
podName := fmt.Sprintf("%s-pod", daemonSetName)
podReport, proxies, err := ic.playKubePod(ctx, podName, &podSpec, options, ipIndex, daemonSetYAML.Annotations, configMaps, serviceContainer)
if err != nil {
return nil, nil, fmt.Errorf("encountered while bringing up pod %s: %w", podName, err)
}
report.Pods = podReport.Pods
return &report, proxies, nil
}
func (ic *ContainerEngine) playKubeDeployment(ctx context.Context, deploymentYAML *v1apps.Deployment, options entities.PlayKubeOptions, ipIndex *int, configMaps []v1.ConfigMap, serviceContainer *libpod.Container) (*entities.PlayKubeReport, []*notifyproxy.NotifyProxy, error) {
var (
deploymentName string
podSpec v1.PodTemplateSpec
numReplicas int32
report entities.PlayKubeReport
)
deploymentName = deploymentYAML.ObjectMeta.Name
if deploymentName == "" {
return nil, nil, errors.New("deployment does not have a name")
}
numReplicas = 1
if deploymentYAML.Spec.Replicas != nil {
numReplicas = *deploymentYAML.Spec.Replicas
}
if numReplicas > 1 {
logrus.Warnf("Limiting replica count to 1, more than one replica is not supported by Podman")
}
podSpec = deploymentYAML.Spec.Template
podName := fmt.Sprintf("%s-pod", deploymentName)
podReport, proxies, err := ic.playKubePod(ctx, podName, &podSpec, options, ipIndex, deploymentYAML.Annotations, configMaps, serviceContainer)
if err != nil {
return nil, nil, fmt.Errorf("encountered while bringing up pod %s: %w", podName, err)
}
report.Pods = podReport.Pods
return &report, proxies, nil
}
func (ic *ContainerEngine) playKubeJob(ctx context.Context, jobYAML *v1.Job, options entities.PlayKubeOptions, ipIndex *int, configMaps []v1.ConfigMap, serviceContainer *libpod.Container) (*entities.PlayKubeReport, []*notifyproxy.NotifyProxy, error) {
var (
jobName string
podSpec v1.PodTemplateSpec
report entities.PlayKubeReport
)
jobName = jobYAML.ObjectMeta.Name
if jobName == "" {
return nil, nil, errors.New("job does not have a name")
}
podSpec = jobYAML.Spec.Template
podName := fmt.Sprintf("%s-pod", jobName)
podReport, proxies, err := ic.playKubePod(ctx, podName, &podSpec, options, ipIndex, jobYAML.Annotations, configMaps, serviceContainer)
if err != nil {
return nil, nil, fmt.Errorf("encountered while bringing up pod %s: %w", podName, err)
}
report.Pods = podReport.Pods
return &report, proxies, nil
}
func (ic *ContainerEngine) playKubePod(ctx context.Context, podName string, podYAML *v1.PodTemplateSpec, options entities.PlayKubeOptions, ipIndex *int, annotations map[string]string, configMaps []v1.ConfigMap, serviceContainer *libpod.Container) (*entities.PlayKubeReport, []*notifyproxy.NotifyProxy, error) {
cfg, err := ic.Libpod.GetConfigNoCopy()
if err != nil {
return nil, nil, err
}
var (
writer io.Writer
playKubePod entities.PlayKubePod
report entities.PlayKubeReport
)
mainSdNotifyMode, err := getSdNotifyMode(annotations, "")
if err != nil {
return nil, nil, err
}
// Create the secret manager before hand
secretsManager, err := ic.Libpod.SecretsManager()
if err != nil {
return nil, nil, err
}
// Assert the pod has a name
if podName == "" {
return nil, nil, fmt.Errorf("pod does not have a name")
}
if _, ok := annotations[define.VolumesFromAnnotation]; ok {
return nil, nil, fmt.Errorf("annotation %s without target volume is reserved for internal use", define.VolumesFromAnnotation)
}
podOpt := entities.PodCreateOptions{
Infra: true,
Net: &entities.NetOptions{NoHosts: options.NoHosts},
ExitPolicy: string(config.PodExitPolicyStop),
}
podOpt, err = kube.ToPodOpt(ctx, podName, podOpt, options.PublishAllPorts, podYAML)
if err != nil {
return nil, nil, err
}
// add kube default network if no network is explicitly added
if podOpt.Net.Network.NSMode != "host" && len(options.Networks) == 0 {
options.Networks = []string{kubeDefaultNetwork}
}
if len(options.Networks) > 0 {
ns, networks, netOpts, err := specgen.ParseNetworkFlag(options.Networks)
if err != nil {
return nil, nil, err
}
podOpt.Net.Network = ns
podOpt.Net.Networks = networks
podOpt.Net.NetworkOptions = netOpts
}
if options.Userns == "" {
if v, ok := annotations[define.UserNsAnnotation]; ok {
options.Userns = v
} else if v, ok := annotations[define.UserNsAnnotation+"/"+podName]; ok {
options.Userns = v
} else if podYAML.Spec.HostUsers != nil && !*podYAML.Spec.HostUsers {
options.Userns = "auto"
} else {
options.Userns = "host"
}
// FIXME: how to deal with explicit mappings?
if options.Userns == "private" {
options.Userns = "auto"
}
} else if podYAML.Spec.HostUsers != nil {
logrus.Info("overriding the user namespace mode in the pod spec")
}
// Validate the userns modes supported.
podOpt.Userns, err = specgen.ParseUserNamespace(options.Userns)
if err != nil {
return nil, nil, err
}
// FIXME This is very hard to support properly with a good ux
if len(options.StaticIPs) > *ipIndex {
if !podOpt.Net.Network.IsBridge() {
return nil, nil, fmt.Errorf("static ip addresses can only be set when the network mode is bridge: %w", define.ErrInvalidArg)
}
if len(podOpt.Net.Networks) != 1 {
return nil, nil, fmt.Errorf("cannot set static ip addresses for more than network, use netname:ip=<ip> syntax to specify ips for more than network: %w", define.ErrInvalidArg)
}
for name, netOpts := range podOpt.Net.Networks {
netOpts.StaticIPs = append(netOpts.StaticIPs, options.StaticIPs[*ipIndex])
podOpt.Net.Networks[name] = netOpts
}
} else if len(options.StaticIPs) > 0 {
// only warn if the user has set at least one ip
logrus.Warn("No more static ips left using a random one")
}
if len(options.StaticMACs) > *ipIndex {
if !podOpt.Net.Network.IsBridge() {
return nil, nil, fmt.Errorf("static mac address can only be set when the network mode is bridge: %w", define.ErrInvalidArg)
}
if len(podOpt.Net.Networks) != 1 {
return nil, nil, fmt.Errorf("cannot set static mac address for more than network, use netname:mac=<mac> syntax to specify mac for more than network: %w", define.ErrInvalidArg)
}
for name, netOpts := range podOpt.Net.Networks {
netOpts.StaticMAC = nettypes.HardwareAddr(options.StaticMACs[*ipIndex])
podOpt.Net.Networks[name] = netOpts
}
} else if len(options.StaticIPs) > 0 {
// only warn if the user has set at least one mac
logrus.Warn("No more static macs left using a random one")
}
*ipIndex++
if len(options.PublishPorts) > 0 {
publishPorts, err := specgenutil.CreatePortBindings(options.PublishPorts)
if err != nil {
return nil, nil, err
}
mergePublishPorts(&podOpt, publishPorts)
}
p := specgen.NewPodSpecGenerator()
if err != nil {
return nil, nil, err
}
p, err = entities.ToPodSpecGen(*p, &podOpt)
if err != nil {
return nil, nil, err
}
podSpec := entities.PodSpec{PodSpecGen: *p}
configMapIndex := make(map[string]struct{})
for _, configMap := range configMaps {
configMapIndex[configMap.Name] = struct{}{}
}
for _, p := range options.ConfigMaps {
f, err := os.Open(p)
if err != nil {
return nil, nil, err
}
defer f.Close()
cms, err := readConfigMapFromFile(f)
if err != nil {
return nil, nil, fmt.Errorf("%q: %w", p, err)
}
for _, cm := range cms {
if _, present := configMapIndex[cm.Name]; present {
return nil, nil, fmt.Errorf("ambiguous configuration: the same config map %s is present in YAML and in --configmaps %s file", cm.Name, p)
}
configMaps = append(configMaps, cm)
}
}
mountLabel, err := getMountLabel(podYAML.Spec.SecurityContext)
if err != nil {
return nil, nil, err
}
volumes, err := kube.InitializeVolumes(podYAML.Spec.Volumes, configMaps, secretsManager, mountLabel)
if err != nil {
return nil, nil, err
}
// Go through the volumes and create a podman volume for all volumes that have been
// defined by a configmap or secret
for _, v := range volumes {
if (v.Type == kube.KubeVolumeTypeConfigMap || v.Type == kube.KubeVolumeTypeSecret) && !v.Optional {
volumeOptions := []libpod.VolumeCreateOption{
libpod.WithVolumeName(v.Source),
libpod.WithVolumeMountLabel(mountLabel),
}
vol, err := ic.Libpod.NewVolume(ctx, volumeOptions...)
if err != nil {
if errors.Is(err, define.ErrVolumeExists) {
// Volume for this configmap already exists do not
// error out instead reuse the current volume.
vol, err = ic.Libpod.GetVolume(v.Source)
if err != nil {
return nil, nil, fmt.Errorf("cannot reuse local volume for volume from configmap %q: %w", v.Source, err)
}
} else {
return nil, nil, fmt.Errorf("cannot create a local volume for volume from configmap %q: %w", v.Source, err)
}
}
mountPoint, err := vol.MountPoint()
if err != nil || mountPoint == "" {
return nil, nil, fmt.Errorf("unable to get mountpoint of volume %q: %w", vol.Name(), err)
}
defaultMode := v.DefaultMode
// Create files and add data to the volume mountpoint based on the Items in the volume
for k, v := range v.Items {
dataPath := filepath.Join(mountPoint, k)
f, err := os.Create(dataPath)
if err != nil {
return nil, nil, fmt.Errorf("cannot create file %q at volume mountpoint %q: %w", k, mountPoint, err)
}
defer f.Close()
_, err = f.Write(v)
if err != nil {
return nil, nil, err
}
// Set file permissions
if err := os.Chmod(f.Name(), os.FileMode(defaultMode)); err != nil {
return nil, nil, err
}
}
} else if v.Type == kube.KubeVolumeTypeImage {
var cwd string
if options.ContextDir != "" {
cwd = options.ContextDir
} else {
cwd, err = os.Getwd()
if err != nil {
return nil, nil, err
}
}
_, err := ic.buildOrPullImage(ctx, cwd, writer, v.Source, v.ImagePullPolicy, options)
if err != nil {
return nil, nil, err
}
}
}
seccompPaths, err := kube.InitializeSeccompPaths(podYAML.ObjectMeta.Annotations, options.SeccompProfileRoot)
if err != nil {
return nil, nil, err
}
// Set the restart policy from the kube yaml at the pod level in podman
switch podYAML.Spec.RestartPolicy {
case v1.RestartPolicyAlways:
podSpec.PodSpecGen.RestartPolicy = define.RestartPolicyAlways
case v1.RestartPolicyOnFailure:
podSpec.PodSpecGen.RestartPolicy = define.RestartPolicyOnFailure
case v1.RestartPolicyNever:
podSpec.PodSpecGen.RestartPolicy = define.RestartPolicyNo
default: // Default to Always
podSpec.PodSpecGen.RestartPolicy = define.RestartPolicyAlways
}
if podOpt.Infra {
infraImage := cfg.Engine.InfraImage
infraOptions := entities.NewInfraContainerCreateOptions()
infraOptions.Hostname = podSpec.PodSpecGen.PodBasicConfig.Hostname
infraOptions.ReadOnly = true
infraOptions.ReadWriteTmpFS = false
infraOptions.UserNS = options.Userns
podSpec.PodSpecGen.InfraImage = infraImage
podSpec.PodSpecGen.NoInfra = false
podSpec.PodSpecGen.InfraContainerSpec = specgen.NewSpecGenerator(infraImage, false)
podSpec.PodSpecGen.InfraContainerSpec.NetworkOptions = p.NetworkOptions
podSpec.PodSpecGen.InfraContainerSpec.SdNotifyMode = define.SdNotifyModeIgnore
// If the infraNameAnnotation is set in the yaml, use that as the infra container name
// If not, fall back to the default infra container name
if v, ok := podYAML.Annotations[define.InfraNameAnnotation]; ok {
podSpec.PodSpecGen.InfraContainerSpec.Name = v
}
err = specgenutil.FillOutSpecGen(podSpec.PodSpecGen.InfraContainerSpec, &infraOptions, []string{})
if err != nil {
return nil, nil, err
}
}
// Add the original container names from the kube yaml as aliases for it. This will allow network to work with
// both just containerName as well as containerName-podName.
// In the future, we want to extend this to the CLI as well, where the name of the container created will not have
// the podName appended to it, but this is a breaking change and will be done in podman 5.0
ctrNameAliases := make([]string, 0, len(podYAML.Spec.Containers))
for _, container := range podYAML.Spec.Containers {
ctrNameAliases = append(ctrNameAliases, container.Name)
}
for k, v := range podSpec.PodSpecGen.Networks {
v.Aliases = append(v.Aliases, ctrNameAliases...)
podSpec.PodSpecGen.Networks[k] = v
}
if serviceContainer != nil {
podSpec.PodSpecGen.ServiceContainerID = serviceContainer.ID()
}
if options.Replace {
if _, err := ic.PodRm(ctx, []string{podName}, entities.PodRmOptions{Force: true, Ignore: true}); err != nil {
return nil, nil, fmt.Errorf("replacing pod %v: %w", podName, err)
}
}
// Create the Pod
pod, err := generate.MakePod(&podSpec, ic.Libpod)
if err != nil {
return nil, nil, err
}
podInfraID, err := pod.InfraContainerID()
if err != nil {
return nil, nil, err
}
if !options.Quiet {
writer = os.Stderr
}
containers := make([]*libpod.Container, 0, len(podYAML.Spec.Containers))
initContainers := make([]*libpod.Container, 0, len(podYAML.Spec.InitContainers))
var cwd string
if options.ContextDir != "" {
cwd = options.ContextDir
} else {
cwd, err = os.Getwd()
if err != nil {
return nil, nil, err
}
}
var readOnly types.OptionalBool
if cfg.Containers.ReadOnly {
readOnly = types.NewOptionalBool(cfg.Containers.ReadOnly)
}
ctrNames := make(map[string]string)
for _, initCtr := range podYAML.Spec.InitContainers {
// Error out if same name is used for more than one container
if _, ok := ctrNames[initCtr.Name]; ok {
return nil, nil, fmt.Errorf("the pod %q is invalid; duplicate container name %q detected", podName, initCtr.Name)
}
ctrNames[initCtr.Name] = ""
// Init containers cannot have either of lifecycle, livenessProbe, readinessProbe, or startupProbe set
if initCtr.Lifecycle != nil || initCtr.LivenessProbe != nil || initCtr.ReadinessProbe != nil || initCtr.StartupProbe != nil {
return nil, nil, fmt.Errorf("cannot create an init container that has either of lifecycle, livenessProbe, readinessProbe, or startupProbe set")
}
pulledImage, labels, err := ic.getImageAndLabelInfo(ctx, cwd, annotations, writer, initCtr, options)
if err != nil {
return nil, nil, err
}
for k, v := range podSpec.PodSpecGen.Labels { // add podYAML labels
labels[k] = v
}
initCtrType := annotations[define.InitContainerType]
if initCtrType == "" {
initCtrType = define.OneShotInitContainer
}
automountImages, err := ic.prepareAutomountImages(ctx, initCtr.Name, annotations)
if err != nil {
return nil, nil, err
}
var volumesFrom []string
if list, err := prepareVolumesFrom(initCtr.Name, podName, ctrNames, annotations); err != nil {
return nil, nil, err
} else if list != nil {
volumesFrom = list
}
specgenOpts := kube.CtrSpecGenOptions{
Annotations: annotations,
ConfigMaps: configMaps,
Container: initCtr,
Image: pulledImage,
InitContainerType: initCtrType,
Labels: labels,
LogDriver: options.LogDriver,
LogOptions: options.LogOptions,
NetNSIsHost: p.NetNS.IsHost(),
PodID: pod.ID(),
PodInfraID: podInfraID,
PodName: podName,
PodSecurityContext: podYAML.Spec.SecurityContext,
ReadOnly: readOnly,
RestartPolicy: define.RestartPolicyNo,
SeccompPaths: seccompPaths,
SecretsManager: secretsManager,
UserNSIsHost: p.Userns.IsHost(),
Volumes: volumes,
VolumesFrom: volumesFrom,
ImageVolumes: automountImages,
UtsNSIsHost: p.UtsNs.IsHost(),
}
specGen, err := kube.ToSpecGen(ctx, &specgenOpts)
if err != nil {
return nil, nil, err
}
// ensure the environment is setup for initContainers as well: https://github.com/containers/podman/issues/18384
warn, err := generate.CompleteSpec(ctx, ic.Libpod, specGen)
if err != nil {
return nil, nil, err
}
for _, w := range warn {
logrus.Warn(w)
}
specGen.SdNotifyMode = define.SdNotifyModeIgnore
expandForKube(specGen)
rtSpec, spec, opts, err := generate.MakeContainer(ctx, ic.Libpod, specGen, false, nil)
if err != nil {
return nil, nil, err
}
opts = append(opts, libpod.WithSdNotifyMode(define.SdNotifyModeIgnore))