-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathcontainer.go
More file actions
2293 lines (2068 loc) · 79.5 KB
/
container.go
File metadata and controls
2293 lines (2068 loc) · 79.5 KB
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 2018 The gVisor Authors.
//
// 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 container creates and manipulates containers.
package container
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path"
"regexp"
"slices"
"strconv"
"strings"
"syscall"
"time"
"github.com/cenkalti/backoff"
specs "github.com/opencontainers/runtime-spec/specs-go"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/cleanup"
"gvisor.dev/gvisor/pkg/log"
"gvisor.dev/gvisor/pkg/sentry/control"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/erofs"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs"
"gvisor.dev/gvisor/pkg/sentry/pgalloc"
"gvisor.dev/gvisor/pkg/sighandling"
"gvisor.dev/gvisor/pkg/unet"
"gvisor.dev/gvisor/pkg/urpc"
"gvisor.dev/gvisor/runsc/boot"
"gvisor.dev/gvisor/runsc/cgroup"
"gvisor.dev/gvisor/runsc/config"
"gvisor.dev/gvisor/runsc/console"
"gvisor.dev/gvisor/runsc/donation"
"gvisor.dev/gvisor/runsc/profile"
"gvisor.dev/gvisor/runsc/sandbox"
"gvisor.dev/gvisor/runsc/specutils"
"gvisor.dev/gvisor/runsc/starttime"
)
const cgroupParentAnnotation = "dev.gvisor.spec.cgroup-parent"
// validateID validates the container id.
func validateID(id string) error {
// See libcontainer/factory_linux.go.
idRegex := regexp.MustCompile(`^[\w+\.-]+$`)
if !idRegex.MatchString(id) {
return fmt.Errorf("invalid container id: %v", id)
}
return nil
}
// Container represents a containerized application. When running, the
// container is associated with a single Sandbox.
//
// Container metadata can be saved and loaded to disk. Within a root directory,
// we maintain subdirectories for each container named with the container id.
// The container metadata is stored as a json within the container directory
// in a file named "meta.json". This metadata format is defined by us and is
// not part of the OCI spec.
//
// Containers must write their metadata files after any change to their internal
// states. The entire container directory is deleted when the container is
// destroyed.
//
// When the container is stopped, all processes that belong to the container
// must be stopped before Destroy() returns. containerd makes roughly the
// following calls to stop a container:
// - First it attempts to kill the container process with
// 'runsc kill SIGTERM'. After some time, it escalates to SIGKILL. In a
// separate thread, it's waiting on the container. As soon as the wait
// returns, it moves on to the next step:
// - It calls 'runsc kill --all SIGKILL' to stop every process that belongs to
// the container. 'kill --all SIGKILL' waits for all processes before
// returning.
// - Containerd waits for stdin, stdout and stderr to drain and be closed.
// - It calls 'runsc delete'. runc implementation kills --all SIGKILL once
// again just to be sure, waits, and then proceeds with remaining teardown.
//
// Container is thread-unsafe.
type Container struct {
// ID is the container ID.
ID string `json:"id"`
// Spec is the OCI runtime spec that configures this container.
Spec *specs.Spec `json:"spec"`
// BundleDir is the directory containing the container bundle.
BundleDir string `json:"bundleDir"`
// CreatedAt is the time the container was created.
CreatedAt time.Time `json:"createdAt"`
// Owner is the container owner.
Owner string `json:"owner"`
// ConsoleSocket is the path to a unix domain socket that will receive
// the console FD.
ConsoleSocket string `json:"consoleSocket"`
// Status is the current container Status.
Status Status `json:"status"`
// GoferPid is the PID of the gofer running along side the sandbox. May
// be 0 if the gofer has been killed.
GoferPid sandbox.Pid `json:"goferPid"`
// Sandbox is the sandbox this container is running in. It's set when the
// container is created and reset when the sandbox is destroyed.
Sandbox *sandbox.Sandbox `json:"sandbox"`
// CompatCgroup has the cgroup configuration for the container. For the single
// container case, container cgroup is set in `c.Sandbox` only. CompactCgroup
// is only set for multi-container, where the `c.Sandbox` cgroup represents
// the entire pod.
//
// Note that CompatCgroup is created only for compatibility with tools
// that expect container cgroups to exist. Setting limits here makes no change
// to the container in question.
CompatCgroup cgroup.CgroupJSON `json:"compatCgroup"`
// Saver handles load from/save to the state file safely from multiple
// processes.
Saver StateFile `json:"saver"`
// GoferMountConfs contains information about how the gofer mounts have been
// overlaid (with tmpfs or overlayfs). The first entry is for rootfs and the
// following entries are for bind mounts in Spec.Mounts (in the same order).
GoferMountConfs specutils.GoferMountConfFlags `json:"goferMountConfs"`
//
// Fields below this line are not saved in the state file and will not
// be preserved across commands.
//
// goferIsChild is set if a gofer process is a child of the current process.
//
// This field isn't saved to json, because only a creator of a gofer
// process will have it as a child process.
goferIsChild bool `nojson:"true"`
}
// Args is used to configure a new container.
type Args struct {
// ID is the container unique identifier.
ID string
// Spec is the OCI spec that describes the container.
Spec *specs.Spec
// BundleDir is the directory containing the container bundle.
BundleDir string
// ConsoleSocket is the path to a unix domain socket that will receive
// the console FD. It may be empty.
ConsoleSocket string
// PIDFile is the filename where the container's root process PID will be
// written to. It may be empty.
PIDFile string
// UserLog is the filename to send user-visible logs to. It may be empty.
//
// It only applies for the init container.
UserLog string
// Attached indicates that the sandbox lifecycle is attached with the caller.
// If the caller exits, the sandbox should exit too.
//
// It only applies for the init container.
Attached bool
// PassFiles are user-supplied files from the host to be exposed to the
// sandboxed app.
PassFiles map[int]*os.File
// ExecFile is the host file used for program execution.
ExecFile *os.File
// If FSRestoreImagePath is non-empty, it is a path to a filesystem
// checkpoint that should be restored. FSRestoreImagePath may only be set
// for containers in a new Sandbox process.
FSRestoreImagePath string
FSRestoreDirect bool
}
// New creates the container in a new Sandbox process, unless the metadata
// indicates that an existing Sandbox should be used. The caller must call
// Destroy() on the container.
func New(conf *config.Config, args Args) (*Container, error) {
log.Debugf("Create container, cid: %s, rootDir: %q", args.ID, conf.RootDir)
if err := validateID(args.ID); err != nil {
return nil, err
}
if err := os.MkdirAll(conf.RootDir, 0711); err != nil {
return nil, fmt.Errorf("creating container root directory %q: %v", conf.RootDir, err)
}
if err := modifySpecForDirectfs(conf, args.Spec); err != nil {
return nil, fmt.Errorf("failed to modify spec for directfs: %v", err)
}
sandboxID := args.ID
if !specutils.IsRootContainer(args.Spec) {
var ok bool
sandboxID, ok = specutils.SandboxID(args.Spec)
if !ok {
return nil, fmt.Errorf("no sandbox ID found when creating container")
}
if args.FSRestoreImagePath != "" {
return nil, fmt.Errorf("cannot set FSRestoreImagePath when creating container in existing sandbox")
}
}
c := &Container{
ID: args.ID,
Spec: args.Spec,
ConsoleSocket: args.ConsoleSocket,
BundleDir: args.BundleDir,
Status: Creating,
CreatedAt: time.Now(),
Owner: os.Getenv("USER"),
Saver: StateFile{
RootDir: conf.RootDir,
ID: FullID{
SandboxID: sandboxID,
ContainerID: args.ID,
},
},
}
// The Cleanup object cleans up partially created containers when an error
// occurs. Any errors occurring during cleanup itself are ignored.
cu := cleanup.Make(func() { _ = c.Destroy() })
defer cu.Clean()
// Lock the container metadata file to prevent concurrent creations of
// containers with the same id.
if err := c.Saver.LockForNew(); err != nil {
// As we have not allocated any resources yet, we revoke the clean-up operation.
// Otherwise, we may accidentally destroy an existing container.
cu.Release()
return nil, fmt.Errorf("cannot lock container metadata file: %w", err)
}
defer c.Saver.UnlockOrDie()
// If the metadata annotations indicate that this container should be started
// in an existing sandbox, we must do so. These are the possible metadata
// annotation states:
// 1. No annotations: it means that there is a single container and this
// container is obviously the root. Both container and sandbox share the
// ID.
// 2. Container type == sandbox: it means this is the root container
// starting the sandbox. Both container and sandbox share the same ID.
// 3. Container type == container: it means this is a subcontainer of an
// already started sandbox. In this case, container ID is different than
// the sandbox ID.
if specutils.IsRootContainer(args.Spec) {
if err := c.createRoot(conf, args, sandboxID); err != nil {
return nil, err
}
} else {
log.Debugf("Creating new container, cid: %s, sandbox: %s", c.ID, sandboxID)
// Find the sandbox associated with this ID.
fullID := FullID{
SandboxID: sandboxID,
ContainerID: sandboxID,
}
sb, err := Load(conf.RootDir, fullID, LoadOpts{Exact: true})
if err != nil {
return nil, fmt.Errorf("cannot load sandbox: %w", err)
}
c.Sandbox = sb.Sandbox
if err := c.createSubcontainer(conf, args.Spec); err != nil {
return nil, err
}
}
c.changeStatus(Created)
// Save the metadata file.
if err := c.saveLocked(); err != nil {
return nil, err
}
// "If any prestart hook fails, the runtime MUST generate an error,
// stop and destroy the container" -OCI spec.
if c.Spec.Hooks != nil {
// Even though the hook name is Prestart, runc used to call it from create.
// For this reason, it's now deprecated, but the spec requires it to be
// called *before* CreateRuntime and CreateRuntime must be called in create.
//
// "For runtimes that implement the deprecated prestart hooks as
// createRuntime hooks, createRuntime hooks MUST be called after the
// prestart hooks."
if err := executeHooks(c.Spec.Hooks.Prestart, c.State()); err != nil {
return nil, err
}
if err := executeHooks(c.Spec.Hooks.CreateRuntime, c.State()); err != nil {
return nil, err
}
if len(c.Spec.Hooks.CreateContainer) > 0 {
log.Warningf("CreateContainer hook skipped because running inside container namespace is not supported")
}
}
// Write the PID file. Containerd considers the call to create complete after
// this file is created, so it must be the last thing we do.
if args.PIDFile != "" {
if err := os.WriteFile(args.PIDFile, []byte(strconv.Itoa(c.SandboxPid())), 0644); err != nil {
return nil, fmt.Errorf("error writing PID file: %v", err)
}
}
cu.Release()
return c, nil
}
func (c *Container) createRoot(conf *config.Config, args Args, sandboxID string) error {
log.Debugf("Creating new sandbox for container, cid: %s", args.ID)
if args.Spec.Linux == nil {
args.Spec.Linux = &specs.Linux{}
}
// Don't force the use of cgroups in tests because they lack permission to do so.
if args.Spec.Linux.CgroupsPath == "" && !conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {
args.Spec.Linux.CgroupsPath = "/" + args.ID
}
var subCgroup, parentCgroup, containerCgroup cgroup.Cgroup
if !conf.IgnoreCgroups {
var err error
// Create and join cgroup before processes are created to ensure they are
// part of the cgroup from the start (and all their children processes).
parentCgroup, subCgroup, err = c.setupCgroupForRoot(conf, args.Spec)
if err != nil {
return fmt.Errorf("cannot set up cgroup for root: %w", err)
}
// Join the child cgroup when using cgroupfs. Joining non leaf-node
// cgroups is illegal in cgroupsv2 and will return EBUSY.
if subCgroup != nil && !conf.SystemdCgroup && cgroup.IsOnlyV2() {
containerCgroup = subCgroup
} else {
containerCgroup = parentCgroup
}
}
c.CompatCgroup = cgroup.CgroupJSON{Cgroup: subCgroup}
mountHints, err := boot.NewPodMountHints(args.Spec)
if err != nil {
return fmt.Errorf("error creating pod mount hints: %w", err)
}
if err := nvProxyPreGoferHostSetup(args.Spec, conf); err != nil {
return err
}
if err := cgroup.RunInCgroup(containerCgroup, func() error {
ioFiles, goferFilestores, devIOFile, specFile, err := c.createGoferProcess(conf, mountHints, args.Attached)
if err != nil {
return fmt.Errorf("cannot create gofer process: %w", err)
}
// Start a new sandbox for this container. Any errors after this point
// must destroy the container.
sandArgs := &sandbox.Args{
ID: sandboxID,
Spec: args.Spec,
BundleDir: args.BundleDir,
ConsoleSocket: args.ConsoleSocket,
UserLog: args.UserLog,
IOFiles: ioFiles,
DevIOFile: devIOFile,
MountsFile: specFile,
Cgroup: containerCgroup,
Attached: args.Attached,
GoferFilestoreFiles: goferFilestores,
GoferMountConfs: c.GoferMountConfs,
MountHints: mountHints,
PassFiles: args.PassFiles,
ExecFile: args.ExecFile,
FSRestoreImagePath: args.FSRestoreImagePath,
FSRestoreDirect: args.FSRestoreDirect,
}
sand, err := sandbox.New(conf, sandArgs)
if err != nil {
return fmt.Errorf("cannot create sandbox: %w", err)
}
c.Sandbox = sand
return nil
}); err != nil {
return err
}
return nil
}
func (c *Container) createSubcontainer(conf *config.Config, spec *specs.Spec) error {
subCgroup, err := c.setupCgroupForSubcontainer(conf, spec)
if err != nil {
return err
}
c.CompatCgroup = cgroup.CgroupJSON{Cgroup: subCgroup}
// If the console control socket file is provided, then create a new
// pty master/slave pair and send the TTY to the sandbox process.
var tty *os.File
if c.ConsoleSocket != "" {
// Create a new TTY pair and send the master on the provided socket.
var err error
tty, err = console.NewWithSocket(c.ConsoleSocket)
if err != nil {
return fmt.Errorf("setting up console with socket %q: %w", c.ConsoleSocket, err)
}
// tty file is transferred to the sandbox, then it can be closed here.
defer tty.Close()
}
if err := c.Sandbox.CreateSubcontainer(conf, c.ID, tty); err != nil {
return fmt.Errorf("cannot create subcontainer: %w", err)
}
return nil
}
// Start starts running the containerized process inside the sandbox.
func (c *Container) Start(conf *config.Config) error {
log.Debugf("Start container, cid: %s", c.ID)
return c.startImpl(conf, "start", c.Sandbox.StartRoot, c.Sandbox.StartSubcontainer)
}
// Restore takes a container and replaces its kernel and file system
// to restore a container from its state file.
func (c *Container) Restore(conf *config.Config, imagePath string, direct, background bool) error {
log.Debugf("Restore container, cid: %s", c.ID)
restore := func(conf *config.Config, spec *specs.Spec) error {
return c.Sandbox.Restore(conf, spec, c.ID, imagePath, direct, background)
}
return c.startImpl(conf, "restore", restore, c.Sandbox.RestoreSubcontainer)
}
func (c *Container) startImpl(conf *config.Config, action string, startRoot func(conf *config.Config, spec *specs.Spec) error, startSub func(spec *specs.Spec, conf *config.Config, cid string, stdios, goferFiles, goferFilestores []*os.File, devIOFile *os.File, goferConfs []specutils.GoferMountConf) error) error {
if err := c.Saver.lock(BlockAcquire); err != nil {
return err
}
unlock := cleanup.Make(c.Saver.UnlockOrDie)
defer unlock.Clean()
if err := c.requireStatus(action, Created); err != nil {
return err
}
// "If any prestart hook fails, the runtime MUST generate an error,
// stop and destroy the container" -OCI spec.
if c.Spec.Hooks != nil && len(c.Spec.Hooks.StartContainer) > 0 {
log.Warningf("StartContainer hook skipped because running inside container namespace is not supported")
}
if specutils.IsRootContainer(c.Spec) {
if err := startRoot(conf, c.Spec); err != nil {
return err
}
} else {
// Join cgroup to start gofer process to ensure it's part of the cgroup from
// the start (and all their children processes).
if err := cgroup.RunInCgroup(c.Sandbox.CgroupJSON.Cgroup, func() error {
// Create the gofer process.
goferFiles, goferFilestores, devIOFile, mountsFile, err := c.createGoferProcess(conf, c.Sandbox.MountHints, false /* attached */)
if err != nil {
return err
}
defer func() {
if mountsFile != nil {
_ = mountsFile.Close()
}
if devIOFile != nil {
_ = devIOFile.Close()
}
for _, f := range goferFiles {
_ = f.Close()
}
for _, f := range goferFilestores {
_ = f.Close()
}
}()
if mountsFile != nil {
cleanMounts, err := specutils.ReadMounts(mountsFile)
if err != nil {
return fmt.Errorf("reading mounts file: %v", err)
}
c.Spec.Mounts = cleanMounts
}
// Setup stdios if the container is not using terminal. Otherwise TTY was
// already setup in create.
var stdios []*os.File
if !c.Spec.Process.Terminal {
stdios = []*os.File{os.Stdin, os.Stdout, os.Stderr}
}
return startSub(c.Spec, conf, c.ID, stdios, goferFiles, goferFilestores, devIOFile, c.GoferMountConfs)
}); err != nil {
return err
}
}
// "If any poststart hook fails, the runtime MUST log a warning, but
// the remaining hooks and lifecycle continue as if the hook had
// succeeded" -OCI spec.
if c.Spec.Hooks != nil {
executeHooksBestEffort(c.Spec.Hooks.Poststart, c.State())
}
c.changeStatus(Running)
if err := c.saveLocked(); err != nil {
return err
}
// Release lock before adjusting OOM score because the lock is acquired there.
unlock.Clean()
// Adjust the oom_score_adj for sandbox. This must be done after saveLocked().
if err := adjustSandboxOOMScoreAdj(c.Sandbox, c.Spec, c.Saver.RootDir, false); err != nil {
return err
}
// Set container's oom_score_adj to the gofer since it is dedicated to
// the container, in case the gofer uses up too much memory.
return c.adjustGoferOOMScoreAdj()
}
// Run is a helper that calls Create + Start + Wait.
func Run(conf *config.Config, args Args) (unix.WaitStatus, error) {
log.Debugf("Run container, cid: %s, rootDir: %q", args.ID, conf.RootDir)
c, err := New(conf, args)
if err != nil {
return 0, fmt.Errorf("creating container: %v", err)
}
// Clean up partially created container if an error occurs.
// Any errors returned by Destroy() itself are ignored.
cu := cleanup.Make(func() {
c.Destroy()
})
defer cu.Clean()
if err := c.Start(conf); err != nil {
return 0, fmt.Errorf("starting container: %v", err)
}
// If we allocate a terminal, forward signals to the sandbox process.
// Otherwise, Ctrl+C will terminate this process and its children,
// including the terminal.
if c.Spec.Process.Terminal {
stopForwarding := c.ForwardSignals(0, true /* fgProcess */)
defer stopForwarding()
}
if args.Attached {
return c.Wait()
}
cu.Release()
return 0, nil
}
// Update sets the resources of a running container as configured.
func (c *Container) Update(res *specs.LinuxResources) error {
log.Debugf("Set resources for container, cid: %s", c.ID)
if err := c.requireStatus("set resources for", Created, Running); err != nil {
return err
}
if c.Sandbox == nil {
return fmt.Errorf("sandbox cannot be nil")
}
if !c.Sandbox.IsRootContainer(c.ID) {
return fmt.Errorf("update can only be called on the root container")
}
cg := c.Sandbox.CgroupJSON.Cgroup
if cg == nil {
return fmt.Errorf("cgroup cannot be nil")
}
if err := cg.Update(res); err != nil {
// set back to original
if err2 := cg.Update(c.Spec.Linux.Resources); err2 != nil {
return fmt.Errorf("setting back cgroup configs failed due to error: %v, your state file and actual configs might be inconsistent", err2)
}
return err
}
c.Spec.Linux.Resources = res
c.Saver.lock(BlockAcquire)
defer c.Saver.unlock()
return c.saveLocked()
}
// Execute runs the specified command in the container. It returns the PID of
// the newly created process.
func (c *Container) Execute(conf *config.Config, args *control.ExecArgs) (int32, error) {
log.Debugf("Execute in container, cid: %s, args: %+v", c.ID, args)
if err := c.requireStatus("execute in", Created, Running); err != nil {
return 0, err
}
args.ContainerID = c.ID
return c.Sandbox.Execute(conf, args)
}
// Event returns events for the container.
func (c *Container) Event() (*boot.EventOut, error) {
log.Debugf("Getting events for container, cid: %s", c.ID)
if err := c.requireStatus("get events for", Created, Running, Paused); err != nil {
return nil, err
}
event, err := c.Sandbox.Event(c.ID)
if err != nil {
return nil, err
}
// CPU stats can utilize host cgroups for accuracy.
c.populateStats(event)
return event, nil
}
// PortForward starts port forwarding to the container.
func (c *Container) PortForward(opts *boot.PortForwardOpts) error {
if err := c.requireStatus("port forward", Running); err != nil {
return err
}
opts.ContainerID = c.ID
return c.Sandbox.PortForward(opts)
}
// SandboxPid returns the Getpid of the sandbox the container is running in, or -1 if the
// container is not running.
func (c *Container) SandboxPid() int {
if err := c.requireStatus("get PID", Created, Running, Paused); err != nil {
return -1
}
return c.Sandbox.Getpid()
}
// Wait waits for the container to exit, and returns its WaitStatus.
// Call to wait on a stopped container is needed to retrieve the exit status
// and wait returns immediately.
func (c *Container) Wait() (unix.WaitStatus, error) {
log.Debugf("Wait on container, cid: %s", c.ID)
if c.goferIsChild {
// The gofer process is a child of the current process, so we need to wait
// on it and collect its zombie. Start a goroutine to reap c.GoferPid. Do
// not block the main thread waiting for the gofer to exit. In certain
// multi-container scenarios, the gofer may outlive its container. For
// example, if a gofer-backed FD is donated by the application to another
// container within the sandbox. The lifecycle of the gofer will be tied to
// both containers, whichever lives longer.
go func() {
goferPid := c.GoferPid.Load()
if goferPid == 0 {
return
}
// The gofer process could be racily reaped by c.waitForStopped() so
// ignore ECHILD errors.
var status unix.WaitStatus
if _, err := unix.Wait4(goferPid, &status, 0, nil); err == nil {
log.Infof("Gofer process (PID=%d) reaped: exit code = %v", goferPid, status.ExitStatus())
} else if !errors.Is(err, unix.ECHILD) {
log.Warningf("error reaping the gofer process (PID=%d) from background goroutine: %v", goferPid, err)
}
c.GoferPid.Store(0)
}()
}
ws, err := c.Sandbox.Wait(c.ID)
if err == nil {
// Wait succeeded, container is not running anymore.
c.changeStatus(Stopped)
}
return ws, err
}
// WaitRootPID waits for process 'pid' in the sandbox's PID namespace and
// returns its WaitStatus.
func (c *Container) WaitRootPID(pid int32) (unix.WaitStatus, error) {
log.Debugf("Wait on process %d in sandbox, cid: %s", pid, c.Sandbox.ID)
if !c.IsSandboxRunning() {
return 0, fmt.Errorf("sandbox is not running")
}
return c.Sandbox.WaitPID(c.Sandbox.ID, pid)
}
// WaitPID waits for process 'pid' in the container's PID namespace and returns
// its WaitStatus.
func (c *Container) WaitPID(pid int32) (unix.WaitStatus, error) {
log.Debugf("Wait on process %d in container, cid: %s", pid, c.ID)
if !c.IsSandboxRunning() {
return 0, fmt.Errorf("sandbox is not running")
}
return c.Sandbox.WaitPID(c.ID, pid)
}
// WaitCheckpoint waits for the Kernel to have been successfully checkpointed.
func (c *Container) WaitCheckpoint() error {
log.Debugf("Waiting for checkpoint to complete in container, cid: %s", c.ID)
if !c.IsSandboxRunning() {
return fmt.Errorf("sandbox is not running")
}
return c.Sandbox.WaitCheckpoint()
}
// WaitRestore waits for the Kernel to have been successfully restored.
func (c *Container) WaitRestore() error {
log.Debugf("Waiting for restore to complete in container, cid: %s", c.ID)
if !c.IsSandboxRunning() {
return fmt.Errorf("sandbox is not running")
}
return c.Sandbox.WaitRestore()
}
// WaitFSCheckpoint waits for a filesystem checkpoint to have successfully been
// saved.
func (c *Container) WaitFSCheckpoint() error {
log.Debugf("Waiting for filesystem checkpoint to complete in container, cid: %s", c.ID)
if !c.IsSandboxRunning() {
return fmt.Errorf("sandbox is not running")
}
return c.Sandbox.WaitFSCheckpoint()
}
// WaitFSRestore waits for filesystems to have been successfully restored from
// checkpoint.
func (c *Container) WaitFSRestore() error {
log.Debugf("Waiting for filesystem restore to complete in container, cid: %s", c.ID)
if !c.IsSandboxRunning() {
return fmt.Errorf("sandbox is not running")
}
return c.Sandbox.WaitFSRestore(c.ID)
}
// TarRootfsUpperLayer serializes the rootfs upper layer of the container to a tar file. When
// the rootfs is not an overlayfs, it returns an error. It writes the tar file
// to outFD.
func (c *Container) TarRootfsUpperLayer(outFD *os.File) error {
log.Debugf("TarRootfsUpperLayer, cid: %s", c.ID)
if !c.IsSandboxRunning() {
return fmt.Errorf("sandbox is not running")
}
return c.Sandbox.TarRootfsUpperLayer(c.ID, outFD)
}
// SignalContainer sends the signal to the container. If all is true and signal
// is SIGKILL, then waits for all processes to exit before returning.
// SignalContainer returns an error if the container is already stopped.
// TODO(b/113680494): Distinguish different error types.
func (c *Container) SignalContainer(sig unix.Signal, all bool) error {
log.Debugf("Signal container, cid: %s, signal: %v (%d)", c.ID, sig, sig)
// Signaling container in Stopped state is allowed. When all=false,
// an error will be returned anyway; when all=true, this allows
// sending signal to other processes inside the container even
// after the init process exits. This is especially useful for
// container cleanup.
if err := c.requireStatus("signal", Running, Stopped); err != nil {
return err
}
if !c.IsSandboxRunning() {
return fmt.Errorf("sandbox is not running")
}
return c.Sandbox.SignalContainer(c.ID, sig, all)
}
// SignalProcess sends sig to a specific process in the container.
func (c *Container) SignalProcess(sig unix.Signal, pid int32) error {
log.Debugf("Signal process %d in container, cid: %s, signal: %v (%d)", pid, c.ID, sig, sig)
if err := c.requireStatus("signal a process inside", Running); err != nil {
return err
}
if !c.IsSandboxRunning() {
return fmt.Errorf("sandbox is not running")
}
return c.Sandbox.SignalProcess(c.ID, int32(pid), sig, false)
}
// SignalProcessGroup sends sig to all processes in the given process group
// inside the container.
func (c *Container) SignalProcessGroup(sig unix.Signal, pgid int32) error {
log.Debugf("Signal process group %d in container, cid: %s, signal: %v (%d)", pgid, c.ID, sig, sig)
if err := c.requireStatus("signal a process group inside", Running); err != nil {
return err
}
if !c.IsSandboxRunning() {
return fmt.Errorf("sandbox is not running")
}
return c.Sandbox.SignalProcessGroup(c.ID, pgid, sig)
}
// ForwardSignals forwards all signals received by the current process to the
// container process inside the sandbox. It returns a function that will stop
// forwarding signals.
func (c *Container) ForwardSignals(pid int32, fgProcess bool) func() {
log.Debugf("Forwarding all signals to container, cid: %s, PIDPID: %d, fgProcess: %t", c.ID, pid, fgProcess)
stop := sighandling.StartSignalForwarding(func(sig linux.Signal) {
log.Debugf("Forwarding signal %d to container, cid: %s, PID: %d, fgProcess: %t", sig, c.ID, pid, fgProcess)
if err := c.Sandbox.SignalProcess(c.ID, pid, unix.Signal(sig), fgProcess); err != nil {
log.Warningf("error forwarding signal %d to container %q: %v", sig, c.ID, err)
}
})
return func() {
log.Debugf("Done forwarding signals to container, cid: %s, PID: %d, fgProcess: %t", c.ID, pid, fgProcess)
stop()
}
}
// Checkpoint sends the checkpoint call to the container.
// The statefile will be written to f, the file at the specified image-path.
func (c *Container) Checkpoint(conf *config.Config, imagePath string, opts sandbox.CheckpointOpts) error {
log.Debugf("Checkpoint container, cid: %s", c.ID)
if err := c.requireStatus("checkpoint", Created, Running, Paused); err != nil {
return err
}
return c.Sandbox.Checkpoint(conf, c.ID, imagePath, opts)
}
// FSSave sends the filesystem checkpointing call to the container.
func (c *Container) FSSave(conf *config.Config, imagePath string, opts sandbox.FSSaveOpts) error {
log.Debugf("Checkpoint container filesystem, cid: %s", c.ID)
if err := c.requireStatus("filesystem checkpoint", Created, Running, Paused); err != nil {
return err
}
return c.Sandbox.FSSave(conf, c.ID, imagePath, opts)
}
// Pause suspends the container and its kernel.
// The call only succeeds if the container's status is created or running.
func (c *Container) Pause() error {
log.Debugf("Pausing container, cid: %s", c.ID)
if err := c.Saver.lock(BlockAcquire); err != nil {
return err
}
defer c.Saver.UnlockOrDie()
if c.Status != Created && c.Status != Running {
return fmt.Errorf("cannot pause container %q in state %v", c.ID, c.Status)
}
if err := c.Sandbox.Pause(c.ID); err != nil {
return fmt.Errorf("pausing container %q: %v", c.ID, err)
}
c.changeStatus(Paused)
return c.saveLocked()
}
// Resume unpauses the container and its kernel.
// The call only succeeds if the container's status is paused.
func (c *Container) Resume() error {
log.Debugf("Resuming container, cid: %s", c.ID)
if err := c.Saver.lock(BlockAcquire); err != nil {
return err
}
defer c.Saver.UnlockOrDie()
if c.Status != Paused {
return fmt.Errorf("cannot resume container %q in state %v", c.ID, c.Status)
}
if err := c.Sandbox.Resume(c.ID); err != nil {
return fmt.Errorf("resuming container: %v", err)
}
c.changeStatus(Running)
return c.saveLocked()
}
// State returns the metadata of the container.
func (c *Container) State() specs.State {
return specs.State{
Version: specs.Version,
ID: c.ID,
Status: c.Status,
Pid: c.SandboxPid(),
Bundle: c.BundleDir,
Annotations: c.Spec.Annotations,
}
}
// Processes retrieves the list of processes and associated metadata inside a
// container.
func (c *Container) Processes() ([]*control.Process, error) {
if err := c.requireStatus("get processes of", Running, Paused); err != nil {
return nil, err
}
return c.Sandbox.Processes(c.ID)
}
// Destroy stops all processes and frees all resources associated with the
// container.
func (c *Container) Destroy() error {
log.Debugf("Destroy container, cid: %s", c.ID)
if err := c.Saver.lock(BlockAcquire); err != nil {
return err
}
defer func() {
c.Saver.UnlockOrDie()
_ = c.Saver.close()
}()
// Stored for later use as stop() sets c.Sandbox to nil.
sb := c.Sandbox
// We must perform the following cleanup steps:
// * stop the container and gofer processes,
// * remove the container filesystem on the host, and
// * delete the container metadata directory.
//
// It's possible for one or more of these steps to fail, but we should
// do our best to perform all of the cleanups. Hence, we keep a slice
// of errors return their concatenation.
var errs []string
if err := c.stop(); err != nil {
err = fmt.Errorf("stopping container: %v", err)
log.Warningf("%v", err)
errs = append(errs, err.Error())
}
if err := c.Saver.Destroy(); err != nil {
err = fmt.Errorf("deleting container state files: %v", err)
log.Warningf("%v", err)
errs = append(errs, err.Error())
}
// Clean up self-backed filestore files created in their respective mounts.
c.forEachSelfMount(func(mountSrc string) {
if sb != nil {
if hint := sb.MountHints.FindMount(mountSrc); hint != nil && hint.ShouldShareMount() {
// Don't delete filestore file for shared mounts. The sandbox owns a
// shared master mount which uses this filestore and is shared with
// multiple mount points.
return
}
}
filestorePath := boot.SelfFilestorePath(mountSrc, c.sandboxID())
if err := os.Remove(filestorePath); err != nil {
err = fmt.Errorf("failed to delete filestore file %q: %v", filestorePath, err)
log.Warningf("%v", err)
errs = append(errs, err.Error())
}
})
if sb != nil && sb.IsRootContainer(c.ID) {
// When the root container is being destroyed, we can clean up filestores
// used by shared mounts.
for _, hint := range sb.MountHints.Mounts {
if !hint.ShouldShareMount() {
continue
}
// Assume this is a self-backed shared mount and try to delete the
// filestore. Subsequently ignore the ENOENT if the assumption is wrong.
filestorePath := boot.SelfFilestorePath(hint.Mount.Source, c.sandboxID())
if err := os.Remove(filestorePath); err != nil && !os.IsNotExist(err) {
err = fmt.Errorf("failed to delete shared filestore file %q: %v", filestorePath, err)
log.Warningf("%v", err)
errs = append(errs, err.Error())
}
}
}
c.changeStatus(Stopped)
// Adjust oom_score_adj for the sandbox. This must be done after the container
// is stopped and the directory at c.Root is removed.
//
// Use 'sb' to tell whether it has been executed before because Destroy must
// be idempotent.
if sb != nil {
if err := adjustSandboxOOMScoreAdj(sb, c.Spec, c.Saver.RootDir, true); err != nil {
errs = append(errs, err.Error())
}
}
// "If any poststop hook fails, the runtime MUST log a warning, but the
// remaining hooks and lifecycle continue as if the hook had
// succeeded" - OCI spec.
//
// Based on the OCI, "The post-stop hooks MUST be called after the container
// is deleted but before the delete operation returns"
// Run it here to:
// 1) Conform to the OCI.
// 2) Make sure it only runs once, because the root has been deleted, the