Beispiel #1
0
func TestExecRequest(t *testing.T) {
	StartTest(t)
	defer FinishTest(t)
	TestRequiresRoot(t)

	// Start the initd process.
	cgroup, socket, _, pid := StartInitd(t)

	// Make a request against the initd server.
	dir := TempDir(t)
	stdout := path.Join(dir, "stdout")
	stderr := path.Join(dir, "stderr")
	cmd := []string{"/bin/sleep", "60"}
	request := [][]string{
		[]string{"EXEC"},
		cmd,
		[]string{"KTEST=VTEST"},
		[]string{stdout, stderr},
	}
	reply, err := MakeRequest(socket, request, 10*time.Second)
	TestExpectSuccess(t, err)
	TestEqual(t, reply, "REQUEST OK\n")
	sleepPid, tasks := waitTask(t, cgroup, cmd, 5*time.Second)

	// Check the command line of both the tasks and see if the proper process
	// tree exists for what we would expect:
	// 		(parent) /sbin/sleep
	//		    |--- (child) os.Argv[0]
	// Ensure correct parent properties
	cmdline, env, ppid, children := taskInfo(t, sleepPid)
	TestEqual(t, cmdline, []string{"/bin/sleep", "60"})
	TestEqual(t, env, []string{"KTEST=VTEST"})
	TestEqual(t, ppid, pid)
	TestEqual(t, children, []int{tasks[2]})

	// Ensure correct child properties
	_, t1env, t1ppid, t1children := taskInfo(t, tasks[2])
	TestEqual(t, t1env, []string{"INITD_DEBUG=1", "INITD_INTERCEPT=1", "INITD_SOCKET=" + socket})
	TestEqual(t, t1ppid, tasks[1])
	TestEqual(t, t1children, []int{})

	// Check the three normal file descriptors, 0 -> /dev/null, 1 -> stdout,
	// 2 -> stderr (stdout/stderr were allocated earlier.)
	stdinLink, err := os.Readlink(fmt.Sprintf("/proc/%d/fd/0", sleepPid))
	TestExpectSuccess(t, err)
	TestEqual(t, stdinLink, "/dev/null")
	stdoutLink, err := os.Readlink(fmt.Sprintf("/proc/%d/fd/1", sleepPid))
	TestExpectSuccess(t, err)
	TestEqual(t, stdoutLink, stdout)
	stderrLink, err := os.Readlink(fmt.Sprintf("/proc/%d/fd/2", sleepPid))
	TestExpectSuccess(t, err)
	TestEqual(t, stderrLink, stderr)

	// Check that the file descriptors on the sleep binary are all closed and
	// nothing was shared that was not supposed to be. Walk the list and check
	// that each and every value is normal.
	dirs, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", sleepPid))
	TestExpectSuccess(t, err)
	TestEqual(t, len(dirs), 3)
}
Beispiel #2
0
func TestPrune(t *testing.T) {
	sb := FakeServiceBuilder()
	defer os.RemoveAll(sb.ConfigRoot)
	defer os.RemoveAll(sb.StagingRoot)
	defer os.RemoveAll(sb.RunitRoot)

	// first create the service
	err := sb.Activate("foo", fakeTemplate)
	Assert(t).IsNil(err, "should have activated service")
	_, err = os.Readlink(filepath.Join(sb.RunitRoot, "foo"))
	Assert(t).IsNil(err, "should have created activation symlink")

	// now remove the service's yaml file
	err = sb.Activate("foo", map[string]ServiceTemplate{})
	Assert(t).IsNil(err, "should have activated service")
	// symlink should still exist, haven't pruned yet
	_, err = os.Readlink(filepath.Join(sb.RunitRoot, "foo"))
	Assert(t).IsNil(err, "should have created activation symlink")

	err = sb.Prune()
	Assert(t).IsNil(err, "should have pruned")
	_, err = os.Readlink(filepath.Join(sb.RunitRoot, "foo"))
	Assert(t).IsTrue(os.IsNotExist(err), "should have removed activation symlink")
	_, err = os.Stat(filepath.Join(sb.StagingRoot, "foo"))
	Assert(t).IsTrue(os.IsNotExist(err), "should have removed staging dir")
}
Beispiel #3
0
func NamespacePostStart(output string) error {
	nsout := utils.GetBetweenStr(output, "[namespace_output_start]", "[namespace_output_end]")
	if strings.EqualFold(nsout, "") {
		return nil
	}
	for _, ns := range strings.Split(nsout, "\n") {
		if !strings.EqualFold(ns, "") {
			if len(strings.Split(ns, ",")) != 2 {
				break
			}
			linkc := strings.Split(ns, ",")[0]
			if len(strings.Split(linkc, ",")) != 2 {
				break
			}
			nsname := strings.Split(linkc, ":")[0]
			path := strings.Split(ns, ",")[1]
			if !strings.EqualFold(path, "") {
				linkh, _ := os.Readlink(path)
				if !strings.EqualFold(linkh, linkc) {
					return fmt.Errorf("%v namespace expected: %v, actual: %v ",
						nsname, linkh, linkc)

				}
			}
			if strings.EqualFold(path, "") {
				linkh, _ := os.Readlink("/proc/1/ns/" + nsname)
				if strings.EqualFold(linkh, linkc) {
					return fmt.Errorf("namespace %v path is empty, but namespace inside and "+
						"outside container is the same", nsname)
				}
			}
		}
	}
	return nil
}
Beispiel #4
0
// checkHostNs checks whether network sysctl is used in host namespace.
func checkHostNs(sysctlConfig string, path string) error {
	var currentProcessNetns = "/proc/self/ns/net"
	// readlink on the current processes network namespace
	destOfCurrentProcess, err := os.Readlink(currentProcessNetns)
	if err != nil {
		return fmt.Errorf("read soft link %q error", currentProcessNetns)
	}

	// First check if the provided path is a symbolic link
	symLink, err := isSymbolicLink(path)
	if err != nil {
		return fmt.Errorf("could not check that %q is a symlink: %v", path, err)
	}

	if symLink == false {
		// The provided namespace is not a symbolic link,
		// it is not the host namespace.
		return nil
	}

	// readlink on the path provided in the struct
	destOfContainer, err := os.Readlink(path)
	if err != nil {
		return fmt.Errorf("read soft link %q error", path)
	}
	if destOfContainer == destOfCurrentProcess {
		return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", sysctlConfig)
	}
	return nil
}
Beispiel #5
0
// ExecInCoreSnap makes sure you're executing the binary that ships in
// the core snap.
func ExecInCoreSnap() {
	if !release.OnClassic {
		// you're already the real deal, natch
		return
	}

	if os.Getenv(key) != "1" {
		return
	}

	exe, err := os.Readlink("/proc/self/exe")
	if err != nil {
		return
	}

	full := filepath.Join(newCore, exe)
	if !osutil.FileExists(full) {
		if rev, err := os.Readlink(oldCore); err != nil {
			return
		} else if revno, err := strconv.Atoi(rev); err != nil || revno < minOldRevno {
			return
		}

		full = filepath.Join(oldCore, exe)
		if !osutil.FileExists(full) {
			return
		}
	}

	logger.Debugf("restarting into %q", full)

	env := append(os.Environ(), key+"=0")
	panic(syscall.Exec(full, os.Args, env))
}
Beispiel #6
0
func executable() (string, error) {
	switch runtime.GOOS {
	case "linux":
		const deletedTag = " (deleted)"
		execpath, err := os.Readlink("/proc/self/exe")
		if err != nil {
			return execpath, err
		}
		execpath = strings.TrimSuffix(execpath, deletedTag)
		execpath = strings.TrimPrefix(execpath, deletedTag)
		return execpath, nil
	case "netbsd":
		return os.Readlink("/proc/curproc/exe")
	case "dragonfly":
		return os.Readlink("/proc/curproc/file")
	case "solaris":
		return os.Readlink(fmt.Sprintf("/proc/%d/path/a.out", os.Getpid()))
	//
	case "freebsd":
		return executablesysctl()
	case "darwin":
		return executablesysctl()
	case "openbsd":
		return executablesysctl()
	}
	return "", errors.New("ExecPath not implemented for " + runtime.GOOS)
}
Beispiel #7
0
func gcNetworking(podID *types.UUID) error {
	var flavor string
	// we first try to read the flavor from stage1 for backwards compatibility
	flavor, err := os.Readlink(filepath.Join(common.Stage1RootfsPath("."), "flavor"))
	if err != nil {
		// if we couldn't read the flavor from stage1 it could mean the overlay
		// filesystem is already unmounted (e.g. the system has been rebooted).
		// In that case we try to read it from the pod's root directory
		flavor, err = os.Readlink("flavor")
		if err != nil {
			return errwrap.Wrap(errors.New("failed to get stage1 flavor"), err)
		}
	}

	n, err := networking.Load(".", podID)
	switch {
	case err == nil:
		n.Teardown(flavor, debug)
	case os.IsNotExist(err):
		// probably ran with --net=host
	default:
		return errwrap.Wrap(errors.New("failed loading networking state"), err)
	}

	return nil
}
// checkStatusTxt - read file "filename" and verify that it contains
// "It works!\n"
func checkExampleFS(t *testing.T, dir string) {
	// Read regular file
	statusFile := filepath.Join(dir, "status.txt")
	contentBytes, err := ioutil.ReadFile(statusFile)
	if err != nil {
		t.Fatal(err)
	}
	content := string(contentBytes)
	if content != statusTxtContent {
		t.Errorf("Unexpected content: %s\n", content)
	}
	// Read relative symlink
	symlink := filepath.Join(dir, "rel")
	target, err := os.Readlink(symlink)
	if err != nil {
		t.Fatal(err)
	}
	if target != "status.txt" {
		t.Errorf("Unexpected link target: %s\n", target)
	}
	// Read absolute symlink
	symlink = filepath.Join(dir, "abs")
	target, err = os.Readlink(symlink)
	if err != nil {
		t.Fatal(err)
	}
	if target != "/a/b/c/d" {
		t.Errorf("Unexpected link target: %s\n", target)
	}
	// Test directory operations
	testRename(t, dir)
	testMkdirRmdir(t, dir)
}
Beispiel #9
0
// Prune will attempt to get the total size of the launchable's installs
// directory to be equal to or less than the maximum specified number of
// bytes. This method will preserve any directories that are pointed to
// by the `current` or `last` symlinks. Installations will be removed from
// oldest to newest.
func (hl *Launchable) Prune(maxSize size.ByteCount) error {
	curTarget, err := os.Readlink(hl.CurrentDir())
	if os.IsNotExist(err) {
		curTarget = ""
	} else if err != nil {
		return err
	}
	curTarget = filepath.Base(curTarget)

	lastTarget, err := os.Readlink(hl.LastDir())
	if os.IsNotExist(err) {
		lastTarget = ""
	} else if err != nil {
		return err
	}
	lastTarget = filepath.Base(lastTarget)

	installs, err := ioutil.ReadDir(hl.AllInstallsDir())
	if os.IsNotExist(err) {
		return nil
	} else if err != nil {
		return err
	}

	var totalSize size.ByteCount = 0

	installSizes := map[string]size.ByteCount{}

	for _, i := range installs {
		installSize, err := hl.sizeOfInstall(i.Name())
		if err != nil {
			return err
		}
		totalSize += size.ByteCount(installSize)
		installSizes[i.Name()] = installSize
	}

	oldestFirst := installsByAge(installs)
	sort.Sort(oldestFirst)

	for _, i := range oldestFirst {
		if totalSize <= maxSize {
			return nil
		}

		if i.Name() == curTarget || i.Name() == lastTarget {
			continue
		}

		installSize := installSizes[i.Name()]
		err = os.RemoveAll(filepath.Join(hl.AllInstallsDir(), i.Name()))
		if err != nil {
			return err
		}
		totalSize = totalSize - size.ByteCount(installSize)
	}

	return nil
}
Beispiel #10
0
// InContainer detects if a process is running in a Linux container.
func InContainer(pid string) bool {
	pidNameSpaceFile := fmt.Sprintf("/proc/%v/ns/pid", pid)
	if pidNameSpace, err := os.Readlink(pidNameSpaceFile); err == nil {
		if initNameSpace, err := os.Readlink("/proc/1/ns/pid"); err == nil {
			return initNameSpace != pidNameSpace
		}
	}
	return false
}
Beispiel #11
0
func (lr *LocalRepository) JumpBack(pkgName string) error {
	currentLinkPath := lr.currentRevisionFilePath(pkgName)
	previousLinkPath := lr.previousRevisionFilePath(pkgName)

	currentRevision := lr.GetCurrentRevision(pkgName)
	previousRevision := lr.GetPreviousRevision(pkgName)

	previousRevPath, err := os.Readlink(previousLinkPath)
	if err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("There is no previous revision")
		}
		return fmt.Errorf("Failed to read previous version: %v", err)
	}

	currentRevPath, err := os.Readlink(currentLinkPath)
	if err != nil {
		return fmt.Errorf("Failed to read current version: %v", err)
	}

	err = lr.RunPackageScript(previousRevision, PKG_SCRIPT_PRE_JUMP)
	if err != nil {
		return err
	}

	err = lr.RunPackageScript(currentRevision, PKG_SCRIPT_UN_JUMP)
	if err != nil {
		return err
	}

	err = os.Remove(currentLinkPath)
	if err != nil {
		return fmt.Errorf("Failed to remove current version: %v", err)
	}

	err = os.Symlink(previousRevPath, currentLinkPath)
	if err != nil {
		return fmt.Errorf("Failed creating symlink", err)
	}

	err = os.Remove(previousLinkPath)
	if err != nil {
		return fmt.Errorf("Failed to remove previous version: %v", err)
	}

	err = os.Symlink(currentRevPath, previousLinkPath)
	if err != nil {
		fmt.Println("Failed creating symlink", err)
	}

	err = lr.RunPackageScript(previousRevision, PKG_SCRIPT_POST_JUMP)
	if err != nil {
		return err
	}

	return nil
}
Beispiel #12
0
func getTags(bdev string) map[string]string {
	backingDevFile, _ := os.Readlink(bdev)
	backingDevPath := strings.Split(backingDevFile, "/")
	backingDev := backingDevPath[len(backingDevPath)-2]

	bcacheDevFile, _ := os.Readlink(bdev + "/dev")
	bcacheDevPath := strings.Split(bcacheDevFile, "/")
	bcacheDev := bcacheDevPath[len(bcacheDevPath)-1]

	return map[string]string{"backing_dev": backingDev, "bcache_dev": bcacheDev}
}
Beispiel #13
0
func executable() (string, error) {
	switch runtime.GOOS {
	case "linux":
		return os.Readlink("/proc/self/exe")
	case "netbsd":
		return os.Readlink("/proc/curproc/exe")
	case "openbsd":
		return os.Readlink("/proc/curproc/file")
	}
	return "", errors.New("ExecPath not implemented for " + runtime.GOOS)
}
Beispiel #14
0
func getProcessInfo(pid int32) (*processInfo, error) {
	info := &processInfo{Pid: pid}
	var err error

	info.Path, err = os.Readlink(procFilePath(int(pid), "exe"))
	if err != nil {
		return nil, err
	}

	info.Cwd, err = os.Readlink(procFilePath(int(pid), "cwd"))
	if err != nil {
		return nil, err
	}

	info.Root, err = os.Readlink(procFilePath(int(pid), "root"))
	if err != nil {
		return nil, err
	}

	rawCmdline, err := ioutil.ReadFile(procFilePath(int(pid), "cmdline"))
	if err != nil {
		return nil, err
	}

	if len(rawCmdline) > 0 {
		rawCmdline = bytes.TrimRight(rawCmdline, "\x00")
		//NOTE: later/future (when we do more app analytics)
		//split rawCmdline and resolve the "entry point" (exe or cmd param)
		info.Cmd = string(bytes.Replace(rawCmdline, []byte("\x00"), []byte(" "), -1))
	}

	//note: will need to get "environ" at some point :)
	//rawEnviron, err := ioutil.ReadFile(procFilePath(int(pid), "environ"))
	//if err != nil {
	//	return nil, err
	//}
	//if len(rawEnviron) > 0 {
	//	rawEnviron = bytes.TrimRight(rawEnviron,"\x00")
	//	info.Env = strings.Split(string(rawEnviron),"\x00")
	//}

	stat, err := ioutil.ReadFile(procFilePath(int(pid), "stat"))
	var procPid int
	var procName string
	var procStatus string
	var procPpid int
	fmt.Sscanf(string(stat), "%d %s %s %d", &procPid, &procName, &procStatus, &procPpid)

	info.Name = procName[1 : len(procName)-1]
	info.ParentPid = int32(procPpid)

	return info, nil
}
func isProcessRunningInHost(pid int) (bool, error) {
	// Get init mount namespace. Mount namespace is unique for all containers.
	initMntNs, err := os.Readlink("/proc/1/ns/mnt")
	if err != nil {
		return false, fmt.Errorf("failed to find mount namespace of init process")
	}
	processMntNs, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/mnt", pid))
	if err != nil {
		return false, fmt.Errorf("failed to find mount namespace of process %q", pid)
	}
	return initMntNs == processMntNs, nil
}
Beispiel #16
0
func executable() (string, error) {
	switch runtime.GOOS {
	case "linux":
		return os.Readlink("/proc/self/exe")
	case "netbsd":
		return os.Readlink("/proc/curproc/exe")
	case "openbsd", "dragonfly":
		return os.Readlink("/proc/curproc/file")
	case "solaris":
		return os.Readlink(fmt.Sprintf("/proc/%d/path/a.out", os.Getpid()))
	}
	return "", errors.New("ExecPath not implemented for " + runtime.GOOS)
}
Beispiel #17
0
func verifyMountNamespace() {
	// if [[ "$(readlink /proc/1/ns/mnt)" == "$(readlink /proc/self/ns/mnt)" ]]; then
	initMountNS, err := os.Readlink("/proc/1/ns/mnt")
	if err != nil {
		Fatal("Unable to readlink(/proc/1/ns/mnt). Aborting.")
	}
	myMountNS, err := os.Readlink("/proc/self/ns/mnt")
	if err != nil {
		Fatal("Unable to readlink(/proc/self/ns/mnt). Aborting.")
	}
	if initMountNS == myMountNS {
		Fatal("Not in mount namespace. Abort.")
	}
}
func isProcessRunningInHost(pid int) (bool, error) {
	// Get init pid namespace.
	initPidNs, err := os.Readlink("/proc/1/ns/pid")
	if err != nil {
		return false, fmt.Errorf("failed to find pid namespace of init process")
	}
	glog.V(10).Infof("init pid ns is %q", initPidNs)
	processPidNs, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid))
	if err != nil {
		return false, fmt.Errorf("failed to find pid namespace of process %q", pid)
	}
	glog.V(10).Infof("Pid %d pid ns is %q", pid, processPidNs)
	return initPidNs == processPidNs, nil
}
Beispiel #19
0
func TestEnsureSymlink(t *testing.T) {
	dir, err := ioutil.TempDir("", "symlink")
	assert.NoError(t, err)

	source := path.Join(dir, "source")
	err = ioutil.WriteFile(source, []byte("source"), 0755)
	assert.NoError(t, err)

	dest := path.Join(dir, "symlink-dest")

	//
	// Case 1: Symlink does not exist
	//

	err = ensureSymlink(source, dest)
	assert.NoError(t, err)

	actual, err := os.Readlink(dest)
	assert.Equal(t, source, actual)

	//
	// Case 2: Symlink does exist
	//
	// Consists solely of re-running the previous test case.
	//

	err = ensureSymlink(source, dest)
	assert.NoError(t, err)

	actual, err = os.Readlink(dest)
	assert.Equal(t, source, actual)

	//
	// Case 3: Symlink file exists, but source doesn't
	//

	err = os.RemoveAll(dest)
	assert.NoError(t, err)

	source = path.Join(dir, "source")
	err = ioutil.WriteFile(source, []byte("source"), 0755)
	assert.NoError(t, err)

	err = ensureSymlink(source, dest)
	assert.NoError(t, err)

	actual, err = os.Readlink(dest)
	assert.Equal(t, source, actual)
}
Beispiel #20
0
func GetProcInfo(id int) (Proc, error) {
	binLinkPath := fmt.Sprintf("/proc/%d/exe", id)
	cwdLinkPath := fmt.Sprintf("/proc/%d/cwd", id)
	binPath, err := os.Readlink(binLinkPath)
	if err != nil {
		return Proc{}, err
	}

	cwdPath, err := os.Readlink(cwdLinkPath)
	if err != nil {
		return Proc{}, err
	}

	return Proc{Id: id, ExePath: binPath, CurrentDir: cwdPath}, nil
}
Beispiel #21
0
Datei: path.go Projekt: ssrl/go
// EvalSymlinks returns the path name after the evaluation of any symbolic
// links.
// If path is relative it will be evaluated relative to the current directory.
func EvalSymlinks(path string) (string, os.Error) {
	if runtime.GOOS == "windows" {
		// Symlinks are not supported under windows.
		_, err := os.Lstat(path)
		if err != nil {
			return "", err
		}
		return Clean(path), nil
	}
	const maxIter = 255
	originalPath := path
	// consume path by taking each frontmost path element,
	// expanding it if it's a symlink, and appending it to b
	var b bytes.Buffer
	for n := 0; path != ""; n++ {
		if n > maxIter {
			return "", os.NewError("EvalSymlinks: too many links in " + originalPath)
		}

		// find next path component, p
		i := strings.IndexRune(path, Separator)
		var p string
		if i == -1 {
			p, path = path, ""
		} else {
			p, path = path[:i], path[i+1:]
		}

		if p == "" {
			if b.Len() == 0 {
				// must be absolute path
				b.WriteRune(Separator)
			}
			continue
		}

		fi, err := os.Lstat(b.String() + p)
		if err != nil {
			return "", err
		}
		if !fi.IsSymlink() {
			b.WriteString(p)
			if path != "" {
				b.WriteRune(Separator)
			}
			continue
		}

		// it's a symlink, put it at the front of path
		dest, err := os.Readlink(b.String() + p)
		if err != nil {
			return "", err
		}
		if IsAbs(dest) {
			b.Reset()
		}
		path = dest + string(Separator) + path
	}
	return Clean(b.String()), nil
}
Beispiel #22
0
// mirrorLocalZoneInfo tries to reproduce the /etc/localtime target in stage1/ to satisfy systemd-nspawn
func mirrorLocalZoneInfo(root string) {
	zif, err := os.Readlink(localtimePath)
	if err != nil {
		return
	}

	// On some systems /etc/localtime is a relative symlink, make it absolute
	if !filepath.IsAbs(zif) {
		zif = filepath.Join(filepath.Dir(localtimePath), zif)
		zif = filepath.Clean(zif)
	}

	src, err := os.Open(zif)
	if err != nil {
		return
	}
	defer src.Close()

	destp := filepath.Join(common.Stage1RootfsPath(root), zif)

	if err = os.MkdirAll(filepath.Dir(destp), 0755); err != nil {
		return
	}

	dest, err := os.OpenFile(destp, os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return
	}
	defer dest.Close()

	_, _ = io.Copy(dest, src)
}
Beispiel #23
0
Datei: run.go Projekt: fdserr/rkt
func init() {
	cmdRkt.AddCommand(cmdRun)

	// if not set by linker, try discover the directory rkt is running
	// from, and assume the default stage1.aci is stored alongside it.
	if defaultStage1Image == "" {
		if exePath, err := os.Readlink("/proc/self/exe"); err == nil {
			defaultStage1Image = filepath.Join(filepath.Dir(exePath), "stage1.aci")
		}
	}

	cmdRun.Flags().StringVar(&flagStage1Image, "stage1-image", defaultStage1Image, `image to use as stage1. Local paths and http/https URLs are supported. If empty, rkt will look for a file called "stage1.aci" in the same directory as rkt itself`)
	cmdRun.Flags().Var(&flagVolumes, "volume", "volumes to mount into the pod")
	cmdRun.Flags().Var(&flagPorts, "port", "ports to expose on the host (requires --private-net)")
	cmdRun.Flags().Var(&flagPrivateNet, "private-net", "give pod a private network that defaults to the default network plus all user-configured networks. Can be limited to a comma-separated list of network names")
	cmdRun.Flags().Lookup("private-net").NoOptDefVal = "all"
	cmdRun.Flags().BoolVar(&flagInheritEnv, "inherit-env", false, "inherit all environment variables not set by apps")
	cmdRun.Flags().BoolVar(&flagNoOverlay, "no-overlay", false, "disable overlay filesystem")
	cmdRun.Flags().Var(&flagExplicitEnv, "set-env", "an environment variable to set for apps in the form name=value")
	cmdRun.Flags().BoolVar(&flagInteractive, "interactive", false, "run pod interactively")
	cmdRun.Flags().Var((*appAsc)(&rktApps), "signature", "local signature file to use in validating the preceding image")
	cmdRun.Flags().BoolVar(&flagLocal, "local", false, "use only local images (do not discover or download from remote URLs)")
	cmdRun.Flags().StringVar(&flagPodManifest, "pod-manifest", "", "the path to the pod manifest. If it's non-empty, then only '--private-net', '--no-overlay' and '--interactive' will have effects")
	cmdRun.Flags().BoolVar(&flagMDSRegister, "mds-register", true, "register pod with metadata service")
	flagVolumes = volumeList{}
	flagPorts = portList{}

	// Disable interspersed flags to stop parsing after the first non flag
	// argument. All the subsequent parsing will be done by parseApps.
	// This is needed to correctly handle image args
	cmdRun.Flags().SetInterspersed(false)
}
Beispiel #24
0
func (pfs *ProcFS) Get(k string) {
	var uf = path.Join(procfsdir, "uptime")
	switch k {
	case PROCFS_SELF:
		var selfdir = path.Join(procfsdir, "self")
		if !exists(selfdir) {
			return
		}
		fi, _ := os.Readlink(selfdir)
		pfs.Self = fi
	case PROCFS_UPTIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[0], 64)
				pfs.Uptime = int(it)
			}
		}
	case PROCFS_IDLETIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[1], 64)
				pfs.Idletime = int(it)
			}
		}
	case PROCFS_MOUNTS:
		pfs.Mounts = getMounts(path.Join(procfsdir, "mounts"))
	}
}
Beispiel #25
0
func TestIPCHost(t *testing.T) {
	if testing.Short() {
		return
	}

	rootfs, err := newRootfs()
	ok(t, err)
	defer remove(rootfs)

	l, err := os.Readlink("/proc/1/ns/ipc")
	ok(t, err)

	config := newTemplateConfig(rootfs)
	config.Namespaces.Remove(configs.NEWIPC)
	buffers, exitCode, err := runContainer(config, "", "readlink", "/proc/self/ns/ipc")
	ok(t, err)

	if exitCode != 0 {
		t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr)
	}

	if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual != l {
		t.Fatalf("ipc link not equal to host link %q %q", actual, l)
	}
}
Beispiel #26
0
func TestFlyNetns(t *testing.T) {
	testImageArgs := []string{"--exec=/inspect --print-netns"}
	testImage := patchTestACI("rkt-inspect-stage1-fly.aci", testImageArgs...)
	defer os.Remove(testImage)

	ctx := testutils.NewRktRunCtx()
	defer ctx.Cleanup()

	cmd := fmt.Sprintf("%s --debug --insecure-options=image run %s", ctx.Cmd(), testImage)
	child := spawnOrFail(t, cmd)
	ctx.RegisterChild(child)
	defer waitOrFail(t, child, 0)

	expectedRegex := `NetNS: (net:\[\d+\])`
	result, out, err := expectRegexWithOutput(child, expectedRegex)
	if err != nil {
		t.Fatalf("Error: %v\nOutput: %v", err, out)
	}

	ns, err := os.Readlink("/proc/self/ns/net")
	if err != nil {
		t.Fatalf("Cannot evaluate NetNS symlink: %v", err)
	}

	if nsChanged := ns != result[1]; nsChanged {
		t.Fatalf("container left host netns")
	}
}
Beispiel #27
0
func (w Work) ListEnvs() []string {
	path := ggn.Home.Config.WorkPath + PATH_ENV
	if _, err := os.Stat(path); os.IsNotExist(err) {
		logs.WithEF(err, w.fields).WithField("path", path).Fatal("env directory not found")
	}

	files, err := ioutil.ReadDir(path)
	if err != nil {
		logs.WithEF(err, w.fields).WithField("path", path).Fatal("Cannot read env directory")
	}

	var envs []string
	for _, file := range files {
		if file.Mode()&os.ModeSymlink == os.ModeSymlink {
			followed_file, err := os.Readlink(path + "/" + file.Name())
			if err != nil {
				continue
			}
			if followed_file[0] != '/' {
				followed_file = path + "/" + followed_file
			}
			file, err = os.Lstat(followed_file)
			if err != nil {
				continue
			}
			logs.WithField("followed_link", file.Name()).Trace("Followed Link")
		}

		if !file.IsDir() {
			continue
		}
		envs = append(envs, file.Name())
	}
	return envs
}
Beispiel #28
0
/*
 readFiles reads all files with the .go extension and creates their AST.
 It also creates a list of local imports (everything starting with ./)
 and searches the main package files for the main function.
*/
func readFiles(rootpath string) {
	var realpath, symname string
	// path walker error channel
	errorChannel := make(chan os.Error, 64)

	// check if this is a symlink
	if dir, err := os.Stat(rootpath); err == nil {
		if dir.FollowedSymlink {
			realpath, _ = os.Readlink(rootpath)
			if realpath[0] != '/' {
				realpath = rootpath[0:strings.LastIndex(rootpath, "/")+1] + realpath
			}
			symname = rootpath[len(rootPath)+1:]
		} else {
			realpath = rootpath
		}
	} else {
		logger.Warn("%s\n", err)
	}

	// visitor for the path walker
	visitor := &goFileVisitor{rootpath, realpath, symname}

	path.Walk(visitor.realpath, visitor, errorChannel)

	if err, ok := <-errorChannel; ok {
		logger.Error("Error while traversing directories: %s\n", err)
	}
}
Beispiel #29
0
// writeTarHeader writes tar header for given file, returns error if operation fails
func (t *stiTar) writeTarHeader(tarWriter *tar.Writer, dir string, path string, info os.FileInfo, includeDirInPath bool) error {
	var (
		link string
		err  error
	)
	if info.Mode()&os.ModeSymlink != 0 {
		link, err = os.Readlink(path)
		if err != nil {
			return err
		}
	}
	header, err := tar.FileInfoHeader(info, link)
	if err != nil {
		return err
	}
	prefix := dir
	if includeDirInPath {
		prefix = filepath.Dir(prefix)
	}
	header.Name = filepath.ToSlash(path[1+len(prefix):])
	glog.V(5).Infof("Adding to tar: %s as %s", path, header.Name)
	if err = tarWriter.WriteHeader(header); err != nil {
		return err
	}

	return nil
}
Beispiel #30
0
func ReleaseExternalPorts(ports PortPairs) error {
	var err error
	for i := range ports {
		_, direct := ports[i].External.PortPathsFor()
		path, errl := os.Readlink(direct)
		if errl != nil {
			if !os.IsNotExist(errl) {
				// REPAIR: link can't be checked, may be broken
				log.Printf("ports: Path cannot be checked: %v", errl)
				err = errl
			}
			// the port is no longer reserved (link does not exist)
			continue
		}
		if _, errs := os.Stat(path); errs != nil {
			if os.IsNotExist(errs) {
				// referenced container does not exist, remove the link
				os.Remove(direct)
				continue
			}
			// REPAIR: can't read the referenced container
			err = errs
			continue
		}
		if errr := os.Remove(direct); errr != nil {
			log.Printf("ports: Unable to remove symlink %v", errr)
			err = errr
			// REPAIR: reserved ports may not be properly released
			continue
		}
	}
	return err
}