forked from containers/podman
-
Notifications
You must be signed in to change notification settings - Fork 2
/
container_internal.go
2363 lines (2076 loc) · 73.9 KB
/
container_internal.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 libpod
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
metadata "github.com/checkpoint-restore/checkpointctl/lib"
"github.com/containers/buildah/copier"
"github.com/containers/buildah/pkg/overlay"
butil "github.com/containers/buildah/util"
"github.com/containers/common/pkg/cgroups"
"github.com/containers/common/pkg/chown"
"github.com/containers/podman/v3/libpod/define"
"github.com/containers/podman/v3/libpod/events"
"github.com/containers/podman/v3/pkg/ctime"
"github.com/containers/podman/v3/pkg/hooks"
"github.com/containers/podman/v3/pkg/hooks/exec"
"github.com/containers/podman/v3/pkg/lookup"
"github.com/containers/podman/v3/pkg/rootless"
"github.com/containers/podman/v3/pkg/selinux"
"github.com/containers/podman/v3/pkg/util"
"github.com/containers/storage"
"github.com/containers/storage/pkg/archive"
"github.com/containers/storage/pkg/idtools"
"github.com/containers/storage/pkg/mount"
"github.com/coreos/go-systemd/v22/daemon"
securejoin "github.com/cyphar/filepath-securejoin"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
"github.com/opencontainers/selinux/go-selinux/label"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
const (
// name of the directory holding the artifacts
artifactsDir = "artifacts"
execDirPermission = 0755
preCheckpointDir = "pre-checkpoint"
)
// rootFsSize gets the size of the container's root filesystem
// A container FS is split into two parts. The first is the top layer, a
// mutable layer, and the rest is the RootFS: the set of immutable layers
// that make up the image on which the container is based.
func (c *Container) rootFsSize() (int64, error) {
if c.config.Rootfs != "" {
return 0, nil
}
if c.runtime.store == nil {
return 0, nil
}
container, err := c.runtime.store.Container(c.ID())
if err != nil {
return 0, err
}
// Ignore the size of the top layer. The top layer is a mutable RW layer
// and is not considered a part of the rootfs
rwLayer, err := c.runtime.store.Layer(container.LayerID)
if err != nil {
return 0, err
}
layer, err := c.runtime.store.Layer(rwLayer.Parent)
if err != nil {
return 0, err
}
size := int64(0)
for layer.Parent != "" {
layerSize, err := c.runtime.store.DiffSize(layer.Parent, layer.ID)
if err != nil {
return size, errors.Wrapf(err, "getting diffsize of layer %q and its parent %q", layer.ID, layer.Parent)
}
size += layerSize
layer, err = c.runtime.store.Layer(layer.Parent)
if err != nil {
return 0, err
}
}
// Get the size of the last layer. Has to be outside of the loop
// because the parent of the last layer is "", and lstore.Get("")
// will return an error.
layerSize, err := c.runtime.store.DiffSize(layer.Parent, layer.ID)
return size + layerSize, err
}
// rwSize gets the size of the mutable top layer of the container.
func (c *Container) rwSize() (int64, error) {
if c.config.Rootfs != "" {
var size int64
err := filepath.Walk(c.config.Rootfs, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
size += info.Size()
return nil
})
return size, err
}
container, err := c.runtime.store.Container(c.ID())
if err != nil {
return 0, err
}
// The top layer of a container is
// the only readable/writeable layer, all others are immutable.
rwLayer, err := c.runtime.store.Layer(container.LayerID)
if err != nil {
return 0, err
}
// Get the size of the top layer by calculating the size of the diff
// between the layer and its parent.
return c.runtime.store.DiffSize(rwLayer.Parent, rwLayer.ID)
}
// bundlePath returns the path to the container's root filesystem - where the OCI spec will be
// placed, amongst other things
func (c *Container) bundlePath() string {
return c.config.StaticDir
}
// ControlSocketPath returns the path to the containers control socket for things like tty
// resizing
func (c *Container) ControlSocketPath() string {
return filepath.Join(c.bundlePath(), "ctl")
}
// CheckpointPath returns the path to the directory containing the checkpoint
func (c *Container) CheckpointPath() string {
return filepath.Join(c.bundlePath(), metadata.CheckpointDirectory)
}
// PreCheckpointPath returns the path to the directory containing the pre-checkpoint-images
func (c *Container) PreCheckPointPath() string {
return filepath.Join(c.bundlePath(), preCheckpointDir)
}
// AttachSocketPath retrieves the path of the container's attach socket
func (c *Container) AttachSocketPath() (string, error) {
return c.ociRuntime.AttachSocketPath(c)
}
// exitFilePath gets the path to the container's exit file
func (c *Container) exitFilePath() (string, error) {
return c.ociRuntime.ExitFilePath(c)
}
// Wait for the container's exit file to appear.
// When it does, update our state based on it.
func (c *Container) waitForExitFileAndSync() error {
exitFile, err := c.exitFilePath()
if err != nil {
return err
}
chWait := make(chan error)
defer close(chWait)
_, err = WaitForFile(exitFile, chWait, time.Second*5)
if err != nil {
// Exit file did not appear
// Reset our state
c.state.ExitCode = -1
c.state.FinishedTime = time.Now()
c.state.State = define.ContainerStateStopped
if err2 := c.save(); err2 != nil {
logrus.Errorf("Saving container %s state: %v", c.ID(), err2)
}
return err
}
if err := c.checkExitFile(); err != nil {
return err
}
return c.save()
}
// Handle the container exit file.
// The exit file is used to supply container exit time and exit code.
// This assumes the exit file already exists.
func (c *Container) handleExitFile(exitFile string, fi os.FileInfo) error {
c.state.FinishedTime = ctime.Created(fi)
statusCodeStr, err := ioutil.ReadFile(exitFile)
if err != nil {
return errors.Wrapf(err, "failed to read exit file for container %s", c.ID())
}
statusCode, err := strconv.Atoi(string(statusCodeStr))
if err != nil {
return errors.Wrapf(err, "error converting exit status code (%q) for container %s to int",
c.ID(), statusCodeStr)
}
c.state.ExitCode = int32(statusCode)
oomFilePath := filepath.Join(c.bundlePath(), "oom")
if _, err = os.Stat(oomFilePath); err == nil {
c.state.OOMKilled = true
}
c.state.Exited = true
// Write an event for the container's death
c.newContainerExitedEvent(c.state.ExitCode)
return nil
}
func (c *Container) shouldRestart() bool {
// If we did not get a restart policy match, return false
// Do the same if we're not a policy that restarts.
if !c.state.RestartPolicyMatch ||
c.config.RestartPolicy == define.RestartPolicyNo ||
c.config.RestartPolicy == define.RestartPolicyNone {
return false
}
// If we're RestartPolicyOnFailure, we need to check retries and exit
// code.
if c.config.RestartPolicy == define.RestartPolicyOnFailure {
if c.state.ExitCode == 0 {
return false
}
// If we don't have a max retries set, continue
if c.config.RestartRetries > 0 {
if c.state.RestartCount >= c.config.RestartRetries {
return false
}
}
}
return true
}
// Handle container restart policy.
// This is called when a container has exited, and was not explicitly stopped by
// an API call to stop the container or pod it is in.
func (c *Container) handleRestartPolicy(ctx context.Context) (_ bool, retErr error) {
if !c.shouldRestart() {
return false, nil
}
logrus.Debugf("Restarting container %s due to restart policy %s", c.ID(), c.config.RestartPolicy)
// Need to check if dependencies are alive.
if err := c.checkDependenciesAndHandleError(); err != nil {
return false, err
}
// Is the container running again?
// If so, we don't have to do anything
if c.ensureState(define.ContainerStateRunning, define.ContainerStatePaused) {
return false, nil
} else if c.state.State == define.ContainerStateUnknown {
return false, errors.Wrapf(define.ErrInternal, "invalid container state encountered in restart attempt!")
}
c.newContainerEvent(events.Restart)
// Increment restart count
c.state.RestartCount++
logrus.Debugf("Container %s now on retry %d", c.ID(), c.state.RestartCount)
if err := c.save(); err != nil {
return false, err
}
defer func() {
if retErr != nil {
if err := c.cleanup(ctx); err != nil {
logrus.Errorf("Cleaning up container %s: %v", c.ID(), err)
}
}
}()
if err := c.prepare(); err != nil {
return false, err
}
// setup slirp4netns again because slirp4netns will die when conmon exits
if c.config.NetMode.IsSlirp4netns() {
err := c.runtime.setupSlirp4netns(c, c.state.NetNS)
if err != nil {
return false, err
}
}
// setup rootlesskit port forwarder again since it dies when conmon exits
// we use rootlesskit port forwarder only as rootless and when bridge network is used
if rootless.IsRootless() && c.config.NetMode.IsBridge() && len(c.config.PortMappings) > 0 {
err := c.runtime.setupRootlessPortMappingViaRLK(c, c.state.NetNS.Path(), c.state.NetworkStatus)
if err != nil {
return false, err
}
}
if c.state.State == define.ContainerStateStopped {
// Reinitialize the container if we need to
if err := c.reinit(ctx, true); err != nil {
return false, err
}
} else if c.ensureState(define.ContainerStateConfigured, define.ContainerStateExited) {
// Initialize the container
if err := c.init(ctx, true); err != nil {
return false, err
}
}
if err := c.start(); err != nil {
return false, err
}
return true, nil
}
// Ensure that the container is in a specific state or state.
// Returns true if the container is in one of the given states,
// or false otherwise.
func (c *Container) ensureState(states ...define.ContainerStatus) bool {
for _, state := range states {
if state == c.state.State {
return true
}
}
return false
}
// Sync this container with on-disk state and runtime status
// Should only be called with container lock held
// This function should suffice to ensure a container's state is accurate and
// it is valid for use.
func (c *Container) syncContainer() error {
if err := c.runtime.state.UpdateContainer(c); err != nil {
return err
}
// If runtime knows about the container, update its status in runtime
// And then save back to disk
if c.ensureState(define.ContainerStateCreated, define.ContainerStateRunning, define.ContainerStateStopped, define.ContainerStatePaused) {
oldState := c.state.State
if err := c.checkExitFile(); err != nil {
return err
}
// Only save back to DB if state changed
if c.state.State != oldState {
// Check for a restart policy match
if c.config.RestartPolicy != define.RestartPolicyNone && c.config.RestartPolicy != define.RestartPolicyNo &&
(oldState == define.ContainerStateRunning || oldState == define.ContainerStatePaused) &&
(c.state.State == define.ContainerStateStopped || c.state.State == define.ContainerStateExited) &&
!c.state.StoppedByUser {
c.state.RestartPolicyMatch = true
}
if err := c.save(); err != nil {
return err
}
}
}
if !c.valid {
return errors.Wrapf(define.ErrCtrRemoved, "container %s is not valid", c.ID())
}
return nil
}
func (c *Container) setupStorageMapping(dest, from *storage.IDMappingOptions) {
if c.config.Rootfs != "" {
return
}
*dest = *from
// If we are creating a container inside a pod, we always want to inherit the
// userns settings from the infra container. So clear the auto userns settings
// so that we don't request storage for a new uid/gid map.
if c.PodID() != "" && !c.IsInfra() {
dest.AutoUserNs = false
}
if dest.AutoUserNs {
overrides := c.getUserOverrides()
dest.AutoUserNsOpts.PasswdFile = overrides.ContainerEtcPasswdPath
dest.AutoUserNsOpts.GroupFile = overrides.ContainerEtcGroupPath
if c.config.User != "" {
initialSize := uint32(0)
parts := strings.Split(c.config.User, ":")
for _, p := range parts {
s, err := strconv.ParseUint(p, 10, 32)
if err == nil && uint32(s) > initialSize {
initialSize = uint32(s)
}
}
dest.AutoUserNsOpts.InitialSize = initialSize + 1
}
} else if c.config.Spec.Linux != nil {
dest.UIDMap = nil
for _, r := range c.config.Spec.Linux.UIDMappings {
u := idtools.IDMap{
ContainerID: int(r.ContainerID),
HostID: int(r.HostID),
Size: int(r.Size),
}
dest.UIDMap = append(dest.UIDMap, u)
}
dest.GIDMap = nil
for _, r := range c.config.Spec.Linux.GIDMappings {
g := idtools.IDMap{
ContainerID: int(r.ContainerID),
HostID: int(r.HostID),
Size: int(r.Size),
}
dest.GIDMap = append(dest.GIDMap, g)
}
dest.HostUIDMapping = false
dest.HostGIDMapping = false
}
}
// Create container root filesystem for use
func (c *Container) setupStorage(ctx context.Context) error {
if !c.valid {
return errors.Wrapf(define.ErrCtrRemoved, "container %s is not valid", c.ID())
}
if c.state.State != define.ContainerStateConfigured {
return errors.Wrapf(define.ErrCtrStateInvalid, "container %s must be in Configured state to have storage set up", c.ID())
}
// Need both an image ID and image name, plus a bool telling us whether to use the image configuration
if c.config.Rootfs == "" && (c.config.RootfsImageID == "" || c.config.RootfsImageName == "") {
return errors.Wrapf(define.ErrInvalidArg, "must provide image ID and image name to use an image")
}
options := storage.ContainerOptions{
IDMappingOptions: storage.IDMappingOptions{
HostUIDMapping: true,
HostGIDMapping: true,
},
LabelOpts: c.config.LabelOpts,
}
nopts := len(c.config.StorageOpts)
if nopts > 0 {
options.StorageOpt = make(map[string]string, nopts)
for _, opt := range c.config.StorageOpts {
split2 := strings.SplitN(opt, "=", 2)
if len(split2) > 2 {
return errors.Wrapf(define.ErrInvalidArg, "invalid storage options %q for %s", opt, c.ID())
}
options.StorageOpt[split2[0]] = split2[1]
}
}
if c.restoreFromCheckpoint && c.config.ProcessLabel != "" && c.config.MountLabel != "" {
// If restoring from a checkpoint, the root file-system needs
// to be mounted with the same SELinux labels as it was mounted
// previously. But only if both labels have been set. For
// privileged containers or '--ipc host' only ProcessLabel will
// be set and so we will skip it for cases like that.
if options.Flags == nil {
options.Flags = make(map[string]interface{})
}
options.Flags["ProcessLabel"] = c.config.ProcessLabel
options.Flags["MountLabel"] = c.config.MountLabel
}
if c.config.Privileged {
privOpt := func(opt string) bool {
for _, privopt := range []string{"nodev", "nosuid", "noexec"} {
if opt == privopt {
return true
}
}
return false
}
defOptions, err := storage.GetMountOptions(c.runtime.store.GraphDriverName(), c.runtime.store.GraphOptions())
if err != nil {
return errors.Wrapf(err, "error getting default mount options")
}
var newOptions []string
for _, opt := range defOptions {
if !privOpt(opt) {
newOptions = append(newOptions, opt)
}
}
options.MountOpts = newOptions
}
options.Volatile = c.config.Volatile
c.setupStorageMapping(&options.IDMappingOptions, &c.config.IDMappings)
// Unless the user has specified a name, use a randomly generated one.
// Note that name conflicts may occur (see #11735), so we need to loop.
generateName := c.config.Name == ""
var containerInfo ContainerInfo
var containerInfoErr error
for {
if generateName {
name, err := c.runtime.generateName()
if err != nil {
return err
}
c.config.Name = name
}
containerInfo, containerInfoErr = c.runtime.storageService.CreateContainerStorage(ctx, c.runtime.imageContext, c.config.RootfsImageName, c.config.RootfsImageID, c.config.Name, c.config.ID, options)
if !generateName || errors.Cause(containerInfoErr) != storage.ErrDuplicateName {
break
}
}
if containerInfoErr != nil {
return errors.Wrapf(containerInfoErr, "error creating container storage")
}
// only reconfig IDMappings if layer was mounted from storage
// if its a external overlay do not reset IDmappings
if !c.config.RootfsOverlay {
c.config.IDMappings.UIDMap = containerInfo.UIDMap
c.config.IDMappings.GIDMap = containerInfo.GIDMap
}
processLabel, err := c.processLabel(containerInfo.ProcessLabel)
if err != nil {
return err
}
c.config.ProcessLabel = processLabel
c.config.MountLabel = containerInfo.MountLabel
c.config.StaticDir = containerInfo.Dir
c.state.RunDir = containerInfo.RunDir
if len(c.config.IDMappings.UIDMap) != 0 || len(c.config.IDMappings.GIDMap) != 0 {
if err := os.Chown(containerInfo.RunDir, c.RootUID(), c.RootGID()); err != nil {
return err
}
if err := os.Chown(containerInfo.Dir, c.RootUID(), c.RootGID()); err != nil {
return err
}
}
// Set the default Entrypoint and Command
if containerInfo.Config != nil {
// Set CMD in the container to the default configuration only if ENTRYPOINT is not set by the user.
if c.config.Entrypoint == nil && c.config.Command == nil {
c.config.Command = containerInfo.Config.Config.Cmd
}
if c.config.Entrypoint == nil {
c.config.Entrypoint = containerInfo.Config.Config.Entrypoint
}
}
artifacts := filepath.Join(c.config.StaticDir, artifactsDir)
if err := os.MkdirAll(artifacts, 0755); err != nil {
return errors.Wrap(err, "error creating artifacts directory")
}
return nil
}
func (c *Container) processLabel(processLabel string) (string, error) {
if !c.config.Systemd && !c.ociRuntime.SupportsKVM() {
return processLabel, nil
}
ctrSpec, err := c.specFromState()
if err != nil {
return "", err
}
label, ok := ctrSpec.Annotations[define.InspectAnnotationLabel]
if !ok || !strings.Contains(label, "type:") {
switch {
case c.ociRuntime.SupportsKVM():
return selinux.KVMLabel(processLabel)
case c.config.Systemd:
return selinux.InitLabel(processLabel)
}
}
return processLabel, nil
}
// Tear down a container's storage prior to removal
func (c *Container) teardownStorage() error {
if c.ensureState(define.ContainerStateRunning, define.ContainerStatePaused) {
return errors.Wrapf(define.ErrCtrStateInvalid, "cannot remove storage for container %s as it is running or paused", c.ID())
}
artifacts := filepath.Join(c.config.StaticDir, artifactsDir)
if err := os.RemoveAll(artifacts); err != nil {
return errors.Wrapf(err, "error removing container %s artifacts %q", c.ID(), artifacts)
}
if err := c.cleanupStorage(); err != nil {
return errors.Wrapf(err, "failed to cleanup container %s storage", c.ID())
}
if err := c.runtime.storageService.DeleteContainer(c.ID()); err != nil {
// If the container has already been removed, warn but do not
// error - we wanted it gone, it is already gone.
// Potentially another tool using containers/storage already
// removed it?
if errors.Cause(err) == storage.ErrNotAContainer || errors.Cause(err) == storage.ErrContainerUnknown {
logrus.Infof("Storage for container %s already removed", c.ID())
return nil
}
return errors.Wrapf(err, "error removing container %s root filesystem", c.ID())
}
return nil
}
// Reset resets state fields to default values.
// It is performed before a refresh and clears the state after a reboot.
// It does not save the results - assumes the database will do that for us.
func resetState(state *ContainerState) {
state.PID = 0
state.ConmonPID = 0
state.Mountpoint = ""
state.Mounted = false
if state.State != define.ContainerStateExited {
state.State = define.ContainerStateConfigured
}
state.ExecSessions = make(map[string]*ExecSession)
state.LegacyExecSessions = nil
state.BindMounts = make(map[string]string)
state.StoppedByUser = false
state.RestartPolicyMatch = false
state.RestartCount = 0
state.Checkpointed = false
state.Restored = false
state.CheckpointedTime = time.Time{}
state.RestoredTime = time.Time{}
state.CheckpointPath = ""
state.CheckpointLog = ""
state.RestoreLog = ""
}
// Refresh refreshes the container's state after a restart.
// Refresh cannot perform any operations that would lock another container.
// We cannot guarantee any other container has a valid lock at the time it is
// running.
func (c *Container) refresh() error {
// Don't need a full sync, but we do need to update from the database to
// pick up potentially-missing container state
if err := c.runtime.state.UpdateContainer(c); err != nil {
return err
}
if !c.valid {
return errors.Wrapf(define.ErrCtrRemoved, "container %s is not valid - may have been removed", c.ID())
}
// We need to get the container's temporary directory from c/storage
// It was lost in the reboot and must be recreated
dir, err := c.runtime.storageService.GetRunDir(c.ID())
if err != nil {
return errors.Wrapf(err, "error retrieving temporary directory for container %s", c.ID())
}
c.state.RunDir = dir
if len(c.config.IDMappings.UIDMap) != 0 || len(c.config.IDMappings.GIDMap) != 0 {
info, err := os.Stat(c.runtime.config.Engine.TmpDir)
if err != nil {
return err
}
if err := os.Chmod(c.runtime.config.Engine.TmpDir, info.Mode()|0111); err != nil {
return err
}
root := filepath.Join(c.runtime.config.Engine.TmpDir, "containers-root", c.ID())
if err := os.MkdirAll(root, 0755); err != nil {
return errors.Wrapf(err, "error creating userNS tmpdir for container %s", c.ID())
}
if err := os.Chown(root, c.RootUID(), c.RootGID()); err != nil {
return err
}
}
// We need to pick up a new lock
lock, err := c.runtime.lockManager.AllocateAndRetrieveLock(c.config.LockID)
if err != nil {
return errors.Wrapf(err, "error acquiring lock %d for container %s", c.config.LockID, c.ID())
}
c.lock = lock
c.state.NetworkStatus = nil
c.state.NetworkStatusOld = nil
// Rewrite the config if necessary.
// Podman 4.0 uses a new port format in the config.
// getContainerConfigFromDB() already converted the old ports to the new one
// but it did not write the config to the db back for performance reasons.
// If a rewrite must happen the config.rewrite field is set to true.
if c.config.rewrite {
// SafeRewriteContainerConfig must be used with care. Make sure to not change config fields by accident.
if err := c.runtime.state.SafeRewriteContainerConfig(c, "", "", c.config); err != nil {
return errors.Wrapf(err, "failed to rewrite the config for container %s", c.config.ID)
}
c.config.rewrite = false
}
if err := c.save(); err != nil {
return errors.Wrapf(err, "error refreshing state for container %s", c.ID())
}
// Remove ctl and attach files, which may persist across reboot
if err := c.removeConmonFiles(); err != nil {
return err
}
return nil
}
// Remove conmon attach socket and terminal resize FIFO
// This is necessary for restarting containers
func (c *Container) removeConmonFiles() error {
// Files are allowed to not exist, so ignore ENOENT
attachFile, err := c.AttachSocketPath()
if err != nil {
return errors.Wrapf(err, "failed to get attach socket path for container %s", c.ID())
}
if err := os.Remove(attachFile); err != nil && !os.IsNotExist(err) {
return errors.Wrapf(err, "error removing container %s attach file", c.ID())
}
ctlFile := filepath.Join(c.bundlePath(), "ctl")
if err := os.Remove(ctlFile); err != nil && !os.IsNotExist(err) {
return errors.Wrapf(err, "error removing container %s ctl file", c.ID())
}
winszFile := filepath.Join(c.bundlePath(), "winsz")
if err := os.Remove(winszFile); err != nil && !os.IsNotExist(err) {
return errors.Wrapf(err, "error removing container %s winsz file", c.ID())
}
oomFile := filepath.Join(c.bundlePath(), "oom")
if err := os.Remove(oomFile); err != nil && !os.IsNotExist(err) {
return errors.Wrapf(err, "error removing container %s OOM file", c.ID())
}
// Remove the exit file so we don't leak memory in tmpfs
exitFile, err := c.exitFilePath()
if err != nil {
return err
}
if err := os.Remove(exitFile); err != nil && !os.IsNotExist(err) {
return errors.Wrapf(err, "error removing container %s exit file", c.ID())
}
return nil
}
func (c *Container) export(path string) error {
mountPoint := c.state.Mountpoint
if !c.state.Mounted {
containerMount, err := c.runtime.store.Mount(c.ID(), c.config.MountLabel)
if err != nil {
return errors.Wrapf(err, "mounting container %q", c.ID())
}
mountPoint = containerMount
defer func() {
if _, err := c.runtime.store.Unmount(c.ID(), false); err != nil {
logrus.Errorf("Unmounting container %q: %v", c.ID(), err)
}
}()
}
input, err := archive.Tar(mountPoint, archive.Uncompressed)
if err != nil {
return errors.Wrapf(err, "error reading container directory %q", c.ID())
}
outFile, err := os.Create(path)
if err != nil {
return errors.Wrapf(err, "error creating file %q", path)
}
defer outFile.Close()
_, err = io.Copy(outFile, input)
return err
}
// Get path of artifact with a given name for this container
func (c *Container) getArtifactPath(name string) string {
return filepath.Join(c.config.StaticDir, artifactsDir, name)
}
// Used with Wait() to determine if a container has exited
func (c *Container) isStopped() (bool, int32, error) {
if !c.batched {
c.lock.Lock()
defer c.lock.Unlock()
}
err := c.syncContainer()
if err != nil {
return true, -1, err
}
return !c.ensureState(define.ContainerStateRunning, define.ContainerStatePaused, define.ContainerStateStopping), c.state.ExitCode, nil
}
// save container state to the database
func (c *Container) save() error {
if err := c.runtime.state.SaveContainer(c); err != nil {
return errors.Wrapf(err, "error saving container %s state", c.ID())
}
return nil
}
// Checks the container is in the right state, then initializes the container in preparation to start the container.
// If recursive is true, each of the containers dependencies will be started.
// Otherwise, this function will return with error if there are dependencies of this container that aren't running.
func (c *Container) prepareToStart(ctx context.Context, recursive bool) (retErr error) {
// Container must be created or stopped to be started
if !c.ensureState(define.ContainerStateConfigured, define.ContainerStateCreated, define.ContainerStateStopped, define.ContainerStateExited) {
return errors.Wrapf(define.ErrCtrStateInvalid, "container %s must be in Created or Stopped state to be started", c.ID())
}
if !recursive {
if err := c.checkDependenciesAndHandleError(); err != nil {
return err
}
} else {
if err := c.startDependencies(ctx); err != nil {
return err
}
}
defer func() {
if retErr != nil {
if err := c.cleanup(ctx); err != nil {
logrus.Errorf("Cleaning up container %s: %v", c.ID(), err)
}
}
}()
if err := c.prepare(); err != nil {
return err
}
if c.state.State == define.ContainerStateStopped {
// Reinitialize the container if we need to
if err := c.reinit(ctx, false); err != nil {
return err
}
} else if c.ensureState(define.ContainerStateConfigured, define.ContainerStateExited) {
// Or initialize it if necessary
if err := c.init(ctx, false); err != nil {
return err
}
}
return nil
}
// checks dependencies are running and prints a helpful message
func (c *Container) checkDependenciesAndHandleError() error {
notRunning, err := c.checkDependenciesRunning()
if err != nil {
return errors.Wrapf(err, "error checking dependencies for container %s", c.ID())
}
if len(notRunning) > 0 {
depString := strings.Join(notRunning, ",")
return errors.Wrapf(define.ErrCtrStateInvalid, "some dependencies of container %s are not started: %s", c.ID(), depString)
}
return nil
}
// Recursively start all dependencies of a container so the container can be started.
func (c *Container) startDependencies(ctx context.Context) error {
depCtrIDs := c.Dependencies()
if len(depCtrIDs) == 0 {
return nil
}
depVisitedCtrs := make(map[string]*Container)
if err := c.getAllDependencies(depVisitedCtrs); err != nil {
return errors.Wrapf(err, "error starting dependency for container %s", c.ID())
}
// Because of how Go handles passing slices through functions, a slice cannot grow between function calls
// without clunky syntax. Circumnavigate this by translating the map to a slice for buildContainerGraph
depCtrs := make([]*Container, 0)
for _, ctr := range depVisitedCtrs {
depCtrs = append(depCtrs, ctr)
}
// Build a dependency graph of containers
graph, err := BuildContainerGraph(depCtrs)
if err != nil {
return errors.Wrapf(err, "error generating dependency graph for container %s", c.ID())
}
// If there are no containers without dependencies, we can't start
// Error out
if len(graph.noDepNodes) == 0 {
// we have no dependencies that need starting, go ahead and return
if len(graph.nodes) == 0 {
return nil
}
return errors.Wrapf(define.ErrNoSuchCtr, "All dependencies have dependencies of %s", c.ID())
}
ctrErrors := make(map[string]error)
ctrsVisited := make(map[string]bool)
// Traverse the graph beginning at nodes with no dependencies
for _, node := range graph.noDepNodes {
startNode(ctx, node, false, ctrErrors, ctrsVisited, true)
}
if len(ctrErrors) > 0 {
logrus.Errorf("Starting some container dependencies")
for _, e := range ctrErrors {
logrus.Errorf("%q", e)
}
return errors.Wrapf(define.ErrInternal, "error starting some containers")
}
return nil
}
// getAllDependencies is a precursor to starting dependencies.
// To start a container with all of its dependencies, we need to recursively find all dependencies
// a container has, as well as each of those containers' dependencies, and so on
// To do so, keep track of containers already visited (so there aren't redundant state lookups),
// and recursively search until we have reached the leafs of every dependency node.
// Since we need to start all dependencies for our original container to successfully start, we propagate any errors
// in looking up dependencies.
// Note: this function is currently meant as a robust solution to a narrow problem: start an infra-container when
// a container in the pod is run. It has not been tested for performance past one level, so expansion of recursive start
// must be tested first.
func (c *Container) getAllDependencies(visited map[string]*Container) error {
depIDs := c.Dependencies()
if len(depIDs) == 0 {
return nil
}
for _, depID := range depIDs {
if _, ok := visited[depID]; !ok {
dep, err := c.runtime.state.Container(depID)
if err != nil {
return err
}
status, err := dep.State()
if err != nil {
return err
}
// if the dependency is already running, we can assume its dependencies are also running
// so no need to add them to those we need to start
if status != define.ContainerStateRunning {
visited[depID] = dep
if err := dep.getAllDependencies(visited); err != nil {
return err
}
}
}
}
return nil
}
// Check if a container's dependencies are running
// Returns a []string containing the IDs of dependencies that are not running
func (c *Container) checkDependenciesRunning() ([]string, error) {
deps := c.Dependencies()
notRunning := []string{}
// We were not passed a set of dependency containers
// Make it ourselves
depCtrs := make(map[string]*Container, len(deps))
for _, dep := range deps {
// Get the dependency container
depCtr, err := c.runtime.state.Container(dep)
if err != nil {
return nil, errors.Wrapf(err, "error retrieving dependency %s of container %s from state", dep, c.ID())
}
// Check the status
state, err := depCtr.State()
if err != nil {
return nil, errors.Wrapf(err, "error retrieving state of dependency %s of container %s", dep, c.ID())
}
if state != define.ContainerStateRunning && !depCtr.config.IsInfra {
notRunning = append(notRunning, dep)
}
depCtrs[dep] = depCtr
}
return notRunning, nil
}
func (c *Container) completeNetworkSetup() error {
var outResolvConf []string
netDisabled, err := c.NetworkDisabled()
if err != nil {