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


Golang osutil.FileExists函数代码示例

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


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

示例1: TestInstallingSnapCreatesModulesConf

func (s *backendSuite) TestInstallingSnapCreatesModulesConf(c *C) {
	// NOTE: Hand out a permanent snippet so that .conf file is generated.
	s.Iface.PermanentSlotSnippetCallback = func(slot *interfaces.Slot, securitySystem interfaces.SecuritySystem) ([]byte, error) {
		if securitySystem == interfaces.SecurityKMod {
			return []byte("module1    \n    module2\nmodule1\n#\n"), nil
		}
		return nil, nil
	}

	path := filepath.Join(dirs.SnapKModModulesDir, "snap.samba.conf")
	c.Assert(osutil.FileExists(path), Equals, false)

	for _, devMode := range []bool{true, false} {
		s.modprobeCmd.ForgetCalls()
		snapInfo := s.InstallSnap(c, devMode, backendtest.SambaYamlV1, 0)

		c.Assert(osutil.FileExists(path), Equals, true)
		modfile, err := ioutil.ReadFile(path)
		c.Assert(err, IsNil)
		c.Assert(string(modfile), Equals, "# This file is automatically generated.\nmodule1\nmodule2\n")

		c.Assert(s.modprobeCmd.Calls(), DeepEquals, [][]string{
			{"modprobe", "--syslog", "module1"},
			{"modprobe", "--syslog", "module2"},
		})
		s.RemoveSnap(c, snapInfo)
	}
}
开发者ID:niemeyer,项目名称:snapd,代码行数:28,代码来源:backend_test.go

示例2: TestLinkDoUndoCurrentSymlink

func (s *linkSuite) TestLinkDoUndoCurrentSymlink(c *C) {
	const yaml = `name: hello
version: 1.0
`

	info := snaptest.MockSnap(c, yaml, &snap.SideInfo{Revision: snap.R(11)})

	err := s.be.LinkSnap(info)
	c.Assert(err, IsNil)

	mountDir := info.MountDir()
	dataDir := info.DataDir()
	currentActiveSymlink := filepath.Join(mountDir, "..", "current")
	currentActiveDir, err := filepath.EvalSymlinks(currentActiveSymlink)
	c.Assert(err, IsNil)
	c.Assert(currentActiveDir, Equals, mountDir)

	currentDataSymlink := filepath.Join(dataDir, "..", "current")
	currentDataDir, err := filepath.EvalSymlinks(currentDataSymlink)
	c.Assert(err, IsNil)
	c.Assert(currentDataDir, Equals, dataDir)

	// undo will remove the symlinks
	err = s.be.UnlinkSnap(info, &s.nullProgress)
	c.Assert(err, IsNil)

	c.Check(osutil.FileExists(currentActiveSymlink), Equals, false)
	c.Check(osutil.FileExists(currentDataSymlink), Equals, false)

}
开发者ID:niemeyer,项目名称:snapd,代码行数:30,代码来源:link_test.go

示例3: ExecInCoreSnap

// ExecInCoreSnap makes sure you're executing the binary that ships in
// the core snap.
func ExecInCoreSnap() {
	if !release.OnClassic {
		// you're already the real deal, natch
		return
	}

	if os.Getenv(key) != "1" {
		return
	}

	exe, err := os.Readlink("/proc/self/exe")
	if err != nil {
		return
	}

	full := filepath.Join(newCore, exe)
	if !osutil.FileExists(full) {
		if rev, err := os.Readlink(oldCore); err != nil {
			return
		} else if revno, err := strconv.Atoi(rev); err != nil || revno < minOldRevno {
			return
		}

		full = filepath.Join(oldCore, exe)
		if !osutil.FileExists(full) {
			return
		}
	}

	logger.Debugf("restarting into %q", full)

	env := append(os.Environ(), key+"=0")
	panic(syscall.Exec(full, os.Args, env))
}
开发者ID:niemeyer,项目名称:snapd,代码行数:36,代码来源:cmd.go

示例4: TestSetupUndoIdempotent

func (s *setupSuite) TestSetupUndoIdempotent(c *C) {
	// make sure that a retry wouldn't stumble on partial work
	// use a kernel because that does and need to do strictly more

	// this cannot check systemd own behavior though around mounts!

	bootloader := boottest.NewMockBootloader("mock", c.MkDir())
	partition.ForceBootloader(bootloader)
	// we don't get real mounting
	os.Setenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS", "1")
	defer os.Unsetenv("SNAPPY_SQUASHFS_UNPACK_FOR_TESTS")

	testFiles := [][]string{
		{"kernel.img", "kernel"},
		{"initrd.img", "initrd"},
		{"modules/4.4.0-14-generic/foo.ko", "a module"},
		{"firmware/bar.bin", "some firmware"},
		{"meta/kernel.yaml", "version: 4.2"},
	}
	snapPath := snaptest.MakeTestSnapWithFiles(c, `name: kernel
version: 1.0
type: kernel
`, testFiles)

	si := snap.SideInfo{
		RealName: "kernel",
		Revision: snap.R(140),
	}

	err := s.be.SetupSnap(snapPath, &si, &s.nullProgress)
	c.Assert(err, IsNil)

	minInfo := snap.MinimalPlaceInfo("kernel", snap.R(140))

	err = s.be.UndoSetupSnap(minInfo, "kernel", &s.nullProgress)
	c.Assert(err, IsNil)

	// retry run
	err = s.be.UndoSetupSnap(minInfo, "kernel", &s.nullProgress)
	c.Assert(err, IsNil)

	// sanity checks
	l, _ := filepath.Glob(filepath.Join(dirs.SnapServicesDir, "*.mount"))
	c.Assert(l, HasLen, 0)
	c.Assert(osutil.FileExists(minInfo.MountDir()), Equals, false)

	c.Assert(osutil.FileExists(minInfo.MountFile()), Equals, false)

	l, _ = filepath.Glob(filepath.Join(bootloader.Dir(), "*"))
	c.Assert(l, HasLen, 0)
}
开发者ID:clobrano,项目名称:snappy,代码行数:51,代码来源:setup_test.go

示例5: loadState

func loadState(backend state.Backend) (*state.State, error) {
	if !osutil.FileExists(dirs.SnapStateFile) {
		// fail fast, mostly interesting for tests, this dir is setup
		// by the snapd package
		stateDir := filepath.Dir(dirs.SnapStateFile)
		if !osutil.IsDirectory(stateDir) {
			return nil, fmt.Errorf("fatal: directory %q must be present", stateDir)
		}
		s := state.New(backend)
		patch.Init(s)
		return s, nil
	}

	r, err := os.Open(dirs.SnapStateFile)
	if err != nil {
		return nil, fmt.Errorf("cannot read the state file: %s", err)
	}
	defer r.Close()

	s, err := state.ReadState(backend, r)
	if err != nil {
		return nil, err
	}

	// one-shot migrations
	err = patch.Apply(s)
	if err != nil {
		return nil, err
	}
	return s, nil
}
开发者ID:clobrano,项目名称:snappy,代码行数:31,代码来源:overlord.go

示例6: TestSnapRunCreateDataDirs

func (s *SnapSuite) TestSnapRunCreateDataDirs(c *check.C) {
	info, err := snap.InfoFromSnapYaml(mockYaml)
	c.Assert(err, check.IsNil)
	info.SideInfo.Revision = snap.R(42)

	fakeHome := c.MkDir()
	restorer := snaprun.MockUserCurrent(func() (*user.User, error) {
		return &user.User{HomeDir: fakeHome}, nil
	})
	defer restorer()

	err = snaprun.CreateUserDataDirs(info)
	c.Assert(err, check.IsNil)
	c.Check(osutil.FileExists(filepath.Join(fakeHome, "/snap/snapname/42")), check.Equals, true)
	c.Check(osutil.FileExists(filepath.Join(fakeHome, "/snap/snapname/common")), check.Equals, true)
}
开发者ID:clobrano,项目名称:snappy,代码行数:16,代码来源:cmd_run_test.go

示例7: TestClientLogin

func (cs *clientSuite) TestClientLogin(c *check.C) {
	cs.rsp = `{"type": "sync", "result":
                     {"username": "the-user-name",
                      "macaroon": "the-root-macaroon",
                      "discharges": ["discharge-macaroon"]}}`

	outfile := filepath.Join(c.MkDir(), "json")
	os.Setenv(client.TestAuthFileEnvKey, outfile)
	defer os.Unsetenv(client.TestAuthFileEnvKey)

	c.Assert(cs.cli.LoggedIn(), check.Equals, false)

	user, err := cs.cli.Login("username", "pass", "")
	c.Check(err, check.IsNil)
	c.Check(user, check.DeepEquals, &client.User{
		Macaroon:   "the-root-macaroon",
		Discharges: []string{"discharge-macaroon"}})

	c.Assert(cs.cli.LoggedIn(), check.Equals, true)

	c.Check(osutil.FileExists(outfile), check.Equals, true)
	content, err := ioutil.ReadFile(outfile)
	c.Check(err, check.IsNil)
	c.Check(string(content), check.Equals, `{"macaroon":"the-root-macaroon","discharges":["discharge-macaroon"]}`)
}
开发者ID:clobrano,项目名称:snappy,代码行数:25,代码来源:login_test.go

示例8: removeMountUnit

func removeMountUnit(baseDir string, meter progress.Meter) error {
	sysd := systemd.New(dirs.GlobalRootDir, meter)
	unit := systemd.MountUnitPath(dirs.StripRootDir(baseDir), "mount")
	if osutil.FileExists(unit) {
		// use umount -l (lazy) to ensure that even busy mount points
		// can be unmounted.
		// note that the long option --lazy is not supported on trusty.
		if output, err := exec.Command("umount", "-l", baseDir).CombinedOutput(); err != nil {
			return osutil.OutputErr(output, err)
		}

		if err := sysd.Stop(filepath.Base(unit), time.Duration(1*time.Second)); err != nil {
			return err
		}
		if err := sysd.Disable(filepath.Base(unit)); err != nil {
			return err
		}
		if err := os.Remove(unit); err != nil {
			return err
		}
		// daemon-reload to ensure that systemd actually really
		// forgets about this mount unit
		if err := sysd.DaemonReload(); err != nil {
			return err
		}
	}

	return nil
}
开发者ID:clobrano,项目名称:snappy,代码行数:29,代码来源:mountunit.go

示例9: Open

// Open opens a given snap file with the right backend
func Open(path string) (Container, error) {

	// see if it's a snapdir first
	if osutil.FileExists(filepath.Join(path, "meta", "snap.yaml")) {
		return snapdir.New(path), nil
	}

	// open the file and check magic
	f, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("cannot open snap: %v", err)
	}
	defer f.Close()

	header := make([]byte, 20)
	if _, err := f.ReadAt(header, 0); err != nil {
		return nil, fmt.Errorf("cannot read snap: %v", err)
	}

	for _, h := range formatHandlers {
		if bytes.HasPrefix(header, h.magic) {
			return h.open(path)
		}
	}

	return nil, fmt.Errorf("cannot open snap: unknown header: %q", header)
}
开发者ID:pedronis,项目名称:snappy,代码行数:28,代码来源:container.go

示例10: TestExtractKernelAssetsNoUnpacksKernelForGrub

func (s *kernelOSSuite) TestExtractKernelAssetsNoUnpacksKernelForGrub(c *C) {
	// pretend to be a grub system
	mockGrub := boottest.NewMockBootloader("grub", c.MkDir())
	partition.ForceBootloader(mockGrub)

	files := [][]string{
		{"kernel.img", "I'm a kernel"},
		{"initrd.img", "...and I'm an initrd"},
		{"meta/kernel.yaml", "version: 4.2"},
	}
	si := &snap.SideInfo{
		RealName: "ubuntu-kernel",
		Revision: snap.R(42),
	}
	fn := snaptest.MakeTestSnapWithFiles(c, packageKernel, files)
	snapf, err := snap.Open(fn)
	c.Assert(err, IsNil)

	info, err := snap.ReadInfoFromSnapFile(snapf, si)
	c.Assert(err, IsNil)

	err = boot.ExtractKernelAssets(info, snapf)
	c.Assert(err, IsNil)

	// kernel is *not* here
	kernimg := filepath.Join(mockGrub.Dir(), "ubuntu-kernel_42.snap", "kernel.img")
	c.Assert(osutil.FileExists(kernimg), Equals, false)
}
开发者ID:elopio,项目名称:snappy,代码行数:28,代码来源:kernel_os_test.go

示例11: Execute

func (x *cmdShell) Execute(args []string) error {
	if len(args) > 0 {
		return ErrExtraArgs
	}

	shellType := x.Positional.ShellType

	// FIXME: make this generic so that all snaps can provide a
	//        shell
	if shellType == "classic" {
		if !osutil.FileExists("/snap/classic/current") {
			return fmt.Errorf(i18n.G(`Classic dimension disabled on this system.
Use "sudo snap install --devmode classic && sudo classic.create" to enable it.`))
		}

		// we need to re-exec if we do not run as root
		if os.Getuid() != 0 {
			if err := reexecWithSudo(); err != nil {
				return err
			}
		}

		fmt.Fprintln(Stdout, i18n.G(`Entering classic dimension`))
		fmt.Fprintln(Stdout, i18n.G(`

The home directory is shared between snappy and the classic dimension.
Run "exit" to leave the classic shell.
`))
		args := []string{"/snap/bin/classic.shell"}
		return syscall.Exec(args[0], args, os.Environ())
	}

	return fmt.Errorf(i18n.G("unsupported shell %v"), shellType)
}
开发者ID:niemeyer,项目名称:snapd,代码行数:34,代码来源:cmd_shell.go

示例12: RemoveSnapServices

// RemoveSnapServices disables and removes service units for the applications from the snap which are services.
func RemoveSnapServices(s *snap.Info, inter interacter) error {
	sysd := systemd.New(dirs.GlobalRootDir, inter)

	nservices := 0

	for _, app := range s.Apps {
		if app.Daemon == "" || !osutil.FileExists(app.ServiceFile()) {
			continue
		}
		nservices++

		serviceName := filepath.Base(app.ServiceFile())
		if err := sysd.Disable(serviceName); err != nil {
			return err
		}

		if err := os.Remove(app.ServiceFile()); err != nil && !os.IsNotExist(err) {
			logger.Noticef("Failed to remove service file for %q: %v", serviceName, err)
		}

		if err := os.Remove(app.ServiceSocketFile()); err != nil && !os.IsNotExist(err) {
			logger.Noticef("Failed to remove socket file for %q: %v", serviceName, err)
		}
	}

	// only reload if we actually had services
	if nservices > 0 {
		if err := sysd.DaemonReload(); err != nil {
			return err
		}
	}

	return nil
}
开发者ID:pedronis,项目名称:snappy,代码行数:35,代码来源:services.go

示例13: StopSnapServices

// StopSnapServices stops service units for the applications from the snap which are services.
func StopSnapServices(s *snap.Info, inter interacter) error {
	sysd := systemd.New(dirs.GlobalRootDir, inter)

	for _, app := range s.Apps {
		// Handle the case where service file doesn't exist and don't try to stop it as it will fail.
		// This can happen with snap try when snap.yaml is modified on the fly and a daemon line is added.
		if app.Daemon == "" || !osutil.FileExists(app.ServiceFile()) {
			continue
		}
		serviceName := filepath.Base(app.ServiceFile())
		tout := serviceStopTimeout(app)
		if err := sysd.Stop(serviceName, tout); err != nil {
			if !systemd.IsTimeout(err) {
				return err
			}
			inter.Notify(fmt.Sprintf("%s refused to stop, killing.", serviceName))
			// ignore errors for kill; nothing we'd do differently at this point
			sysd.Kill(serviceName, "TERM")
			time.Sleep(killWait)
			sysd.Kill(serviceName, "KILL")
		}
	}

	return nil

}
开发者ID:pedronis,项目名称:snappy,代码行数:27,代码来源:services.go

示例14: InDeveloperMode

// InDeveloperMode returns true if the image was build with --developer-mode
func InDeveloperMode() bool {
	// FIXME: this is a bit terrible, we really need a single
	//        bootloader dir like /boot or /boot/loader
	//        instead of having to query the partition code
	bootloader, err := findBootloader()
	if err != nil {
		// can only happy on systems like ubuntu classic
		// that are not full snappy systems
		return false
	}

	file := filepath.Join(bootloader.Dir(), InstallYamlFile)
	if !osutil.FileExists(file) {
		// no idea
		return false
	}

	InstallYaml, err := parseInstallYaml(file)
	if err != nil {
		// no idea
		return false
	}

	return InstallYaml.InstallOptions.DeveloperMode
}
开发者ID:niemeyer,项目名称:snapd,代码行数:26,代码来源:provisioning.go

示例15: newGrub

// newGrub create a new Grub bootloader object
func newGrub() Bootloader {
	g := &grub{}
	if !osutil.FileExists(g.ConfigFile()) {
		return nil
	}

	return g
}
开发者ID:clobrano,项目名称:snappy,代码行数:9,代码来源:grub.go


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