本文整理汇总了Golang中os.Readlink函数的典型用法代码示例。如果您正苦于以下问题:Golang Readlink函数的具体用法?Golang Readlink怎么用?Golang Readlink使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Readlink函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestExecRequest
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)
}
示例2: TestPrune
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")
}
示例3: NamespacePostStart
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
}
示例4: checkHostNs
// 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
}
示例5: ExecInCoreSnap
// 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))
}
示例6: executable
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)
}
示例7: gcNetworking
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
}
示例8: checkExampleFS
// 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)
}
示例9: Prune
// 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
}
示例10: InContainer
// 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
}
示例11: JumpBack
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
}
示例12: getTags
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}
}
示例13: executable
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)
}
示例14: getProcessInfo
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
}
示例15: isProcessRunningInHost
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
}