Exemplo n.º 1
0
func (p linux) SetupDataDir() error {
	dataDir := p.dirProvider.DataDir()

	sysDir := filepath.Join(dataDir, "sys")

	logDir := filepath.Join(sysDir, "log")
	err := p.fs.MkdirAll(logDir, os.FileMode(0750))
	if err != nil {
		return bosherr.WrapError(err, "Making %s dir", logDir)
	}

	_, _, _, err = p.cmdRunner.RunCommand("chown", "root:vcap", sysDir)
	if err != nil {
		return bosherr.WrapError(err, "chown %s", sysDir)
	}

	_, _, _, err = p.cmdRunner.RunCommand("chown", "root:vcap", logDir)
	if err != nil {
		return bosherr.WrapError(err, "chown %s", logDir)
	}

	runDir := filepath.Join(sysDir, "run")
	err = p.fs.MkdirAll(runDir, os.FileMode(0750))
	if err != nil {
		return bosherr.WrapError(err, "Making %s dir", runDir)
	}

	_, _, _, err = p.cmdRunner.RunCommand("chown", "root:vcap", runDir)
	if err != nil {
		return bosherr.WrapError(err, "chown %s", runDir)
	}

	return nil
}
Exemplo n.º 2
0
func TestExecutor_MakeExecutable(t *testing.T) {
	// Create a temp file
	f, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()
	defer os.Remove(f.Name())

	// Set its permissions to be non-executable
	f.Chmod(os.FileMode(0610))

	// Make a fake exececutor
	ctx := testExecutorContext(t)
	defer ctx.AllocDir.Destroy()
	executor := NewExecutor(log.New(os.Stdout, "", log.LstdFlags))

	err = executor.(*UniversalExecutor).makeExecutable(f.Name())
	if err != nil {
		t.Fatalf("makeExecutable() failed: %v", err)
	}

	// Check the permissions
	stat, err := f.Stat()
	if err != nil {
		t.Fatalf("Stat() failed: %v", err)
	}

	act := stat.Mode().Perm()
	exp := os.FileMode(0755)
	if act != exp {
		t.Fatalf("expected permissions %v; got %v", err)
	}
}
Exemplo n.º 3
0
// sameConfig reports whether src and dest config files are equal.
// Two config files are equal when they have the same file contents and
// Unix permissions. The owner, group, and mode must match.
// It return false in other cases.
func sameConfig(src, dest string) (bool, error) {
	if !isFileExist(dest) {
		return false, nil
	}
	d, err := fileStat(dest)
	if err != nil {
		return false, err
	}
	s, err := fileStat(src)
	if err != nil {
		return false, err
	}
	if d.Uid != s.Uid {
		log.Info(fmt.Sprintf("%s has UID %d should be %d", dest, d.Uid, s.Uid))
	}
	if d.Gid != s.Gid {
		log.Info(fmt.Sprintf("%s has GID %d should be %d", dest, d.Gid, s.Gid))
	}
	if d.Mode != s.Mode {
		log.Info(fmt.Sprintf("%s has mode %s should be %s", dest, os.FileMode(d.Mode), os.FileMode(s.Mode)))
	}
	if d.Md5 != s.Md5 {
		log.Info(fmt.Sprintf("%s has md5sum %s should be %s", dest, d.Md5, s.Md5))
	}
	if d.Uid != s.Uid || d.Gid != s.Gid || d.Mode != s.Mode || d.Md5 != s.Md5 {
		return false, nil
	}
	return true, nil
}
Exemplo n.º 4
0
func (r *RestoreSuite) createTestFiles(c *gc.C) {
	tarDirE := path.Join(r.cwd, "TarDirectoryEmpty")
	err := os.Mkdir(tarDirE, os.FileMode(0755))
	c.Check(err, jc.ErrorIsNil)

	tarDirP := path.Join(r.cwd, "TarDirectoryPopulated")
	err = os.Mkdir(tarDirP, os.FileMode(0755))
	c.Check(err, jc.ErrorIsNil)

	tarSubFile1 := path.Join(tarDirP, "TarSubFile1")
	tarSubFile1Handle, err := os.Create(tarSubFile1)
	c.Check(err, jc.ErrorIsNil)
	tarSubFile1Handle.WriteString("TarSubFile1")
	tarSubFile1Handle.Close()

	tarSubDir := path.Join(tarDirP, "TarDirectoryPopulatedSubDirectory")
	err = os.Mkdir(tarSubDir, os.FileMode(0755))
	c.Check(err, jc.ErrorIsNil)

	tarFile1 := path.Join(r.cwd, "TarFile1")
	tarFile1Handle, err := os.Create(tarFile1)
	c.Check(err, jc.ErrorIsNil)
	tarFile1Handle.WriteString("TarFile1")
	tarFile1Handle.Close()

	tarFile2 := path.Join(r.cwd, "TarFile2")
	tarFile2Handle, err := os.Create(tarFile2)
	c.Check(err, jc.ErrorIsNil)
	tarFile2Handle.WriteString("TarFile2")
	tarFile2Handle.Close()
	r.testFiles = []string{tarDirE, tarDirP, tarFile1, tarFile2}
}
Exemplo n.º 5
0
func createDevices() error {
	err := os.MkdirAll(pathPrefix, 644)
	if err != nil {
		log.Warnf("Failed to ensure presence of tether device directory: %s", err)
	}

	// create serial devices
	for i := 0; i < 3; i++ {
		path := fmt.Sprintf("%s/ttyS%d", pathPrefix, i)
		minor := 64 + i
		err = syscall.Mknod(path, syscall.S_IFCHR|uint32(os.FileMode(0660)), tether.Mkdev(4, minor))
		if err != nil {
			return fmt.Errorf("failed to create %s for com%d: %s", path, i+1, err)
		}
	}

	// make an access to urandom
	path := fmt.Sprintf("%s/urandom", pathPrefix)
	err = syscall.Mknod(path, syscall.S_IFCHR|uint32(os.FileMode(0444)), tether.Mkdev(1, 9))
	if err != nil {
		return fmt.Errorf("failed to create urandom access %s: %s", path, err)
	}

	return nil
}
Exemplo n.º 6
0
// Write the pidfile based on the flag. It is an error if the pidfile hasn't
// been configured.
func Write() error {
	if *pidfile == "" {
		return errNotConfigured
	}

	if err := os.MkdirAll(filepath.Dir(*pidfile), os.FileMode(0755)); err != nil {
		return err
	}

	file, err := atomicfile.New(*pidfile, os.FileMode(0644))
	if err != nil {
		return fmt.Errorf("error opening pidfile %s: %s", *pidfile, err)
	}
	defer file.Close() // in case we fail before the explicit close

	_, err = fmt.Fprintf(file, "%d", os.Getpid())
	if err != nil {
		return err
	}

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

	return nil
}
Exemplo n.º 7
0
// Close writes symlinks and dirs of the container, then closes
// the zip writer.
func (zwp *ZipWriterPool) Close() error {
	for _, symlink := range zwp.container.Symlinks {
		fh := zip.FileHeader{
			Name: symlink.Path,
		}
		fh.SetMode(os.FileMode(symlink.Mode))

		entryWriter, eErr := zwp.zw.CreateHeader(&fh)
		if eErr != nil {
			return errors.Wrap(eErr, 1)
		}

		entryWriter.Write([]byte(symlink.Dest))
	}

	for _, dir := range zwp.container.Dirs {
		fh := zip.FileHeader{
			Name: dir.Path + "/",
		}
		fh.SetMode(os.FileMode(dir.Mode))
		fh.SetModTime(time.Now())

		_, hErr := zwp.zw.CreateHeader(&fh)
		if hErr != nil {
			return errors.Wrap(hErr, 1)
		}
	}

	err := zwp.zw.Close()
	if err != nil {
		return errors.Wrap(err, 1)
	}

	return nil
}
Exemplo n.º 8
0
func (t *FlagsTest) Defaults() {
	f := parseArgs([]string{})

	// File system
	ExpectNe(nil, f.MountOptions)
	ExpectEq(0, len(f.MountOptions), "Options: %v", f.MountOptions)

	ExpectEq(os.FileMode(0755), f.DirMode)
	ExpectEq(os.FileMode(0644), f.FileMode)
	ExpectEq(-1, f.Uid)
	ExpectEq(-1, f.Gid)
	ExpectFalse(f.ImplicitDirs)

	// GCS
	ExpectEq("", f.KeyFile)
	ExpectEq(-1, f.EgressBandwidthLimitBytesPerSecond)
	ExpectEq(5, f.OpRateLimitHz)

	// Tuning
	ExpectEq(time.Minute, f.StatCacheTTL)
	ExpectEq(time.Minute, f.TypeCacheTTL)
	ExpectEq(1<<24, f.GCSChunkSize)
	ExpectEq("", f.TempDir)
	ExpectEq(1<<31, f.TempDirLimit)

	// Debugging
	ExpectFalse(f.DebugCPUProfile)
	ExpectFalse(f.DebugFuse)
	ExpectFalse(f.DebugGCS)
	ExpectFalse(f.DebugHTTP)
	ExpectFalse(f.DebugInvariants)
	ExpectFalse(f.DebugMemProfile)
}
Exemplo n.º 9
0
func TestSetPermissions(t *testing.T) {
	testPerm := 0755
	resp, err := remote.Tell("setPermissions", struct {
		Path      string
		Mode      os.FileMode
		Recursive bool
	}{
		Path: testfile1,
		Mode: os.FileMode(testPerm),
	})
	if err != nil {
		t.Fatal(err)
	}

	if !resp.MustBool() {
		t.Fatal("setPermissions should return true")
	}

	f, err := os.Open(testfile1)
	if err != nil {
		t.Fatal(err)
	}
	fi, err := f.Stat()
	if err != nil {
		t.Fatal(err)
	}

	if fi.Mode() != os.FileMode(testPerm) {
		t.Errorf("got %v expecting %v", fi.Mode(), testPerm)
	}

}
Exemplo n.º 10
0
func ProcessWriteFile(base string, wf *WriteFile) error {
	fullPath := path.Join(base, wf.Path)

	if err := os.MkdirAll(path.Dir(fullPath), os.FileMode(0744)); err != nil {
		return err
	}

	// Parse string representation of file mode as octal
	perm, err := strconv.ParseInt(wf.Permissions, 8, 32)
	if err != nil {
		return errors.New("Unable to parse file permissions as octal integer")
	}

	if err := ioutil.WriteFile(fullPath, []byte(wf.Content), os.FileMode(perm)); err != nil {
		return err
	}

	if wf.Owner != "" {
		// We shell out since we don't have a way to look up unix groups natively
		cmd := exec.Command("chown", wf.Owner, fullPath)
		if err := cmd.Run(); err != nil {
			return err
		}
	}

	return nil
}
Exemplo n.º 11
0
// Add the flags accepted by run to the supplied flag set, returning the
// variables into which the flags will parse.
func populateFlags(c *cli.Context) (flags *flagStorage) {
	flags = &flagStorage{
		// File system
		MountOptions: make(map[string]string),
		DirMode:      os.FileMode(c.Int("dir-mode")),
		FileMode:     os.FileMode(c.Int("file-mode")),
		Uid:          int64(c.Int("uid")),
		Gid:          int64(c.Int("gid")),

		// GCS,
		KeyFile: c.String("key-file"),
		EgressBandwidthLimitBytesPerSecond: c.Float64("limit-bytes-per-sec"),
		OpRateLimitHz:                      c.Float64("limit-ops-per-sec"),

		// Tuning,
		StatCacheTTL: c.Duration("stat-cache-ttl"),
		TypeCacheTTL: c.Duration("type-cache-ttl"),
		TempDir:      c.String("temp-dir"),
		ImplicitDirs: c.Bool("implicit-dirs"),

		// Debugging,
		DebugFuse:       c.Bool("debug_fuse"),
		DebugGCS:        c.Bool("debug_gcs"),
		DebugHTTP:       c.Bool("debug_http"),
		DebugInvariants: c.Bool("debug_invariants"),
	}

	// Handle the repeated "-o" flag.
	for _, o := range c.StringSlice("o") {
		mountpkg.ParseOptions(flags.MountOptions, o)
	}

	return
}
Exemplo n.º 12
0
func TestUbuntuSetupSsh(t *testing.T) {
	fakeFs, fakeCmdRunner, fakePartitioner, fakeFormatter := getUbuntuDependencies()
	fakeFs.HomeDirHomeDir = "/some/home/dir"

	ubuntu := newUbuntuPlatform(fakeFs, fakeCmdRunner, fakePartitioner, fakeFormatter)
	ubuntu.SetupSsh("some public key", "vcap")

	sshDirPath := "/some/home/dir/.ssh"
	sshDirStat := fakeFs.GetFileTestStat(sshDirPath)

	assert.Equal(t, fakeFs.HomeDirUsername, "vcap")

	assert.NotNil(t, sshDirStat)
	assert.Equal(t, sshDirStat.CreatedWith, "MkdirAll")
	assert.Equal(t, sshDirStat.FileMode, os.FileMode(0700))
	assert.Equal(t, sshDirStat.Username, "vcap")

	authKeysStat := fakeFs.GetFileTestStat(filepath.Join(sshDirPath, "authorized_keys"))

	assert.NotNil(t, authKeysStat)
	assert.Equal(t, authKeysStat.CreatedWith, "WriteToFile")
	assert.Equal(t, authKeysStat.FileMode, os.FileMode(0600))
	assert.Equal(t, authKeysStat.Username, "vcap")
	assert.Equal(t, authKeysStat.Content, "some public key")
}
Exemplo n.º 13
0
Arquivo: run.go Projeto: varung/droot
func createDevices(rootDir string, uid, gid int) error {
	nullDir := fp.Join(rootDir, os.DevNull)
	if err := osutil.Mknod(nullDir, syscall.S_IFCHR|uint32(os.FileMode(0666)), 1*256+3); err != nil {
		return err
	}

	if err := os.Lchown(nullDir, uid, gid); err != nil {
		return errwrap.Wrapff(err, "Failed to lchown %s: {{err}}", nullDir)
	}

	zeroDir := fp.Join(rootDir, "/dev/zero")
	if err := osutil.Mknod(zeroDir, syscall.S_IFCHR|uint32(os.FileMode(0666)), 1*256+3); err != nil {
		return err
	}

	if err := os.Lchown(zeroDir, uid, gid); err != nil {
		return errwrap.Wrapff(err, "Failed to lchown %s:", zeroDir)
	}

	for _, f := range []string{"/dev/random", "/dev/urandom"} {
		randomDir := fp.Join(rootDir, f)
		if err := osutil.Mknod(randomDir, syscall.S_IFCHR|uint32(os.FileMode(0666)), 1*256+9); err != nil {
			return err
		}

		if err := os.Lchown(randomDir, uid, gid); err != nil {
			return errwrap.Wrapff(err, "Failed to lchown %s: {{err}}", randomDir)
		}
	}

	return nil
}
Exemplo n.º 14
0
func WritePidfile(pidfile string, pid int) error {
	if pidfile == "" {
		return errors.New("pidfile not configured")
	}

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

	file, err := atomicfile.New(pidfile, os.FileMode(0644))
	if err != nil {
		return fmt.Errorf("error opening pidfile %s: %s", pidfile, err)
	}
	defer file.Close()

	_, err = fmt.Fprintf(file, "%d", pid)
	if err != nil {
		return err
	}

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

	return nil
}
Exemplo n.º 15
0
func TestWriterReset(t *testing.T) {
	b := new(bytes.Buffer)
	w := NewWriter(b)
	for i := 0; i < 2; i++ {
		debian := &fileInfo{
			name:  "debian-binary",
			mtime: time.Unix(1385068169, 0),
			mode:  os.FileMode(0100644) & os.ModePerm,
			size:  4,
		}
		if _, err := w.WriteFile(debian, strings.NewReader("2.0\n")); err != nil {
			t.Errorf("%d: %q", i, err)
			return
		}

		control := &fileInfo{
			name:  "control.tar.gz",
			mtime: time.Unix(1385068169, 0),
			mode:  os.FileMode(0100644) & os.ModePerm,
			size:  0,
		}
		if _, err := w.WriteFile(control, strings.NewReader("")); err != nil {
			t.Errorf("%d: %q", i, err)
			return
		}

		if archive := b.String(); archive != testCommon {
			t.Errorf("%d: got\n%q\nwant\n%q", i, archive, testCommon)
		}
		b.Reset()
		w.Reset(b)
	}
}
Exemplo n.º 16
0
func make_file(store *FileStore, name string, contents string) {
	file_location := store.OsPath(CloudPath(name))
	os.MkdirAll(path.Dir(file_location), os.FileMode(0777))
	if err := ioutil.WriteFile(file_location, []byte(contents), os.FileMode(0666)); err != nil {
		log.Panic(err.Error())
	}
}
Exemplo n.º 17
0
// GenerateSelfSignedCert creates a self-signed certificate and key for the given host.
// Host may be an IP or a DNS name
// The certificate will be created with file mode 0644. The key will be created with file mode 0600.
// If the certificate or key files already exist, they will be overwritten.
// Any parent directories of the certPath or keyPath will be created as needed with file mode 0755.
func GenerateSelfSignedCert(host, certPath, keyPath string) error {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return err
	}

	template := x509.Certificate{
		SerialNumber: big.NewInt(1),
		Subject: pkix.Name{
			CommonName: fmt.Sprintf("%s@%d", host, time.Now().Unix()),
		},
		NotBefore: time.Now(),
		NotAfter:  time.Now().Add(time.Hour * 24 * 365),

		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	if ip := net.ParseIP(host); ip != nil {
		template.IPAddresses = append(template.IPAddresses, ip)
	} else {
		template.DNSNames = append(template.DNSNames, host)
	}

	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return err
	}

	// Generate cert
	certBuffer := bytes.Buffer{}
	if err := pem.Encode(&certBuffer, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
		return err
	}

	// Generate key
	keyBuffer := bytes.Buffer{}
	if err := pem.Encode(&keyBuffer, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
		return err
	}

	// Write cert
	if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {
		return err
	}
	if err := ioutil.WriteFile(certPath, certBuffer.Bytes(), os.FileMode(0644)); err != nil {
		return err
	}

	// Write key
	if err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil {
		return err
	}
	if err := ioutil.WriteFile(keyPath, keyBuffer.Bytes(), os.FileMode(0600)); err != nil {
		return err
	}

	return nil
}
Exemplo n.º 18
0
func uploadBuildpackRequest(filename string) testnet.TestRequest {
	return testnet.TestRequest{
		Method: "PUT",
		Path:   "/v2/buildpacks/my-cool-buildpack-guid/bits",
		Response: testnet.TestResponse{
			Status: http.StatusCreated,
			Body:   `{ "metadata":{ "guid": "my-job-guid" } }`,
		},
		Matcher: func(request *http.Request) {
			err := request.ParseMultipartForm(4096)
			defer request.MultipartForm.RemoveAll()
			Expect(err).NotTo(HaveOccurred())

			Expect(len(request.MultipartForm.Value)).To(Equal(0))
			Expect(len(request.MultipartForm.File)).To(Equal(1))

			files, ok := request.MultipartForm.File["buildpack"]
			Expect(ok).To(BeTrue(), "Buildpack file part not present")
			Expect(len(files)).To(Equal(1), "Wrong number of files")

			buildpackFile := files[0]
			Expect(buildpackFile.Filename).To(Equal(filepath.Base(filename)), "Wrong file name")

			file, err := buildpackFile.Open()
			Expect(err).NotTo(HaveOccurred())

			zipReader, err := zip.NewReader(file, 4096)
			Expect(err).NotTo(HaveOccurred())

			actualFileNames := []string{}
			actualFileContents := []string{}
			for _, f := range zipReader.File {
				actualFileNames = append(actualFileNames, f.Name)
				c, _ := f.Open()
				content, _ := ioutil.ReadAll(c)
				actualFileContents = append(actualFileContents, string(content))
			}
			sort.Strings(actualFileNames)

			Expect(actualFileNames).To(Equal([]string{
				"bin/compile",
				"bin/detect",
				"bin/release",
				"lib/helper",
			}))
			Expect(actualFileContents).To(Equal([]string{
				"the-compile-script\n",
				"the-detect-script\n",
				"the-release-script\n",
				"the-helper-script\n",
			}))

			if runtime.GOOS != "windows" {
				Expect(zipReader.File[0].Mode()).To(Equal(os.FileMode(0755)))
				Expect(zipReader.File[1].Mode()).To(Equal(os.FileMode(0755)))
				Expect(zipReader.File[2].Mode()).To(Equal(os.FileMode(0755)))
			}
		},
	}
}
Exemplo n.º 19
0
Arquivo: files.go Projeto: m1911/hyper
func WriteFile(src io.Reader, targetFile string, permFile, uid, gid int) error {

	targetDir := filepath.Dir(targetFile)
	permDir := permFile | 0111

	if stat, err := os.Stat(targetDir); err != nil {
		if os.IsNotExist(err) {
			err = os.MkdirAll(targetDir, os.FileMode(permDir))
		}
		if err != nil {
			return err
		}
	} else if !stat.IsDir() {
		return errors.New("File target is not a dir: " + targetDir)
	}

	f, err := os.OpenFile(targetFile, os.O_RDWR|os.O_CREATE, os.FileMode(permFile))
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = io.Copy(f, src)
	if err != nil {
		return err
	}

	if err = syscall.Chown(targetFile, uid, gid); err != nil {
		return err
	}

	return nil

}
Exemplo n.º 20
0
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
}
Exemplo n.º 21
0
Arquivo: mount.go Projeto: ncw/rclone
// Mount mounts the remote at mountpoint.
//
// If noModTime is set then it
func Mount(f fs.Fs, mountpoint string) error {
	if debugFUSE {
		fuse.Debug = func(msg interface{}) {
			fs.Debug("fuse", "%v", msg)
		}
	}

	// Set permissions
	dirPerms = 0777 &^ os.FileMode(umask)
	filePerms = 0666 &^ os.FileMode(umask)

	// Show stats if the user has specifically requested them
	if cmd.ShowStats() {
		stopStats := cmd.StartStats()
		defer close(stopStats)
	}

	// Mount it
	errChan, err := mount(f, mountpoint)
	if err != nil {
		return errors.Wrap(err, "failed to mount FUSE fs")
	}

	// Wait for umount
	err = <-errChan
	if err != nil {
		return errors.Wrap(err, "failed to umount FUSE fs")
	}

	return nil
}
Exemplo n.º 22
0
func (p *instanceManager) SaveMetadata(instanceName string, metadata instanceMetadata) (err error) {
	if instanceName == "" {
		err = ERR_INSTANCE_NAME_IS_EMPTY.New()
		return
	}

	instanceHome := getInstanceHome(instanceName)

	if e := os.MkdirAll(instanceHome, os.FileMode(0755)); e != nil {
		err = ERR_INSTANCE_HOME_CREATE_FAILED.New(errors.Params{"dir": instanceHome})
		return
	}

	metadata.UpdateTime = time.Now()

	strMeta := ""
	if strMeta, err = metadata.Serialize(); err != nil {
		return
	}

	if e := ioutil.WriteFile(instanceHome+"/metadata", []byte(strMeta), os.FileMode(0644)); e != nil {
		err = ERR_SAVE_INSTANCE_METADATA_FAILED.New(errors.Params{"name": instanceName, "err": e})
		return
	}

	return
}
Exemplo n.º 23
0
func TestReadLocalMachineIDFound(t *testing.T) {
	dir, err := ioutil.TempDir(os.TempDir(), "fleet-")
	if err != nil {
		t.Fatalf("Failed creating tempdir: %v", err)
	}
	defer os.RemoveAll(dir)

	tmpMachineIDPath := filepath.Join(dir, "/etc/machine-id")
	err = os.MkdirAll(filepath.Dir(tmpMachineIDPath), os.FileMode(0755))
	if err != nil {
		t.Fatalf("Failed setting up fake mach ID path: %v", err)
	}

	err = ioutil.WriteFile(tmpMachineIDPath, []byte("pingpong"), os.FileMode(0644))
	if err != nil {
		t.Fatalf("Failed writing fake mach ID file: %v", err)
	}

	machID, err := readLocalMachineID(dir)
	if err != nil {
		t.Fatalf("Unexpected error reading machID: %v", err)
	}
	if machID != "pingpong" {
		t.Fatalf("Received incorrect machID %q, expected 'pingpong'", machID)
	}
}
Exemplo n.º 24
0
func TestFileInfo(t *testing.T) {
	f, err := os.Open(arTest[0].file)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	defer f.Close()

	ar := NewReader(f)
	hdr, err := ar.Next()
	if err != nil || hdr == nil {
		t.Fatalf("didn't get first file: %v", err)
	}

	fi := hdr.FileInfo()
	if name := fi.Name(); name != hdr.Name {
		t.Errorf("fi.Name() = %v; want %v", name, hdr.Name)
	}
	if size := fi.Size(); size != hdr.Size {
		t.Errorf("fi.Size() = %v; want %v", size, hdr.Size)
	}
	if mode := fi.Mode(); mode != os.FileMode(hdr.Mode).Perm() {
		t.Errorf("fi.Mode() = %v; want %v", mode, os.FileMode(hdr.Mode).Perm())
	}
	if modTime := fi.ModTime(); modTime != hdr.ModTime {
		t.Errorf("fi.ModTime() = %v; want %v", modTime, hdr.ModTime)
	}
	if isDir := fi.IsDir(); isDir != false {
		t.Errorf("fi.IsDir() = %v; want %v", isDir, false)
	}
}
Exemplo n.º 25
0
func TestHeaderCreationFromExistingFile(t *testing.T) {
	tmpFile, err := ioutil.TempFile("", "empty")
	if err != nil {
		t.Error(err)
		return
	}
	defer tmpFile.Close()

	err = tmpFile.Chmod(os.FileMode(0644))
	if err != nil {
		t.Error(err)
		return
	}
	defer os.Remove(tmpFile.Name())

	expected := &Operation{
		Mode: os.FileMode(0644),
		Size: 0,
		Name: filepath.Base(tmpFile.Name()),
	}

	actual, err := OpenFile(tmpFile.Name(), os.O_RDONLY, 0)
	if err != nil {
		t.Error(err)
		return
	}
	defer actual.Close()

	err = checkHeader(expected, actual)
	if err != nil {
		t.Error(err)
		return
	}
}
Exemplo n.º 26
0
func TestFileInfo(t *testing.T) {
	test := &fileInfo{
		name:  "debian-binary",
		mtime: time.Unix(1385068169, 0),
		mode:  os.FileMode(0644),
		size:  4,
	}

	if test.IsDir() != false {
		t.Error("IsDir")
	}
	if test.Mode() != os.FileMode(0644) {
		t.Error("Mode")
	}
	if test.ModTime() != time.Unix(1385068169, 0) {
		t.Error("ModTime")
	}
	if test.Name() != "debian-binary" {
		t.Error("Name")
	}
	if test.Size() != 4 {
		t.Error("Size")
	}
	if test.Sys() != nil {
		t.Error("Sys")
	}
}
Exemplo n.º 27
0
Arquivo: flags.go Projeto: x5u/goofys
// Add the flags accepted by run to the supplied flag set, returning the
// variables into which the flags will parse.
func PopulateFlags(c *cli.Context) (flags *FlagStorage) {
	flags = &FlagStorage{
		// File system
		MountOptions: make(map[string]string),
		DirMode:      os.FileMode(c.Int("dir-mode")),
		FileMode:     os.FileMode(c.Int("file-mode")),
		Uid:          uint32(c.Int("uid")),
		Gid:          uint32(c.Int("gid")),

		// Tuning,
		StatCacheTTL: c.Duration("stat-cache-ttl"),
		TypeCacheTTL: c.Duration("type-cache-ttl"),

		// S3
		Endpoint:       c.String("endpoint"),
		StorageClass:   c.String("storage-class"),
		UsePathRequest: c.Bool("use-path-request"),

		// Debugging,
		DebugFuse:  c.Bool("debug_fuse"),
		DebugS3:    c.Bool("debug_s3"),
		Foreground: c.Bool("f"),
	}

	// Handle the repeated "-o" flag.
	for _, o := range c.StringSlice("o") {
		parseOptions(flags.MountOptions, o)
	}
	return
}
Exemplo n.º 28
0
func TestWriterBasics(t *testing.T) {
	b := new(bytes.Buffer)
	b.Grow(len(testCommon))
	w := NewWriter(b)
	debian := &fileInfo{
		name:  "debian-binary",
		mtime: time.Unix(1385068169, 0),
		mode:  os.FileMode(0100644) & os.ModePerm,
		size:  4,
	}
	if _, err := w.WriteFile(debian, strings.NewReader("2.0\n")); err != nil {
		t.Error(err)
		return
	}

	control := &fileInfo{
		name:  "control.tar.gz",
		mtime: time.Unix(1385068169, 0),
		mode:  os.FileMode(0100644) & os.ModePerm,
		size:  0,
	}
	if _, err := w.WriteFile(control, strings.NewReader("")); err != nil {
		t.Error(err)
		return
	}

	if archive := b.String(); archive != testCommon {
		t.Errorf("got\n%q\nwant\n%q", archive, testCommon)
	}
}
Exemplo n.º 29
0
func (ca *CA) MakeClientCertificate(certFile, keyFile string, u user.Info) (*TLSCertificateConfig, error) {
	glog.V(4).Infof("Generating client cert in %s and key in %s", certFile, keyFile)
	// ensure parent dirs
	if err := os.MkdirAll(filepath.Dir(certFile), os.FileMode(0755)); err != nil {
		return nil, err
	}
	if err := os.MkdirAll(filepath.Dir(keyFile), os.FileMode(0755)); err != nil {
		return nil, err
	}

	clientPublicKey, clientPrivateKey, _ := NewKeyPair()
	clientTemplate, _ := newClientCertificateTemplate(x509request.UserToSubject(u))
	clientCrt, _ := ca.signCertificate(clientTemplate, clientPublicKey)

	certData, err := encodeCertificates(clientCrt)
	if err != nil {
		return nil, err
	}
	keyData, err := encodeKey(clientPrivateKey)
	if err != nil {
		return nil, err
	}

	if err = ioutil.WriteFile(certFile, certData, os.FileMode(0644)); err != nil {
		return nil, err
	}
	if err = ioutil.WriteFile(keyFile, keyData, os.FileMode(0600)); err != nil {
		return nil, err
	}

	return GetTLSCertificateConfig(certFile, keyFile)
}
Exemplo n.º 30
0
func TestUbuntuSetupSsh(t *testing.T) {
	fakeStats, fakeFs, fakeCmdRunner, fakeDiskManager, fakeCompressor := getUbuntuDependencies()
	fakeFs.HomeDirHomePath = "/some/home/dir"

	ubuntu := newUbuntuPlatform(fakeStats, fakeFs, fakeCmdRunner, fakeDiskManager, fakeCompressor)
	ubuntu.SetupSsh("some public key", "vcap")

	sshDirPath := "/some/home/dir/.ssh"
	sshDirStat := fakeFs.GetFileTestStat(sshDirPath)

	assert.Equal(t, fakeFs.HomeDirUsername, "vcap")

	assert.NotNil(t, sshDirStat)
	assert.Equal(t, fakesys.FakeFileTypeDir, sshDirStat.FileType)
	assert.Equal(t, sshDirStat.FileMode, os.FileMode(0700))
	assert.Equal(t, sshDirStat.Username, "vcap")

	authKeysStat := fakeFs.GetFileTestStat(filepath.Join(sshDirPath, "authorized_keys"))

	assert.NotNil(t, authKeysStat)
	assert.Equal(t, authKeysStat.FileType, fakesys.FakeFileTypeFile)
	assert.Equal(t, authKeysStat.FileMode, os.FileMode(0600))
	assert.Equal(t, authKeysStat.Username, "vcap")
	assert.Equal(t, authKeysStat.Content, "some public key")
}