github.com/maier/nomad@v0.4.1-0.20161110003312-a9e3d0b8549d/client/allocdir/alloc_dir_unix.go (about)

     1  // +build darwin dragonfly freebsd linux netbsd openbsd solaris
     2  
     3  // Functions shared between linux/darwin.
     4  package allocdir
     5  
     6  import (
     7  	"fmt"
     8  	"os"
     9  	"os/user"
    10  	"path/filepath"
    11  	"strconv"
    12  
    13  	"golang.org/x/sys/unix"
    14  )
    15  
    16  var (
    17  	// SharedAllocContainerPath is the path inside container for mounted
    18  	// directory shared across tasks in a task group.
    19  	SharedAllocContainerPath = filepath.Join("/", SharedAllocName)
    20  
    21  	// TaskLocalContainer is the path inside a container for mounted directory
    22  	// for local storage.
    23  	TaskLocalContainerPath = filepath.Join("/", TaskLocal)
    24  
    25  	// TaskSecretsContainerPath is the path inside a container for mounted
    26  	// secrets directory
    27  	TaskSecretsContainerPath = filepath.Join("/", TaskSecrets)
    28  )
    29  
    30  func (d *AllocDir) linkOrCopy(src, dst string, perm os.FileMode) error {
    31  	// Avoid link/copy if the file already exists in the chroot
    32  	// TODO 0.6 clean this up. This was needed because chroot creation fails
    33  	// when a process restarts.
    34  	if fileInfo, _ := os.Stat(dst); fileInfo != nil {
    35  		return nil
    36  	}
    37  	// Attempt to hardlink.
    38  	if err := os.Link(src, dst); err == nil {
    39  		return nil
    40  	}
    41  
    42  	return fileCopy(src, dst, perm)
    43  }
    44  
    45  func (d *AllocDir) dropDirPermissions(path string) error {
    46  	if err := os.Chmod(path, 0777); err != nil {
    47  		return fmt.Errorf("Chmod(%v) failed: %v", path, err)
    48  	}
    49  
    50  	// Can't change owner if not root.
    51  	if unix.Geteuid() != 0 {
    52  		return nil
    53  	}
    54  
    55  	u, err := user.Lookup("nobody")
    56  	if err != nil {
    57  		return err
    58  	}
    59  
    60  	uid, err := getUid(u)
    61  	if err != nil {
    62  		return err
    63  	}
    64  
    65  	gid, err := getGid(u)
    66  	if err != nil {
    67  		return err
    68  	}
    69  
    70  	if err := os.Chown(path, uid, gid); err != nil {
    71  		return fmt.Errorf("Couldn't change owner/group of %v to (uid: %v, gid: %v): %v", path, uid, gid, err)
    72  	}
    73  
    74  	return nil
    75  }
    76  
    77  func getUid(u *user.User) (int, error) {
    78  	uid, err := strconv.Atoi(u.Uid)
    79  	if err != nil {
    80  		return 0, fmt.Errorf("Unable to convert Uid to an int: %v", err)
    81  	}
    82  
    83  	return uid, nil
    84  }
    85  
    86  func getGid(u *user.User) (int, error) {
    87  	gid, err := strconv.Atoi(u.Gid)
    88  	if err != nil {
    89  		return 0, fmt.Errorf("Unable to convert Gid to an int: %v", err)
    90  	}
    91  
    92  	return gid, nil
    93  }