-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmgr.go
1546 lines (1255 loc) · 43.5 KB
/
mgr.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 2019-2022 Nestybox, Inc.
//
// 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
//
// https://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 main
import (
"fmt"
"path"
"sync"
"time"
systemd "github.com/coreos/go-systemd/daemon"
grpc "github.com/nestybox/sysbox-ipc/sysboxMgrGrpc"
ipcLib "github.com/nestybox/sysbox-ipc/sysboxMgrLib"
"github.com/nestybox/sysbox-libs/dockerUtils"
"github.com/nestybox/sysbox-libs/fileMonitor"
"github.com/nestybox/sysbox-libs/formatter"
"github.com/nestybox/sysbox-libs/idMap"
"github.com/nestybox/sysbox-libs/idShiftUtils"
"github.com/nestybox/sysbox-libs/linuxUtils"
"github.com/nestybox/sysbox-libs/shiftfs"
libutils "github.com/nestybox/sysbox-libs/utils"
intf "github.com/nestybox/sysbox-mgr/intf"
"github.com/nestybox/sysbox-mgr/rootfsCloner"
"github.com/nestybox/sysbox-mgr/shiftfsMgr"
"github.com/opencontainers/runc/libcontainer/configs"
specs "github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
var sysboxLibDir string
type containerState int
const (
started containerState = iota
stopped
restarted
)
type mntPrepRevInfo struct {
path string
uidShifted bool
origUid uint32
origGid uint32
targetUid uint32
targetGid uint32
}
type mountInfo struct {
kind ipcLib.MntKind
mounts []specs.Mount
}
type containerInfo struct {
state containerState
rootfs string
mntPrepRev []mntPrepRevInfo
reqMntInfos []mountInfo
containerMnts []specs.Mount
shiftfsMarks []shiftfs.MountPoint
autoRemove bool
userns string
netns string
netnsInode uint64
uidMappings []specs.LinuxIDMapping
gidMappings []specs.LinuxIDMapping
subidAllocated bool
rootfsCloned bool
origRootfs string // if rootfs was cloned, this is the original rootfs
rootfsUidShiftType idShiftUtils.IDShiftType
rootfsOnOvfs bool
rootfsOvfsUpper string
rootfsOvfsUpperChowned bool
}
type mgrConfig struct {
aliasDns bool
shiftfsOk bool
shiftfsOnOverlayfsOk bool
idMapMountOk bool
overlayfsOnIDMapMountOk bool
noRootfsCloning bool
ignoreSysfsChown bool
allowTrustedXattr bool
honorCaps bool
syscontMode bool
fsuidMapFailOnErr bool
noInnerImgPreload bool
noShiftfsOnFuse bool
relaxedReadOnly bool
}
type SysboxMgr struct {
mgrCfg mgrConfig
grpcServer *grpc.ServerStub
subidAlloc intf.SubidAlloc
dockerVolMgr intf.VolMgr
kubeletVolMgr intf.VolMgr
k0sVolMgr intf.VolMgr
k3sVolMgr intf.VolMgr
rke2VolMgr intf.VolMgr
buildkitVolMgr intf.VolMgr
containerdVolMgr intf.VolMgr
shiftfsMgr intf.ShiftfsMgr
rootfsCloner intf.RootfsCloner
hostDistro string
hostKernelHdrPath string
linuxHeaderMounts []specs.Mount
libModMounts []specs.Mount
// Tracks containers known to sysbox (cont id -> cont info)
contTable map[string]containerInfo
ctLock sync.Mutex
// Tracks container rootfs (cont rootfs -> cont id); used by the rootfs monitor
rootfsTable map[string]string
rtLock sync.Mutex
rootfsMonStop chan int
rootfsMon *fileMonitor.FileMon
exclMntTable *exclusiveMntTable
// tracks containers using the same netns (netns inode -> list of container ids)
netnsTable map[uint64][]string
ntLock sync.Mutex
}
// newSysboxMgr creates an instance of the sysbox manager
func newSysboxMgr(ctx *cli.Context) (*SysboxMgr, error) {
var err error
err = libutils.CheckPidFile("sysbox-mgr", sysboxMgrPidFile)
if err != nil {
return nil, err
}
err = preFlightCheck()
if err != nil {
return nil, fmt.Errorf("preflight check failed: %s", err)
}
sysboxLibDir = ctx.GlobalString("data-root")
if sysboxLibDir == "" {
sysboxLibDir = sysboxLibDirDefault
}
logrus.Infof("Sysbox data root: %s", sysboxLibDir)
err = setupRunDir()
if err != nil {
return nil, fmt.Errorf("failed to setup the sysbox run dir: %v", err)
}
err = setupWorkDirs()
if err != nil {
return nil, fmt.Errorf("failed to setup the sysbox work dirs: %v", err)
}
subidAlloc, err := setupSubidAlloc(ctx)
if err != nil {
return nil, fmt.Errorf("failed to setup subid allocator: %v", err)
}
syncVolToRootfs := !ctx.GlobalBool("disable-inner-image-preload")
dockerVolMgr, err := setupDockerVolMgr(syncVolToRootfs)
if err != nil {
return nil, fmt.Errorf("failed to setup docker vol mgr: %v", err)
}
kubeletVolMgr, err := setupKubeletVolMgr(syncVolToRootfs)
if err != nil {
return nil, fmt.Errorf("failed to setup kubelet vol mgr: %v", err)
}
k0sVolMgr, err := setupK0sVolMgr(syncVolToRootfs)
if err != nil {
return nil, fmt.Errorf("failed to setup k0s vol mgr: %v", err)
}
k3sVolMgr, err := setupK3sVolMgr(syncVolToRootfs)
if err != nil {
return nil, fmt.Errorf("failed to setup k3s vol mgr: %v", err)
}
rke2VolMgr, err := setupRke2VolMgr(syncVolToRootfs)
if err != nil {
return nil, fmt.Errorf("failed to setup rke2 vol mgr: %v", err)
}
buildkitVolMgr, err := setupBuildkitVolMgr(syncVolToRootfs)
if err != nil {
return nil, fmt.Errorf("failed to setup buildkit vol mgr: %v", err)
}
containerdVolMgr, err := setupContainerdVolMgr(syncVolToRootfs)
if err != nil {
return nil, fmt.Errorf("failed to setup containerd vol mgr: %v", err)
}
shiftfsMgr, err := shiftfsMgr.New(sysboxLibDir)
if err != nil {
return nil, fmt.Errorf("failed to setup shiftfs mgr: %v", err)
}
rootfsCloner := rootfsCloner.New(sysboxLibDir)
if err != nil {
return nil, fmt.Errorf("failed to setup rootfs mgr: %v", err)
}
hostDistro, err := linuxUtils.GetDistro()
if err != nil {
return nil, fmt.Errorf("failed to identify system's linux distribution: %v", err)
}
hostKernelHdrPath, err := linuxUtils.GetLinuxHeaderPath(hostDistro)
if err != nil {
return nil, fmt.Errorf("failed to identify system's linux-header path: %v", err)
}
linuxHeaderMounts, err := getLinuxHeaderMounts(hostKernelHdrPath)
if err != nil {
return nil, fmt.Errorf("failed to compute linux header mounts: %v", err)
}
libModMounts, err := getLibModMounts()
if err != nil {
return nil, fmt.Errorf("failed to compute kernel-module mounts: %v", err)
}
idMapMountOk := false
ovfsOnIDMapMountOk := false
if !ctx.GlobalBool("disable-idmapped-mount") {
idMapMountOk, ovfsOnIDMapMountOk, err = checkIDMapMountSupport(ctx)
if err != nil {
return nil, fmt.Errorf("ID-mapping check failed: %v", err)
}
}
if ctx.GlobalBool("disable-ovfs-on-idmapped-mount") {
ovfsOnIDMapMountOk = false
}
shiftfsModPresent := false
shiftfsOk := false
shiftfsOnOvfsOk := false
if !ctx.GlobalBool("disable-shiftfs") {
shiftfsModPresent, err = linuxUtils.KernelModSupported("shiftfs")
if err != nil {
return nil, fmt.Errorf("shiftfs kernel module check failed: %v", err)
}
if shiftfsModPresent {
if ctx.GlobalBool("disable-shiftfs-precheck") {
shiftfsOk = shiftfsModPresent
shiftfsOnOvfsOk = shiftfsModPresent
} else {
shiftfsOk, shiftfsOnOvfsOk, err = checkShiftfsSupport(ctx)
if err != nil {
return nil, fmt.Errorf("shiftfs check failed: %v", err)
}
}
}
}
mgrCfg := mgrConfig{
aliasDns: ctx.GlobalBoolT("alias-dns"),
shiftfsOk: shiftfsOk,
shiftfsOnOverlayfsOk: shiftfsOnOvfsOk,
idMapMountOk: idMapMountOk,
overlayfsOnIDMapMountOk: ovfsOnIDMapMountOk,
noRootfsCloning: ctx.GlobalBool("disable-rootfs-cloning"),
ignoreSysfsChown: ctx.GlobalBool("ignore-sysfs-chown"),
allowTrustedXattr: ctx.GlobalBool("allow-trusted-xattr"),
honorCaps: ctx.GlobalBool("honor-caps"),
syscontMode: ctx.GlobalBoolT("syscont-mode"),
relaxedReadOnly: ctx.GlobalBool("relaxed-read-only"),
fsuidMapFailOnErr: ctx.GlobalBool("fsuid-map-fail-on-error"),
noInnerImgPreload: !syncVolToRootfs,
noShiftfsOnFuse: ctx.GlobalBool("disable-shiftfs-on-fuse"),
}
if !mgrCfg.aliasDns {
logrus.Info("Sys container DNS aliasing disabled.")
}
if ctx.GlobalBool("disable-shiftfs") {
logrus.Info("Use of shiftfs disabled.")
} else {
logrus.Infof("Shiftfs module found in kernel: %s", ifThenElse(shiftfsModPresent, "yes", "no"))
if !ctx.GlobalBool("disable-shiftfs-precheck") {
logrus.Infof("Shiftfs works properly: %s", ifThenElse(mgrCfg.shiftfsOk, "yes", "no"))
logrus.Infof("Shiftfs-on-overlayfs works properly: %s", ifThenElse(mgrCfg.shiftfsOnOverlayfsOk, "yes", "no"))
}
}
if ctx.GlobalBool("disable-idmapped-mount") {
logrus.Info("Use of ID-mapped mounts disabled.")
} else {
logrus.Infof("ID-mapped mounts supported by kernel: %s", ifThenElse(mgrCfg.idMapMountOk, "yes", "no"))
}
if ctx.GlobalBool("disable-ovfs-on-idmapped-mount") {
logrus.Info("Use of overlayfs on ID-mapped mounts disabled.")
} else {
logrus.Infof("Overlayfs on ID-mapped mounts supported by kernel: %s", ifThenElse(mgrCfg.overlayfsOnIDMapMountOk, "yes", "no"))
}
if mgrCfg.noRootfsCloning {
logrus.Info("Rootfs cloning disabled.")
}
if mgrCfg.ignoreSysfsChown {
logrus.Info("Ignoring chown of /sys inside container.")
}
if mgrCfg.allowTrustedXattr {
logrus.Info("Allowing trusted.overlay.opaque inside container.")
}
if mgrCfg.honorCaps {
logrus.Info("Honoring process capabilities in OCI spec (--honor-caps).")
}
if mgrCfg.syscontMode {
logrus.Info("Operating in system container mode.")
} else {
logrus.Info("Operating in regular container mode.")
}
if mgrCfg.relaxedReadOnly {
logrus.Info("Relaxed read-only mode enabled.")
} else {
logrus.Info("Relaxed read-only mode disabled.")
}
if mgrCfg.fsuidMapFailOnErr {
logrus.Info("fsuid-map-fail-on-error = true.")
}
if mgrCfg.noInnerImgPreload {
logrus.Info("Inner container image preloading disabled.")
} else {
logrus.Info("Inner container image preloading enabled.")
}
mgr := &SysboxMgr{
mgrCfg: mgrCfg,
subidAlloc: subidAlloc,
dockerVolMgr: dockerVolMgr,
kubeletVolMgr: kubeletVolMgr,
k0sVolMgr: k0sVolMgr,
k3sVolMgr: k3sVolMgr,
rke2VolMgr: rke2VolMgr,
buildkitVolMgr: buildkitVolMgr,
containerdVolMgr: containerdVolMgr,
shiftfsMgr: shiftfsMgr,
rootfsCloner: rootfsCloner,
hostDistro: hostDistro,
hostKernelHdrPath: hostKernelHdrPath,
linuxHeaderMounts: linuxHeaderMounts,
libModMounts: libModMounts,
contTable: make(map[string]containerInfo),
rootfsTable: make(map[string]string),
rootfsMonStop: make(chan int),
netnsTable: make(map[uint64][]string),
exclMntTable: newExclusiveMntTable(),
}
cb := &grpc.ServerCallbacks{
Register: mgr.register,
Update: mgr.update,
Unregister: mgr.unregister,
SubidAlloc: mgr.allocSubid,
ReqMounts: mgr.reqMounts,
PrepMounts: mgr.prepMounts,
ReqShiftfsMark: mgr.reqShiftfsMark,
ReqFsState: mgr.reqFsState,
CloneRootfs: mgr.cloneRootfs,
ChownClonedRootfs: mgr.chownClonedRootfs,
RevertClonedRootfsChown: mgr.revertClonedRootfsChown,
Pause: mgr.pause,
Resume: mgr.resume,
}
mgr.grpcServer = grpc.NewServerStub(cb)
return mgr, nil
}
func (mgr *SysboxMgr) Start() error {
// setup the container rootfs monitor (detects container removal)
cfg := &fileMonitor.Cfg{
EventBufSize: 10,
PollInterval: 50 * time.Millisecond,
}
mon, err := fileMonitor.New(cfg)
if err != nil {
return fmt.Errorf("failed to setup rootfs monitor: %v", err)
}
mgr.rootfsMon = mon
// start the rootfs monitor thread (listens for rootfsMon events)
go mgr.rootfsMonitor()
systemd.SdNotify(false, systemd.SdNotifyReady)
err = libutils.CreatePidFile("sysbox-mgr", sysboxMgrPidFile)
if err != nil {
return fmt.Errorf("failed to create sysmgr.pid file: %s", err)
}
logrus.Info("Ready ...")
// listen for grpc connections
return mgr.grpcServer.Init()
}
func (mgr *SysboxMgr) Stop() error {
logrus.Info("Stopping (gracefully) ...")
systemd.SdNotify(false, systemd.SdNotifyStopping)
mgr.ctLock.Lock()
if len(mgr.contTable) > 0 {
logrus.Warn("The following containers are active and will stop operating properly:")
for id := range mgr.contTable {
logrus.Warnf("container id: %s", formatter.ContainerID{id})
}
}
mgr.ctLock.Unlock()
mgr.rootfsMonStop <- 1
mgr.rootfsMon.Close()
mgr.dockerVolMgr.SyncOutAndDestroyAll()
mgr.kubeletVolMgr.SyncOutAndDestroyAll()
mgr.k0sVolMgr.SyncOutAndDestroyAll()
mgr.k3sVolMgr.SyncOutAndDestroyAll()
mgr.rke2VolMgr.SyncOutAndDestroyAll()
mgr.buildkitVolMgr.SyncOutAndDestroyAll()
mgr.containerdVolMgr.SyncOutAndDestroyAll()
mgr.shiftfsMgr.UnmarkAll()
// Note: this will cause the container's cloned rootfs to be removed when
// Sysbox is stopped, thus loosing the container's runtime data. In the
// future we may want to make this persistent across Sysbox stop-restart
// events.
mgr.rootfsCloner.RemoveAll()
if err := cleanupWorkDirs(); err != nil {
logrus.Warnf("failed to cleanup work dirs: %v", err)
}
if err := libutils.DestroyPidFile(sysboxMgrPidFile); err != nil {
logrus.Warnf("failed to destroy sysbox-mgr pid file: %v", err)
}
logrus.Info("Stopped.")
return nil
}
// Registers a container with sysbox-mgr
func (mgr *SysboxMgr) register(regInfo *ipcLib.RegistrationInfo) (*ipcLib.ContainerConfig, error) {
id := regInfo.Id
rootfs := regInfo.Rootfs
userns := regInfo.Userns
netns := regInfo.Netns
uidMappings := regInfo.UidMappings
gidMappings := regInfo.GidMappings
mgr.ctLock.Lock()
info, found := mgr.contTable[id]
newContainer := !found
if newContainer {
// new container
info = containerInfo{
state: started,
mntPrepRev: []mntPrepRevInfo{},
shiftfsMarks: []shiftfs.MountPoint{},
}
} else {
// re-started container
if info.state != stopped {
mgr.ctLock.Unlock()
return nil, fmt.Errorf("redundant container registration for container %s",
formatter.ContainerID{id})
}
info.state = restarted
}
if !info.rootfsCloned {
info.rootfs = rootfs
info.origRootfs = rootfs
}
rootfsOnOvfs, err := isRootfsOnOverlayfs(rootfs)
if err != nil {
mgr.ctLock.Unlock()
return nil, err
}
info.rootfsOnOvfs = rootfsOnOvfs
info.netns = netns
info.userns = userns
if !info.subidAllocated {
info.uidMappings = uidMappings
info.gidMappings = gidMappings
}
// Track the container's net-ns, so we can later determine if multiple sys
// containers are sharing a net-ns (which implies they share the user-ns too).
var sameNetns []string
if netns != "" {
netnsInode, err := getInode(netns)
if err != nil {
mgr.ctLock.Unlock()
return nil, fmt.Errorf("unable to get inode for netns %s: %s", netns, err)
}
sameNetns, err = mgr.trackNetns(id, netnsInode)
if err != nil {
mgr.ctLock.Unlock()
return nil, fmt.Errorf("failed to track netns for container %s: %s",
formatter.ContainerID{id}, err)
}
info.netnsInode = netnsInode
}
// If this container's netns is shared with other containers, it's userns
// (and associated ID mappings) must be shared too.
if len(sameNetns) > 1 && userns == "" {
otherContSameNetnsInfo, ok := mgr.contTable[sameNetns[0]]
if !ok {
mgr.ctLock.Unlock()
return nil,
fmt.Errorf("container %s shares net-ns with other containers, but unable to find info for those.",
formatter.ContainerID{id})
}
info.userns = otherContSameNetnsInfo.userns
info.uidMappings = otherContSameNetnsInfo.uidMappings
info.gidMappings = otherContSameNetnsInfo.gidMappings
}
mgr.contTable[id] = info
mgr.ctLock.Unlock()
if info.state == restarted {
if info.origRootfs != "" {
// remove the container's rootfs watch
origRootfs := sanitizeRootfs(id, info.origRootfs)
mgr.rootfsMon.Remove(origRootfs)
mgr.rtLock.Lock()
delete(mgr.rootfsTable, origRootfs)
mgr.rtLock.Unlock()
logrus.Debugf("removed fs watch on %s", origRootfs)
}
logrus.Infof("registered container %s", formatter.ContainerID{id})
} else {
logrus.Infof("registered new container %s", formatter.ContainerID{id})
}
containerCfg := &ipcLib.ContainerConfig{
AliasDns: mgr.mgrCfg.aliasDns,
ShiftfsOk: mgr.mgrCfg.shiftfsOk,
ShiftfsOnOverlayfsOk: mgr.mgrCfg.shiftfsOnOverlayfsOk,
IDMapMountOk: mgr.mgrCfg.idMapMountOk,
OverlayfsOnIDMapMountOk: mgr.mgrCfg.overlayfsOnIDMapMountOk,
NoRootfsCloning: mgr.mgrCfg.noRootfsCloning,
IgnoreSysfsChown: mgr.mgrCfg.ignoreSysfsChown,
AllowTrustedXattr: mgr.mgrCfg.allowTrustedXattr,
HonorCaps: mgr.mgrCfg.honorCaps,
SyscontMode: mgr.mgrCfg.syscontMode,
FsuidMapFailOnErr: mgr.mgrCfg.fsuidMapFailOnErr,
Userns: info.userns,
UidMappings: info.uidMappings,
GidMappings: info.gidMappings,
RootfsUidShiftType: info.rootfsUidShiftType,
NoShiftfsOnFuse: mgr.mgrCfg.noShiftfsOnFuse,
RelaxedReadOnly: mgr.mgrCfg.relaxedReadOnly,
}
return containerCfg, nil
}
// Updates info for a given container
func (mgr *SysboxMgr) update(updateInfo *ipcLib.UpdateInfo) error {
id := updateInfo.Id
userns := updateInfo.Userns
netns := updateInfo.Netns
uidMappings := updateInfo.UidMappings
gidMappings := updateInfo.GidMappings
rootfsUidShiftType := updateInfo.RootfsUidShiftType
mgr.ctLock.Lock()
defer mgr.ctLock.Unlock()
info, found := mgr.contTable[id]
if !found {
return fmt.Errorf("can't update container %s; not found in container table",
formatter.ContainerID{id})
}
// If the container's rootfs is on overlayfs and it's ID-mapped, then
// sysbox-runc will chown the upper layer as it can't be ID-mapped (overlayfs
// does not support it). Track this fact so we can revert that chown when
// the container is stopped or paused.
if info.rootfsOnOvfs && rootfsUidShiftType == idShiftUtils.IDMappedMount {
rootfsOvfsUpper, err := getRootfsOverlayUpperLayer(info.rootfs)
if err != nil {
return nil
}
info.rootfsOvfsUpper = rootfsOvfsUpper
info.rootfsOvfsUpperChowned = true
}
if info.netns == "" && netns != "" {
netnsInode, err := getInode(netns)
if err != nil {
return fmt.Errorf("can't update container %s: unable to get inode for netns %s: %s",
formatter.ContainerID{id}, netns, err)
}
if _, err := mgr.trackNetns(id, netnsInode); err != nil {
return fmt.Errorf("can't update container %s: failed to track netns: %s",
formatter.ContainerID{id}, err)
}
info.netns = netns
info.netnsInode = netnsInode
}
if info.userns == "" && userns != "" {
info.userns = userns
}
if len(info.uidMappings) == 0 && len(uidMappings) > 0 {
info.uidMappings = uidMappings
}
if len(info.gidMappings) == 0 && len(gidMappings) > 0 {
info.gidMappings = gidMappings
}
info.rootfsUidShiftType = rootfsUidShiftType
mgr.contTable[id] = info
return nil
}
// Unregisters a container with sysbox-mgr
func (mgr *SysboxMgr) unregister(id string) error {
var err error
// update container state
mgr.ctLock.Lock()
info, found := mgr.contTable[id]
mgr.ctLock.Unlock()
if !found {
return fmt.Errorf("can't unregister container %s; not found in container table",
formatter.ContainerID{id})
}
if info.state == stopped {
return fmt.Errorf("redundant container unregistration for container %s",
formatter.ContainerID{id})
}
info.state = stopped
if len(info.shiftfsMarks) != 0 {
if err = mgr.shiftfsMgr.Unmark(id, info.shiftfsMarks); err != nil {
logrus.Warnf("failed to remove shiftfs marks for container %s: %s",
formatter.ContainerID{id}, err)
}
info.shiftfsMarks = []shiftfs.MountPoint{}
}
// If the rootfs is ID-mapped and on overlayfs, then chown the upper dir from
// [userns-host-ID -> 0] when the container stops (i.e., revert uid:gid to
// it's original). This way snapshots of the container rootfs (e.g., docker
// commit or docker build) will capture the correct uid:gid.
//
// TODO: before checking for info.autoRemove, we should ensure that the
// autoRemoveCheck() goroutine has run to completion. Otherwise the
// value of autoRemove is not guaranteed to be correct.
if info.rootfsOvfsUpperChowned && !info.autoRemove {
uidOffset := -int32(info.uidMappings[0].HostID)
gidOffset := -int32(info.gidMappings[0].HostID)
logrus.Infof("unregister %s: chown rootfs overlayfs upper layer at %s (%d -> %d)",
formatter.ContainerID{id}, info.rootfsOvfsUpper, info.uidMappings[0].HostID, 0)
if err := idShiftUtils.ShiftIdsWithChown(info.rootfsOvfsUpper, uidOffset, gidOffset); err != nil {
return err
}
info.rootfsOvfsUpperChowned = false
}
// revert mount prep actions
for _, revInfo := range info.mntPrepRev {
if revInfo.uidShifted {
uidOffset := int32(revInfo.origUid) - int32(revInfo.targetUid)
gidOffset := int32(revInfo.origGid) - int32(revInfo.targetGid)
logrus.Infof("reverting uid-shift on %s for %s (%d -> %d)", revInfo.path, formatter.ContainerID{id}, revInfo.targetUid, revInfo.origUid)
if err = idShiftUtils.ShiftIdsWithChown(revInfo.path, uidOffset, gidOffset); err != nil {
logrus.Warnf("failed to revert uid-shift of mount source at %s: %s", revInfo.path, err)
}
logrus.Infof("done reverting uid-shift on %s for %s", revInfo.path, formatter.ContainerID{id})
}
mgr.exclMntTable.remove(revInfo.path, id)
}
info.mntPrepRev = []mntPrepRevInfo{}
// update the netns sharing table
//
// note: we don't do error checking because this can fail if the netns is not
// yet tracked for the container (e.g., if a container is registered and
// then unregistered because the container failed to start for some reason).
mgr.untrackNetns(id, info.netnsInode)
// ns tracking info is reset for new or restarted containers
info.userns = ""
info.netns = ""
info.netnsInode = 0
// uid mappings for the container are also reset, except if they were
// allocated by sysbox-mgr (those are kept across container restarts).
if !info.subidAllocated {
info.uidMappings = nil
info.gidMappings = nil
}
mgr.ctLock.Lock()
mgr.contTable[id] = info
mgr.ctLock.Unlock()
// Request the volume managers to copy their contents to the container's rootfs.
if !info.autoRemove {
if err := mgr.volSyncOut(id, info); err != nil {
logrus.Warnf("sync-out for container %s failed: %v",
formatter.ContainerID{id}, err)
}
}
// Notify rootfs cloner that container has stopped
if info.rootfsCloned {
if err := mgr.rootfsCloner.ContainerStopped(id); err != nil {
return err
}
}
// setup a rootfs watch (allows us to get notified when the container's rootfs is removed)
if info.origRootfs != "" {
origRootfs := sanitizeRootfs(id, info.origRootfs)
mgr.rtLock.Lock()
mgr.rootfsTable[origRootfs] = id
mgr.rootfsMon.Add(origRootfs)
mgr.rtLock.Unlock()
logrus.Debugf("added fs watch on %s", origRootfs)
}
logrus.Infof("unregistered container %s", formatter.ContainerID{id})
return nil
}
func (mgr *SysboxMgr) volSyncOut(id string, info containerInfo) error {
var err, err2 error
failedVols := []string{}
for _, mnt := range info.reqMntInfos {
switch mnt.kind {
case ipcLib.MntVarLibDocker:
err = mgr.dockerVolMgr.SyncOut(id)
case ipcLib.MntVarLibKubelet:
err = mgr.kubeletVolMgr.SyncOut(id)
case ipcLib.MntVarLibK0s:
err = mgr.k0sVolMgr.SyncOut(id)
case ipcLib.MntVarLibRancherK3s:
err = mgr.k3sVolMgr.SyncOut(id)
case ipcLib.MntVarLibRancherRke2:
err = mgr.rke2VolMgr.SyncOut(id)
case ipcLib.MntVarLibBuildkit:
err = mgr.buildkitVolMgr.SyncOut(id)
case ipcLib.MntVarLibContainerdOvfs:
err = mgr.containerdVolMgr.SyncOut(id)
}
if err != nil {
failedVols = append(failedVols, mnt.kind.String())
err2 = err
}
}
if len(failedVols) > 0 {
return fmt.Errorf("sync-out for volume backing %s: %v", failedVols, err2)
}
return nil
}
// rootfs monitor thread: checks for rootfs removal event and removes container state.
func (mgr *SysboxMgr) rootfsMonitor() {
logrus.Debugf("rootfsMon starting ...")
for {
select {
case events := <-mgr.rootfsMon.Events():
for _, e := range events {
rootfs := e.Filename
if e.Err != nil {
logrus.Warnf("rootfsMon: container rootfs watch error on %s", rootfs)
continue
}
mgr.rtLock.Lock()
id, found := mgr.rootfsTable[rootfs]
if !found {
logrus.Warnf("rootfsMon: event on unknown container rootfs %s", rootfs)
mgr.rtLock.Unlock()
continue
}
logrus.Debugf("rootfsMon: detected removal of container rootfs %s", rootfs)
delete(mgr.rootfsTable, rootfs)
mgr.rtLock.Unlock()
mgr.removeCont(id)
}
case <-mgr.rootfsMonStop:
logrus.Debugf("rootfsMon exiting ...")
return
}
}
}
// removes all resources associated with a container
func (mgr *SysboxMgr) removeCont(id string) {
mgr.ctLock.Lock()
info, found := mgr.contTable[id]
if !found {
mgr.ctLock.Unlock()
return
}
delete(mgr.contTable, id)
mgr.ctLock.Unlock()
for _, mnt := range info.reqMntInfos {
var err error
switch mnt.kind {
case ipcLib.MntVarLibDocker:
err = mgr.dockerVolMgr.DestroyVol(id)
case ipcLib.MntVarLibKubelet:
err = mgr.kubeletVolMgr.DestroyVol(id)
case ipcLib.MntVarLibK0s:
err = mgr.k0sVolMgr.DestroyVol(id)
case ipcLib.MntVarLibRancherK3s:
err = mgr.k3sVolMgr.DestroyVol(id)
case ipcLib.MntVarLibRancherRke2:
err = mgr.rke2VolMgr.DestroyVol(id)
case ipcLib.MntVarLibBuildkit:
err = mgr.buildkitVolMgr.DestroyVol(id)
case ipcLib.MntVarLibContainerdOvfs:
err = mgr.containerdVolMgr.DestroyVol(id)
}
if err != nil {
logrus.Errorf("rootfsMon: failed to destroy volume backing %s for container %s: %s",
mnt.kind, formatter.ContainerID{id}, err)
}
}
if info.subidAllocated {
if err := mgr.subidAlloc.Free(id); err != nil {
logrus.Errorf("rootfsMon: failed to free uid(gid) for container %s: %s",
formatter.ContainerID{id}, err)
}
}
if info.rootfsCloned {
if err := mgr.rootfsCloner.RemoveClone(id); err != nil {
logrus.Warnf("failed to unbind cloned rootfs for container %s: %s",
formatter.ContainerID{id}, err)
}
}
logrus.Infof("released resources for container %s",
formatter.ContainerID{id})
}
func (mgr *SysboxMgr) reqMounts(id string, rootfsUidShiftType idShiftUtils.IDShiftType, reqList []ipcLib.MountReqInfo) ([]specs.Mount, error) {
var (
volChownOnSync bool
volUid, volGid uint32
)
// get container info
mgr.ctLock.Lock()
info, found := mgr.contTable[id]
mgr.ctLock.Unlock()
if !found {
return nil, fmt.Errorf("container %s is not registered",
formatter.ContainerID{id})
}
// if this is a stopped container that is being re-started, reuse its prior mounts
if info.state == restarted {
return info.containerMnts, nil
}
// Setup Sysbox's implicit container mounts. The mounts may need chowning
// according to the following rules:
//
// Rootfs Container Rootfs Owner Sysbox Special Sync-in Sync-out
// ID-shift (Stopped) (Running) Mount Owner Chown Chown
// -------------------------------------------------------------------------------
// ID-mapping root:root root:root root:root None None
// Shiftfs root:root root:root uid:gid root->uid uid->root
// Chown root:root uid:gid uid:gid root->uid uid->root
// No-shift uid:gid uid:gid uid:gid None None
switch rootfsUidShiftType {
case idShiftUtils.IDMappedMount:
volChownOnSync = false
volUid = 0
volGid = 0
case idShiftUtils.Shiftfs:
volChownOnSync = true
volUid = info.uidMappings[0].HostID
volGid = info.gidMappings[0].HostID
case idShiftUtils.Chown:
volChownOnSync = true
volUid = info.uidMappings[0].HostID
volGid = info.gidMappings[0].HostID
case idShiftUtils.NoShift:
volChownOnSync = false
volUid = info.uidMappings[0].HostID
volGid = info.gidMappings[0].HostID
default:
return nil, fmt.Errorf("unexpected rootfs ID shift type: %v", rootfsUidShiftType)
}
containerMnts := []specs.Mount{}
reqMntInfos := []mountInfo{}
rootfs := info.rootfs
for _, req := range reqList {
var err error
m := []specs.Mount{}
switch req.Kind {
case ipcLib.MntVarLibDocker:
m, err = mgr.dockerVolMgr.CreateVol(id, rootfs, req.Dest, volUid, volGid, volChownOnSync, 0700)
case ipcLib.MntVarLibKubelet:
m, err = mgr.kubeletVolMgr.CreateVol(id, rootfs, req.Dest, volUid, volGid, volChownOnSync, 0755)
case ipcLib.MntVarLibK0s:
m, err = mgr.k0sVolMgr.CreateVol(id, rootfs, req.Dest, volUid, volGid, volChownOnSync, 0755)
case ipcLib.MntVarLibRancherK3s: