当前位置: 首页>>代码示例>>Golang>>正文


Golang uid.NewBlankUidRange函数代码示例

本文整理汇总了Golang中github.com/coreos/rkt/pkg/uid.NewBlankUidRange函数的典型用法代码示例。如果您正苦于以下问题:Golang NewBlankUidRange函数的具体用法?Golang NewBlankUidRange怎么用?Golang NewBlankUidRange使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewBlankUidRange函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestCopyTree

func TestCopyTree(t *testing.T) {
	td, err := ioutil.TempDir("", tstprefix)
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(td)

	src := filepath.Join(td, "src")
	dst := filepath.Join(td, "dst")
	if err := os.MkdirAll(filepath.Join(td, "src"), 0755); err != nil {
		t.Fatal(err)
	}

	tr := []tree{
		{
			path: "dir1",
			dir:  true,
		},
		{
			path: "dir2",
			dir:  true,
		},
		{
			path: "dir1/foo",
			dir:  false,
		},
		{
			path: "dir1/bar",
			dir:  false,
		},
	}

	createTree(t, src, tr)

	// absolute paths
	if err := CopyTree(src, dst, uid.NewBlankUidRange()); err != nil {
		t.Fatal(err)
	}
	checkTree(t, dst, tr)

	// relative paths
	if err := os.Chdir(td); err != nil {
		t.Fatal(err)
	}

	dst = "dst-rel1"
	if err := CopyTree("././src/", dst, uid.NewBlankUidRange()); err != nil {
		t.Fatal(err)
	}
	checkTree(t, dst, tr)

	dst = "./dst-rel2"
	if err := CopyTree("./src", dst, uid.NewBlankUidRange()); err != nil {
		t.Fatal(err)
	}
	checkTree(t, dst, tr)
}
开发者ID:matomesc,项目名称:rkt,代码行数:57,代码来源:fileutil_test.go

示例2: extractTarInsecureHelperPWL

func extractTarInsecureHelperPWL(rdr io.Reader, target string, pwl PathWhitelistMap) error {
	editor, err := NewUidShiftingFilePermEditor(uid.NewBlankUidRange())
	if err != nil {
		return err
	}
	return ExtractTarInsecure(tar.NewReader(rdr), target, true, pwl, editor)
}
开发者ID:coderhaoxin,项目名称:rkt,代码行数:7,代码来源:tar_test.go

示例3: writeEnvFile

// writeEnvFile creates an environment file for given app name, the minimum
// required environment variables by the appc spec will be set to sensible
// defaults here if they're not provided by env.
func writeEnvFile(p *stage1commontypes.Pod, env types.Environment, appName types.ACName, privateUsers string) error {
	ef := bytes.Buffer{}

	for dk, dv := range defaultEnv {
		if _, exists := env.Get(dk); !exists {
			fmt.Fprintf(&ef, "%s=%s\000", dk, dv)
		}
	}

	for _, e := range env {
		fmt.Fprintf(&ef, "%s=%s\000", e.Name, e.Value)
	}

	uidRange := uid.NewBlankUidRange()
	if err := uidRange.Deserialize([]byte(privateUsers)); err != nil {
		return err
	}

	envFilePath := EnvFilePath(p.Root, appName)
	if err := ioutil.WriteFile(envFilePath, ef.Bytes(), 0644); err != nil {
		return err
	}

	if uidRange.Shift != 0 && uidRange.Count != 0 {
		if err := os.Chown(envFilePath, int(uidRange.Shift), int(uidRange.Shift)); err != nil {
			return err
		}
	}

	return nil
}
开发者ID:matomesc,项目名称:rkt,代码行数:34,代码来源:pod.go

示例4: makeRktBundle

/*input: ocidirectory
output:rktdirectrory
*/
func (this *oci2rkt) makeRktBundle() (err error) {
	//this.RktBunldePath = "/var/lib/rkt/rktbunld"
	stage1Path := this.RktBundlePath + "/stage1"
	err = os.MkdirAll(stage1Path, 0755)
	if err != nil {
		return err
	}

	//extra stage1.aci
	r, err := os.Open(this.Stage1Image)
	if err != nil {
		return err
	}
	defer r.Close()

	dr, err := aci.NewCompressedReader(r)
	if err != nil {
		return fmt.Errorf("error decompressing image: %v", err)
	}

	err = ptar.ExtractTar(dr, stage1Path, true, uid.NewBlankUidRange(), nil)
	if err != nil {
		fmt.Printf("extra stage1 image error,%v\n", err)
		return err
	}
	return nil
}
开发者ID:sdgdsffdsfff,项目名称:rkt,代码行数:30,代码来源:oci2rkt.go

示例5: Write

// Write renders the ACI with the provided key in the treestore. id references
// that specific tree store rendered image.
// Write, to avoid having a rendered ACI with old stale files, requires that
// the destination directory doesn't exist (usually Remove should be called
// before Write)
func (ts *TreeStore) Write(id string, key string, s *Store) error {
	treepath := filepath.Join(ts.path, id)
	fi, _ := os.Stat(treepath)
	if fi != nil {
		return fmt.Errorf("treestore: path %s already exists", treepath)
	}
	imageID, err := types.NewHash(key)
	if err != nil {
		return fmt.Errorf("treestore: cannot convert key to imageID: %v", err)
	}
	if err := os.MkdirAll(treepath, 0755); err != nil {
		return fmt.Errorf("treestore: cannot create treestore directory %s: %v", treepath, err)
	}
	err = aci.RenderACIWithImageID(*imageID, treepath, s, uid.NewBlankUidRange())
	if err != nil {
		return fmt.Errorf("treestore: cannot render aci: %v", err)
	}
	hash, err := ts.Hash(id)
	if err != nil {
		return fmt.Errorf("treestore: cannot calculate tree hash: %v", err)
	}
	err = ioutil.WriteFile(filepath.Join(treepath, hashfilename), []byte(hash), 0644)
	if err != nil {
		return fmt.Errorf("treestore: cannot write hash file: %v", err)
	}
	// before creating the "rendered" flag file we need to ensure that all data is fsynced
	dfd, err := syscall.Open(treepath, syscall.O_RDONLY, 0)
	if err != nil {
		return err
	}
	defer syscall.Close(dfd)
	if err := sys.Syncfs(dfd); err != nil {
		return fmt.Errorf("treestore: failed to sync data: %v", err)
	}
	// Create rendered file
	f, err := os.Create(filepath.Join(treepath, renderedfilename))
	if err != nil {
		return fmt.Errorf("treestore: failed to write rendered file: %v", err)
	}
	f.Close()

	if err := syscall.Fsync(dfd); err != nil {
		return fmt.Errorf("treestore: failed to sync tree store directory: %v", err)
	}
	return nil
}
开发者ID:NeilW,项目名称:rkt,代码行数:51,代码来源:tree.go

示例6: PrepareMountpoints

// PrepareMountpoints creates and sets permissions for empty volumes.
// If the mountpoint comes from a Docker image and it is an implicit empty
// volume, we copy files from the image to the volume, see
// https://docs.docker.com/engine/userguide/containers/dockervolumes/#data-volumes
func PrepareMountpoints(volPath string, targetPath string, vol *types.Volume, dockerImplicit bool) error {
	if vol.Kind != "empty" {
		return nil
	}

	diag.Printf("creating an empty volume folder for sharing: %q", volPath)
	m, err := strconv.ParseUint(*vol.Mode, 8, 32)
	if err != nil {
		return errwrap.Wrap(fmt.Errorf("invalid mode %q for volume %q", *vol.Mode, vol.Name), err)
	}
	mode := os.FileMode(m)
	Uid := *vol.UID
	Gid := *vol.GID

	if dockerImplicit {
		fi, err := os.Stat(targetPath)
		if err == nil {
			// the directory exists in the image, let's set the same
			// permissions and copy files from there to the empty volume
			mode = fi.Mode()
			Uid = int(fi.Sys().(*syscall.Stat_t).Uid)
			Gid = int(fi.Sys().(*syscall.Stat_t).Gid)

			if err := fileutil.CopyTree(targetPath, volPath, uid.NewBlankUidRange()); err != nil {
				return errwrap.Wrap(fmt.Errorf("error copying image files to empty volume %q", volPath), err)
			}
		}
	}

	if err := os.MkdirAll(volPath, 0770); err != nil {
		return errwrap.Wrap(fmt.Errorf("error creating %q", volPath), err)
	}
	if err := os.Chown(volPath, Uid, Gid); err != nil {
		return errwrap.Wrap(fmt.Errorf("could not change owner of %q", volPath), err)
	}
	if err := os.Chmod(volPath, mode); err != nil {
		return errwrap.Wrap(fmt.Errorf("could not change permissions of %q", volPath), err)
	}

	return nil
}
开发者ID:coderhaoxin,项目名称:rkt,代码行数:45,代码来源:mount.go

示例7: createBackup

// createBackup backs a database up in a given directory. It basically
// copies this directory into a given backups directory. The backups
// directory has a simple structure - a directory inside named "0" is
// the most recent backup. A directory name for oldest backup is
// deduced from a given limit. For instance, for limit being 5 the
// name for the oldest backup would be "4". If a backups number
// exceeds the given limit then only newest ones are kept and the rest
// is removed.
func createBackup(dbDir, backupsDir string, limit int) error {
	tmpBackupDir := filepath.Join(backupsDir, "tmp")
	if err := os.MkdirAll(backupsDir, defaultPathPerm); err != nil {
		return err
	}
	if err := fileutil.CopyTree(dbDir, tmpBackupDir, uid.NewBlankUidRange()); err != nil {
		return err
	}
	defer os.RemoveAll(tmpBackupDir)
	// prune backups
	if err := pruneOldBackups(backupsDir, limit-1); err != nil {
		return err
	}
	if err := shiftBackups(backupsDir, limit-2); err != nil {
		return err
	}
	if err := os.Rename(tmpBackupDir, filepath.Join(backupsDir, "0")); err != nil {
		return err
	}
	return nil
}
开发者ID:matomesc,项目名称:rkt,代码行数:29,代码来源:backup.go

示例8: runPrepare

func runPrepare(cmd *cobra.Command, args []string) (exit int) {
	var err error
	origStdout := os.Stdout
	privateUsers := uid.NewBlankUidRange()
	if flagQuiet {
		if os.Stdout, err = os.Open("/dev/null"); err != nil {
			stderr("prepare: unable to open /dev/null")
			return 1
		}
	}

	if flagPrivateUsers {
		if !common.SupportsUserNS() {
			stderr("prepare: --private-users is not supported, kernel compiled without user namespace support")
			return 1
		}
		privateUsers.SetRandomUidRange(uid.DefaultRangeCount)
	}

	if err = parseApps(&rktApps, args, cmd.Flags(), true); err != nil {
		stderr("prepare: error parsing app image arguments: %v", err)
		return 1
	}

	if len(flagPodManifest) > 0 && (len(flagVolumes) > 0 || len(flagPorts) > 0 || flagInheritEnv || !flagExplicitEnv.IsEmpty() || flagLocal) {
		stderr("prepare: conflicting flags set with --pod-manifest (see --help)")
		return 1
	}

	if rktApps.Count() < 1 && len(flagPodManifest) == 0 {
		stderr("prepare: must provide at least one image or specify the pod manifest")
		return 1
	}

	if globalFlags.Dir == "" {
		log.Printf("dir unset - using temporary directory")
		globalFlags.Dir, err = ioutil.TempDir("", "rkt")
		if err != nil {
			stderr("prepare: error creating temporary directory: %v", err)
			return 1
		}
	}

	s, err := store.NewStore(globalFlags.Dir)
	if err != nil {
		stderr("prepare: cannot open store: %v", err)
		return 1
	}

	config, err := getConfig()
	if err != nil {
		stderr("prepare: cannot get configuration: %v", err)
		return 1
	}
	fn := &finder{
		imageActionData: imageActionData{
			s:                  s,
			headers:            config.AuthPerHost,
			dockerAuth:         config.DockerCredentialsPerRegistry,
			insecureSkipVerify: globalFlags.InsecureSkipVerify,
			debug:              globalFlags.Debug,
		},
		local:    flagLocal,
		withDeps: false,
	}

	s1img, err := getStage1Hash(s, flagStage1Image)
	if err != nil {
		stderr("prepare: %v", err)
		return 1
	}

	fn.ks = getKeystore()
	fn.withDeps = true
	if err := fn.findImages(&rktApps); err != nil {
		stderr("%v", err)
		return 1
	}

	p, err := newPod()
	if err != nil {
		stderr("prepare: error creating new pod: %v", err)
		return 1
	}

	cfg := stage0.CommonConfig{
		Store:       s,
		Stage1Image: *s1img,
		UUID:        p.uuid,
		Debug:       globalFlags.Debug,
	}

	pcfg := stage0.PrepareConfig{
		CommonConfig: cfg,
		UseOverlay:   !flagNoOverlay && common.SupportsOverlay(),
		PrivateUsers: privateUsers,
	}

	if len(flagPodManifest) > 0 {
		pcfg.PodManifest = flagPodManifest
//.........这里部分代码省略.........
开发者ID:harpe1999,项目名称:rkt,代码行数:101,代码来源:prepare.go

示例9: TestExtractTarPWL

func TestExtractTarPWL(t *testing.T) {
	if !sys.HasChrootCapability() {
		t.Skipf("chroot capability not available. Disabling test.")
	}
	entries := []*testTarEntry{
		{
			header: &tar.Header{
				Name:     "folder/",
				Typeflag: tar.TypeDir,
				Mode:     int64(0747),
			},
		},
		{
			contents: "foo",
			header: &tar.Header{
				Name: "folder/foo.txt",
				Size: 3,
			},
		},
		{
			contents: "bar",
			header: &tar.Header{
				Name: "folder/bar.txt",
				Size: 3,
			},
		},
		{
			header: &tar.Header{
				Name:     "folder/symlink.txt",
				Typeflag: tar.TypeSymlink,
				Linkname: "folder/foo.txt",
			},
		},
	}
	testTarPath, err := newTestTar(entries)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	defer os.Remove(testTarPath)
	containerTar, err := os.Open(testTarPath)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	defer containerTar.Close()
	tmpdir, err := ioutil.TempDir("", "rkt-temp-dir")
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	defer os.RemoveAll(tmpdir)

	pwl := make(PathWhitelistMap)
	pwl["folder/foo.txt"] = struct{}{}
	err = ExtractTar(containerTar, tmpdir, false, uid.NewBlankUidRange(), pwl)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	matches, err := filepath.Glob(filepath.Join(tmpdir, "folder/*.txt"))
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if len(matches) != 1 {
		t.Errorf("unexpected number of files found: %d, wanted 1", len(matches))
	}
}
开发者ID:NeilW,项目名称:rkt,代码行数:64,代码来源:tar_test.go

示例10: runRun

func runRun(cmd *cobra.Command, args []string) (exit int) {
	privateUsers := uid.NewBlankUidRange()
	err := parseApps(&rktApps, args, cmd.Flags(), true)
	if err != nil {
		stderr("run: error parsing app image arguments: %v", err)
		return 1
	}

	if flagStoreOnly && flagNoStore {
		stderr("both --store-only and --no-store specified")
		return 1
	}

	if flagPrivateUsers {
		if !common.SupportsUserNS() {
			stderr("run: --private-users is not supported, kernel compiled without user namespace support")
			return 1
		}
		privateUsers.SetRandomUidRange(uid.DefaultRangeCount)
	}

	if len(flagPorts) > 0 && flagNet.None() {
		stderr("--port flag does not work with 'none' networking")
		return 1
	}
	if len(flagPorts) > 0 && flagNet.Host() {
		stderr("--port flag does not work with 'host' networking")
		return 1
	}

	if flagMDSRegister && flagNet.None() {
		stderr("--mds-register flag does not work with --net=none. Please use 'host', 'default' or an equivalent network")
		return 1
	}

	if len(flagPodManifest) > 0 && (len(flagPorts) > 0 || flagInheritEnv || !flagExplicitEnv.IsEmpty() || rktApps.Count() > 0 || flagStoreOnly || flagNoStore) {
		stderr("conflicting flags set with --pod-manifest (see --help)")
		return 1
	}

	if flagInteractive && rktApps.Count() > 1 {
		stderr("run: interactive option only supports one image")
		return 1
	}

	if rktApps.Count() < 1 && len(flagPodManifest) == 0 {
		stderr("run: must provide at least one image or specify the pod manifest")
		return 1
	}

	s, err := store.NewStore(globalFlags.Dir)
	if err != nil {
		stderr("run: cannot open store: %v", err)
		return 1
	}

	config, err := getConfig()
	if err != nil {
		stderr("run: cannot get configuration: %v", err)
		return 1
	}
	fn := &finder{
		imageActionData: imageActionData{
			s:                  s,
			headers:            config.AuthPerHost,
			dockerAuth:         config.DockerCredentialsPerRegistry,
			insecureSkipVerify: globalFlags.InsecureSkipVerify,
			debug:              globalFlags.Debug,
		},
		storeOnly: flagStoreOnly,
		noStore:   flagNoStore,
		withDeps:  false,
	}

	s1img, err := getStage1Hash(s, cmd)
	if err != nil {
		stderr("%v", err)
		return 1
	}

	fn.ks = getKeystore()
	fn.withDeps = true
	if err := fn.findImages(&rktApps); err != nil {
		stderr("%v", err)
		return 1
	}

	p, err := newPod()
	if err != nil {
		stderr("Error creating new pod: %v", err)
		return 1
	}

	// if requested, write out pod UUID early so "rkt rm" can
	// clean it up even if something goes wrong
	if flagUUIDFileSave != "" {
		if err := writeUUIDToFile(p.uuid, flagUUIDFileSave); err != nil {
			stderr("Error saving pod UUID to file: %v", err)
			return 1
		}
//.........这里部分代码省略.........
开发者ID:atd-schubert,项目名称:rkt,代码行数:101,代码来源:run.go

示例11: runPrepare

func runPrepare(cmd *cobra.Command, args []string) (exit int) {
	var err error
	origStdout := os.Stdout
	privateUsers := uid.NewBlankUidRange()
	if flagQuiet {
		if os.Stdout, err = os.Open("/dev/null"); err != nil {
			stderr("prepare: unable to open /dev/null: %v", err)
			return 1
		}
	}

	if flagStoreOnly && flagNoStore {
		stderr("both --store-only and --no-store specified")
		return 1
	}

	if flagPrivateUsers {
		if !common.SupportsUserNS() {
			stderr("prepare: --private-users is not supported, kernel compiled without user namespace support")
			return 1
		}
		privateUsers.SetRandomUidRange(uid.DefaultRangeCount)
	}

	if err = parseApps(&rktApps, args, cmd.Flags(), true); err != nil {
		stderr("prepare: error parsing app image arguments: %v", err)
		return 1
	}

	if len(flagPodManifest) > 0 && (len(flagPorts) > 0 || flagInheritEnv || !flagExplicitEnv.IsEmpty() || flagStoreOnly || flagNoStore) {
		stderr("prepare: conflicting flags set with --pod-manifest (see --help)")
		return 1
	}

	if rktApps.Count() < 1 && len(flagPodManifest) == 0 {
		stderr("prepare: must provide at least one image or specify the pod manifest")
		return 1
	}

	s, err := store.NewStore(getDataDir())
	if err != nil {
		stderr("prepare: cannot open store: %v", err)
		return 1
	}

	config, err := getConfig()
	if err != nil {
		stderr("prepare: cannot get configuration: %v", err)
		return 1
	}

	s1img, err := getStage1Hash(s, cmd)
	if err != nil {
		stderr("prepare: %v", err)
		return 1
	}

	fn := &image.Finder{
		S:                  s,
		Ks:                 getKeystore(),
		Headers:            config.AuthPerHost,
		DockerAuth:         config.DockerCredentialsPerRegistry,
		InsecureFlags:      globalFlags.InsecureFlags,
		Debug:              globalFlags.Debug,
		TrustKeysFromHttps: globalFlags.TrustKeysFromHttps,

		StoreOnly: flagStoreOnly,
		NoStore:   flagNoStore,
		WithDeps:  true,
	}
	if err := fn.FindImages(&rktApps); err != nil {
		stderr("prepare: %v", err)
		return 1
	}

	p, err := newPod()
	if err != nil {
		stderr("prepare: error creating new pod: %v", err)
		return 1
	}

	cfg := stage0.CommonConfig{
		Store:       s,
		Stage1Image: *s1img,
		UUID:        p.uuid,
		Debug:       globalFlags.Debug,
	}

	pcfg := stage0.PrepareConfig{
		CommonConfig: &cfg,
		UseOverlay:   !flagNoOverlay && common.SupportsOverlay(),
		PrivateUsers: privateUsers,
	}

	if len(flagPodManifest) > 0 {
		pcfg.PodManifest = flagPodManifest
	} else {
		pcfg.Ports = []types.ExposedPort(flagPorts)
		pcfg.InheritEnv = flagInheritEnv
		pcfg.ExplicitEnv = flagExplicitEnv.Strings()
//.........这里部分代码省略.........
开发者ID:matomesc,项目名称:rkt,代码行数:101,代码来源:prepare.go

示例12: runImageExtract

func runImageExtract(cmd *cobra.Command, args []string) (exit int) {
	if len(args) != 2 {
		cmd.Usage()
		return 1
	}
	outputDir := args[1]

	s, err := store.NewStore(globalFlags.Dir)
	if err != nil {
		stderr("image extract: cannot open store: %v", err)
		return 1
	}

	key, err := getStoreKeyFromAppOrHash(s, args[0])
	if err != nil {
		stderr("image extract: %v", err)
		return 1
	}

	aci, err := s.ReadStream(key)
	if err != nil {
		stderr("image extract: error reading ACI from the store: %v", err)
		return 1
	}

	// ExtractTar needs an absolute path
	absOutputDir, err := filepath.Abs(outputDir)
	if err != nil {
		stderr("image extract: error converting output to an absolute path: %v", err)
		return 1
	}

	if _, err := os.Stat(absOutputDir); err == nil {
		if !flagExtractOverwrite {
			stderr("image extract: output directory exists (try --overwrite)")
			return 1
		}

		// don't allow the user to delete the root filesystem by mistake
		if absOutputDir == "/" {
			stderr("image extract: this would delete your root filesystem. Refusing.")
			return 1
		}

		if err := os.RemoveAll(absOutputDir); err != nil {
			stderr("image extract: error removing existing output dir: %v", err)
			return 1
		}
	}

	// if the user only asks for the rootfs we extract the image to a temporary
	// directory and then move/copy the rootfs to the output directory, if not
	// we just extract the image to the output directory
	extractDir := absOutputDir
	if flagExtractRootfsOnly {
		rktTmpDir, err := s.TmpDir()
		if err != nil {
			stderr("image extract: error creating rkt temporary directory: %v", err)
			return 1
		}

		tmpDir, err := ioutil.TempDir(rktTmpDir, "rkt-image-extract-")
		if err != nil {
			stderr("image extract: error creating temporary directory: %v", err)
			return 1
		}
		defer os.RemoveAll(tmpDir)

		extractDir = tmpDir
	} else {
		if err := os.MkdirAll(absOutputDir, 0755); err != nil {
			stderr("image extract: error creating output directory: %v", err)
			return 1
		}
	}

	if err := tar.ExtractTar(aci, extractDir, false, uid.NewBlankUidRange(), nil); err != nil {
		stderr("image extract: error extracting ACI: %v", err)
		return 1
	}

	if flagExtractRootfsOnly {
		rootfsDir := filepath.Join(extractDir, "rootfs")
		if err := os.Rename(rootfsDir, absOutputDir); err != nil {
			if e, ok := err.(*os.LinkError); ok && e.Err == syscall.EXDEV {
				// it's on a different device, fall back to copying
				if err := fileutil.CopyTree(rootfsDir, absOutputDir, uid.NewBlankUidRange()); err != nil {
					stderr("image extract: error copying ACI rootfs: %v", err)
					return 1
				}
			} else {
				stderr("image extract: error moving ACI rootfs: %v", err)
				return 1
			}
		}
	}

	return 0
}
开发者ID:NeilW,项目名称:rkt,代码行数:99,代码来源:image_extract.go

示例13: TestExtractTarOverwrite

func TestExtractTarOverwrite(t *testing.T) {
	if !sys.HasChrootCapability() {
		t.Skipf("chroot capability not available. Disabling test.")
	}

	tmpdir, err := ioutil.TempDir("", "rkt-temp-dir")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	defer os.RemoveAll(tmpdir)

	entries := []*testTarEntry{
		{
			contents: "hello",
			header: &tar.Header{
				Name: "hello.txt",
				Size: 5,
			},
		},
		{
			header: &tar.Header{
				Name:     "afolder",
				Typeflag: tar.TypeDir,
			},
		},
		{
			contents: "hello",
			header: &tar.Header{
				Name: "afolder/hello.txt",
				Size: 5,
			},
		},
		{
			contents: "hello",
			header: &tar.Header{
				Name: "afile",
				Size: 5,
			},
		},
		{
			header: &tar.Header{
				Name:     "folder01",
				Typeflag: tar.TypeDir,
			},
		},
		{
			contents: "hello",
			header: &tar.Header{
				Name: "folder01/file01",
				Size: 5,
			},
		},
		{
			contents: "hello",
			header: &tar.Header{
				Name: "filesymlinked",
				Size: 5,
			},
		},
		{
			header: &tar.Header{
				Name:     "linktofile",
				Linkname: "filesymlinked",
				Typeflag: tar.TypeSymlink,
			},
		},

		{
			header: &tar.Header{
				Name:     "dirsymlinked",
				Typeflag: tar.TypeDir,
			},
		},
		{
			header: &tar.Header{
				Name:     "linktodir",
				Linkname: "dirsymlinked",
				Typeflag: tar.TypeSymlink,
			},
		},
	}

	testTarPath, err := newTestTar(entries)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	defer os.Remove(testTarPath)
	containerTar1, err := os.Open(testTarPath)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	defer containerTar1.Close()
	err = ExtractTar(containerTar1, tmpdir, false, uid.NewBlankUidRange(), nil)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	// Now overwrite:
	// a file with a new file
	// a dir with a file
//.........这里部分代码省略.........
开发者ID:NeilW,项目名称:rkt,代码行数:101,代码来源:tar_test.go

示例14: runImageRender

func runImageRender(cmd *cobra.Command, args []string) (exit int) {
	if len(args) != 2 {
		cmd.Usage()
		return 1
	}
	outputDir := args[1]

	s, err := store.NewStore(getDataDir())
	if err != nil {
		stderr("image render: cannot open store: %v", err)
		return 1
	}

	key, err := getStoreKeyFromAppOrHash(s, args[0])
	if err != nil {
		stderr("image render: %v", err)
		return 1
	}

	id, _, err := s.RenderTreeStore(key, false)
	if err != nil {
		stderr("image render: error rendering ACI: %v", err)
		return 1
	}
	if _, err := s.CheckTreeStore(id); err != nil {
		stderr("image render: warning: tree cache is in a bad state. Rebuilding...")
		var err error
		if id, _, err = s.RenderTreeStore(key, true); err != nil {
			stderr("image render: error rendering ACI: %v", err)
			return 1
		}
	}

	if _, err := os.Stat(outputDir); err == nil {
		if !flagRenderOverwrite {
			stderr("image render: output directory exists (try --overwrite)")
			return 1
		}

		// don't allow the user to delete the root filesystem by mistake
		if outputDir == "/" {
			stderr("image extract: this would delete your root filesystem. Refusing.")
			return 1
		}

		if err := os.RemoveAll(outputDir); err != nil {
			stderr("image render: error removing existing output dir: %v", err)
			return 1
		}
	}
	rootfsOutDir := outputDir
	if !flagRenderRootfsOnly {
		if err := os.MkdirAll(outputDir, 0755); err != nil {
			stderr("image render: error creating output directory: %v", err)
			return 1
		}
		rootfsOutDir = filepath.Join(rootfsOutDir, "rootfs")

		manifest, err := s.GetImageManifest(key)
		if err != nil {
			stderr("image render: error getting manifest: %v", err)
			return 1
		}

		mb, err := json.Marshal(manifest)
		if err != nil {
			stderr("image render: error marshalling image manifest: %v", err)
			return 1
		}

		if err := ioutil.WriteFile(filepath.Join(outputDir, "manifest"), mb, 0700); err != nil {
			stderr("image render: error writing image manifest: %v", err)
			return 1
		}
	}

	cachedTreePath := s.GetTreeStoreRootFS(id)
	if err := fileutil.CopyTree(cachedTreePath, rootfsOutDir, uid.NewBlankUidRange()); err != nil {
		stderr("image render: error copying ACI rootfs: %v", err)
		return 1
	}

	return 0
}
开发者ID:matomesc,项目名称:rkt,代码行数:84,代码来源:image_render.go

示例15: TestExtractTarFolders

func TestExtractTarFolders(t *testing.T) {
	if !sys.HasChrootCapability() {
		t.Skipf("chroot capability not available. Disabling test.")
	}

	entries := []*testTarEntry{
		{
			contents: "foo",
			header: &tar.Header{
				Name: "deep/folder/foo.txt",
				Size: 3,
			},
		},
		{
			header: &tar.Header{
				Name:     "deep/folder/",
				Typeflag: tar.TypeDir,
				Mode:     int64(0747),
			},
		},
		{
			contents: "bar",
			header: &tar.Header{
				Name: "deep/folder/bar.txt",
				Size: 3,
			},
		},
		{
			header: &tar.Header{
				Name:     "deep/folder2/symlink.txt",
				Typeflag: tar.TypeSymlink,
				Linkname: "deep/folder/foo.txt",
			},
		},
		{
			header: &tar.Header{
				Name:     "deep/folder2/",
				Typeflag: tar.TypeDir,
				Mode:     int64(0747),
			},
		},
		{
			contents: "bar",
			header: &tar.Header{
				Name: "deep/folder2/bar.txt",
				Size: 3,
			},
		},
		{
			header: &tar.Header{
				Name:     "deep/deep/folder",
				Typeflag: tar.TypeDir,
				Mode:     int64(0755),
			},
		},
		{
			header: &tar.Header{
				Name:     "deep/deep/",
				Typeflag: tar.TypeDir,
				Mode:     int64(0747),
			},
		},
	}

	testTarPath, err := newTestTar(entries)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	defer os.Remove(testTarPath)
	containerTar, err := os.Open(testTarPath)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	defer containerTar.Close()
	tmpdir, err := ioutil.TempDir("", "rkt-temp-dir")
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	os.RemoveAll(tmpdir)
	err = os.MkdirAll(tmpdir, 0755)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	defer os.RemoveAll(tmpdir)
	err = ExtractTar(containerTar, tmpdir, false, uid.NewBlankUidRange(), nil)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	matches, err := filepath.Glob(filepath.Join(tmpdir, "deep/folder/*.txt"))
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if len(matches) != 2 {
		t.Errorf("unexpected number of files found: %d, wanted 2", len(matches))
	}
	matches, err = filepath.Glob(filepath.Join(tmpdir, "deep/folder2/*.txt"))
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if len(matches) != 2 {
//.........这里部分代码省略.........
开发者ID:NeilW,项目名称:rkt,代码行数:101,代码来源:tar_test.go


注:本文中的github.com/coreos/rkt/pkg/uid.NewBlankUidRange函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。