Golang Chmod示例

说明

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

编程语言: Golang

命名空间/包名称: os

示例#1
文件: proxy_keyring.go 项目: daveadams/vaulted

func (pk *ProxyKeyring) Listen() (string, error) {
	if pk.listener != nil {
		return "", errors.New("Already listening")
	}

	dir, err := ioutil.TempDir("", "proxykeyring")
	if err != nil {
		return "", err
	}

	err = os.Chmod(dir, 0700)
	if err != nil {
		return "", err
	}

	listener := filepath.Join(dir, "listener")
	pk.listener, err = net.Listen("unix", listener)
	if err != nil {
		return "", err
	}

	err = os.Chmod(listener, 0600)
	if err != nil {
		return "", err
	}

	return listener, nil
}

示例#2
文件: file_snapshot_test.go 项目: eswdd/bosun

func TestFileSS_BadPerm(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("skipping file permission test on windows")
	}

	// Create a temp dir
	dir1, err := ioutil.TempDir("", "raft")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(dir1)

	// Create a sub dir and remove all permissions
	dir2, err := ioutil.TempDir(dir1, "badperm")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chmod(dir2, 000); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chmod(dir2, 777) // Set perms back for delete

	// Should fail
	if _, err := NewFileSnapshotStore(dir2, 3, nil); err == nil {
		t.Fatalf("should fail to use dir with bad perms")
	}
}

示例#3
文件: osutil.go 项目: hernad/syncthing

// InWritableDir calls fn(path), while making sure that the directory
// containing `path` is writable for the duration of the call.
func InWritableDir(fn func(string) error, path string) error {
	dir := filepath.Dir(path)
	info, err := os.Stat(dir)
	if err != nil {
		return err
	}
	if !info.IsDir() {
		return errors.New("Not a directory: " + path)
	}
	if info.Mode()&0200 == 0 {
		// A non-writeable directory (for this user; we assume that's the
		// relevant part). Temporarily change the mode so we can delete the
		// file or directory inside it.
		err = os.Chmod(dir, 0755)
		if err == nil {
			defer func() {
				err = os.Chmod(dir, info.Mode())
				if err != nil {
					// We managed to change the permission bits like a
					// millisecond ago, so it'd be bizarre if we couldn't
					// change it back.
					panic(err)
				}
			}()
		}
	}

	return fn(path)
}

示例#4
文件: sharedpullerstate.go 项目: rwx-zwx-awx/syncthing

// tempFile returns the fd for the temporary file, reusing an open fd
// or creating the file as necessary.
func (s *sharedPullerState) tempFile() (io.WriterAt, error) {
	s.mut.Lock()
	defer s.mut.Unlock()

	// If we've already hit an error, return early
	if s.err != nil {
		return nil, s.err
	}

	// If the temp file is already open, return the file descriptor
	if s.fd != nil {
		return lockedWriterAt{&s.mut, s.fd}, nil
	}

	// Ensure that the parent directory is writable. This is
	// osutil.InWritableDir except we need to do more stuff so we duplicate it
	// here.
	dir := filepath.Dir(s.tempName)
	if info, err := os.Stat(dir); err != nil {
		s.failLocked("dst stat dir", err)
		return nil, err
	} else if info.Mode()&0200 == 0 {
		err := os.Chmod(dir, 0755)
		if !s.ignorePerms && err == nil {
			defer func() {
				err := os.Chmod(dir, info.Mode().Perm())
				if err != nil {
					panic(err)
				}
			}()
		}
	}

	// Attempt to create the temp file
	flags := os.O_WRONLY
	if s.reused == 0 {
		flags |= os.O_CREATE | os.O_EXCL
	} else {
		// With sufficiently bad luck when exiting or crashing, we may have
		// had time to chmod the temp file to read only state but not yet
		// moved it to it's final name. This leaves us with a read only temp
		// file that we're going to try to reuse. To handle that, we need to
		// make sure we have write permissions on the file before opening it.
		err := os.Chmod(s.tempName, 0644)
		if !s.ignorePerms && err != nil {
			s.failLocked("dst create chmod", err)
			return nil, err
		}
	}
	fd, err := os.OpenFile(s.tempName, flags, 0666)
	if err != nil {
		s.failLocked("dst create", err)
		return nil, err
	}

	// Same fd will be used by all writers
	s.fd = fd

	return lockedWriterAt{&s.mut, s.fd}, nil
}

示例#5
文件: cert-manager.go 项目: TSRAppLabs/pbc

func InitDataDir() {
	if !exists(getDataDir()) {
		fmt.Println("Adding datadir")
		os.MkdirAll(getDataDir(), 0750)
		os.Chmod(getDataDir(), 0750)
	}

	if !exists(filepath.Join(getDataDir(), "index.json")) {
		fmt.Println("Adding index.json")
		file, err := os.Create(filepath.Join(getDataDir(), "index.json"))
		if err == nil {
			_, err := file.WriteString("{}")

			if err != nil {
				fmt.Println(err)
			}
			file.Close()
		}
	}

	if !exists(filepath.Join(getDataDir(), "wwdr.pem")) {
		fmt.Println("Copying wwdr.pem")
		if err := copyWWDR(); err != nil {
			fmt.Println(err)
		}
	}

	if !exists(filepath.Join(getDataDir(), "profiles")) {
		fmt.Println("Adding profiles")
		os.MkdirAll(filepath.Join(getDataDir(), "profiles"), 0750)
		os.Chmod(getDataDir(), 0750)
	}
}

示例#6
文件: osutil_test.go 项目: letiemble/syncthing

func TestInWritableDirWindowsRemoveAll(t *testing.T) {
	// os.RemoveAll should remove read only things on windows

	if runtime.GOOS != "windows" {
		t.Skipf("Tests not required")
		return
	}

	err := os.RemoveAll("testdata")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Chmod("testdata/windows/ro/readonlynew", 0700)
	defer os.RemoveAll("testdata")

	create := func(name string) error {
		fd, err := os.Create(name)
		if err != nil {
			return err
		}
		fd.Close()
		return nil
	}

	os.Mkdir("testdata", 0700)

	os.Mkdir("testdata/windows", 0500)
	os.Mkdir("testdata/windows/ro", 0500)
	create("testdata/windows/ro/readonly")
	os.Chmod("testdata/windows/ro/readonly", 0500)

	if err := os.RemoveAll("testdata/windows"); err != nil {
		t.Errorf("Unexpected error: %s", err)
	}
}

示例#7
文件: handler_test.go 项目: nats-io/graft

// The only real errors right now are log based or RPC.
func TestErrorHandler(t *testing.T) {
	ci := ClusterInfo{Name: "foo", Size: 1}
	_, rpc, log := genNodeArgs(t)

	// Use ChanHandler
	scCh := make(chan StateChange)
	errCh := make(chan error)
	chHand := NewChanHandler(scCh, errCh)

	node, err := New(ci, chHand, rpc, log)
	if err != nil {
		t.Fatalf("Expected no error, got: %v", err)
	}
	defer node.Close()

	// Force a write to err
	os.Chmod(node.logPath, 0400)
	defer os.Chmod(node.logPath, 0660)

	err = errWait(t, errCh)

	perr, ok := err.(*os.PathError)
	if !ok {
		t.Fatalf("Got wrong error type")
	}
	if perr.Op != "open" {
		t.Fatalf("Got wrong operation, wanted 'open', got %q", perr.Op)
	}
	if perr.Path != node.LogPath() {
		t.Fatalf("Expected the logPath, got %s \n", perr.Path)
	}
}

示例#8
文件: loopback_test.go 项目: taruti/go-fuse

func TestAccess(t *testing.T) {
	if os.Geteuid() == 0 {
		t.Log("Skipping TestAccess() as root.")
		return
	}
	me := NewTestCase(t)
	defer me.Cleanup()

	err := ioutil.WriteFile(me.origFile, []byte(contents), 0700)
	CheckSuccess(err)
	err = os.Chmod(me.origFile, 0)
	CheckSuccess(err)
	// Ugh - copied from unistd.h
	const W_OK uint32 = 2

	errCode := syscall.Access(me.mountFile, W_OK)
	if errCode != syscall.EACCES {
		t.Errorf("Expected EACCES for non-writable, %v %v", errCode, syscall.EACCES)
	}
	err = os.Chmod(me.origFile, 0222)
	CheckSuccess(err)
	errCode = syscall.Access(me.mountFile, W_OK)
	if errCode != nil {
		t.Errorf("Expected no error code for writable. %v", errCode)
	}
}

示例#9
文件: tar.go 项目: icsnju/apt-mesos

// UnTar a tar file
func UnTar(srcTar string, dstDir string) (err error) {
	// 清理路径字符串
	dstDir = path.Clean(dstDir) + string(os.PathSeparator)

	fr, er := os.Open(srcTar)
	if er != nil {
		return er
	}
	defer fr.Close()

	tr := tar.NewReader(fr)

	for hdr, er := tr.Next(); er != io.EOF; hdr, er = tr.Next() {
		if er != nil {
			return er
		}

		fi := hdr.FileInfo()

		dstFullPath := dstDir + hdr.Name

		if hdr.Typeflag == tar.TypeDir {
			os.MkdirAll(dstFullPath, fi.Mode().Perm())
			os.Chmod(dstFullPath, fi.Mode().Perm())
		} else {
			os.MkdirAll(path.Dir(dstFullPath), os.ModePerm)
			if er := unTarFile(dstFullPath, tr); er != nil {
				return er
			}
			os.Chmod(dstFullPath, fi.Mode().Perm())
		}
	}
	return nil
}

示例#10
文件: linux.go 项目: lucmichalski/rexray

func (d *driver) Mount(
	device, target, mountOptions, mountLabel string) error {

	if d.isNfsDevice(device) {

		if err := d.nfsMount(device, target); err != nil {
			return err
		}

		os.MkdirAll(d.volumeMountPath(target), d.fileModeMountPath())
		os.Chmod(d.volumeMountPath(target), d.fileModeMountPath())

		return nil
	}

	fsType, err := probeFsType(device)
	if err != nil {
		return err
	}

	options := label.FormatMountLabel("", mountLabel)
	options = fmt.Sprintf("%s,%s", mountOptions, mountLabel)
	if fsType == "xfs" {
		options = fmt.Sprintf("%s,nouuid", mountOptions)
	}

	if err := mount.Mount(device, target, fsType, options); err != nil {
		return fmt.Errorf("Couldn't mount directory %s at %s: %s", device, target, err)
	}

	os.MkdirAll(d.volumeMountPath(target), d.fileModeMountPath())
	os.Chmod(d.volumeMountPath(target), d.fileModeMountPath())

	return nil
}

示例#11
文件: tar.go 项目: asiainfoLDP/datafactory

// StreamFileAsTar streams the source file as a tar archive.
// The permissions of the file is changed to 0666.
func (t *stiTar) StreamDirAsTar(source, dest string, writer io.Writer) error {
	f, err := os.Open(source)
	if err != nil {
		return err
	}
	if info, _ := f.Stat(); !info.IsDir() {
		return fmt.Errorf("the source %q has to be directory, not a file", source)
	}
	defer f.Close()
	fs := util.NewFileSystem()
	tmpDir, err := ioutil.TempDir("", "s2i-")
	if err != nil {
		return err
	}
	defer os.RemoveAll(tmpDir)
	if err := fs.Copy(source, tmpDir); err != nil {
		return err
	}
	// Skip chmod if on windows OS
	if runtime.GOOS != "windows" {
		err = filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if info.IsDir() {
				return os.Chmod(path, 0777)
			}
			return os.Chmod(path, 0666)
		})
		if err != nil {
			return err
		}
	}
	return t.CreateTarStream(tmpDir, false, writer)
}

示例#12
文件: loopback_test.go 项目: seacoastboy/go-fuse

func TestAccess(t *testing.T) {
	if os.Geteuid() == 0 {
		t.Log("Skipping TestAccess() as root.")
		return
	}
	tc := NewTestCase(t)
	defer tc.Cleanup()

	contents := []byte{1, 2, 3}
	err := ioutil.WriteFile(tc.origFile, []byte(contents), 0700)
	if err != nil {
		t.Fatalf("WriteFile failed: %v", err)
	}
	err = os.Chmod(tc.origFile, 0)
	if err != nil {
		t.Fatalf("Chmod failed: %v", err)
	}
	// Ugh - copied from unistd.h
	const W_OK uint32 = 2

	errCode := syscall.Access(tc.mountFile, W_OK)
	if errCode != syscall.EACCES {
		t.Errorf("Expected EACCES for non-writable, %v %v", errCode, syscall.EACCES)
	}
	err = os.Chmod(tc.origFile, 0222)
	if err != nil {
		t.Fatalf("Chmod failed: %v", err)
	}
	errCode = syscall.Access(tc.mountFile, W_OK)
	if errCode != nil {
		t.Errorf("Expected no error code for writable. %v", errCode)
	}
}

示例#13
文件: gen.go 项目: essentialkaos/mockka

func updatePerms(dirPath, mockPath string) {
	if knf.GetS(ACCESS_USER) != "" || knf.GetS(ACCESS_GROUP) != "" {
		dirOwnerUID, dirOwnerGID, _ := fsutil.GetOwner(dirPath)
		mockOwnerUID, mockOwnerGID, _ := fsutil.GetOwner(mockPath)

		if knf.GetS(ACCESS_USER) != "" {
			userInfo, err := system.LookupUser(knf.GetS(ACCESS_USER))

			if err == nil {
				dirOwnerUID = userInfo.UID
				mockOwnerUID = userInfo.UID
			}
		}

		if knf.GetS(ACCESS_GROUP) != "" {
			groupInfo, err := system.LookupGroup(knf.GetS(ACCESS_GROUP))

			if err == nil {
				dirOwnerGID = groupInfo.GID
				mockOwnerGID = groupInfo.GID
			}
		}

		os.Chown(dirPath, dirOwnerUID, dirOwnerGID)
		os.Chown(mockPath, mockOwnerUID, mockOwnerGID)
	}

	os.Chmod(dirPath, knf.GetM(ACCESS_MOCK_DIR_PERMS))
	os.Chmod(mockPath, knf.GetM(ACCESS_MOCK_PERMS))
}

示例#14
文件: main.go 项目: nickschuch/permissions

func update(p string, f os.FileInfo, err error) error {
	// Check the file mode.
	if f.IsDir() {
		m := os.FileMode(*cliChmodDir)
		if f.Mode().Perm() != m.Perm() {
			err := os.Chmod(p, m)
			if err != nil {
				log.Printf("Failed to chmod directory: %s", p)
			}
			log.Printf("Updated chmod directory: %s", p)
		}
	} else {
		m := os.FileMode(*cliChmodFile)
		if f.Mode().Perm() != m.Perm() {
			err := os.Chmod(p, m)
			if err != nil {
				log.Printf("Failed to chmod file: %s", p)
			}
			log.Printf("Updated chmod file: %s", p)
		}
	}

	// Check the file owner.
	fu := f.Sys().(*syscall.Stat_t).Uid
	fg := f.Sys().(*syscall.Stat_t).Gid
	if int(fu) != uid && int(fg) != gid {
		err := os.Chown(p, uid, gid)
		if err != nil {
			log.Printf("Failed to chown file: %s", p)
		}
		log.Printf("Updated chown file: %s", p)
	}

	return nil
}

示例#15

func (s *BootstrapSuite) TestGUIArchiveInfoError(c *gc.C) {
	if runtime.GOOS == "windows" {
		// TODO frankban: skipping for now due to chmod problems with mode 0000
		// on Windows. We will re-enable this test after further investigation:
		// "jujud bootstrap" is never run on Windows anyway.
		c.Skip("needs chmod investigation")
	}
	dir := filepath.FromSlash(agenttools.SharedGUIDir(s.dataDir))
	info := filepath.Join(dir, "downloaded-gui.txt")
	err := os.Chmod(info, 0000)
	c.Assert(err, jc.ErrorIsNil)
	defer os.Chmod(info, 0600)
	_, cmd, err := s.initBootstrapCommand(
		c, nil, "--model-config", s.b64yamlControllerModelConfig,
		"--hosted-model-config", s.b64yamlHostedModelConfig,
		"--instance-id", string(s.instanceId))
	c.Assert(err, jc.ErrorIsNil)

	var tw loggo.TestWriter
	err = loggo.RegisterWriter("bootstrap-test", &tw, loggo.DEBUG)
	c.Assert(err, jc.ErrorIsNil)
	defer loggo.RemoveWriter("bootstrap-test")

	err = cmd.Run(nil)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(tw.Log(), jc.LogMatches, jc.SimpleMessages{{
		loggo.WARNING,
		`cannot set up Juju GUI: cannot fetch GUI info: cannot read GUI metadata in tools directory: .*`,
	}})
}

示例#16
文件: start-gogs.go 项目: maxwhale/docker-gogs-centos

func createCerts() {
	basedir := filepath.Dir(defaultCertFile)
	if _, err := os.Stat(basedir); os.IsNotExist(err) {
		if err := os.MkdirAll(basedir, 0755); err != nil {
			log.Fatal(err)
		}
	}
	if _, err := os.Stat(defaultCertFile); os.IsExist(err) {
		return
	}
	os.Chdir(basedir)
	certHosts := []string{"localhost", "127.0.0.1"}
	if hostname, err := os.Hostname(); err == nil {
		certHosts = append(certHosts, hostname)
	}
	if len(os.Getenv("GOGS_SERVER__ROOT_URL")) > 0 {
		certHosts = append(certHosts, os.Getenv("GOGS_SERVER__ROOT_URL"))
	}
	cmd := exec.Command("/opt/gogs/gogs", "cert", fmt.Sprintf("%s=%s", "-host", strings.Join(certHosts, ",")))
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	os.Chmod("cert.pem", 0644)
	os.Chmod("key.pem", 0644)
}

示例#17
文件: file_action.go 项目: qingxialanshan/Work

func copyFile(source string, dest string) (err error) {
	sourcefile, err := os.Open(source)
	if err != nil {
		return err
	}

	defer sourcefile.Close()

	if _, e := os.Stat(dest); e == nil {
		//fmt.Println("the file is not overide able", filepath.Join(dest, file.Name()))
		os.Chmod(dest, 0777)
	}

	destfile, err := os.Create(dest)
	if err != nil {
		return err
	}

	defer destfile.Close()

	_, err = io.Copy(destfile, sourcefile)
	if err == nil {
		sourceinfo, err := os.Stat(source)
		fmt.Println(sourceinfo.Mode())
		if err == nil {
			err = os.Chmod(dest, sourceinfo.Mode())
		}

	}

	return
}

示例#18
文件: core_test.go 项目: kc87654321/goxc

func TestSanityCheck(t *testing.T) {
	//goroot := runtime.GOROOT()
	err := SanityCheck("i")
	if err == nil {
		t.Fatalf("sanity check failed! Expected to flag incorrect GOROOT variable")
	}
	tmpDir, err := ioutil.TempDir("", "goxc_test_sanityCheck")
	defer os.RemoveAll(tmpDir)
	err = SanityCheck(tmpDir)
	if err == nil {
		t.Fatalf("sanity check failed! Expected to notice missing src folder")
	}

	srcDir := filepath.Join(tmpDir, "src")
	os.Mkdir(srcDir, 0700)
	scriptname := GetMakeScriptPath(tmpDir)
	ioutil.WriteFile(scriptname, []byte("1"), 0111)
	err = SanityCheck(tmpDir)
	if err != nil {
		t.Fatalf("sanity check failed! Did not find src folder: %v", err)
	}
	//chmod doesnt work in Windows.
	//TODO: verify which OSes support chmod
	if runtime.GOOS == "linux" {
		os.Chmod(srcDir, 0600)
		defer os.Chmod(srcDir, 0700)
		err = SanityCheck(tmpDir)
		if err == nil {
			t.Fatalf("sanity check failed! Expected NOT to be able to open src folder")
		}
	}
}

示例#19
文件: filetesting_test.go 项目: fabricematrat/testing

func (s *EntrySuite) TestRemovedCreateFailure(c *gc.C) {
	ft.File{"some-file", "content", 0644}.Create(c, s.basePath)
	os.Chmod(s.basePath, 0444)
	defer os.Chmod(s.basePath, 0777)
	c.ExpectFailure("should fail to remove file")
	ft.Removed{"some-file"}.Create(c, s.basePath)
}

示例#20
文件: policy_test.go 项目: robert-ancell/snapd

func (s *policySuite) TestIterOpRemoveBadDirmode(c *C) {
	err := iterOp(install, filepath.Join(s.appg, "*"), s.dest, "foo_")
	c.Assert(err, IsNil)
	c.Assert(os.Chmod(s.dest, 0), IsNil)
	defer os.Chmod(s.dest, 0755)
	err = iterOp(remove, filepath.Join(s.appg, "*"), s.dest, "foo_")
	c.Assert(err, ErrorMatches, ".*unable to remove.*")
}

示例#21
文件: config.go 项目: ncw/rclone

// SaveConfig saves configuration file.
// if configKey has been set, the file will be encrypted.
func SaveConfig() {
	if len(configKey) == 0 {
		err := goconfig.SaveConfigFile(configData, ConfigPath)
		if err != nil {
			log.Fatalf("Failed to save config file: %v", err)
		}
		err = os.Chmod(ConfigPath, 0600)
		if err != nil {
			ErrorLog(nil, "Failed to set permissions on config file: %v", err)
		}
		return
	}
	var buf bytes.Buffer
	err := goconfig.SaveConfigData(configData, &buf)
	if err != nil {
		log.Fatalf("Failed to save config file: %v", err)
	}

	f, err := os.Create(ConfigPath)
	if err != nil {
		log.Fatalf("Failed to save config file: %v", err)
	}

	fmt.Fprintln(f, "# Encrypted rclone configuration File")
	fmt.Fprintln(f, "")
	fmt.Fprintln(f, "RCLONE_ENCRYPT_V0:")

	// Generate new nonce and write it to the start of the ciphertext
	var nonce [24]byte
	n, _ := rand.Read(nonce[:])
	if n != 24 {
		log.Fatalf("nonce short read: %d", n)
	}
	enc := base64.NewEncoder(base64.StdEncoding, f)
	_, err = enc.Write(nonce[:])
	if err != nil {
		log.Fatalf("Failed to write config file: %v", err)
	}

	var key [32]byte
	copy(key[:], configKey[:32])

	b := secretbox.Seal(nil, buf.Bytes(), &nonce, &key)
	_, err = enc.Write(b)
	if err != nil {
		log.Fatalf("Failed to write config file: %v", err)
	}
	_ = enc.Close()
	err = f.Close()
	if err != nil {
		log.Fatalf("Failed to close config file: %v", err)
	}

	err = os.Chmod(ConfigPath, 0600)
	if err != nil {
		ErrorLog(nil, "Failed to set permissions on config file: %v", err)
	}
}

示例#22
文件: ask_windows.go 项目: sadasant/go-utils

func AskPass(q string) string {
	var pass string

	cloudwalk_dir := GetPathFromHome("/.cloudwalk")
	pass_file := cloudwalk_dir + "/getpass.sh"
	pass_script := `#!/bin/bash
function finish {
	reset
}
trap finish EXIT
unset password
read -e -s password
echo $password
`

	os.Mkdir(cloudwalk_dir, 0755)
	ioutil.WriteFile(pass_file, []byte(pass_script), 0755)

	os.Chmod(cloudwalk_dir, 0755)
	os.Chmod(pass_file, 0755)

	cmd := exec.Command("bash", pass_file)

	var b bytes.Buffer
	cmd.Stdout = &b
	cmd.Stdin = os.Stdin

	fmt.Printf("%s", q)

	// Clean OS Exit
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)
	go func() {
		<-c
		if pass == "" {
			println("\nDone. Press Enter.")
		}
	}()

	if err := cmd.Start(); err != nil {
		Exitf(2, "Failed to start the password request. Error: %s\n", err.Error())
	}

	if err := cmd.Wait(); err != nil {
		Exitf(2, "Failed to wait for the password request. Error: %s\n", err.Error())
	}

	pass = b.String()
	pass = pass[:len(pass)-1]

	os.Remove(pass_file)

	close(c)
	println()
	return pass
}

示例#23
文件: upgradegui_test.go 项目: bac/juju

func (s *upgradeGUISuite) TestUpgradeGUIFileError(c *gc.C) {
	path, _, _ := saveGUIArchive(c, "2.0.0")
	err := os.Chmod(path, 0000)
	c.Assert(err, jc.ErrorIsNil)
	defer os.Chmod(path, 0600)
	out, err := s.run(c, path)
	c.Assert(err, gc.ErrorMatches, "cannot open GUI archive: .*")
	c.Assert(out, gc.Equals, "")
}

示例#24
文件: patch_test.go 项目: cmars/replican-sync

func DoTestSetModeNew(t *testing.T, mkrepo repoMaker) {
	tg := treegen.New()
	treeSpec := tg.D("foo",
		tg.D("bar",
			tg.D("aleph",
				tg.F("A", tg.B(42, 65537)),
				tg.F("a", tg.B(42, 65537)))))
	srcpath := treegen.TestTree(t, treeSpec)
	os.Chmod(filepath.Join(srcpath, "foo", "bar", "aleph", "A"), 0765)
	os.Chmod(filepath.Join(srcpath, "foo", "bar"), 0711)
	defer os.RemoveAll(srcpath)
	srcRepo := mkrepo(t)
	defer srcRepo.Close()
	srcStore, err := fs.NewLocalStore(srcpath, srcRepo)
	assert.T(t, err == nil)

	tg = treegen.New()
	treeSpec = tg.D("foo")
	dstpath := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(dstpath)
	dstRepo := mkrepo(t)
	defer dstRepo.Close()
	dstStore, err := fs.NewLocalStore(dstpath, dstRepo)
	assert.T(t, err == nil)

	patchPlan := NewPatchPlan(srcStore, dstStore)
	failedCmd, err := patchPlan.Exec()
	assert.Tf(t, failedCmd == nil, "%v", failedCmd)
	assert.Tf(t, err == nil, "%v", err)

	errors := make(chan os.Error)
	go func() {
		patchPlan.Clean(errors)
		close(errors)
	}()
	for err := range errors {
		assert.Tf(t, err == nil, "%v", err)
	}

	errors = make(chan os.Error)
	go func() {
		patchPlan.SetMode(errors)
		close(errors)
	}()
	for err := range errors {
		assert.Tf(t, err == nil, "%v", err)
	}

	fileinfo, err := os.Stat(filepath.Join(dstpath, "foo", "bar", "aleph", "A"))
	assert.T(t, fileinfo != nil)
	assert.Equal(t, uint32(0765), fileinfo.Permission())

	fileinfo, err = os.Stat(filepath.Join(dstpath, "foo", "bar"))
	assert.T(t, fileinfo != nil)
	assert.Equal(t, uint32(0711), fileinfo.Permission())
}

示例#25
文件: host.go 项目: kevinawalsh/cloudproxy

func startHost(domain *tao.Domain) {

	if *options.Bool["daemon"] && *options.Bool["foreground"] {
		options.Usage("Can supply only one of -daemon and -foreground")
	}
	if *options.Bool["daemon"] {
		daemonize()
	}

	cfg := configureFromFile()
	configureFromOptions(cfg)
	host, err := loadHost(domain, cfg)
	options.FailIf(err, "Can't create host")

	sockPath := path.Join(hostPath(), "admin_socket")
	// Set the socketPath directory go+rx so tao_launch can access sockPath and
	// connect to this linux host, even when tao_launch is run as non-root.
	err = os.Chmod(path.Dir(sockPath), 0755)
	options.FailIf(err, "Can't change permissions")
	uaddr, err := net.ResolveUnixAddr("unix", sockPath)
	options.FailIf(err, "Can't resolve unix socket")
	sock, err := net.ListenUnix("unix", uaddr)
	options.FailIf(err, "Can't create admin socket")
	defer sock.Close()
	err = os.Chmod(sockPath, 0666)
	if err != nil {
		sock.Close()
		options.Fail(err, "Can't change permissions on admin socket")
	}

	go func() {
		verbose.Printf("Linux Tao Service (%s) started and waiting for requests\n", host.HostName())
		err = tao.NewLinuxHostAdminServer(host).Serve(sock)
		verbose.Printf("Linux Tao Service finished\n")
		sock.Close()
		options.FailIf(err, "Error serving admin requests")
		os.Exit(0)
	}()

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM)
	<-c
	verbose.Printf("Linux Tao Service shutting down\n")
	err = shutdown()
	if err != nil {
		sock.Close()
		options.Fail(err, "Can't shut down admin socket")
	}

	// The above goroutine will normally end by calling os.Exit(), so we
	// can block here indefinitely. But if we get a second kill signal,
	// let's abort.
	verbose.Printf("Waiting for shutdown....\n")
	<-c
	options.Fail(nil, "Could not shut down linux_host")
}

示例#26
文件: 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")
		}
	}
}

示例#27
文件: storage_test.go 项目: jameinel/core

func (s *storageSuite) TestTmpDirPermissions(c *gc.C) {
	// newSSHStorage will fail if it can't create or change the
	// permissions of the temporary directory.
	storageDir := c.MkDir()
	tmpdir := c.MkDir()
	os.Chmod(tmpdir, 0400)
	defer os.Chmod(tmpdir, 0755)
	_, err := newSSHStorage("example.com", storageDir, filepath.Join(tmpdir, "subdir2"))
	c.Assert(err, gc.ErrorMatches, ".*install: cannot create directory.*Permission denied.*")
}

示例#28
文件: heartbeat_test.go 项目: nats-io/graft

func TestHeartBeatAsLeaderErrorOnWrite(t *testing.T) {
	node := hbNode(t, 3)
	defer node.Close()

	// Set term to artificial higher value.
	newTerm := uint64(8)
	node.setTerm(newTerm)

	// Create fake node to elect the Leader.
	fake := fakeNode("fake")

	// Hook up to MockRPC layer
	mockRegisterPeer(fake)
	defer mockUnregisterPeer(fake.id)

	node.mu.Lock()
	node.electTimer.Reset(1 * time.Millisecond)
	node.mu.Unlock()

	vreq := <-fake.VoteRequests

	// Send Fake VoteResponse to promote node to Leader
	node.VoteResponses <- &pb.VoteResponse{Term: vreq.Term, Granted: true}

	if state := waitForState(node, LEADER); state != LEADER {
		t.Fatalf("Expected Node to be in Leader state, got: %s", state)
	}
	if curLeader := waitForLeader(node, node.Id()); curLeader != node.Id() {
		t.Fatalf("Expected us to be leader, got: %s\n", curLeader)
	}
	if node.CurrentTerm() != vreq.Term {
		t.Fatalf("Expected CurrentTerm of %d, got: %d\n",
			vreq.Term, node.CurrentTerm())
	}

	// Test persistent state
	testStateOfNode(t, node)

	// Change log permissions to cause error
	if err := os.Chmod(node.logPath, 0400); err != nil {
		t.Fatalf("Unable to change log permissions: %v", err)
	}

	// Send an heartbeat with higher term, which should cause the current leader
	// to step down.
	sendAndWait(node, &pb.Heartbeat{Term: newTerm + 10, Leader: "other"})

	// Server should stepdown
	if state := waitForState(node, FOLLOWER); state != FOLLOWER {
		t.Fatalf("Expected Node to be in Follower state, got %s", state)
	}

	// Reset the permission
	os.Chmod(node.logPath, 0660)
}

示例#29
文件: puller.go 项目: WIZARD-CXY/golang-devops-stuff

func (p *puller) handleEmptyBlock(b bqBlock) {
	f := b.file
	of := p.openFiles[f.Name]

	if b.last {
		if of.err == nil {
			of.file.Close()
		}
	}

	if protocol.IsDeleted(f.Flags) {
		if debug {
			l.Debugf("pull: delete %q", f.Name)
		}
		os.Remove(of.temp)

		// Ensure the file and the directory it is in is writeable so we can remove the file
		dirName := filepath.Dir(of.filepath)
		os.Chmod(of.filepath, 0666)
		if dirName != p.repoCfg.Directory {
			os.Chmod(dirName, 0777)
		}
		if p.versioner != nil {
			if debug {
				l.Debugln("pull: deleting with versioner")
			}
			if err := p.versioner.Archive(p.repoCfg.Directory, of.filepath); err == nil {
				p.model.updateLocal(p.repoCfg.ID, f)
			} else if debug {
				l.Debugln("pull: error:", err)
			}
		} else if err := os.Remove(of.filepath); err == nil || os.IsNotExist(err) {
			p.model.updateLocal(p.repoCfg.ID, f)
		}
	} else {
		if debug {
			l.Debugf("pull: no blocks to fetch and nothing to copy for %q / %q", p.repoCfg.ID, f.Name)
		}
		t := time.Unix(f.Modified, 0)
		if os.Chtimes(of.temp, t, t) != nil {
			delete(p.openFiles, f.Name)
			return
		}
		if !p.repoCfg.IgnorePerms && protocol.HasPermissionBits(f.Flags) && os.Chmod(of.temp, os.FileMode(f.Flags&0777)) != nil {
			delete(p.openFiles, f.Name)
			return
		}
		osutil.ShowFile(of.temp)
		if osutil.Rename(of.temp, of.filepath) == nil {
			p.model.updateLocal(p.repoCfg.ID, f)
		}
	}
	delete(p.openFiles, f.Name)
}

示例#30
文件: main.go 项目: rrudduck/golang-stuff

func shipCircuit() string {
	tmpdir, err := MakeTempDir()
	if err != nil {
		Fatalf("Problem making packaging directory (%s)\n", err)
	}

	// Copy worker binary over to shipping directory
	println("--Packaging worker", x.binary)
	binpkg := workerPkgPath()
	_, workerName := path.Split(binpkg)
	shipFile := path.Join(tmpdir, x.binary) // Destination binary location and name
	if _, err = CopyFile(path.Join(binpkg, workerName), shipFile); err != nil {
		Fatalf("Problem copying circuit worker binary (%s)\n", err)
	}
	if err = os.Chmod(shipFile, 0755); err != nil {
		Fatalf("Problem chmod'ing circuit worker binary (%s)\n", err)
	}

	// Copy command-line helper tools over to shipping directory
	for _, cpkg := range cmdPkg {
		println("--Packaging helper", cpkg)
		shipHelper := path.Join(tmpdir, cpkg)
		if _, err = CopyFile(path.Join(helperPkgPath(cpkg), cpkg), shipHelper); err != nil {
			Fatalf("Problem copying circuit helper binary (%s)\n", err)
		}
		if err = os.Chmod(shipHelper, 0755); err != nil {
			Fatalf("Problem chmod'ing circuit helper binary (%s)\n", err)
		}
	}

	// Copy additional user commands to shipping directory
	for _, cmdpkg := range x.cmdPkgs {
		println("--Packaging command", cmdpkg)
		_, cmd := path.Split(cmdpkg)
		shipCommand := path.Join(tmpdir, cmd)
		if _, err = CopyFile(path.Join(cmdPkgPath(cmdpkg), cmd), shipCommand); err != nil {
			Fatalf("Problem copying command binary (%s)\n", err)
		}
		if err = os.Chmod(shipCommand, 0755); err != nil {
			Fatalf("Problem chmod'ing command binary (%s)\n", err)
		}
	}

	// Place the zookeeper dynamic libraries in the shipment
	// Shipping Zookeeper is not necessary when static linking (currently enabled).
	/*
		println("--Packaging Zookeeper libraries")
		if err = ShellCopyFile(path.Join(x.zlib, "libzookeeper*"), tmpdir+"/"); err != nil {
			Fatalf("Problem copying Zookeeper library files (%s)\n", err)
		}
	*/

	return tmpdir
}

展开阅读全文