-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathloader.go
2047 lines (1809 loc) · 65.7 KB
/
loader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 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 boot loads the kernel and runs a container.
package boot
import (
"encoding/json"
"errors"
"fmt"
"os"
"runtime"
"strconv"
gtime "time"
"github.com./moby/sys/capability"
specs "github.com./opencontainers/runtime-spec/specs-go"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/bpf"
"gvisor.dev/gvisor/pkg/cleanup"
"gvisor.dev/gvisor/pkg/context"
"gvisor.dev/gvisor/pkg/coverage"
"gvisor.dev/gvisor/pkg/cpuid"
"gvisor.dev/gvisor/pkg/fd"
"gvisor.dev/gvisor/pkg/gomaxprocs"
"gvisor.dev/gvisor/pkg/log"
"gvisor.dev/gvisor/pkg/memutil"
"gvisor.dev/gvisor/pkg/metric"
"gvisor.dev/gvisor/pkg/rand"
"gvisor.dev/gvisor/pkg/refs"
"gvisor.dev/gvisor/pkg/sentry/control"
"gvisor.dev/gvisor/pkg/sentry/devices/nvproxy"
"gvisor.dev/gvisor/pkg/sentry/devices/nvproxy/nvconf"
"gvisor.dev/gvisor/pkg/sentry/fdimport"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/host"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/user"
"gvisor.dev/gvisor/pkg/sentry/inet"
"gvisor.dev/gvisor/pkg/sentry/kernel"
"gvisor.dev/gvisor/pkg/sentry/kernel/auth"
"gvisor.dev/gvisor/pkg/sentry/loader"
"gvisor.dev/gvisor/pkg/sentry/pgalloc"
"gvisor.dev/gvisor/pkg/sentry/platform"
_ "gvisor.dev/gvisor/pkg/sentry/platform/platforms" // register all platforms.
"gvisor.dev/gvisor/pkg/sentry/seccheck"
pb "gvisor.dev/gvisor/pkg/sentry/seccheck/points/points_go_proto"
"gvisor.dev/gvisor/pkg/sentry/socket/netfilter"
"gvisor.dev/gvisor/pkg/sentry/socket/plugin"
"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport"
"gvisor.dev/gvisor/pkg/sentry/time"
"gvisor.dev/gvisor/pkg/sentry/usage"
"gvisor.dev/gvisor/pkg/sentry/vfs"
"gvisor.dev/gvisor/pkg/sentry/watchdog"
"gvisor.dev/gvisor/pkg/sighandling"
"gvisor.dev/gvisor/pkg/sync"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/link/ethernet"
"gvisor.dev/gvisor/pkg/tcpip/link/loopback"
"gvisor.dev/gvisor/pkg/tcpip/link/sniffer"
"gvisor.dev/gvisor/pkg/tcpip/network/arp"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
"gvisor.dev/gvisor/pkg/tcpip/transport/raw"
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
"gvisor.dev/gvisor/runsc/boot/filter"
pf "gvisor.dev/gvisor/runsc/boot/portforward"
"gvisor.dev/gvisor/runsc/boot/pprof"
"gvisor.dev/gvisor/runsc/config"
"gvisor.dev/gvisor/runsc/profile"
"gvisor.dev/gvisor/runsc/specutils"
"gvisor.dev/gvisor/runsc/specutils/seccomp"
// Top-level inet providers.
"gvisor.dev/gvisor/pkg/sentry/socket/hostinet"
"gvisor.dev/gvisor/pkg/sentry/socket/netstack"
// Include other supported socket providers.
_ "gvisor.dev/gvisor/pkg/sentry/socket/netlink"
_ "gvisor.dev/gvisor/pkg/sentry/socket/netlink/route"
_ "gvisor.dev/gvisor/pkg/sentry/socket/netlink/uevent"
_ "gvisor.dev/gvisor/pkg/sentry/socket/unix"
)
// ContainerRuntimeState is the runtime state of a container.
type ContainerRuntimeState int
const (
// RuntimeStateInvalid used just in case of error.
RuntimeStateInvalid ContainerRuntimeState = iota
// RuntimeStateCreating indicates that the container is being
// created, but has not started running yet.
RuntimeStateCreating
// RuntimeStateRunning indicates that the container is running.
RuntimeStateRunning
// RuntimeStateStopped indicates that the container has stopped.
RuntimeStateStopped
)
type containerInfo struct {
cid string
containerName string
conf *config.Config
// spec is the base configuration for the root container.
spec *specs.Spec
// procArgs refers to the container's init task.
procArgs kernel.CreateProcessArgs
// stdioFDs contains stdin, stdout, and stderr.
stdioFDs []*fd.FD
// passFDs are mappings of user-supplied host to guest file descriptors.
passFDs []fdMapping
// execFD is the host file descriptor used for program execution.
execFD *fd.FD
// goferFDs are the FDs that attach the sandbox to the gofers.
goferFDs []*fd.FD
// devGoferFD is the FD to attach the sandbox to the dev gofer.
devGoferFD *fd.FD
// goferFilestoreFDs are FDs to the regular files that will back the tmpfs or
// overlayfs mount for certain gofer mounts.
goferFilestoreFDs []*fd.FD
// goferMountConfs contains information about how the gofer mounts have been
// configured. The first entry is for rootfs and the following entries are
// for bind mounts in Spec.Mounts (in the same order).
goferMountConfs []GoferMountConf
// nvidiaUVMDevMajor is the device major number used for nvidia-uvm.
nvidiaUVMDevMajor uint32
// nvidiaDriverVersion is the NVIDIA driver ABI version to use for
// communicating with NVIDIA devices on the host.
nvidiaDriverVersion nvconf.DriverVersion
}
type loaderState int
const (
// created indicates that the Loader has been created, but not started yet.
created loaderState = iota
// started indicates that the Loader has been started.
started
// restoring indicates that the Loader has been created and is restoring
// containers. It will change to started after restore is completed.
restoring
)
// Loader keeps state needed to start the kernel and run the container.
type Loader struct {
// k is the kernel.
k *kernel.Kernel
// ctrl is the control server.
ctrl *controller
// root contains information about the root container in the sandbox.
root containerInfo
watchdog *watchdog.Watchdog
// stopSignalForwarding disables forwarding of signals to the sandboxed
// container. It should be called when a sandbox is destroyed.
stopSignalForwarding func()
// stopProfiling stops profiling started at container creation. It
// should be called when a sandbox is destroyed.
stopProfiling func()
// PreSeccompCallback is called right before installing seccomp filters.
PreSeccompCallback func()
// restore is set to true if we are restoring a container.
restore bool
restoreWaiters *sync.Cond
// sandboxID is the ID for the whole sandbox.
sandboxID string
// mountHints provides extra information about mounts for containers that
// apply to the entire pod.
mountHints *PodMountHints
// productName is the value to show in
// /sys/devices/virtual/dmi/id/product_name.
productName string
hostTHP HostTHP
// mu guards the fields below.
mu sync.Mutex
// +checklocks:mu
state loaderState
// sharedMounts holds VFS mounts that may be shared between containers within
// the same pod. It is mapped by mount source.
//
// +checklocks:mu
sharedMounts map[string]*vfs.Mount
// processes maps containers init process and invocation of exec. Root
// processes are keyed with container ID and pid=0, while exec invocations
// have the corresponding pid set.
//
// +checklocks:mu
processes map[execID]*execProcess
// containerIDs store container names and IDs to assist with restore and container
// naming when user didn't provide one.
//
// Mapping: name -> cid.
// +checklocks:mu
containerIDs map[string]string
// containerSpecs stores container specs for each container in sandbox.
//
// Mapping: name -> spec.
// +checklocks:mu
containerSpecs map[string]*specs.Spec
// portForwardProxies is a list of active port forwarding connections.
//
// +checklocks:mu
portForwardProxies []*pf.Proxy
// +checklocks:mu
saveFDs []*fd.FD
// saveRestoreNet indicates if the saved network stack should be used
// during restore.
saveRestoreNet bool
}
// execID uniquely identifies a sentry process that is executed in a container.
type execID struct {
cid string
pid kernel.ThreadID
}
// execProcess contains the thread group and host TTY of a sentry process.
type execProcess struct {
// tg will be nil for containers that haven't started yet.
tg *kernel.ThreadGroup
// tty will be nil if the process is not attached to a terminal.
tty *host.TTYFileDescription
// pidnsPath is the pid namespace path in spec
pidnsPath string
// hostTTY is present when creating a sub-container with terminal enabled.
// TTY file is passed during container create and must be saved until
// container start.
hostTTY *fd.FD
}
// fdMapping maps guest to host file descriptors. Guest file descriptors are
// exposed to the application inside the sandbox through the FD table.
type fdMapping struct {
guest int
host *fd.FD
}
// FDMapping is a helper type to represent a mapping from guest to host file
// descriptors. In contrast to the unexported fdMapping type, it does not imply
// file ownership.
type FDMapping struct {
Guest int
Host int
}
// Args are the arguments for New().
type Args struct {
// Id is the sandbox ID.
ID string
// Spec is the sandbox specification.
Spec *specs.Spec
// Conf is the system configuration.
Conf *config.Config
// ControllerFD is the FD to the URPC controller. The Loader takes ownership
// of this FD and may close it at any time.
ControllerFD int
// Device is an optional argument that is passed to the platform. The Loader
// takes ownership of this file and may close it at any time.
Device *fd.FD
// GoferFDs is an array of FDs used to connect with the Gofer. The Loader
// takes ownership of these FDs and may close them at any time.
GoferFDs []int
// DevGoferFD is the FD for the dev gofer connection. The Loader takes
// ownership of this FD and may close it at any time.
DevGoferFD int
// StdioFDs is the stdio for the application. The Loader takes ownership of
// these FDs and may close them at any time.
StdioFDs []int
// PassFDs are user-supplied FD mappings from host to guest descriptors.
// The Loader takes ownership of these FDs and may close them at any time.
PassFDs []FDMapping
// ExecFD is the host file descriptor used for program execution.
ExecFD int
// GoferFilestoreFDs are FDs to the regular files that will back the tmpfs or
// overlayfs mount for certain gofer mounts.
GoferFilestoreFDs []int
// GoferMountConfs contains information about how the gofer mounts have been
// configured. The first entry is for rootfs and the following entries are
// for bind mounts in Spec.Mounts (in the same order).
GoferMountConfs []GoferMountConf
// NumCPU is the number of CPUs to create inside the sandbox.
NumCPU int
// TotalMem is the initial amount of total memory to report back to the
// container.
TotalMem uint64
// TotalHostMem is the total memory reported by host /proc/meminfo.
TotalHostMem uint64
// UserLogFD is the file descriptor to write user logs to.
UserLogFD int
// ProductName is the value to show in
// /sys/devices/virtual/dmi/id/product_name.
ProductName string
// PodInitConfigFD is the file descriptor to a file passed in the
// --pod-init-config flag
PodInitConfigFD int
// SinkFDs is an ordered array of file descriptors to be used by seccheck
// sinks configured from the --pod-init-config file.
SinkFDs []int
// ProfileOpts contains the set of profiles to enable and the
// corresponding FDs where profile data will be written.
ProfileOpts profile.Opts
// NvidiaDriverVersion is the NVIDIA driver ABI version to use for
// communicating with NVIDIA devices on the host.
NvidiaDriverVersion nvconf.DriverVersion
// HostTHP contains host transparent hugepage settings.
HostTHP HostTHP
SaveFDs []*fd.FD
}
// HostTHP holds host transparent hugepage settings.
type HostTHP struct {
// ShmemEnabled is the selected option in
// /sys/kernel/mm/transparent_hugepage/shmem_enabled.
ShmemEnabled string
// Defrag is the selected option in
// /sys/kernel/mm/transparent_hugepage/defrag.
Defrag string
}
const (
// startingStdioFD is the starting stdioFD number used during sandbox
// start and restore. This makes sure the stdioFDs are always the same
// on initial start and on restore.
startingStdioFD = 256
// containerSpecsKey is the key used to add and pop the container specs to the
// kernel during save/restore.
containerSpecsKey = "container_specs"
)
func getRootCredentials(spec *specs.Spec, conf *config.Config, userNs *auth.UserNamespace) *auth.Credentials {
// Create capabilities.
caps, err := specutils.Capabilities(conf.EnableRaw, spec.Process.Capabilities)
if err != nil {
return nil
}
// Convert the spec's additional GIDs to KGIDs.
extraKGIDs := make([]auth.KGID, 0, len(spec.Process.User.AdditionalGids))
for _, GID := range spec.Process.User.AdditionalGids {
extraKGIDs = append(extraKGIDs, auth.KGID(GID))
}
if userNs == nil {
userNs = auth.NewRootUserNamespace()
}
// Create credentials.
creds := auth.NewUserCredentials(
auth.KUID(spec.Process.User.UID),
auth.KGID(spec.Process.User.GID),
extraKGIDs,
caps,
userNs)
return creds
}
// New initializes a new kernel loader configured by spec.
// New also handles setting up a kernel for restoring a container.
func New(args Args) (*Loader, error) {
stopProfilingRuntime := profile.Start(args.ProfileOpts)
stopProfiling := func() {
stopProfilingRuntime()
metric.StopProfilingMetrics()
}
// Initialize seccheck points.
seccheck.Initialize()
// We initialize the rand package now to make sure /dev/urandom is pre-opened
// on kernels that do not support getrandom(2).
if err := rand.Init(); err != nil {
return nil, fmt.Errorf("setting up rand: %w", err)
}
if err := usage.Init(); err != nil {
return nil, fmt.Errorf("setting up memory usage: %w", err)
}
if specutils.NVProxyEnabled(args.Spec, args.Conf) {
nvproxy.Init()
}
kernel.IOUringEnabled = args.Conf.IOUring
eid := execID{cid: args.ID}
l := &Loader{
sandboxID: args.ID,
processes: map[execID]*execProcess{eid: {}},
sharedMounts: make(map[string]*vfs.Mount),
stopProfiling: stopProfiling,
productName: args.ProductName,
hostTHP: args.HostTHP,
containerIDs: make(map[string]string),
containerSpecs: make(map[string]*specs.Spec),
saveFDs: args.SaveFDs,
}
containerName := l.registerContainer(args.Spec, args.ID)
l.root = containerInfo{
cid: args.ID,
containerName: containerName,
conf: args.Conf,
spec: args.Spec,
goferMountConfs: args.GoferMountConfs,
nvidiaDriverVersion: args.NvidiaDriverVersion,
}
// Make host FDs stable between invocations. Host FDs must map to the exact
// same number when the sandbox is restored. Otherwise the wrong FD will be
// used.
newfd := startingStdioFD
for _, stdioFD := range args.StdioFDs {
// Check that newfd is unused to avoid clobbering over it.
if _, err := unix.FcntlInt(uintptr(newfd), unix.F_GETFD, 0); !errors.Is(err, unix.EBADF) {
if err != nil {
return nil, fmt.Errorf("error checking for FD (%d) conflict: %w", newfd, err)
}
return nil, fmt.Errorf("unable to remap stdios, FD %d is already in use", newfd)
}
err := unix.Dup3(stdioFD, newfd, unix.O_CLOEXEC)
if err != nil {
return nil, fmt.Errorf("dup3 of stdios failed: %w", err)
}
l.root.stdioFDs = append(l.root.stdioFDs, fd.New(newfd))
_ = unix.Close(stdioFD)
newfd++
}
for _, goferFD := range args.GoferFDs {
l.root.goferFDs = append(l.root.goferFDs, fd.New(goferFD))
}
for _, filestoreFD := range args.GoferFilestoreFDs {
l.root.goferFilestoreFDs = append(l.root.goferFilestoreFDs, fd.New(filestoreFD))
}
if args.DevGoferFD >= 0 {
l.root.devGoferFD = fd.New(args.DevGoferFD)
}
if args.ExecFD >= 0 {
l.root.execFD = fd.New(args.ExecFD)
}
for _, customFD := range args.PassFDs {
l.root.passFDs = append(l.root.passFDs, fdMapping{
host: fd.New(customFD.Host),
guest: customFD.Guest,
})
}
// Create kernel and platform.
p, err := createPlatform(args.Conf, args.Device)
if err != nil {
return nil, fmt.Errorf("creating platform: %w", err)
}
if args.Conf.Platform == "kvm" && specutils.NVProxyEnabled(args.Spec, args.Conf) {
if caps, err := specutils.NVProxyDriverCapsAllowed(args.Conf); err == nil && caps&nvconf.CapCompute != 0 {
log.Warningf("Application cudaMallocManaged() is flaky on -platform=kvm, see gvisor.dev/docs/user_guide/gpu/#platforms")
}
}
l.k = &kernel.Kernel{Platform: p}
// Create memory file.
mf, err := createMemoryFile(args.Conf.AppHugePages, args.HostTHP)
if err != nil {
return nil, fmt.Errorf("creating memory file: %w", err)
}
l.k.SetMemoryFile(mf)
// Create VDSO.
//
// Pass k as the platform since it is savable, unlike the actual platform.
vdso, err := loader.PrepareVDSO(l.k.MemoryFile())
if err != nil {
return nil, fmt.Errorf("creating vdso: %w", err)
}
// Create timekeeper.
tk := kernel.NewTimekeeper()
params := kernel.NewVDSOParamPage(l.k.MemoryFile(), vdso.ParamPage.FileRange())
tk.SetClocks(time.NewCalibratedClocks(), params)
if err := enableStrace(args.Conf); err != nil {
return nil, fmt.Errorf("enabling strace: %w", err)
}
creds := getRootCredentials(args.Spec, args.Conf, nil /* UserNamespace */)
if creds == nil {
return nil, fmt.Errorf("getting root credentials")
}
// Create root network namespace/stack.
netns, err := newRootNetworkNamespace(args.Conf, tk, creds.UserNamespace)
if err != nil {
return nil, fmt.Errorf("creating network: %w", err)
}
// S/R is not supported for hostinet.
if l.root.conf.Network != config.NetworkHost && args.Conf.TestOnlySaveRestoreNetstack {
l.saveRestoreNet = true
if err := netns.Stack().EnableSaveRestore(); err != nil {
return nil, fmt.Errorf("enable s/r: %w", err)
}
}
if args.NumCPU == 0 {
args.NumCPU = runtime.NumCPU()
}
log.Infof("CPUs: %d", args.NumCPU)
gomaxprocs.SetBase(args.NumCPU)
if args.TotalHostMem > 0 {
// As per tmpfs(5), the default size limit is 50% of total physical RAM.
// See mm/shmem.c:shmem_default_max_blocks().
tmpfs.SetDefaultSizeLimit(args.TotalHostMem / 2)
}
if args.TotalMem > 0 {
// Adjust the total memory returned by the Sentry so that applications that
// use /proc/meminfo can make allocations based on this limit.
usage.MinimumTotalMemoryBytes = args.TotalMem
usage.MaximumTotalMemoryBytes = args.TotalMem
log.Infof("Setting total memory to %.2f GB", float64(args.TotalMem)/(1<<30))
}
maxFDLimit := kernel.MaxFdLimit
if args.Spec.Linux != nil && args.Spec.Linux.Sysctl != nil {
if val, ok := args.Spec.Linux.Sysctl["fs.nr_open"]; ok {
nrOpen, err := strconv.Atoi(val)
if err != nil {
return nil, fmt.Errorf("setting fs.nr_open=%s: %w", val, err)
}
if nrOpen <= 0 || nrOpen > int(kernel.MaxFdLimit) {
return nil, fmt.Errorf("setting fs.nr_open=%s", val)
}
maxFDLimit = int32(nrOpen)
}
}
// Initiate the Kernel object, which is required by the Context passed
// to createVFS in order to mount (among other things) procfs.
unixSocketOpts := transport.UnixSocketOpts{
DisconnectOnSave: args.Conf.NetDisconnectOk,
}
if err = l.k.Init(kernel.InitKernelArgs{
FeatureSet: cpuid.HostFeatureSet().Fixed(),
Timekeeper: tk,
RootUserNamespace: creds.UserNamespace,
RootNetworkNamespace: netns,
ApplicationCores: uint(args.NumCPU),
Vdso: vdso,
VdsoParams: params,
RootUTSNamespace: kernel.NewUTSNamespace(args.Spec.Hostname, args.Spec.Hostname, creds.UserNamespace),
RootIPCNamespace: kernel.NewIPCNamespace(creds.UserNamespace),
PIDNamespace: kernel.NewRootPIDNamespace(creds.UserNamespace),
MaxFDLimit: maxFDLimit,
UnixSocketOpts: unixSocketOpts,
}); err != nil {
return nil, fmt.Errorf("initializing kernel: %w", err)
}
if err := registerFilesystems(l.k, &l.root); err != nil {
return nil, fmt.Errorf("registering filesystems: %w", err)
}
// Turn on packet logging if enabled.
if args.Conf.LogPackets {
log.Infof("Packet logging enabled")
sniffer.LogPackets.Store(1)
} else {
log.Infof("Packet logging disabled")
sniffer.LogPackets.Store(0)
}
// Create a watchdog.
dogOpts := watchdog.DefaultOpts
dogOpts.TaskTimeoutAction = args.Conf.WatchdogAction
l.watchdog = watchdog.New(l.k, dogOpts)
procArgs, err := createProcessArgs(args.ID, args.Spec, args.Conf, creds, l.k, l.k.RootPIDNamespace())
if err != nil {
return nil, fmt.Errorf("creating init process for root container: %w", err)
}
l.root.procArgs = procArgs
if err := initCompatLogs(args.UserLogFD); err != nil {
return nil, fmt.Errorf("initializing compat logs: %w", err)
}
l.mountHints, err = NewPodMountHints(args.Spec)
if err != nil {
return nil, fmt.Errorf("creating pod mount hints: %w", err)
}
// Set up host mount that will be used for imported fds.
hostFilesystem, err := host.NewFilesystem(l.k.VFS())
if err != nil {
return nil, fmt.Errorf("failed to create hostfs filesystem: %w", err)
}
defer hostFilesystem.DecRef(l.k.SupervisorContext())
l.k.SetHostMount(l.k.VFS().NewDisconnectedMount(hostFilesystem, nil, &vfs.MountOptions{}))
if args.PodInitConfigFD >= 0 {
if err := setupSeccheck(args.PodInitConfigFD, args.SinkFDs); err != nil {
log.Warningf("unable to configure event session: %v", err)
}
}
l.k.RegisterContainerName(args.ID, l.root.containerName)
// We don't care about child signals; some platforms can generate a
// tremendous number of useless ones (I'm looking at you, ptrace).
if err := sighandling.IgnoreChildStop(); err != nil {
return nil, fmt.Errorf("ignore child stop signals failed: %w", err)
}
if len(args.Conf.TestOnlyAutosaveImagePath) != 0 {
enableAutosave(l, args.Conf.TestOnlyAutosaveResume, l.saveFDs)
}
l.kernelInitExtra()
// Create the control server using the provided FD.
//
// This must be done *after* we have initialized the kernel since the
// controller is used to configure the kernel's network stack.
ctrl, err := newController(args.ControllerFD, l)
if err != nil {
return nil, fmt.Errorf("creating control server: %w", err)
}
l.ctrl = ctrl
// Only start serving after Loader is set to controller and controller is set
// to Loader, because they are both used in the urpc methods.
if err := ctrl.srv.StartServing(); err != nil {
return nil, fmt.Errorf("starting control server: %w", err)
}
return l, nil
}
// createProcessArgs creates args that can be used with kernel.CreateProcess.
func createProcessArgs(id string, spec *specs.Spec, conf *config.Config, creds *auth.Credentials, k *kernel.Kernel, pidns *kernel.PIDNamespace) (kernel.CreateProcessArgs, error) {
// Create initial limits.
ls, err := createLimitSet(spec, specutils.TPUProxyIsEnabled(spec, conf))
if err != nil {
return kernel.CreateProcessArgs{}, fmt.Errorf("creating limits: %w", err)
}
env, err := specutils.ResolveEnvs(spec.Process.Env)
if err != nil {
return kernel.CreateProcessArgs{}, fmt.Errorf("resolving env: %w", err)
}
wd := spec.Process.Cwd
if wd == "" {
wd = "/"
}
umask := uint(0022)
if spec.Process.User.Umask != nil {
umask = uint(*spec.Process.User.Umask) & 0777
}
// Create the process arguments.
procArgs := kernel.CreateProcessArgs{
Argv: spec.Process.Args,
Envv: env,
WorkingDirectory: wd,
Credentials: creds,
Umask: umask,
Limits: ls,
MaxSymlinkTraversals: linux.MaxSymlinkTraversals,
UTSNamespace: k.RootUTSNamespace(),
IPCNamespace: k.RootIPCNamespace(),
ContainerID: id,
PIDNamespace: pidns,
}
return procArgs, nil
}
// Destroy cleans up all resources used by the loader.
//
// Note that this will block until all open control server connections have
// been closed. For that reason, this should NOT be called in a defer, because
// a panic in a control server rpc would then hang forever.
func (l *Loader) Destroy() {
if l.stopSignalForwarding != nil {
l.stopSignalForwarding()
}
l.watchdog.Stop()
ctx := l.k.SupervisorContext()
l.mu.Lock()
for _, m := range l.sharedMounts {
m.DecRef(ctx)
}
l.mu.Unlock()
// Stop the control server. This will indirectly stop any
// long-running control operations that are in flight, e.g.
// profiling operations.
l.ctrl.stop()
// Release all kernel resources. This is only safe after we can no longer
// save/restore.
l.k.Release()
// Release any dangling tcp connections.
tcpip.ReleaseDanglingEndpoints()
// In the success case, all FDs in l.root will only contain released/closed
// FDs whose ownership has been passed over to host FDs and gofer sessions.
// Close them here in case of failure.
for _, f := range l.root.stdioFDs {
_ = f.Close()
}
for _, f := range l.root.passFDs {
_ = f.host.Close()
}
for _, f := range l.root.goferFDs {
_ = f.Close()
}
for _, f := range l.root.goferFilestoreFDs {
_ = f.Close()
}
if l.root.devGoferFD != nil {
_ = l.root.devGoferFD.Close()
}
l.stopProfiling()
// Check all references.
refs.OnExit()
}
func createPlatform(conf *config.Config, deviceFile *fd.FD) (platform.Platform, error) {
p, err := platform.Lookup(conf.Platform)
if err != nil {
panic(fmt.Sprintf("invalid platform %s: %s", conf.Platform, err))
}
log.Infof("Platform: %s", conf.Platform)
return p.New(deviceFile)
}
func createMemoryFile(appHugePages bool, hostTHP HostTHP) (*pgalloc.MemoryFile, error) {
const memfileName = "runsc-memory"
memfd, err := memutil.CreateMemFD(memfileName, 0)
if err != nil {
return nil, fmt.Errorf("error creating memfd: %w", err)
}
memfile := os.NewFile(uintptr(memfd), memfileName)
mfopts := pgalloc.MemoryFileOpts{
// We can't enable pgalloc.MemoryFileOpts.UseHostMemcgPressure even if
// there are memory cgroups specified, because at this point we're already
// in a mount namespace in which the relevant cgroupfs is not visible.
}
if appHugePages {
switch hostTHP.ShmemEnabled {
case "":
log.Infof("Disabling application huge pages: host shmem_enabled is unknown")
case "never", "deny":
log.Infof("Disabling application huge pages: host shmem_enabled is %q", hostTHP.ShmemEnabled)
case "advise":
switch hostTHP.Defrag {
case "":
log.Infof("Disabling application huge pages: host shmem_enabled is %q, host defrag is unknown", hostTHP.ShmemEnabled)
case "always", "defer", "never":
// Allocations on MADV_HUGEPAGE pages will invoke direct
// compaction ("always"), wake kcompactd ("defer"), or do
// neither ("never"), consistent with host private anonymous
// memory mappings, so using MADV_HUGEPAGE shouldn't cause a
// regression vs. running natively.
log.Infof("Enabling application huge pages: host shmem_enabled is %q, host defrag is %q", hostTHP.ShmemEnabled, hostTHP.Defrag)
mfopts.ExpectHugepages = true
mfopts.AdviseHugepage = true
case "defer+madvise", "madvise":
// Allocations on MADV_HUGEPAGE pages may invoke direct
// compaction whereas allocations on host private anonymous
// memory mappings will not, so using MADV_HUGEPAGE may degrade
// performance.
log.Infof("Disabling application huge pages: host shmem_enabled is %q, host defrag is %q", hostTHP.ShmemEnabled, hostTHP.Defrag)
default:
log.Warningf("Disabling application huge pages: host shmem_enabled is %q, host defrag is unknown value %q", hostTHP.ShmemEnabled, hostTHP.Defrag)
}
case "always", "within_size":
log.Infof("Enabling application huge pages: host shmem_enabled is %q", hostTHP.ShmemEnabled)
// In these cases, memfds will default to using huge pages, and we have to
// explicitly ask for small pages.
mfopts.ExpectHugepages = true
mfopts.AdviseNoHugepage = true
case "force":
log.Infof("Enabling application huge pages: host shmem_enabled is %q", hostTHP.ShmemEnabled)
// The kernel will ignore MADV_NOHUGEPAGE, so don't bother.
mfopts.ExpectHugepages = true
default:
log.Warningf("Disabling application huge pages: host shmem_enabled is unknown value %q", hostTHP.ShmemEnabled)
}
}
mf, err := pgalloc.NewMemoryFile(memfile, mfopts)
if err != nil {
_ = memfile.Close()
return nil, fmt.Errorf("error creating pgalloc.MemoryFile: %w", err)
}
return mf, nil
}
// installSeccompFilters installs sandbox seccomp filters with the host.
func (l *Loader) installSeccompFilters() error {
if l.PreSeccompCallback != nil {
l.PreSeccompCallback()
}
if l.root.conf.DisableSeccomp {
log.Warningf("*** SECCOMP WARNING: syscall filter is DISABLED. Running in less secure mode.")
} else {
hostnet := l.root.conf.Network == config.NetworkHost
var nvproxyCaps nvconf.DriverCaps
nvproxyEnabled := specutils.NVProxyEnabled(l.root.spec, l.root.conf)
if nvproxyEnabled {
var err error
// We use the set of allowed capabilities here, not the subset of them
// that the root container requests. This is because we need to support
// subsequent containers being able to execute with a wider set than the
// set that the root container requests. Seccomp filters are only
// applied once at sandbox startup, so they need to be as wide as the
// set of capabilities that may ever be requested.
if nvproxyCaps, err = specutils.NVProxyDriverCapsAllowed(l.root.conf); err != nil {
return fmt.Errorf("NVIDIA capabilities: %w", err)
}
}
opts := filter.Options{
Platform: l.k.Platform.SeccompInfo(),
HostNetwork: hostnet,
HostNetworkRawSockets: hostnet && l.root.conf.EnableRaw,
HostFilesystem: l.root.conf.DirectFS,
ProfileEnable: l.root.conf.ProfileEnable,
NVProxy: nvproxyEnabled,
NVProxyCaps: nvproxyCaps,
TPUProxy: specutils.TPUProxyIsEnabled(l.root.spec, l.root.conf),
ControllerFD: uint32(l.ctrl.srv.FD()),
CgoEnabled: config.CgoEnabled,
PluginNetwork: l.root.conf.Network == config.NetworkPlugin,
}
if err := filter.Install(opts); err != nil {
return fmt.Errorf("installing seccomp filters: %w", err)
}
}
return nil
}
// Run runs the root container.
func (l *Loader) Run() error {
err := l.run()
l.ctrl.manager.startResultChan <- err
if err != nil {
// Give the controller some time to send the error to the
// runtime. If we return too quickly here the process will exit
// and the control connection will be closed before the error
// is returned.
gtime.Sleep(2 * gtime.Second)
return err
}
return nil
}
func (l *Loader) run() error {
if l.root.conf.Network == config.NetworkHost {
// Delay host network configuration to this point because network namespace
// is configured after the loader is created and before Run() is called.
log.Debugf("Configuring host network")
s := l.k.RootNetworkNamespace().Stack().(*hostinet.Stack)
if err := s.Configure(l.root.conf.EnableRaw); err != nil {
return err
}
}
l.mu.Lock()
defer l.mu.Unlock()
eid := execID{cid: l.sandboxID}
ep, ok := l.processes[eid]
if !ok {
return fmt.Errorf("trying to start deleted container %q", l.sandboxID)
}
// If we are restoring, we do not want to create a process.
// l.restore is set by the container manager when a restore call is made.
if !l.restore {
if l.root.conf.ProfileEnable {
pprof.Initialize()
}
// Finally done with all configuration. Setup filters before user code
// is loaded.
if err := l.installSeccompFilters(); err != nil {
return err
}
// Create the root container init task. It will begin running
// when the kernel is started.
var (
tg *kernel.ThreadGroup
err error
)
tg, ep.tty, err = l.createContainerProcess(&l.root)
if err != nil {
return err
}
if seccheck.Global.Enabled(seccheck.PointContainerStart) {
evt := pb.Start{
Id: l.sandboxID,
Cwd: l.root.spec.Process.Cwd,
Args: l.root.spec.Process.Args,
Terminal: l.root.spec.Process.Terminal,
}
fields := seccheck.Global.GetFieldSet(seccheck.PointContainerStart)
if fields.Local.Contains(seccheck.FieldContainerStartEnv) {
evt.Env = l.root.spec.Process.Env
}
if !fields.Context.Empty() {
evt.ContextData = &pb.ContextData{}
kernel.LoadSeccheckData(tg.Leader(), fields.Context, evt.ContextData)
}
_ = seccheck.Global.SentToSinks(func(c seccheck.Sink) error {
return c.ContainerStart(context.Background(), fields, &evt)
})
}
}
ep.tg = l.k.GlobalInit()
if ns, ok := specutils.GetNS(specs.PIDNamespace, l.root.spec); ok {
ep.pidnsPath = ns.Path
}
// Handle signals by forwarding them to the root container process
// (except for panic signal, which should cause a panic).
l.stopSignalForwarding = sighandling.StartSignalForwarding(func(sig linux.Signal) {
// Panic signal should cause a panic.
if l.root.conf.PanicSignal != -1 && sig == linux.Signal(l.root.conf.PanicSignal) {
panic("Signal-induced panic")
}
// Otherwise forward to root container.
deliveryMode := DeliverToProcess
if l.root.spec.Process.Terminal {
// Since we are running with a console, we should forward the signal to
// the foreground process group so that job control signals like ^C can
// be handled properly.