github.com/hpcng/singularity@v3.1.1+incompatible/pkg/util/namespaces/setns_linux.go (about)

     1  // Copyright (c) 2018, Sylabs Inc. All rights reserved.
     2  // This software is licensed under a 3-clause BSD license. Please consult the
     3  // LICENSE.md file distributed with the sources of this project regarding your
     4  // rights to use or distribute this software.
     5  
     6  // +build go1.10
     7  
     8  package namespaces
     9  
    10  import (
    11  	"fmt"
    12  	"os"
    13  	"runtime"
    14  	"syscall"
    15  )
    16  
    17  var setnsSysNo = map[string]uintptr{
    18  	"386":     346,
    19  	"arm64":   268,
    20  	"amd64":   308,
    21  	"arm":     375,
    22  	"ppc":     350,
    23  	"ppc64":   350,
    24  	"ppc64le": 350,
    25  	"s390x":   339,
    26  }
    27  
    28  var nsMap = map[string]uintptr{
    29  	"ipc": syscall.CLONE_NEWIPC,
    30  	"net": syscall.CLONE_NEWNET,
    31  	"mnt": syscall.CLONE_NEWNS,
    32  	"uts": syscall.CLONE_NEWUTS,
    33  }
    34  
    35  // Enter enters in provided process namespace.
    36  func Enter(pid int, namespace string) error {
    37  	flag, ok := nsMap[namespace]
    38  	if !ok {
    39  		return fmt.Errorf("namespace %s not supported", namespace)
    40  	}
    41  
    42  	path := fmt.Sprintf("/proc/%d/ns/%s", pid, namespace)
    43  	f, err := os.Open(path)
    44  	if err != nil {
    45  		return fmt.Errorf("can't open namespace path %s: %s", path, err)
    46  	}
    47  	defer f.Close()
    48  
    49  	ns, ok := setnsSysNo[runtime.GOARCH]
    50  	if !ok {
    51  		return fmt.Errorf("unsupported platform %s", runtime.GOARCH)
    52  	}
    53  
    54  	_, _, errSys := syscall.RawSyscall(ns, f.Fd(), flag, 0)
    55  	if errSys != 0 {
    56  		return errSys
    57  	}
    58  
    59  	return nil
    60  }