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
|
// Copyright (c) Contributors to the Apptainer project, established as
// Apptainer a Series of LF Projects LLC.
// For website terms of use, trademark policy, privacy policy and other
// project policies see https://lfprojects.org/policies
// Copyright (c) 2018-2022, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
package oci
import (
"bufio"
"context"
"encoding/json"
"fmt"
"net"
"net/rpc"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/apptainer/apptainer/internal/pkg/cgroups"
"github.com/apptainer/apptainer/internal/pkg/instance"
"github.com/apptainer/apptainer/internal/pkg/runtime/engine/oci/rpc/client"
"github.com/apptainer/apptainer/internal/pkg/util/fs"
"github.com/apptainer/apptainer/internal/pkg/util/fs/mount"
"github.com/apptainer/apptainer/pkg/ociruntime"
"github.com/apptainer/apptainer/pkg/sylog"
"github.com/apptainer/apptainer/pkg/util/fs/proc"
"github.com/apptainer/apptainer/pkg/util/namespaces"
"github.com/apptainer/apptainer/pkg/util/sysctl"
"github.com/apptainer/apptainer/pkg/util/unix"
specs "github.com/opencontainers/runtime-spec/specs-go"
)
var symlinkDevices = []struct {
old string
new string
}{
{"/proc/self/fd", "/dev/fd"},
{"/proc/kcore", "/dev/core"},
{"pts/ptmx", "/dev/ptmx"},
{"/proc/self/fd/0", "/dev/stdin"},
{"/proc/self/fd/1", "/dev/stdout"},
{"/proc/self/fd/2", "/dev/stderr"},
}
type device struct {
major int64
minor int64
path string
mode os.FileMode
uid int
gid int
}
var devices = []device{
{1, 7, "/dev/full", syscall.S_IFCHR | 0o666, 0, 0},
{1, 3, "/dev/null", syscall.S_IFCHR | 0o666, 0, 0},
{1, 8, "/dev/random", syscall.S_IFCHR | 0o666, 0, 0},
{5, 0, "/dev/tty", syscall.S_IFCHR | 0o666, 0, 0},
{1, 9, "/dev/urandom", syscall.S_IFCHR | 0o666, 0, 0},
{1, 5, "/dev/zero", syscall.S_IFCHR | 0o666, 0, 0},
}
var cgroupDevices = []specs.LinuxDeviceCgroup{
{
Allow: true,
Type: "c",
Major: cgroups.Int64ptr(1),
Minor: cgroups.Int64ptr(7),
Access: "rw",
},
{
Allow: true,
Type: "c",
Major: cgroups.Int64ptr(1),
Minor: cgroups.Int64ptr(3),
Access: "rw",
},
{
Allow: true,
Type: "c",
Major: cgroups.Int64ptr(1),
Minor: cgroups.Int64ptr(8),
Access: "rw",
},
{
Allow: true,
Type: "c",
Major: cgroups.Int64ptr(5),
Minor: cgroups.Int64ptr(0),
Access: "rw",
},
{
Allow: true,
Type: "c",
Major: cgroups.Int64ptr(1),
Minor: cgroups.Int64ptr(9),
Access: "rw",
},
{
Allow: true,
Type: "c",
Major: cgroups.Int64ptr(1),
Minor: cgroups.Int64ptr(5),
Access: "rw",
},
{
Allow: true,
Type: "c",
Major: cgroups.Int64ptr(136),
Minor: cgroups.Int64ptr(-1),
Access: "rwm",
},
{
Allow: true,
Type: "c",
Major: cgroups.Int64ptr(5),
Minor: cgroups.Int64ptr(1),
Access: "rw",
},
{
Allow: true,
Type: "c",
Major: cgroups.Int64ptr(5),
Minor: cgroups.Int64ptr(2),
Access: "rw",
},
}
type container struct {
engine *EngineOperations
rpcOps *client.RPC
rootfs string
rpcRoot string
userNS bool
utsNS bool
mntNS bool
devIndex int
cgroupV1MountIndex int
}
var statusChan = make(chan string, 1)
// CreateContainer is called from master process to prepare container
// environment, e.g. perform mount operations, etc.
//
// Additional privileges required for setup may be gained when running
// in suid flow. However, when a user namespace is requested and it is not
// a hybrid workflow (e.g. fakeroot), then there is no privileged saved uid
// and thus no additional privileges can be gained.
//
// Specifically in oci engine, no additional privileges are gained. Container
// setup (e.g. mount operations) where privileges may be required is performed
// by calling RPC server methods (see internal/app/starter/rpc_linux.go for details).
//
// However, most likely this still will be executed as root since `apptainer oci`
// command set requires privileged execution.
//
//nolint:maintidx
func (e *EngineOperations) CreateContainer(_ context.Context, pid int, rpcConn net.Conn) error {
var err error
if e.CommonConfig.EngineName != Name {
return fmt.Errorf("engineName configuration doesn't match runtime name")
}
rpcOps := &client.RPC{}
rpcOps.Client = rpc.NewClient(rpcConn)
rpcOps.Name = e.CommonConfig.EngineName
if rpcOps.Client == nil {
return fmt.Errorf("failed to initialize RPC client")
}
if err := e.createState(pid); err != nil {
return err
}
rootfs := e.EngineConfig.OciConfig.Root.Path
if !filepath.IsAbs(rootfs) {
rootfs = filepath.Join(e.EngineConfig.GetBundlePath(), rootfs)
}
resolvedRootfs, err := filepath.EvalSymlinks(rootfs)
if err != nil {
return fmt.Errorf("failed to resolve %s path: %s", rootfs, err)
}
c := &container{
engine: e,
rpcOps: rpcOps,
rootfs: resolvedRootfs,
rpcRoot: fmt.Sprintf("/proc/%d/root", pid),
cgroupV1MountIndex: -1,
devIndex: -1,
}
for _, ns := range e.EngineConfig.OciConfig.Linux.Namespaces {
switch ns.Type {
case specs.UserNamespace:
c.userNS = true
case specs.UTSNamespace:
c.utsNS = true
case specs.MountNamespace:
c.mntNS = true
}
}
p := &mount.Points{}
if e.EngineConfig.OciConfig.Linux.MountLabel != "" {
if err := p.SetContext(e.EngineConfig.OciConfig.Linux.MountLabel); err != nil {
return err
}
}
system := &mount.System{Points: p, Mount: c.mount}
for i, point := range e.EngineConfig.OciConfig.Config.Mounts {
// A cgroup v1 mount point will be intercepted and handled separately in c.addCgroups(...)
if point.Type == "cgroup" {
c.cgroupV1MountIndex = i
continue
}
// dev creation
if point.Destination == "/dev" && point.Type == "tmpfs" {
c.devIndex = i
}
}
if err := c.addDevices(system); err != nil {
return err
}
if err := c.addCgroups(pid, system); err != nil {
return err
}
// import OCI mount spec
if err := system.Points.ImportFromSpec(e.EngineConfig.OciConfig.Config.Mounts); err != nil {
return err
}
if err := c.addRootfsMount(system); err != nil {
return err
}
if err := system.RunAfterTag(mount.KernelTag, c.addDefaultDevices); err != nil {
return err
}
if err := system.RunAfterTag(mount.KernelTag, c.addAllPaths); err != nil {
return err
}
if err := proc.SetOOMScoreAdj(pid, e.EngineConfig.OciConfig.Process.OOMScoreAdj); err != nil {
return err
}
if err := namespaces.Enter(pid, "ipc"); err != nil {
return err
}
if err := namespaces.Enter(pid, "net"); err != nil {
return err
}
for key, value := range e.EngineConfig.OciConfig.Linux.Sysctl {
if err := sysctl.Set(key, value); err != nil {
return err
}
}
if err := namespaces.Enter(os.Getpid(), "ipc"); err != nil {
return err
}
if err := namespaces.Enter(os.Getpid(), "net"); err != nil {
return err
}
sylog.Debugf("Mount all")
if err := system.MountAll(); err != nil {
return err
}
if c.utsNS && e.EngineConfig.OciConfig.Hostname != "" {
if _, err := rpcOps.SetHostname(e.EngineConfig.OciConfig.Hostname); err != nil {
return err
}
}
// update namespaces configuration path
namespaces := []struct {
nstype string
ns specs.LinuxNamespaceType
checkEnabled bool
}{
{"pid", specs.PIDNamespace, false},
{"uts", specs.UTSNamespace, false},
{"ipc", specs.IPCNamespace, false},
{"mnt", specs.MountNamespace, false},
{"cgroup", specs.CgroupNamespace, false},
{"net", specs.NetworkNamespace, false},
{"user", specs.UserNamespace, true},
}
path := fmt.Sprintf("/proc/%d/ns", pid)
for _, n := range namespaces {
has, err := proc.HasNamespace(pid, n.nstype)
if err == nil && (has || n.checkEnabled) {
enabled := false
if n.checkEnabled {
if e.EngineConfig.OciConfig.Linux != nil {
for _, namespace := range e.EngineConfig.OciConfig.Linux.Namespaces {
if n.ns == namespace.Type {
enabled = true
break
}
}
}
}
if has || enabled {
nspath := filepath.Join(path, n.nstype)
e.EngineConfig.OciConfig.AddOrReplaceLinuxNamespace(n.ns, nspath)
}
} else if err != nil {
return fmt.Errorf("failed to check %s root and container namespace: %s", n.ns, err)
}
}
method := "pivot"
if !c.mntNS {
method = "chroot"
}
_, err = rpcOps.Chroot(c.rootfs, method)
if err != nil {
return fmt.Errorf("chroot failed: %s", err)
}
if e.EngineConfig.SlavePts != -1 {
if err := syscall.Close(e.EngineConfig.SlavePts); err != nil {
return fmt.Errorf("failed to close slave part: %s", err)
}
}
if e.EngineConfig.OutputStreams[0] != -1 {
if err := syscall.Close(e.EngineConfig.OutputStreams[1]); err != nil {
return fmt.Errorf("failed to close write output stream: %s", err)
}
}
if e.EngineConfig.ErrorStreams[0] != -1 {
if err := syscall.Close(e.EngineConfig.ErrorStreams[1]); err != nil {
return fmt.Errorf("failed to close write error stream: %s", err)
}
}
if e.EngineConfig.InputStreams[0] != -1 {
if err := syscall.Close(e.EngineConfig.InputStreams[1]); err != nil {
return fmt.Errorf("failed to close write input stream: %s", err)
}
}
return nil
}
func (e *EngineOperations) createState(pid int) error {
e.EngineConfig.Lock()
defer e.EngineConfig.Unlock()
name := e.CommonConfig.ContainerID
file, err := instance.Add(name, instance.OciSubDir)
if err != nil {
return err
}
e.EngineConfig.State.Version = specs.Version
e.EngineConfig.State.Bundle = e.EngineConfig.GetBundlePath()
e.EngineConfig.State.ID = e.CommonConfig.ContainerID
e.EngineConfig.State.Pid = pid
e.EngineConfig.State.Status = ociruntime.Creating
e.EngineConfig.State.Annotations = e.EngineConfig.OciConfig.Annotations
file.Config, err = json.Marshal(e.CommonConfig)
if err != nil {
return err
}
file.User = "root"
file.Pid = pid
file.PPid = os.Getpid()
file.Image = filepath.Join(e.EngineConfig.GetBundlePath(), e.EngineConfig.OciConfig.Root.Path)
if err := file.Update(); err != nil {
return err
}
socketPath := e.EngineConfig.SyncSocket
if socketPath != "" {
data, err := json.Marshal(e.EngineConfig.State)
if err != nil {
sylog.Warningf("failed to marshal state data: %s", err)
} else if err := unix.WriteSocket(socketPath, data); err != nil {
sylog.Warningf("%s", err)
}
}
return nil
}
func (e *EngineOperations) updateState(status string) error {
e.EngineConfig.Lock()
defer e.EngineConfig.Unlock()
file, err := instance.Get(e.CommonConfig.ContainerID, instance.OciSubDir)
if err != nil {
return err
}
// do nothing if already stopped
if e.EngineConfig.State.Status == ociruntime.Stopped {
return nil
}
oldStatus := e.EngineConfig.State.Status
e.EngineConfig.State.Status = specs.ContainerState(status)
t := time.Now().UnixNano()
switch status {
case ociruntime.Created:
if e.EngineConfig.State.CreatedAt == nil {
e.EngineConfig.State.CreatedAt = &t
}
case ociruntime.Running:
if e.EngineConfig.State.StartedAt == nil {
e.EngineConfig.State.StartedAt = &t
}
case ociruntime.Stopped:
if e.EngineConfig.State.FinishedAt == nil {
e.EngineConfig.State.FinishedAt = &t
}
}
file.Config, err = json.Marshal(e.CommonConfig)
if err != nil {
return err
}
if err := file.Update(); err != nil {
return err
}
socketPath := e.EngineConfig.SyncSocket
if socketPath != "" {
data, err := json.Marshal(e.EngineConfig.State)
if err != nil {
sylog.Warningf("failed to marshal state data: %s", err)
} else if err := unix.WriteSocket(socketPath, data); err != nil {
sylog.Warningf("%s", err)
}
}
// send running or stopped status right after container creation
// to notify that container process started
if statusChan != nil && oldStatus == ociruntime.Created &&
(status == ociruntime.Running || status == ociruntime.Stopped) {
statusChan <- status
}
return nil
}
// one shot function to wait on running or stopped status
func (e *EngineOperations) waitStatusUpdate() {
if statusChan == nil {
return
}
// block until status update is sent
<-statusChan
// close channel and set it to nil
close(statusChan)
statusChan = nil
}
func (c *container) addCgroups(pid int, system *mount.System) error {
name := c.engine.CommonConfig.ContainerID
resources := c.engine.EngineConfig.OciConfig.Linux.Resources
systemd := c.engine.EngineConfig.GetSystemdCgroups()
cgroupsPath := c.engine.EngineConfig.OciConfig.Linux.CgroupsPath
if !systemd && !filepath.IsAbs(cgroupsPath) {
if cgroupsPath == "" {
cgroupsPath = filepath.Join("/apptainer-oci", name)
} else {
cgroupsPath = filepath.Join("/", cgroupsPath)
}
}
if systemd && cgroupsPath == "" {
cgroupsPath = "system.slice:apptainer-oci:" + name
}
c.engine.EngineConfig.OciConfig.Linux.CgroupsPath = cgroupsPath
manager, err := cgroups.NewManagerWithSpec(resources, pid, cgroupsPath, systemd)
if err != nil {
return fmt.Errorf("failed to apply cgroups resources restriction: %s", err)
}
// If a mount point exists for a cgroup v1 hierarchy we will handle it here.
// This is not necessary for cgroups v2 - as the unified hierarchy will be handled with a simple bind.
if c.cgroupV1MountIndex >= 0 {
m := c.engine.EngineConfig.OciConfig.Config.Mounts[c.cgroupV1MountIndex]
c.engine.EngineConfig.OciConfig.Config.Mounts = append(
c.engine.EngineConfig.OciConfig.Config.Mounts[:c.cgroupV1MountIndex],
c.engine.EngineConfig.OciConfig.Config.Mounts[c.cgroupV1MountIndex+1:]...,
)
cgroupRootPath, err := manager.GetCgroupRootPath()
if err != nil {
return fmt.Errorf("failed to determine cgroup root path: %w", err)
}
flags, opt := mount.ConvertOptions(m.Options)
options := strings.Join(opt, ",")
readOnly := false
if flags&syscall.MS_RDONLY != 0 {
readOnly = true
flags &^= uintptr(syscall.MS_RDONLY)
}
hasMode := false
for _, o := range opt {
if strings.HasPrefix(o, "mode=") {
hasMode = true
break
}
}
if !hasMode {
options += ",mode=755"
}
if err := system.Points.AddFS(mount.OtherTag, m.Destination, "tmpfs", flags, options); err != nil {
return err
}
createSymlinks := func(*mount.System) error {
cgroupPath := filepath.Join(c.rpcRoot, c.rootfs, m.Destination)
if _, err := os.Stat(filepath.Join(cgroupPath, "cpu")); err != nil && os.IsNotExist(err) {
if err := c.rpcOps.Symlink("cpu,cpuacct", filepath.Join(c.rootfs, m.Destination, "cpu")); err != nil {
return err
}
if err := c.rpcOps.Symlink("cpu,cpuacct", filepath.Join(c.rootfs, m.Destination, "cpuacct")); err != nil {
return err
}
}
if _, err := os.Stat(filepath.Join(cgroupPath, "net_cls")); err != nil && os.IsNotExist(err) {
if err := c.rpcOps.Symlink("net_cls,net_prio", filepath.Join(c.rootfs, m.Destination, "net_cls")); err != nil {
return err
}
if err := c.rpcOps.Symlink("net_cls,net_prio", filepath.Join(c.rootfs, m.Destination, "net_prio")); err != nil {
return err
}
}
return nil
}
if err := system.RunAfterTag(mount.OtherTag, createSymlinks); err != nil {
return err
}
f, err := os.Open(fmt.Sprintf("/proc/%d/cgroup", pid))
if err != nil {
return err
}
defer f.Close()
flags |= uintptr(syscall.MS_BIND)
if readOnly {
flags |= syscall.MS_RDONLY
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
cgroupLine := strings.Split(scanner.Text(), ":")
if strings.HasPrefix(cgroupLine[1], "name=") {
cgroupLine[1] = strings.Replace(cgroupLine[1], "name=", "", 1)
}
if cgroupLine[1] != "" {
source := filepath.Join(cgroupRootPath, cgroupLine[1], cgroupLine[2])
dest := filepath.Join(m.Destination, cgroupLine[1])
if err := system.Points.AddBind(mount.OtherTag, source, dest, flags); err != nil {
return err
}
if readOnly {
if err := system.Points.AddRemount(mount.OtherTag, dest, flags); err != nil {
return err
}
}
}
}
if readOnly {
if err := system.Points.AddRemount(mount.FinalTag, m.Destination, flags); err != nil {
return err
}
}
}
c.engine.EngineConfig.Cgroups = manager
return nil
}
func (c *container) addAllPaths(system *mount.System) error {
// add masked path
if err := c.addMaskedPathsMount(system); err != nil {
return err
}
// add read-only path
if !c.userNS {
if err := c.addReadonlyPathsMount(system); err != nil {
return err
}
}
return nil
}
func (c *container) addRootfsMount(system *mount.System) error {
flags := uintptr(syscall.MS_BIND)
if c.engine.EngineConfig.OciConfig.Root.Readonly {
sylog.Debugf("Mounted read-only")
flags |= syscall.MS_RDONLY
}
parentRootfs, err := proc.ParentMount(c.rootfs)
if err != nil {
return err
}
sylog.Debugf("Parent rootfs: %s", parentRootfs)
if err := c.rpcOps.Mount("", parentRootfs, "", syscall.MS_PRIVATE, ""); err != nil {
return err
}
if err := system.Points.AddBind(mount.RootfsTag, c.rootfs, c.rootfs, flags); err != nil {
return err
}
if flags&syscall.MS_RDONLY != 0 {
return system.Points.AddRemount(mount.FinalTag, c.rootfs, flags)
}
return nil
}
func (c *container) addDefaultDevices(system *mount.System) error {
oldmask := syscall.Umask(0)
defer syscall.Umask(oldmask)
rootfsPath := filepath.Join(c.rpcRoot, c.rootfs)
devPath := filepath.Join(rootfsPath, fs.EvalRelative("/dev", rootfsPath))
if _, err := os.Lstat(devPath); os.IsNotExist(err) {
if err := os.Mkdir(devPath, 0o755); err != nil {
return err
}
}
for _, symlink := range symlinkDevices {
path := filepath.Join(rootfsPath, symlink.new)
if _, err := os.Lstat(path); os.IsNotExist(err) {
if c.userNS {
path = filepath.Join(c.rootfs, symlink.new)
if err := c.rpcOps.Symlink(symlink.old, path); err != nil {
return err
}
} else {
if err := os.Symlink(symlink.old, path); err != nil {
return err
}
}
}
}
if c.engine.EngineConfig.OciConfig.Process.Terminal {
path := filepath.Join(rootfsPath, "dev", "console")
if _, err := os.Lstat(path); os.IsNotExist(err) {
if c.userNS {
if _, err := c.rpcOps.Touch(filepath.Join(c.rootfs, "dev", "console")); err != nil {
return err
}
} else {
if err := fs.Touch(path); err != nil {
return err
}
}
path = fmt.Sprintf("/proc/self/fd/%d", c.engine.EngineConfig.SlavePts)
console, err := os.Readlink(path)
if err != nil {
return err
}
if err := system.Points.AddBind(mount.OtherTag, console, "/dev/console", syscall.MS_BIND); err != nil {
return err
}
}
}
for _, device := range devices {
dev := int((device.major << 8) | (device.minor & 0xff) | ((device.minor & 0xfff00) << 12))
path := filepath.Join(rootfsPath, device.path)
if _, err := os.Lstat(path); os.IsNotExist(err) {
if c.userNS {
path = filepath.Join(c.rootfs, device.path)
if _, err := os.Stat(device.path); os.IsNotExist(err) {
sylog.Debugf("skipping mount, %s doesn't exists", device.path)
continue
}
dirpath := filepath.Dir(path)
if _, err := c.rpcOps.MkdirAll(dirpath, 0o755); err != nil {
return fmt.Errorf("could not create parent directory %s: %s", dirpath, err)
}
if _, err := c.rpcOps.Touch(path); err != nil {
return fmt.Errorf("could not create file %s: %s", path, err)
}
if err := c.rpcOps.Mount(device.path, path, "", syscall.MS_BIND, ""); err != nil {
return fmt.Errorf("could not mount %s to %s: %s", device.path, path, err)
}
} else {
dirpath := filepath.Dir(path)
if err := os.MkdirAll(dirpath, 0o755); err != nil {
return fmt.Errorf("could not create parent directory %s: %s", dirpath, err)
}
if err := syscall.Mknod(path, uint32(device.mode), dev); err != nil {
return fmt.Errorf("could not create device %s: %s", path, err)
}
if device.uid != 0 || device.gid != 0 {
if err := os.Chown(path, device.uid, device.gid); err != nil {
return fmt.Errorf("could not change %s owner: %s", path, err)
}
}
}
}
}
return nil
}
func (c *container) addDevices(system *mount.System) error {
for _, d := range c.engine.EngineConfig.OciConfig.Linux.Devices {
var dev device
if d.Path == "" {
return fmt.Errorf("device path required")
}
dev.path = d.Path
if d.FileMode != nil {
dev.mode = *d.FileMode
} else {
dev.mode = 0o644
}
switch d.Type {
case "c", "u":
dev.mode |= syscall.S_IFCHR
dev.major = d.Major
dev.minor = d.Minor
case "b":
dev.mode |= syscall.S_IFBLK
dev.major = d.Major
dev.minor = d.Minor
case "p":
dev.mode |= syscall.S_IFIFO
default:
return fmt.Errorf("device type unknown for %s", d.Path)
}
if d.UID != nil {
dev.uid = int(*d.UID)
}
if d.GID != nil {
dev.gid = int(*d.GID)
}
devices = append(devices, dev)
}
if c.devIndex >= 0 {
m := &c.engine.EngineConfig.OciConfig.Config.Mounts[c.devIndex]
flags, _ := mount.ConvertOptions(m.Options)
flags |= uintptr(syscall.MS_BIND)
if flags&syscall.MS_RDONLY != 0 {
if err := system.Points.AddRemount(mount.FinalTag, m.Destination, flags); err != nil {
return err
}
for i := len(m.Options) - 1; i >= 0; i-- {
if m.Options[i] == "ro" {
m.Options = append(m.Options[:i], m.Options[i+1:]...)
break
}
}
}
if c.engine.EngineConfig.OciConfig.Linux.Resources == nil {
c.engine.EngineConfig.OciConfig.Linux.Resources = &specs.LinuxResources{}
}
// cgroupDevices are essential for operation, so must be allowed *prior* to a configured wildcard deny.
c.engine.EngineConfig.OciConfig.Linux.Resources.Devices = append(cgroupDevices, c.engine.EngineConfig.OciConfig.Linux.Resources.Devices...)
}
return nil
}
func (c *container) addMaskedPathsMount(system *mount.System) error {
paths := c.engine.EngineConfig.OciConfig.Linux.MaskedPaths
dir, err := instance.GetDir(c.engine.CommonConfig.ContainerID, instance.OciSubDir)
if err != nil {
return err
}
nullPath := filepath.Join(dir, "null")
if _, err := os.Stat(nullPath); os.IsNotExist(err) {
oldmask := syscall.Umask(0)
defer syscall.Umask(oldmask)
if err := os.Mkdir(nullPath, 0o755); err != nil {
return err
}
}
for _, path := range paths {
relativePath := filepath.Join(c.rootfs, path)
rpcPath := filepath.Join(c.rpcRoot, relativePath)
fi, err := os.Stat(rpcPath)
if err != nil {
sylog.Debugf("ignoring masked path %s: %s", path, err)
continue
}
if fi.IsDir() {
if err := system.Points.AddBind(mount.OtherTag, nullPath, relativePath, syscall.MS_BIND); err != nil {
return err
}
} else if err := system.Points.AddBind(mount.OtherTag, "/dev/null", relativePath, syscall.MS_BIND); err != nil {
return err
}
}
return nil
}
func (c *container) addReadonlyPathsMount(system *mount.System) error {
paths := c.engine.EngineConfig.OciConfig.Linux.ReadonlyPaths
for _, path := range paths {
relativePath := filepath.Join(c.rootfs, path)
rpcPath := filepath.Join(c.rpcRoot, relativePath)
_, err := os.Stat(rpcPath)
if err != nil {
sylog.Debugf("ignoring read-only path %s: %s", path, err)
continue
}
if err := system.Points.AddBind(mount.OtherTag, relativePath, relativePath, syscall.MS_BIND|syscall.MS_RDONLY); err != nil {
return err
}
if err := system.Points.AddRemount(mount.OtherTag, relativePath, syscall.MS_BIND|syscall.MS_RDONLY); err != nil {
return err
}
}
return nil
}
func (c *container) mount(point *mount.Point, _ *mount.System) error {
source := point.Source
dest := point.Destination
flags, opts := mount.ConvertOptions(point.Options)
optsString := strings.Join(opts, ",")
ignore := false
if flags&syscall.MS_REMOUNT != 0 {
ignore = true
}
if !strings.HasPrefix(dest, c.rootfs) {
rootfsPath := filepath.Join(c.rpcRoot, c.rootfs)
relativeDest := fs.EvalRelative(dest, c.rootfs)
procDest := filepath.Join(rootfsPath, relativeDest)
dest = filepath.Join(c.rootfs, relativeDest)
sylog.Debugf("Checking if %s exists", procDest)
if _, err := os.Stat(procDest); os.IsNotExist(err) && !ignore {
oldmask := syscall.Umask(0)
defer syscall.Umask(oldmask)
if point.Type != "" {
sylog.Debugf("Creating %s", procDest)
if c.userNS {
if _, err := c.rpcOps.MkdirAll(dest, 0o755); err != nil {
return err
}
} else {
if err := os.MkdirAll(procDest, 0o755); err != nil {
return err
}
}
} else {
var st syscall.Stat_t
dir := filepath.Dir(procDest)
if _, err := os.Stat(dir); os.IsNotExist(err) {
sylog.Debugf("Creating parent %s", dir)
if c.userNS {
if err := c.rpcOps.Mkdir(filepath.Dir(dest), 0o755); err != nil {
return err
}
} else {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
}
}
if err := syscall.Stat(source, &st); err != nil {
sylog.Debugf("Ignoring %s: %s", source, err)
return nil
}
switch st.Mode & syscall.S_IFMT {
case syscall.S_IFDIR:
sylog.Debugf("Creating dir %s", filepath.Base(procDest))
if c.userNS {
if err := c.rpcOps.Mkdir(dest, 0o755); err != nil {
return err
}
} else {
if err := os.Mkdir(procDest, 0o755); err != nil {
return err
}
}
case syscall.S_IFREG,
syscall.S_IFBLK,
syscall.S_IFCHR,
syscall.S_IFIFO,
syscall.S_IFSOCK:
sylog.Debugf("Creating file %s", filepath.Base(procDest))
if c.userNS {
if _, err := c.rpcOps.Touch(dest); err != nil {
return err
}
} else {
if err := fs.Touch(procDest); err != nil {
return err
}
}
}
}
}
} else {
procDest := filepath.Join(c.rpcRoot, dest)
sylog.Debugf("Checking if %s exists", procDest)
if _, err := os.Stat(procDest); os.IsNotExist(err) {
sylog.Warningf("destination %s doesn't exist", dest)
return nil
}
}
if ignore {
sylog.Debugf("(re)mount %s", dest)
} else {
sylog.Debugf("Mount %s to %s : %s [%s]", source, dest, point.Type, optsString)
}
err := c.rpcOps.Mount(source, dest, point.Type, flags, optsString)
if err != nil {
sylog.Debugf("RPC mount error: %s", err)
}
return err
}
|