Пример #1
1
func authInit() {
	os.MkdirAll(path.Join(common.BaseDir, "auth"), 0755)
	err := os.RemoveAll(path.Join(common.BaseDir, "auth", "secure"))
	if err != nil {
		log.Printf("Failed to clean out the secure directory. %v\n", err)
		os.Exit(-1)
	}
	err = os.RemoveAll(path.Join(common.BaseDir, "auth", "user"))
	if err != nil {
		log.Printf("Failed to clean out the user directory. %v\n", err)
		os.Exit(-1)
	}
	os.MkdirAll(path.Join(common.BaseDir, "auth", "user"), 0755)
	os.MkdirAll(path.Join(common.BaseDir, "auth", "secure"), 0700)
	if common.System && platform.PlatformGet() == platform.Windows {
		err = common.Cacls(path.Join(common.BaseDir, "auth", "secure"), "/p", "NT AUTHORITY\\SYSTEM:f", "BUILTIN\\Administrators:F")
		if err != nil {
			log.Printf("Failed to run cacls %v\n", err)
			os.Exit(-1)
		}
		err = common.Cacls(path.Join(common.BaseDir, "auth", "user"), "/p", "NT AUTHORITY\\SYSTEM:f", "BUILTIN\\Users:r", "BUILTIN\\Administrators:F")
		if err != nil {
			log.Printf("Failed to run cacls on auth user %v\n", err)
			os.Exit(-1)
		}
	}
}
Пример #2
0
// MountSpecialDirs mounts the dev and proc file system from the host to the
// chroot
func (d *AllocDir) MountSpecialDirs(taskDir string) error {
	// Mount dev
	dev := filepath.Join(taskDir, "dev")
	if !d.pathExists(dev) {
		if err := os.MkdirAll(dev, 0777); err != nil {
			return fmt.Errorf("Mkdir(%v) failed: %v", dev, err)
		}

		if err := syscall.Mount("none", dev, "devtmpfs", syscall.MS_RDONLY, ""); err != nil {
			return fmt.Errorf("Couldn't mount /dev to %v: %v", dev, err)
		}
	}

	// Mount proc
	proc := filepath.Join(taskDir, "proc")
	if !d.pathExists(proc) {
		if err := os.MkdirAll(proc, 0777); err != nil {
			return fmt.Errorf("Mkdir(%v) failed: %v", proc, err)
		}

		if err := syscall.Mount("none", proc, "proc", syscall.MS_RDONLY, ""); err != nil {
			return fmt.Errorf("Couldn't mount /proc to %v: %v", proc, err)
		}
	}

	return nil
}
Пример #3
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)
}
Пример #4
0
func TestCopyFileWithTarSrcFile(t *testing.T) {
	folder, err := ioutil.TempDir("", "docker-archive-test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(folder)
	dest := filepath.Join(folder, "dest")
	srcFolder := filepath.Join(folder, "src")
	src := filepath.Join(folder, filepath.Join("src", "src"))
	err = os.MkdirAll(srcFolder, 0740)
	if err != nil {
		t.Fatal(err)
	}
	err = os.MkdirAll(dest, 0740)
	if err != nil {
		t.Fatal(err)
	}
	ioutil.WriteFile(src, []byte("content"), 0777)
	err = CopyWithTar(src, dest+"/")
	if err != nil {
		t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err)
	}
	_, err = os.Stat(dest)
	if err != nil {
		t.Fatalf("Destination folder should contain the source file but did not.")
	}
}
Пример #5
0
func (s *PartitionTestSuite) SetUpTest(c *C) {
	dirs.SetRootDir(c.MkDir())
	err := os.MkdirAll((&grub{}).Dir(), 0755)
	c.Assert(err, IsNil)
	err = os.MkdirAll((&uboot{}).Dir(), 0755)
	c.Assert(err, IsNil)
}
Пример #6
0
func InitDiffFile() error {
	file1Data := "3"
	file2Data := "2"
	file3Data := "1"

	if err := os.MkdirAll(path.Join(diffTempDir, "1"), 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(diffTempDir, "2"), 0755); err != nil {
		return err
	}
	if err := os.MkdirAll(path.Join(diffTempDir, "3"), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path.Join(diffTempDir, "1")+"/1", []byte(file1Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path.Join(diffTempDir, "2")+"/2", []byte(file2Data), 0755); err != nil {
		return err
	}
	if err := ioutil.WriteFile(path.Join(diffTempDir, "3")+"/3", []byte(file3Data), 0755); err != nil {
		return err
	}

	return nil
}
Пример #7
0
func TestMount(t *testing.T) {
	graph := tempGraph(t)
	defer os.RemoveAll(graph.Root)
	archive, err := fakeTar()
	if err != nil {
		t.Fatal(err)
	}
	image, err := graph.Create(archive, nil, "Testing", "", nil)
	if err != nil {
		t.Fatal(err)
	}
	tmp, err := ioutil.TempDir("", "docker-test-graph-mount-")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmp)
	rootfs := path.Join(tmp, "rootfs")
	if err := os.MkdirAll(rootfs, 0700); err != nil {
		t.Fatal(err)
	}
	rw := path.Join(tmp, "rw")
	if err := os.MkdirAll(rw, 0700); err != nil {
		t.Fatal(err)
	}
	if err := image.Mount(rootfs, rw); err != nil {
		t.Fatal(err)
	}
	// FIXME: test for mount contents
	defer func() {
		if err := Unmount(rootfs); err != nil {
			t.Error(err)
		}
	}()
}
Пример #8
0
func fetchCamliSrc() {
	check(os.MkdirAll("/gopath/src/camlistore.org", 0777))
	check(os.Chdir("/gopath/src/camlistore.org"))

	res, err := http.Get("https://camlistore.googlesource.com/camlistore/+archive/" + *rev + ".tar.gz")
	check(err)
	defer res.Body.Close()
	gz, err := gzip.NewReader(res.Body)
	check(err)
	defer gz.Close()
	tr := tar.NewReader(gz)
	for {
		h, err := tr.Next()
		if err == io.EOF {
			break
		}
		check(err)
		if h.Typeflag == tar.TypeDir {
			check(os.MkdirAll(h.Name, os.FileMode(h.Mode)))
			continue
		}
		f, err := os.Create(h.Name)
		check(err)
		n, err := io.Copy(f, tr)
		if err != nil && err != io.EOF {
			log.Fatal(err)
		}
		if n != h.Size {
			log.Fatalf("Error when creating %v: wanted %v bytes, got %v bytes", h.Name, h.Size, n)
		}
		check(f.Close())
	}
}
Пример #9
0
Файл: mzs.go Проект: rose312/mzr
func Download(url string) (string, error) {

	ext := strings.ToLower(path.Ext(url))
	filename := helper.MD5(time.Now().String()) + ext
	ipath := "./file/" + "download/" //time.Now().Format("03/04/")
	if !helper.Exist(ipath) {
		os.MkdirAll(ipath, 0644)
	}

	path := ipath + filename
	if e := helper.GetFile(url, path, "default", "http://www.mzitu.com/"); e == nil {

		filehash, _ := helper.Filehash(path, nil)
		fname := helper.Encrypt_hash(filehash+"1", nil)
		if ext == "" {
			ext = ".jpg"
		}
		opath := "./file/" + time.Now().Format("03/04/")
		if !helper.Exist(opath) {
			os.MkdirAll(opath, 0644)
		}

		finalpath := opath + fname + ext

		fmt.Println("path:", path)
		fmt.Println("finalpath:", finalpath)
		if e := helper.MoveFile(path, finalpath); e == nil {
			return finalpath, e
		}

	} else {
		return "", errors.New("下载错误!")
	}
	return "", errors.New("Download函数出现错误!")
}
Пример #10
0
// 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
}
Пример #11
0
func TestMount(t *testing.T) {
	graph, driver := tempGraph(t)
	defer os.RemoveAll(graph.Root)
	defer driver.Cleanup()

	archive, err := fakeTar()
	if err != nil {
		t.Fatal(err)
	}
	image, err := graph.Create(archive, "", "", "Testing", "", nil, nil)
	if err != nil {
		t.Fatal(err)
	}
	tmp, err := ioutil.TempDir("", "docker-test-graph-mount-")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmp)
	rootfs := path.Join(tmp, "rootfs")
	if err := os.MkdirAll(rootfs, 0700); err != nil {
		t.Fatal(err)
	}
	rw := path.Join(tmp, "rw")
	if err := os.MkdirAll(rw, 0700); err != nil {
		t.Fatal(err)
	}

	if _, err := driver.Get(image.ID, ""); err != nil {
		t.Fatal(err)
	}
}
Пример #12
0
// init is used to initialize the client and perform any setup
// needed before we begin starting its various components.
func (c *Client) init() error {
	// Ensure the state dir exists if we have one
	if c.config.StateDir != "" {
		if err := os.MkdirAll(c.config.StateDir, 0700); err != nil {
			return fmt.Errorf("failed creating state dir: %s", err)
		}

	} else {
		// Othewise make a temp directory to use.
		p, err := ioutil.TempDir("", "NomadClient")
		if err != nil {
			return fmt.Errorf("failed creating temporary directory for the StateDir: %v", err)
		}
		c.config.StateDir = p
	}
	c.logger.Printf("[INFO] client: using state directory %v", c.config.StateDir)

	// Ensure the alloc dir exists if we have one
	if c.config.AllocDir != "" {
		if err := os.MkdirAll(c.config.AllocDir, 0755); err != nil {
			return fmt.Errorf("failed creating alloc dir: %s", err)
		}
	} else {
		// Othewise make a temp directory to use.
		p, err := ioutil.TempDir("", "NomadClient")
		if err != nil {
			return fmt.Errorf("failed creating temporary directory for the AllocDir: %v", err)
		}
		c.config.AllocDir = p
	}

	c.logger.Printf("[INFO] client: using alloc directory %v", c.config.AllocDir)
	return nil
}
Пример #13
0
func main() {
	defer func() {
		if isDelete {
			os.RemoveAll(fpath0)
		}
	}()

	if err := os.MkdirAll(fpath0, 0700); err != nil {
		panic(err)
	}

	if existDir(fpath1) {
		fmt.Println(fpath1, "already exists... skipping...")
		return
	}

	if err := os.MkdirAll(fpath1, 0700); err != nil {
		panic(err)
	}

	if err := toFileWriteString("hello world!", fpath2); err != nil {
		panic(err)
	}

	fmt.Println("Done")
	isDelete = true
}
Пример #14
0
func doSave() error {
	// Create the necessary directories
	err := os.MkdirAll(config.root, 0700)
	if err != nil {
		return err
	}

	err = os.MkdirAll(filepath.Join(config.root, "public"), 0755)
	if err != nil {
		return err
	}

	err = os.MkdirAll(filepath.Join(config.root, "content"), 0700)
	if err != nil {
		return err
	}

	err = os.MkdirAll(filepath.Join(config.root, "templates"), 0700)
	if err != nil {
		return err
	}

	data, err := json.MarshalIndent(&config, "", "  ")
	if err != nil {
		return err
	}

	file := filepath.Join(config.root, "profile.conf")
	return ioutil.WriteFile(file, data, 0600)
}
Пример #15
0
func serve(c *cli.Context) {
	// Ensure api socket directory exists; if not, create it
	apiSocket := getApiSocket(c)
	if _, err := os.Stat(apiSocket); os.IsNotExist(err) {
		os.MkdirAll(path.Dir(apiSocket), 0777)
	}

	d := dokku.New()

	// If caching is enabled, create cache socket if necessary and launch cache
	// server in the background
	if !c.BoolT("enable-cache") {
		cacheSocket := getCacheSocket(c)
		if _, err := os.Stat(cacheSocket); os.IsNotExist(err) {
			os.MkdirAll(path.Dir(cacheSocket), 0777)
		}

		go func() {
			err := listenCache(d, cacheSocket)
			if err != nil {
				panic(err)
			}
		}()
	}

	// Start api server
	err := listenAPI(d, apiSocket)
	if err != nil {
		panic(err)
	}
}
Пример #16
0
// Test CopyWithTar with a file as src
func TestCopyWithTarSrcFile(t *testing.T) {
	folder, err := ioutil.TempDir("", "docker-archive-test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(folder)
	dest := path.Join(folder, "dest")
	srcFolder := path.Join(folder, "src")
	src := path.Join(folder, path.Join("src", "src"))
	err = os.MkdirAll(srcFolder, 0740)
	if err != nil {
		t.Fatal(err)
	}
	err = os.MkdirAll(dest, 0740)
	if err != nil {
		t.Fatal(err)
	}
	ioutil.WriteFile(src, []byte("content"), 0777)
	err = CopyWithTar(src, dest)
	if err != nil {
		t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
	}
	_, err = os.Stat(dest)
	// FIXME Check the content
	if err != nil {
		t.Fatalf("Destination file should be the same as the source.")
	}
}
Пример #17
0
// AddSnapServices adds service units for the applications from the snap which are services.
func AddSnapServices(s *snap.Info, inter interacter) error {
	for _, app := range s.Apps {
		if app.Daemon == "" {
			continue
		}
		// Generate service file
		content, err := generateSnapServiceFile(app)
		if err != nil {
			return err
		}
		svcFilePath := app.ServiceFile()
		os.MkdirAll(filepath.Dir(svcFilePath), 0755)
		if err := osutil.AtomicWriteFile(svcFilePath, []byte(content), 0644, 0); err != nil {
			return err
		}
		// Generate systemd socket file if needed
		if app.Socket {
			content, err := generateSnapSocketFile(app)
			if err != nil {
				return err
			}
			svcSocketFilePath := app.ServiceSocketFile()
			os.MkdirAll(filepath.Dir(svcSocketFilePath), 0755)
			if err := osutil.AtomicWriteFile(svcSocketFilePath, []byte(content), 0644, 0); err != nil {
				return err
			}
		}
	}

	return nil
}
Пример #18
0
func (d *Driver) Get(id, mountLabel string) (string, error) {
	mp := path.Join(d.home, "mnt", id)

	// Create the target directories if they don't exist
	if err := os.MkdirAll(mp, 0755); err != nil && !os.IsExist(err) {
		return "", err
	}

	// Mount the device
	if err := d.DeviceSet.MountDevice(id, mp, mountLabel); err != nil {
		return "", err
	}

	rootFs := path.Join(mp, "rootfs")
	if err := os.MkdirAll(rootFs, 0755); err != nil && !os.IsExist(err) {
		d.DeviceSet.UnmountDevice(id)
		return "", err
	}

	idFile := path.Join(mp, "id")
	if _, err := os.Stat(idFile); err != nil && os.IsNotExist(err) {
		// Create an "id" file with the container/image id in it to help reconscruct this in case
		// of later problems
		if err := ioutil.WriteFile(idFile, []byte(id), 0600); err != nil {
			d.DeviceSet.UnmountDevice(id)
			return "", err
		}
	}

	return rootFs, nil
}
Пример #19
0
func (f *fileStorageWriter) Put(name string, r io.Reader, length int64) error {
	if isInternalPath(name) {
		return &os.PathError{
			Op:   "Put",
			Path: name,
			Err:  os.ErrPermission,
		}
	}
	fullpath := f.fullPath(name)
	dir := filepath.Dir(fullpath)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}
	tmpdir := filepath.Join(f.path, ".tmp")
	if err := os.MkdirAll(tmpdir, 0755); err != nil {
		return err
	}
	defer os.Remove(tmpdir)
	// Write to a temporary file first, and then move (atomically).
	file, err := ioutil.TempFile(tmpdir, "juju-filestorage-")
	if err != nil {
		return err
	}
	_, err = io.CopyN(file, r, length)
	file.Close()
	if err != nil {
		os.Remove(file.Name())
		return err
	}
	return utils.ReplaceFile(file.Name(), fullpath)
}
Пример #20
0
func run() error {
	var (
		debug      = flag.Bool("debug", false, "")
		staticPath = flag.String("static", "./static", "serve static files located in this directory")
		host       = flag.String("host", ":8080", "address:port for HTTP listener")
		pgaddr     = flag.String("postgres", "postgres://*****:*****@localhost/abalone?sslmode=disable", "postgres connection info")
		dir        = flag.String("dir", "/var/abalone", "directory where players are kept")
	)
	flag.Parse()

	configDir := *dir
	configPlayersDir := path.Join(configDir, "players")

	if err := os.MkdirAll(configDir, os.ModePerm); err != nil {
		return err
	}
	if err := os.MkdirAll(configPlayersDir, os.ModePerm); err != nil {
		return err
	}

	const driver = "postgres" // only supported database
	log.Printf("using database %s with config %s", driver, *pgaddr)

	ds, err := db.Open(driver, *pgaddr, configPlayersDir)
	if err != nil {
		return err
	}
	ds.DB.LogMode(*debug)

	r := ConfigureRouter(ds, *staticPath)

	log.Printf("listening at %s", *host)
	log.Fatal(http.ListenAndServe(*host, r))
	return nil
}
Пример #21
0
func TestRelativeTemplate(t *testing.T) {
	dir := "_beeTmp"
	files := []string{
		"easyui/public/menu.tpl",
		"easyui/rbac/user.tpl",
	}
	if err := os.MkdirAll(dir, 0777); err != nil {
		t.Fatal(err)
	}
	for k, name := range files {
		os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0777)
		if f, err := os.Create(filepath.Join(dir, name)); err != nil {
			t.Fatal(err)
		} else {
			if k == 0 {
				f.WriteString(menu)
			} else if k == 1 {
				f.WriteString(user)
			}
			f.Close()
		}
	}
	if err := BuildTemplate(dir); err != nil {
		t.Fatal(err)
	}
	if err := BeeTemplates["easyui/rbac/user.tpl"].ExecuteTemplate(os.Stdout, "easyui/rbac/user.tpl", nil); err != nil {
		t.Fatal(err)
	}
	for _, name := range files {
		os.RemoveAll(filepath.Join(dir, name))
	}
	os.RemoveAll(dir)
}
Пример #22
0
func Mkdir(dstpath string) error {
	dirstat, err := os.Lstat(dstpath)
	if err != nil {
		// main case - dir doesn't exist yet
		err = os.MkdirAll(dstpath, DirMode)
		if err != nil {
			return errors.Wrap(err, 1)
		}
		return nil
	}

	if dirstat.IsDir() {
		// is already a dir, good!
	} else {
		// is a file or symlink for example, turn into a dir
		err = os.Remove(dstpath)
		if err != nil {
			return errors.Wrap(err, 1)
		}
		err = os.MkdirAll(dstpath, DirMode)
		if err != nil {
			return errors.Wrap(err, 1)
		}
	}

	return nil
}
Пример #23
0
Файл: run.go Проект: krieg/rkt
// overlayRender renders the image that corresponds to the given hash using the
// overlay filesystem.
// It writes the manifest in the specified directory and mounts an overlay
// filesystem from the cached tree of the image as rootfs.
func overlayRender(cfg RunConfig, img types.Hash, cdir string, dest string) error {
	if err := writeManifest(cfg.CommonConfig, img, dest); err != nil {
		return err
	}

	destRootfs := path.Join(dest, "rootfs")
	if err := os.MkdirAll(destRootfs, 0755); err != nil {
		return err
	}

	cachedTreePath := cfg.Store.GetTreeStoreRootFS(img.String())

	overlayDir := path.Join(cdir, "overlay", img.String())
	if err := os.MkdirAll(overlayDir, 0755); err != nil {
		return err
	}

	upperDir := path.Join(overlayDir, "upper")
	if err := os.MkdirAll(upperDir, 0755); err != nil {
		return err
	}
	workDir := path.Join(overlayDir, "work")
	if err := os.MkdirAll(workDir, 0755); err != nil {
		return err
	}

	opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", cachedTreePath, upperDir, workDir)
	opts = label.FormatMountLabel(opts, cfg.MountLabel)
	if err := syscall.Mount("overlay", destRootfs, "overlay", 0, opts); err != nil {
		return fmt.Errorf("error mounting: %v", err)
	}

	return nil
}
Пример #24
0
func installPluginUnderTest(t *testing.T, testVendorCNIDirPrefix, testNetworkConfigPath, vendorName string, plugName string) {
	pluginDir := path.Join(testNetworkConfigPath, plugName)
	err := os.MkdirAll(pluginDir, 0777)
	if err != nil {
		t.Fatalf("Failed to create plugin config dir: %v", err)
	}
	pluginConfig := path.Join(pluginDir, plugName+".conf")
	f, err := os.Create(pluginConfig)
	if err != nil {
		t.Fatalf("Failed to install plugin")
	}
	networkConfig := fmt.Sprintf("{ \"name\": \"%s\", \"type\": \"%s\" }", plugName, vendorName)

	_, err = f.WriteString(networkConfig)
	if err != nil {
		t.Fatalf("Failed to write network config file (%v)", err)
	}
	f.Close()

	vendorCNIDir := fmt.Sprintf(VendorCNIDirTemplate, testVendorCNIDirPrefix, vendorName)
	err = os.MkdirAll(vendorCNIDir, 0777)
	if err != nil {
		t.Fatalf("Failed to create plugin dir: %v", err)
	}
	pluginExec := path.Join(vendorCNIDir, vendorName)
	f, err = os.Create(pluginExec)

	const execScriptTempl = `#!/bin/bash
read ignore
env > {{.OutputEnv}}
echo "%@" >> {{.OutputEnv}}
export $(echo ${CNI_ARGS} | sed 's/;/ /g') &> /dev/null
mkdir -p {{.OutputDir}} &> /dev/null
echo -n "$CNI_COMMAND $CNI_NETNS $K8S_POD_NAMESPACE $K8S_POD_NAME $K8S_POD_INFRA_CONTAINER_ID" >& {{.OutputFile}}
echo -n "{ \"ip4\": { \"ip\": \"10.1.0.23/24\" } }"
`
	execTemplateData := &map[string]interface{}{
		"OutputFile": path.Join(pluginDir, plugName+".out"),
		"OutputEnv":  path.Join(pluginDir, plugName+".env"),
		"OutputDir":  pluginDir,
	}

	tObj := template.Must(template.New("test").Parse(execScriptTempl))
	buf := &bytes.Buffer{}
	if err := tObj.Execute(buf, *execTemplateData); err != nil {
		t.Fatalf("Error in executing script template - %v", err)
	}
	execScript := buf.String()
	_, err = f.WriteString(execScript)
	if err != nil {
		t.Fatalf("Failed to write plugin exec - %v", err)
	}

	err = f.Chmod(0777)
	if err != nil {
		t.Fatalf("Failed to set exec perms on plugin")
	}

	f.Close()
}
Пример #25
0
// New returns a new AUFS driver.
// An error is returned if AUFS is not supported.
func Init(root string) (graphdriver.Driver, error) {
	// Try to load the aufs kernel module
	if err := supportsAufs(); err != nil {
		return nil, err
	}
	paths := []string{
		"mnt",
		"diff",
		"layers",
	}

	a := &Driver{
		root:   root,
		active: make(map[string]int),
	}

	// Create the root aufs driver dir and return
	// if it already exists
	// If not populate the dir structure
	if err := os.MkdirAll(root, 0755); err != nil {
		if os.IsExist(err) {
			return a, nil
		}
		return nil, err
	}

	for _, p := range paths {
		if err := os.MkdirAll(path.Join(root, p), 0755); err != nil {
			return nil, err
		}
	}
	return a, nil
}
Пример #26
0
func initBitriseWorkPaths() error {
	bitriseWorkDirPath, err := filepath.Abs("./.bitrise")
	if err != nil {
		return err
	}
	if exist, err := pathutil.IsPathExists(bitriseWorkDirPath); err != nil {
		return err
	} else if !exist {
		if err := os.MkdirAll(bitriseWorkDirPath, 0777); err != nil {
			return err
		}
	}
	BitriseWorkDirPath = bitriseWorkDirPath

	bitriseWorkStepsDirPath, err := filepath.Abs(path.Join(BitriseWorkDirPath, "step_src"))
	if err != nil {
		return err
	}
	if exist, err := pathutil.IsPathExists(bitriseWorkStepsDirPath); err != nil {
		return err
	} else if !exist {
		if err := os.MkdirAll(bitriseWorkStepsDirPath, 0777); err != nil {
			return err
		}
	}
	BitriseWorkStepsDirPath = bitriseWorkStepsDirPath

	return nil
}
Пример #27
0
func (z *ZipArchiveProvider) Extract(dst, src string) error {
	rc, err := zip.OpenReader(src)
	if err != nil {
		return err
	}

	for _, zf := range rc.File {
		fp := filepath.Join(dst, zf.Name)
		if zf.FileInfo().IsDir() {
			os.MkdirAll(fp, 0755)
			continue
		}
		os.MkdirAll(filepath.Dir(fp), 0755)

		zfr, err := zf.Open()
		if err != nil {
			return err
		}

		f, err := os.Create(fp)
		if err != nil {
			zfr.Close()
			return err
		}
		_, err = io.Copy(f, zfr)
		f.Close()
		zfr.Close()
		if err != nil {
			return err
		}
		os.Chmod(fp, zf.Mode())
	}

	return nil
}
Пример #28
0
// Do the same test as above but with the destination folder already exists
// and the destination file is a directory
// It's working, see https://github.com/docker/docker/issues/10040
func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) {
	tmpFolder, err := ioutil.TempDir("", "docker-archive-test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpFolder)
	srcFile := path.Join(tmpFolder, "src")
	tarFile := path.Join(tmpFolder, "src.tar")
	os.Create(srcFile)
	cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile)
	_, err = cmd.CombinedOutput()
	if err != nil {
		t.Fatal(err)
	}
	destFolder := path.Join(tmpFolder, "dest")
	err = os.MkdirAll(destFolder, 0740)
	if err != nil {
		t.Fatalf("Fail to create the destination folder")
	}
	// Let's create a folder that will has the same path as the extracted file (from tar)
	destSrcFileAsFolder := path.Join(destFolder, srcFile)
	err = os.MkdirAll(destSrcFileAsFolder, 0740)
	if err != nil {
		t.Fatal(err)
	}
	err = UntarPath(tarFile, destFolder)
	if err != nil {
		t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder")
	}
}
Пример #29
0
func (n *Node) DownloadByGoGet(ctx *cli.Context, u *url.URL) error {
	baseDir := path.Join(setting.HomeDir, ".gopm/temp/goget")
	os.MkdirAll(baseDir, os.ModePerm)
	defer func() {
		os.RemoveAll(baseDir)
	}()

	oriGopath := os.Getenv("GOPATH")
	os.Setenv("GOPATH", baseDir)
	fmt.Println(baseDir)
	defer func() {
		os.Setenv("GOPATH", oriGopath)
	}()

	log.Debug("RUN 'go get %s'", n.RootPath)
	_, stderr, err := base.ExecCmdDir(baseDir, "go", "get", n.RootPath)
	if err != nil {
		log.Error("Error occurs when 'go get" + n.RootPath + "'")
		log.Error("\t" + stderr)
		return errors.New(stderr)
	}
	tmpPath := path.Join(baseDir, "src", n.RootPath)
	if !n.IsEmptyVal() {
		base.ExecCmdDir(tmpPath, "git", "checkout", n.Value)
		if err != nil {
			log.Error("Error occurs when 'git checkout" + n.Value + "'")
			log.Error("\t" + stderr)
			return errors.New(stderr)
		}
	}
	os.MkdirAll(path.Dir(n.InstallPath), os.ModePerm)
	os.Rename(tmpPath, n.InstallPath)
	return nil
}
Пример #30
0
func testEth(t *testing.T) (ethereum *eth.Ethereum, err error) {
	os.RemoveAll("/tmp/eth-natspec/")
	err = os.MkdirAll("/tmp/eth-natspec/keys/e273f01c99144c438695e10f24926dc1f9fbf62d/", os.ModePerm)
	if err != nil {
		t.Errorf("%v", err)
		return
	}
	err = os.MkdirAll("/tmp/eth-natspec/data", os.ModePerm)
	if err != nil {
		t.Errorf("%v", err)
		return
	}
	ks := crypto.NewKeyStorePlain("/tmp/eth-natspec/keys")
	ioutil.WriteFile("/tmp/eth-natspec/keys/e273f01c99144c438695e10f24926dc1f9fbf62d/e273f01c99144c438695e10f24926dc1f9fbf62d",
		[]byte(`{"Id":"RhRXD+fNRKS4jx+7ZfEsNA==","Address":"4nPwHJkUTEOGleEPJJJtwfn79i0=","PrivateKey":"h4ACVpe74uIvi5Cg/2tX/Yrm2xdr3J7QoMbMtNX2CNc="}`), os.ModePerm)

	port++
	ethereum, err = eth.New(&eth.Config{
		DataDir:        "/tmp/eth-natspec",
		AccountManager: accounts.NewManager(ks),
		Name:           "test",
	})

	if err != nil {
		t.Errorf("%v", err)
		return
	}

	return
}