Golang Symlink示例

说明

golang symlink示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: os

示例#1
文件: docker_cli_run_unix_test.go 项目: ailispaw/docker

// TestRunDeviceSymlink checks run with device that follows symlink (#13840)
func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
	if _, err := os.Stat("/dev/zero"); err != nil {
		c.Skip("Host does not have /dev/zero")
	}

	// Create a temporary directory to create symlink
	tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
	c.Assert(err, checker.IsNil)

	defer os.RemoveAll(tmpDir)

	// Create a symbolic link to /dev/zero
	symZero := filepath.Join(tmpDir, "zero")
	err = os.Symlink("/dev/zero", symZero)
	c.Assert(err, checker.IsNil)

	// Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
	// then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
	tmpFile := filepath.Join(tmpDir, "temp")
	err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
	c.Assert(err, checker.IsNil)
	symFile := filepath.Join(tmpDir, "file")
	err = os.Symlink(tmpFile, symFile)
	c.Assert(err, checker.IsNil)

	// md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
	out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))

	// symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
	out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
	c.Assert(err, check.NotNil)
	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
}

示例#2
文件: geoipupdate.go 项目: abligh/geoipupdate

func main() {

	flag.Parse()
	if randomDelay != nil && *randomDelay != "" {
		if dur, err := time.ParseDuration(*randomDelay); err != nil {
			log.Fatalf("Cannot parse duration '%s': %v", randomDelay, err)
		} else {
			rdur := time.Duration(randInt64(dur.Nanoseconds()))
			log.Printf("Waiting for %s of %s", rdur.String(), dur.String())
			time.Sleep(rdur)
		}
	}

	log.Printf("Updating geoip database at %s from %s via %s", *directory, *sourceHost, *protocol)
	if err := getClientIp(); err != nil {
		log.Fatalf("Can't get client IP: %v", err)
	}
	for _, p := range strings.Split(*productIds, ",") {
		getProduct(p)
	}
	if *dolinks {
		log.Printf("Making legacy links in %s", *directory)
		os.Symlink(path.Join(*directory, "GeoLiteCity.dat"), path.Join(*directory, "GeoIPCity.dat"))
		os.Symlink(path.Join(*directory, "GeoLiteCountry.dat"), path.Join(*directory, "GeoIP.dat"))
	}
	log.Printf("Done\n")
}

示例#3
文件: autounion_test.go 项目: crazy2be/go-fuse

func TestCreationChecks(t *testing.T) {
	wd, clean := setup(t)
	defer clean()

	err := os.Mkdir(wd+"/store/foo", 0755)
	CheckSuccess(err)
	os.Symlink(wd+"/ro", wd+"/store/foo/READONLY")
	CheckSuccess(err)

	err = os.Mkdir(wd+"/store/ws2", 0755)
	CheckSuccess(err)
	os.Symlink(wd+"/ro", wd+"/store/ws2/READONLY")
	CheckSuccess(err)

	err = os.Symlink(wd+"/store/foo", wd+"/mnt/config/bar")
	CheckSuccess(err)

	err = os.Symlink(wd+"/store/foo", wd+"/mnt/config/foo")
	code := fuse.ToStatus(err)
	if code != fuse.EBUSY {
		t.Error("Should return EBUSY", err)
	}

	err = os.Symlink(wd+"/store/ws2", wd+"/mnt/config/config")
	code = fuse.ToStatus(err)
	if code != fuse.EINVAL {
		t.Error("Should return EINVAL", err)
	}
}

示例#4
文件: bundle_test.go 项目: bz2/charm

func (s *BundleSuite) TestExpandToWithBadLink(c *gc.C) {
	charmDir := charmtesting.Charms.ClonedDirPath(c.MkDir(), "dummy")
	badLink := filepath.Join(charmDir, "hooks", "badlink")

	// Symlink targeting a path outside of the charm.
	err := os.Symlink("../../target", badLink)
	c.Assert(err, gc.IsNil)

	bundle := extBundleDir(c, charmDir)
	c.Assert(err, gc.IsNil)

	path := filepath.Join(c.MkDir(), "charm")
	err = bundle.ExpandTo(path)
	c.Assert(err, gc.ErrorMatches, `cannot extract "hooks/badlink": symlink "../../target" leads out of scope`)

	// Symlink targeting an absolute path.
	os.Remove(badLink)
	err = os.Symlink("/target", badLink)
	c.Assert(err, gc.IsNil)

	bundle = extBundleDir(c, charmDir)
	c.Assert(err, gc.IsNil)

	path = filepath.Join(c.MkDir(), "charm")
	err = bundle.ExpandTo(path)
	c.Assert(err, gc.ErrorMatches, `cannot extract "hooks/badlink": symlink "/target" is absolute`)
}

示例#5
文件: util_unix_test.go 项目: kaocs/notify

func TestCanonicalCircular(t *testing.T) {
	tmp1, err := tmpfile("circular")
	if err != nil {
		t.Fatal(err)
	}
	tmp2, err := tmpfile("circular")
	if err != nil {
		t.Fatal(nonil(err, os.Remove(tmp1)))
	}
	defer removeall(tmp1, tmp2)
	// Symlink tmp1 -> tmp2.
	if err = nonil(os.Remove(tmp1), os.Symlink(tmp2, tmp1)); err != nil {
		t.Fatal(err)
	}
	// Symlnik tmp2 -> tmp1.
	if err = nonil(os.Remove(tmp2), os.Symlink(tmp1, tmp2)); err != nil {
		t.Fatal(err)
	}
	if _, err = canonical(tmp1); err == nil {
		t.Fatalf("want canonical(%q)!=nil", tmp1)
	}
	if _, ok := err.(*os.PathError); !ok {
		t.Fatalf("want canonical(%q)=os.PathError; got %T", tmp1, err)
	}
}

示例#6
文件: autounion_test.go 项目: y-okubo/go-fuse

func TestDetectSymlinkedDirectories(t *testing.T) {
	wd, clean := setup(t)
	defer clean()

	err := os.Mkdir(wd+"/backing1", 0755)
	if err != nil {
		t.Fatalf("Mkdir failed: %v", err)
	}

	err = os.Symlink(wd+"/ro", wd+"/backing1/READONLY")
	if err != nil {
		t.Fatalf("Symlink failed: %v", err)
	}

	err = os.Symlink(wd+"/backing1", wd+"/store/backing1")
	if err != nil {
		t.Fatalf("Symlink failed: %v", err)
	}

	scan := wd + "/mnt/config/" + _SCAN_CONFIG
	err = ioutil.WriteFile(scan, []byte("something"), 0644)
	if err != nil {
		t.Error("error writing:", err)
	}

	_, err = os.Lstat(wd + "/mnt/backing1")
	if err != nil {
		t.Fatalf("Lstat failed: %v", err)
	}
}

示例#7
文件: fs.go 项目: cautio/gocryptfs

func (fs *FS) Symlink(target string, linkName string, context *fuse.Context) (code fuse.Status) {
	cryptfs.Debug.Printf("Symlink(\"%s\", \"%s\")", target, linkName)
	if fs.isFiltered(linkName) {
		return fuse.EPERM
	}
	cPath, err := fs.getBackingPath(linkName)
	if err != nil {
		return fuse.ToStatus(err)
	}
	// Old filesystem: symlinks are encrypted like paths (CBC)
	if !fs.args.DirIV {
		cTarget, err := fs.encryptPath(target)
		if err != nil {
			cryptfs.Warn.Printf("Symlink: BUG: we should not get an error here: %v", err)
			return fuse.ToStatus(err)
		}
		err = os.Symlink(cTarget, cPath)
		return fuse.ToStatus(err)
	}
	// Since gocryptfs v0.5 symlinks are encrypted like file contents (GCM)
	cBinTarget := fs.CryptFS.EncryptBlock([]byte(target), 0, nil)
	cTarget := base64.URLEncoding.EncodeToString(cBinTarget)

	err = os.Symlink(cTarget, cPath)
	cryptfs.Debug.Printf("Symlink: os.Symlink(%s, %s) = %v", cTarget, cPath, err)
	return fuse.ToStatus(err)
}

示例#8
文件: tar_test.go 项目: liyangdal/kurma

func makeTestDir(t *testing.T) string {
	cwd, err := os.Getwd()
	TestExpectSuccess(t, err)
	AddTestFinalizer(func() {
		TestExpectSuccess(t, os.Chdir(cwd))
	})
	dir := TempDir(t)
	TestExpectSuccess(t, os.Chdir(dir))
	mode := os.FileMode(0755)
	os.Mkdir(cwd, mode) //Don't care about return value.  For some reason CWD is not created by go test on all systems.
	TestExpectSuccess(t, os.Mkdir("a", mode))
	TestExpectSuccess(t, os.Mkdir("a/b", mode))
	TestExpectSuccess(t, os.Mkdir("a/b/c", mode))
	TestExpectSuccess(t, os.Mkdir("a/b/c/d", mode))
	TestExpectSuccess(t, os.Mkdir("a/b/i", mode))
	TestExpectSuccess(t, os.Mkdir("a/b/i/j", mode))
	TestExpectSuccess(t, ioutil.WriteFile("a/b/c/d/e", []byte{}, mode))
	TestExpectSuccess(t, ioutil.WriteFile("a/b/c/f", []byte{}, mode))
	TestExpectSuccess(t, ioutil.WriteFile("a/b/g", []byte{}, mode))
	TestExpectSuccess(t, ioutil.WriteFile("a/b/i/j/k", []byte{}, mode))
	TestExpectSuccess(t, os.Symlink("/bin/bash", "a/b/bash"))
	TestExpectSuccess(t, os.Symlink("../i", "a/b/c/l"))
	TestExpectSuccess(t, os.Symlink("g", "a/b/h"))
	TestExpectSuccess(t, os.Symlink("k", "a/b/i/j/l"))
	TestExpectSuccess(t, os.Symlink("../../g", "a/b/i/j/m"))
	return dir
}

示例#9
文件: kilt.go 项目: robertkrimen/dogbag

func Symlink(oldname, newname string, overwrite bool) error {
	err := os.Symlink(oldname, newname)
	if err == nil {
		return nil // Success
	}
	if !os.IsExist(err) {
		return err // Failure
	}
	// Failure, file exists
	symbolic := false
	{
		stat, err := os.Lstat(newname)
		if err != nil {
			return err
		}
		symbolic = stat.Mode()&os.ModeSymlink != 0
	}
	if !symbolic {
		return err
	}
	if !overwrite {
		return nil
	}
	err = os.Remove(newname)
	if err != nil {
		return err
	}
	return os.Symlink(oldname, newname)
}

示例#10
文件: main.go 项目: davinche/Jekyll-Build-Server

func symlinkDirs() (err error) {
	err = os.RemoveAll(SITE_DIR + "/_posts")
	if err != nil {
		return err
	}
	err = os.RemoveAll(SITE_DIR + "/uploads")
	if err != nil {
		return err
	}

	postsAbs, err := filepath.Abs(POSTS_REPO_DIR + "/posts")
	if err != nil {
		return errors.New("Unable to get absolute path of posts directory")
	}

	uploadsAbs, err := filepath.Abs(POSTS_REPO_DIR + "/uploads")
	if err != nil {
		return errors.New("Unable to get absolute path of uploads directory")
	}
	err = os.Symlink(postsAbs, SITE_DIR+"/_posts")
	if err != nil {
		return err
	}
	err = os.Symlink(uploadsAbs, SITE_DIR+"/uploads")
	if err != nil {
		return err
	}
	return nil
}

示例#11

func (t *MemFSTest) CreateSymlink_AlreadyExists() {
	var err error

	// Create a file and a directory.
	fileName := path.Join(t.Dir, "foo")
	err = ioutil.WriteFile(fileName, []byte{}, 0400)
	AssertEq(nil, err)

	dirName := path.Join(t.Dir, "bar")
	err = os.Mkdir(dirName, 0700)
	AssertEq(nil, err)

	// Create an existing symlink.
	symlinkName := path.Join(t.Dir, "baz")
	err = os.Symlink("blah", symlinkName)
	AssertEq(nil, err)

	// Symlinking on top of any of them should fail.
	names := []string{
		fileName,
		dirName,
		symlinkName,
	}

	for _, n := range names {
		err = os.Symlink("blah", n)
		ExpectThat(err, Error(HasSubstr("exists")))
	}
}

示例#12
文件: walk_test.go 项目: postfix/symwalk

func TestGeneralCase(t *testing.T) {
	fn := new(WalkFn)
	root := makeEmptyRoot(t)
	defer os.RemoveAll(root)

	ensure.Nil(t, os.MkdirAll(filepath.Join(root, "a", "a1"), 0755))
	createFile(t, filepath.Join(root, "a", "a1", "1"))

	ensure.Nil(t, os.Mkdir(filepath.Join(root, "b"), 0755))
	createFile(t, filepath.Join(root, "b", "2"))

	ensure.Nil(t, os.Symlink(filepath.Join(root, "b"), filepath.Join(root, "a", "a1", "a2")))

	ensure.Nil(t, os.Symlink(filepath.Join(root, "a", "a1", "1"), filepath.Join(root, "top")))

	ensure.Nil(t, Walk(root, fn.walkFn))

	ensure.DeepEqual(t,
		fn.List,
		[]string{
			root,
			filepath.Join(root, "a"),
			filepath.Join(root, "a", "a1"),
			filepath.Join(root, "a", "a1", "1"),
			filepath.Join(root, "a", "a1", "a2"),
			filepath.Join(root, "a", "a1", "a2", "2"),
			filepath.Join(root, "b"),
			filepath.Join(root, "b", "2"),
			filepath.Join(root, "top"),
		},
	)
}

示例#13
文件: bundle_test.go 项目: rif/golang-stuff

func (s *BundleSuite) TestExpandToWithBadLink(c *C) {
	charmDir := testing.Charms.ClonedDirPath(c.MkDir(), "dummy")
	badLink := filepath.Join(charmDir, "hooks", "badlink")

	// Symlink targeting a path outside of the charm.
	err := os.Symlink("../../target", badLink)
	c.Assert(err, IsNil)

	bundle, err := charm.ReadBundle(extBundleDir(c, charmDir))
	c.Assert(err, IsNil)

	path := filepath.Join(c.MkDir(), "charm")
	err = bundle.ExpandTo(path)
	c.Assert(err, ErrorMatches, `symlink "hooks/badlink" links out of charm: "../../target"`)

	// Symlink targeting an absolute path.
	os.Remove(badLink)
	err = os.Symlink("/target", badLink)
	c.Assert(err, IsNil)

	bundle, err = charm.ReadBundle(extBundleDir(c, charmDir))
	c.Assert(err, IsNil)

	path = filepath.Join(c.MkDir(), "charm")
	err = bundle.ExpandTo(path)
	c.Assert(err, ErrorMatches, `symlink "hooks/badlink" is absolute: "/target"`)
}

示例#14
文件: runner.go 项目: sgoings/wercker

// CopySource copies the source into the HostPath
func (p *Runner) CopySource() error {
	timer := util.NewTimer()
	f := p.formatter

	err := os.MkdirAll(p.options.HostPath(), 0755)
	if err != nil {
		return err
	}

	// Link the path to BuildPath("latest") for easy access
	err = os.RemoveAll(p.options.BuildPath("latest"))
	if err != nil {
		return err
	}
	err = os.Symlink(p.options.HostPath(), p.options.BuildPath("latest"))
	if err != nil {
		return err
	}

	err = os.Symlink(p.ProjectDir(), p.options.HostPath("source"))
	if err != nil {
		return err
	}
	if p.options.Verbose {
		p.logger.Printf(f.Success("Source -> Staging Area", timer.String()))
	}
	return nil
}

示例#15
文件: service_sysv_linux.go 项目: grrtrr/golang-kardianos-service

// (Un)install symbolic runlevel links
func (s *sysv) manageSymlinks(confPath string, install bool) error {
	var cmd *exec.Cmd

	if _, err := exec.LookPath("chkconfig"); err == nil {
		if install {
			cmd = exec.Command("chkconfig", "--add", s.Name)
		} else {
			cmd = exec.Command("chkconfig", "--del", s.Name)
		}
	} else if _, err := exec.LookPath("update-rc.d"); err == nil {
		if install {
			cmd = exec.Command("update-rc.d", s.Name, "defaults")
		} else {
			cmd = exec.Command("update-rc.d", "-f", s.Name, "remove")
		}
	}

	if cmd != nil {
		if err := cmd.Run(); err != nil {
			return fmt.Errorf("Failed to run %q: %s", strings.Join(cmd.Args, " "), err)
		}
	} else {
		/* Manually install/remove symlinks */
		var base = "/etc"

		/* Debian/ubuntu use /etc/rc[0-6].d; RedHat uses /etc/rc.d/rc[0-6].d */
		if _, err := os.Stat("/etc/rc.d/"); err == nil {
			base = "/etc/rc.d"
		} else if _, err := os.Stat(base + "/rc0.d"); os.IsNotExist(err) {
			fmt.Fprintf(os.Stderr, "FIXME: no suitable rc.d directory found in /etc")
			os.Exit(1)
		}

		for _, i := range strings.Split(defaultStartLevels, "") {
			path := fmt.Sprintf("%s/rc%s.d/S%s%s", base, i, defaultStartPriority, s.Name)
			if install {
				if err := os.Symlink(confPath, path); err != nil {
					return fmt.Errorf("Failed to create startup link %s: %s", path, err)
				}
			} else {
				if err := os.Remove(path); err != nil {
					return fmt.Errorf("Failed to remove startup link %s: %s", path, err)
				}
			}
		}
		for _, i := range strings.Split(defaultStopLevels, "") {
			path := fmt.Sprintf("%s/rc%s.d/K%s%s", base, i, defaultStopPriority, s.Name)
			if install {
				if err := os.Symlink(confPath, path); err != nil {
					return fmt.Errorf("Failed to create shutdown link %s: %s", path, err)
				}
			} else {
				if err := os.Remove(path); err != nil {
					return fmt.Errorf("Failed to remove shutdown link %s: %s", path, err)
				}
			}
		}
	}
	return nil
}

示例#16
文件: add.go 项目: sombr/ccat

// Add creates a symlink in the SRCLIBPATH so that the toolchain in dir is
// available at the toolchainPath.
func Add(dir, toolchainPath string, opt *AddOpt) error {
	if opt == nil {
		opt = &AddOpt{}
	}
	if !opt.Force {
		if _, err := Lookup(toolchainPath); !os.IsNotExist(err) {
			return fmt.Errorf("a toolchain already exists at toolchain path %q", toolchainPath)
		}
	}

	absDir, err := filepath.Abs(dir)
	if err != nil {
		return err
	}

	srclibpathEntry := strings.SplitN(srclib.Path, ":", 2)[0]
	targetDir := filepath.Join(srclibpathEntry, toolchainPath)

	if err := os.MkdirAll(filepath.Dir(targetDir), 0700); err != nil {
		return err
	}

	if !opt.Force {
		return os.Symlink(absDir, targetDir)
	}
	// Force install the toolchain by removing the directory if
	// the symlink fails, and then try the symlink again.
	if err := os.Symlink(absDir, targetDir); err != nil {
		if err := os.RemoveAll(targetDir); err != nil {
			return err
		}
		return os.Symlink(absDir, targetDir)
	}
	return nil
}

示例#17
文件: overlord.go 项目: dholbach/snappy

// XXX: would really like not to expose this but used in daemon tests atm
func UpdateCurrentSymlink(info *snap.Info, inter interacter) error {
	mountDir := info.MountDir()

	currentActiveSymlink := filepath.Join(mountDir, "..", "current")
	if err := os.Remove(currentActiveSymlink); err != nil && !os.IsNotExist(err) {
		logger.Noticef("Failed to remove %q: %v", currentActiveSymlink, err)
	}

	dataDir := info.DataDir()
	dbase := filepath.Dir(dataDir)
	currentDataSymlink := filepath.Join(dbase, "current")
	if err := os.Remove(currentDataSymlink); err != nil && !os.IsNotExist(err) {
		logger.Noticef("Failed to remove %q: %v", currentDataSymlink, err)
	}

	// symlink is relative to parent dir
	if err := os.Symlink(filepath.Base(mountDir), currentActiveSymlink); err != nil {
		return err
	}

	if err := os.MkdirAll(info.DataDir(), 0755); err != nil {
		return err
	}

	// FIXME: create {Os,Kernel}Snap type instead of adding special
	//        cases here
	if err := setNextBoot(info); err != nil {
		return err
	}

	return os.Symlink(filepath.Base(dataDir), currentDataSymlink)
}

示例#18
文件: service_linux.go 项目: jvehent/mig

func (s *linuxService) Install() error {
	confPath := s.flavor.ConfigPath(s.name)
	_, err := os.Stat(confPath)
	if err == nil {
		return fmt.Errorf("Init already exists: %s", confPath)
	}

	f, err := os.Create(confPath)
	if err != nil {
		return err
	}
	defer f.Close()

	path, err := osext.Executable()
	if err != nil {
		return err
	}

	var to = &struct {
		Display     string
		Description string
		Path        string
	}{
		s.displayName,
		s.description,
		path,
	}

	err = s.flavor.GetTemplate().Execute(f, to)
	if err != nil {
		return err
	}

	if s.flavor == initSystemV {
		if err = os.Chmod(confPath, 0755); err != nil {
			return err
		}
		for _, i := range [...]string{"2", "3", "4", "5"} {
			if err = os.Symlink(confPath, "/etc/rc"+i+".d/S50"+s.name); err != nil {
				continue
			}
		}
		for _, i := range [...]string{"0", "1", "6"} {
			if err = os.Symlink(confPath, "/etc/rc"+i+".d/K02"+s.name); err != nil {
				continue
			}
		}
	}

	if s.flavor == initSystemd {
		err = exec.Command("systemctl", "enable", s.name+".service").Run()
		if err != nil {
			return err
		}
		return exec.Command("systemctl", "daemon-reload").Run()
	}

	return nil
}

示例#19
文件: daemon_linux_ubuntu.go 项目: x88/daemon

func (linux *ubuntuSysVRecord) InstallFromPath(thePath string) (string, error) {
	installAction := "Install " + linux.description + ":"

	if checkPrivileges() == false {
		return installAction + failed, errors.New(rootPrivileges)
	}

	srvPath := linux.servicePath()

	if linux.checkInstalled() == true {
		return installAction + failed, errors.New(linux.description + " already installed")
	}

	file, err := os.Create(srvPath)
	if err != nil {
		return installAction + failed, err
	}
	defer file.Close()

	isexec, err := IsExecutable(thePath)
	if err != nil {
		return installAction + failed, err
	}
	if !isexec {
		return installAction + failed, fmt.Errorf("target is not executable: %s", thePath)
	}

	templ, err := template.New("ubuntuSysVConfig").Parse(ubuntuSysVConf)
	if err != nil {
		return installAction + failed, err
	}

	if err := templ.Execute(
		file,
		&struct {
			Name, Description, Path string
		}{linux.name, linux.description, thePath},
	); err != nil {
		return installAction + failed, err
	}

	if err := os.Chmod(srvPath, 0755); err != nil {
		return installAction + failed, err
	}

	for _, i := range [...]string{"2", "3", "4", "5"} {
		if err := os.Symlink(srvPath, "/etc/rc"+i+".d/S87"+linux.name); err != nil {
			continue
		}
	}
	for _, i := range [...]string{"0", "1", "6"} {
		if err := os.Symlink(srvPath, "/etc/rc"+i+".d/K17"+linux.name); err != nil {
			continue
		}
	}

	return installAction + success, nil
}

示例#20
文件: daemon_linux_systemv.go 项目: radiophysic/daemon

// Install the service
func (linux *systemVRecord) Install() (string, error) {
	installAction := "Install " + linux.description + ":"

	if checkPrivileges() == false {
		return installAction + failed, errors.New(rootPrivileges)
	}

	srvPath := linux.servicePath()

	if linux.checkInstalled() == true {
		return installAction + failed, errors.New(linux.description + " already installed")
	}

	file, err := os.Create(srvPath)
	if err != nil {
		return installAction + failed, err
	}
	defer file.Close()

	execPatch, err := executablePath(linux.name)
	if err != nil {
		return installAction + failed, err
	}

	distroName := distro.FindName()
	initTemplate := getTemplateByDistro(distroName)
	templ, err := template.New("systemVConfig").Parse(initTemplate)

	if err != nil {
		return installAction + failed, err
	}

	if err := templ.Execute(
		file,
		&struct {
			Name, Description, Path string
		}{linux.name, linux.description, execPatch},
	); err != nil {
		return installAction + failed, err
	}

	if err := os.Chmod(srvPath, 0755); err != nil {
		return installAction + failed, err
	}

	for _, i := range [...]string{"2", "3", "4", "5"} {
		if err := os.Symlink(srvPath, "/etc/rc"+i+".d/S87"+linux.name); err != nil {
			continue
		}
	}
	for _, i := range [...]string{"0", "1", "6"} {
		if err := os.Symlink(srvPath, "/etc/rc"+i+".d/K17"+linux.name); err != nil {
			continue
		}
	}

	return installAction + success, nil
}

示例#21
文件: autounion_test.go 项目: y-okubo/go-fuse

func TestAutoFsSymlink(t *testing.T) {
	wd, clean := setup(t)
	defer clean()

	err := os.Mkdir(wd+"/store/backing1", 0755)
	if err != nil {
		t.Fatalf("Mkdir failed: %v", err)
	}

	err = os.Symlink(wd+"/ro", wd+"/store/backing1/READONLY")
	if err != nil {
		t.Fatalf("Symlink failed: %v", err)
	}

	err = os.Symlink(wd+"/store/backing1", wd+"/mnt/config/manual1")
	if err != nil {
		t.Fatalf("Symlink failed: %v", err)
	}

	fi, err := os.Lstat(wd + "/mnt/manual1/file1")
	if err != nil {
		t.Fatalf("Lstat failed: %v", err)
	}

	entries, err := ioutil.ReadDir(wd + "/mnt")
	if err != nil {
		t.Fatalf("ReadDir failed: %v", err)
	}
	if len(entries) != 3 {
		t.Error("readdir mismatch", entries)
	}

	err = os.Remove(wd + "/mnt/config/manual1")
	if err != nil {
		t.Fatalf("Remove failed: %v", err)
	}

	scan := wd + "/mnt/config/" + _SCAN_CONFIG
	err = ioutil.WriteFile(scan, []byte("something"), 0644)
	if err != nil {
		t.Error("error writing:", err)
	}

	fi, _ = os.Lstat(wd + "/mnt/manual1")
	if fi != nil {
		t.Error("Should not have file:", fi)
	}

	_, err = ioutil.ReadDir(wd + "/mnt/config")
	if err != nil {
		t.Fatalf("ReadDir failed: %v", err)
	}

	_, err = os.Lstat(wd + "/mnt/backing1/file1")
	if err != nil {
		t.Fatalf("Lstat failed: %v", err)
	}
}

示例#22
文件: local.go 项目: rhettg/ftl

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
}

示例#23
文件: json_test.go 项目: afajl/ctrl

func TestJsonFac(t *testing.T) {
	type utest struct {
		desc, rawurl string
		ok           bool
	}

	tests := []utest{
		{"bad scheme", "badscheme://p", false},
		{"invalid path", "json:///THIS_SHOULD_NOT_EXIST", false},
		{"missing path", "json:///", false},
		{"dir", "json://testdata/", false},
		{"relative path", "json://rel/ok.json", true},
		// TODO add tilde expansion and environ
	}

	os.Chmod("testdata/rel/noaccess.json", 0000)
	defer os.Chmod("testdata/rel/noaccess.json", 0644)
	tests = append(tests, utest{"unauthorized path", "json://rel/noaccess.json", false})

	// absfile test
	absfile := "/tmp/CTRL_JSON_OK_XXX.json"
	ioutil.WriteFile(absfile, []byte("{}"), 0644)
	defer os.Remove(absfile)
	tests = append(tests, utest{"absolute path", "json://" + absfile, true})

	// rel symlink
	if err := os.Symlink(absfile, "testdata/rel/ok-link.json"); err != nil {
		t.Fatal(err)
	}
	defer os.Remove("testdata/rel/ok-link.json")
	tests = append(tests, utest{"relative link", "json://rel/ok-link.json", true})

	// abs symlink
	abslink := "/tmp/CTRL_JSON_OK_XXX-LINK.json"
	if err := os.Symlink(absfile, abslink); err != nil {
		t.Fatal(err)
	}
	defer os.Remove(abslink)
	tests = append(tests, utest{"absolute link", "json://" + abslink, true})

	config.StartConfig.Rootdir = "testdata"

	for _, test := range tests {
		u, err := url.Parse(test.rawurl)
		if err != nil {
			t.Fatal(err)
		}
		_, err = JsonFac(u)
		if test.ok && err != nil {
			t.Error(test.desc, "should succeed:", err)
		}
		if !test.ok && err == nil {
			t.Error(test.desc, "should fail")
		}
	}
}

示例#24
文件: aliases_test.go 项目: pedronis/snappy

func (s *aliasesSuite) TestMatchingAliases(c *C) {
	err := os.Symlink("x.foo", filepath.Join(dirs.SnapBinariesDir, "foo"))
	c.Assert(err, IsNil)
	err = os.Symlink("y.bar", filepath.Join(dirs.SnapBinariesDir, "bar"))
	c.Assert(err, IsNil)

	aliases, err := s.be.MatchingAliases([]*backend.Alias{{"a", "a"}, {"foo", "x.foo"}, {"bar", "x.bar"}})
	c.Assert(err, IsNil)
	c.Check(aliases, DeepEquals, []*backend.Alias{{"foo", "x.foo"}})
}

示例#25
文件: daemon_linux_systemv.go 项目: ehalpern/go-mysql-elasticsearch

// Install the service
func (linux *systemVRecord) Install(args ...string) (string, error) {
	installAction := "Install " + linux.description + ":"

	if ok, err := checkPrivileges(); !ok {
		return installAction + failed, err
	}

	srvPath := linux.servicePath()

	if linux.isInstalled() {
		return installAction + failed, ErrAlreadyInstalled
	}

	file, err := os.Create(srvPath)
	if err != nil {
		return installAction + failed, err
	}
	defer file.Close()

	execPatch, err := executablePath(linux.name)
	if err != nil {
		return installAction + failed, err
	}

	templ, err := template.New("systemVConfig").Parse(systemVConfig)
	if err != nil {
		return installAction + failed, err
	}

	if err := templ.Execute(
		file,
		&struct {
			Name, Description, Path, Args string
		}{linux.name, linux.description, execPatch, strings.Join(args, " ")},
	); err != nil {
		return installAction + failed, err
	}

	if err := os.Chmod(srvPath, 0755); err != nil {
		return installAction + failed, err
	}

	for _, i := range [...]string{"2", "3", "4", "5"} {
		if err := os.Symlink(srvPath, "/etc/rc"+i+".d/S87"+linux.name); err != nil {
			continue
		}
	}
	for _, i := range [...]string{"0", "1", "6"} {
		if err := os.Symlink(srvPath, "/etc/rc"+i+".d/K17"+linux.name); err != nil {
			continue
		}
	}

	return installAction + success, nil
}

示例#26
文件: service_sysv_linux.go 项目: uda/golang-kardianos-service

func (s *sysv) Install() error {
	confPath, err := s.configPath()
	if err != nil {
		return err
	}
	_, err = os.Stat(confPath)
	if err == nil {
		return fmt.Errorf("Init already exists: %s", confPath)
	}

	f, err := os.Create(confPath)
	if err != nil {
		return err
	}
	defer f.Close()

	path, err := s.execPath()
	if err != nil {
		return err
	}

	var to = &struct {
		*Config
		Path string
	}{
		s.Config,
		path,
	}

	template, err := s.template()
	if err != nil {
		return err
	}
	err = template.Execute(f, to)
	if err != nil {
		return err
	}

	if err = os.Chmod(confPath, 0755); err != nil {
		return err
	}
	for _, i := range [...]string{"2", "3", "4", "5"} {
		if err = os.Symlink(confPath, "/etc/rc"+i+".d/S50"+s.Name); err != nil {
			continue
		}
	}
	for _, i := range [...]string{"0", "1", "6"} {
		if err = os.Symlink(confPath, "/etc/rc"+i+".d/K02"+s.Name); err != nil {
			continue
		}
	}

	return nil
}

示例#27

func (s *sysv) Install() error {
	confPath, err := s.configPath()
	if err != nil {
		return err
	}
	_, err = os.Stat(confPath)
	if err == nil {
		return fmt.Errorf("Init already exists: %s", confPath)
	}

	f, err := os.Create(confPath)
	if err != nil {
		return err
	}
	defer f.Close()

	path, err := s.execPath()
	if err != nil {
		return err
	}

	var to = &struct {
		*Config
		Path          string
		RequiredStart string
	}{
		s.Config,
		path,
		s.Config.Option.string(optionRequiredStart, ""),
	}

	err = s.template().Execute(f, to)
	if err != nil {
		return err
	}

	if err = os.Chmod(confPath, 0755); err != nil {
		return err
	}
	// TODO(rjeczalik): replace with update-rc.d instead?
	for _, i := range [...]string{"2", "3", "4", "5"} {
		if err = os.Symlink(confPath, "/etc/rc"+i+".d/S50"+s.Name); err != nil {
			continue
		}
	}
	for _, i := range [...]string{"0", "1", "6"} {
		if err = os.Symlink(confPath, "/etc/rc"+i+".d/K02"+s.Name); err != nil {
			continue
		}
	}

	return nil
}

示例#28
文件: fs.go 项目: rfjakob/gocryptfs

// Symlink implements pathfs.Filesystem.
func (fs *FS) Symlink(target string, linkName string, context *fuse.Context) (code fuse.Status) {
	tlog.Debug.Printf("Symlink(\"%s\", \"%s\")", target, linkName)
	if fs.isFiltered(linkName) {
		return fuse.EPERM
	}
	cPath, err := fs.getBackingPath(linkName)
	if err != nil {
		return fuse.ToStatus(err)
	}
	if fs.args.PlaintextNames {
		err = os.Symlink(target, cPath)
		return fuse.ToStatus(err)
	}
	// Symlinks are encrypted like file contents (GCM) and base64-encoded
	cBinTarget := fs.contentEnc.EncryptBlock([]byte(target), 0, nil)
	cTarget := base64.URLEncoding.EncodeToString(cBinTarget)
	// Handle long file name
	cName := filepath.Base(cPath)
	if nametransform.IsLongContent(cName) {
		var dirfd *os.File
		dirfd, err = os.Open(filepath.Dir(cPath))
		if err != nil {
			return fuse.ToStatus(err)
		}
		defer dirfd.Close()
		// Create ".name" file
		err = fs.nameTransform.WriteLongName(dirfd, cName, linkName)
		if err != nil {
			return fuse.ToStatus(err)
		}
		// Create "gocryptfs.longfile." symlink
		// TODO use syscall.Symlinkat once it is available in Go
		err = syscall.Symlink(cTarget, cPath)
		if err != nil {
			nametransform.DeleteLongName(dirfd, cName)
		}
	} else {
		// Create symlink
		err = os.Symlink(cTarget, cPath)
	}
	if err != nil {
		return fuse.ToStatus(err)
	}
	// Set owner
	if fs.args.PreserveOwner {
		err = os.Lchown(cPath, int(context.Owner.Uid), int(context.Owner.Gid))
		if err != nil {
			tlog.Warn.Printf("Mknod: Lchown failed: %v", err)
		}
	}
	return fuse.OK
}

示例#29
文件: main.go 项目: nqn/mesos-chapel

func triggerAgents(chapel_program []string, agents map[string]uint64) {
	time.Sleep(2 * time.Second)

	f, err := ioutil.TempFile("/tmp", "chapel")
	if err != nil {
		log.Fatal(err)
	}

	servers := ""
	for hostname, port := range agents {
		line := hostname + ":" + strconv.FormatUint(port, 10) + "\n"
		f.Write([]byte(line))

		servers = hostname + " " + servers
	}

	f.Close()

	pwd, _ := os.Getwd()

	name, _ := ioutil.TempDir("/tmp", "chapel")
	os.Chdir(name)

	// TODO(nnielsen): Assumes program + program_real executables.
	os.Symlink(pwd+"/"+chapel_program[0], name+"/"+chapel_program[0])
	os.Symlink(pwd+"/"+chapel_program[0]+"_real", name+"/"+chapel_program[0]+"_real")
	err = os.Symlink(pwd+"/bin/chapel-client", name+"/chapel-client")
	if err != nil {
		log.Fatal(err.Error())
	}

	cmd := exec.Command(chapel_program[0], chapel_program[1:]...)

	stdout, _ := cmd.StdoutPipe()
	go io.Copy(os.Stdout, stdout)

	stderr, _ := cmd.StderrPipe()
	go io.Copy(os.Stderr, stderr)

	cmd.Env = os.Environ()
	cmd.Env = append(cmd.Env, "SSH_CMD=./chapel-client")
	cmd.Env = append(cmd.Env, "SSH_OPTIONS="+f.Name()+" "+chapel_program[0]+"_real")
	cmd.Env = append(cmd.Env, "SSH_SERVERS="+servers)

	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}

	cmd.Wait()
}

示例#30
文件: metadata.go 项目: cjnygard/origin

// writeData writes requested metadata in specified files.
//
// The file visible in this volume are symlinks to files in the '.current'
// directory. Actual files are stored in an hidden timestamped directory which is
// symlinked to by '.current'. The timestamped directory and '.current' symlink
// are created in the plugin root dir.  This scheme allows the files to be
// atomically updated by changing the target of the '.current' symlink.  When new
// data is available:
//
// 1.  A new timestamped dir is created by writeDataInTimestampDir
// 2.  Symlinks for new files are created if needed
// 3.  The previous timestamped directory is detected reading the '.current' symlink
// 4.  In case no symlink exists then it's created and func returns (first execution)
// 5.  In case symlink exists a new temporary symlink is created .current_tmp
// 6.  .current_tmp is renamed to .current
// 7.  The previous timestamped directory is removed
func (m *metadataVolume) writeData(data *map[string]string) error {
	var timestampDir string
	var err error
	timestampDir, err = m.writeDataInTimestampDir(data)
	if err != nil {
		glog.Error(err)
		return err
	}
	// update symbolic links for relative paths
	if err = m.updateSymlinksToCurrentDir(); err != nil {
		os.RemoveAll(timestampDir)
		glog.Error(err)
		return err
	}

	_, timestampDirBaseName := filepath.Split(timestampDir)
	var oldTimestampDirectory string
	oldTimestampDirectory, err = os.Readlink(path.Join(m.GetPath(), currentDir))
	if err != nil {
		if os.IsNotExist(err) { // no link to currentDir so creates it
			err = os.Symlink(timestampDirBaseName, path.Join(m.GetPath(), currentDir))
		}
		return err // in any cases return
	}

	// nominal case: link to currentDir exists create the link to currentTmpDir
	if err = os.Symlink(timestampDirBaseName, path.Join(m.GetPath(), currentTmpDir)); err != nil {
		os.RemoveAll(timestampDir)
		glog.Error(err)
		return err
	}

	// Rename the symbolic link currentTmpDir to currentDir
	if err = os.Rename(path.Join(m.GetPath(), currentTmpDir), path.Join(m.GetPath(), currentDir)); err != nil {
		// in case of error remove latest data and currentTmpDir
		os.Remove(path.Join(m.GetPath(), currentTmpDir))
		os.RemoveAll(timestampDir)
		glog.Error(err)
		return err
	}
	// Remove oldTimestampDirectory
	if len(oldTimestampDirectory) > 0 {
		if e := os.RemoveAll(path.Join(m.GetPath(), oldTimestampDirectory)); e != nil {
			glog.Error(e)
			return e
		}
	}
	return nil
}

展开阅读全文