Golang IsNotExist示例

说明

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

编程语言: Golang

命名空间/包名称: os

示例#1
文件: main.go 项目: joekr/minecraft_updater

func backupFiles(versionID string, wg *sync.WaitGroup) {
	defer wg.Done()

	if _, err := os.Stat(backupDir); err != nil {
		if os.IsNotExist(err) {
			makeBackupDir()
		}
	}

	if debug {
		fmt.Printf("backupFiles - %s\n", versionID)
	}
	log.Printf("backupFiles - %s\n", versionID)

	fileName := fmt.Sprintf("%s%s%s_backup", backupDir, string(os.PathSeparator), versionID)
	worldDir := fmt.Sprintf("%s", worldDir)

	if _, err := os.Stat(backupDir); err != nil {
		if os.IsNotExist(err) {
			if debug {
				fmt.Println("Nothing to backup right now.")
			}
			log.Println("Nothing to backup right now.")
		} else {
			zip := new(archivex.ZipFile)
			zip.Create(fileName)
			fmt.Printf("worldDir - %s\n", worldDir)
			fmt.Printf("fileName - %s\n", fileName)
			zip.AddAll(worldDir, true)
			fmt.Printf("after addall\n")
			zip.Close()
		}
	}
}

示例#2
文件: services.go 项目: clobrano/snappy

// 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 == "" {
			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
}

示例#3
文件: jekyll-build-server.go 项目: wakermahmud/jekyll-build-server

func main() {
	flag.StringVar(&repoPrefix, "prefix", "", "The repo name prefix required in order to build.")
	flag.Parse()

	if repoPrefix == "" {
		log.Fatal("Specify a prefix to look for in the repo names with -prefix='name'")
	}

	if f, err := os.Stat(sourceBase); f == nil || os.IsNotExist(err) {
		log.Fatalf("The -src folder, %s, doesn't exist.", sourceBase)
	}

	if f, err := os.Stat(destBase); f == nil || os.IsNotExist(err) {
		log.Fatalf("The -dest folder, %s, doesn't exist.", destBase)
	}

	if dbConnString != "" {
		InitDatabase()
	}

	goji.Get("/", buildsIndexHandler)
	goji.Get("/:name/:repo_tag", buildsShowHandler)
	goji.Post("/_github", postReceiveHook)
	goji.Serve()
}

示例#4
文件: fusion.go 项目: rominirani/machine

func (d *Driver) Start() error {
	log.Infof("Starting %s...", d.MachineName)
	vmrun("start", d.vmxPath(), "nogui")

	// Do not execute the rest of boot2docker specific configuration, exit here
	if d.ConfigDriveURL != "" {
		log.Debugf("Leaving start sequence early, configdrive found")
		return nil
	}

	log.Debugf("Mounting Shared Folders...")
	var shareName, shareDir string // TODO configurable at some point
	switch runtime.GOOS {
	case "darwin":
		shareName = "Users"
		shareDir = "/Users"
		// TODO "linux" and "windows"
	}

	if shareDir != "" {
		if _, err := os.Stat(shareDir); err != nil && !os.IsNotExist(err) {
			return err
		} else if !os.IsNotExist(err) {
			// create mountpoint and mount shared folder
			command := "[ ! -d " + shareDir + " ]&& sudo mkdir " + shareDir + "; [ -f /usr/local/bin/vmhgfs-fuse ]&& sudo /usr/local/bin/vmhgfs-fuse -o allow_other .host:/" + shareName + " " + shareDir + " || sudo mount -t vmhgfs .host:/" + shareName + " " + shareDir
			vmrun("-gu", B2DUser, "-gp", B2DPass, "runScriptInGuest", d.vmxPath(), "/bin/sh", command)
		}
	}

	return nil
}

示例#5
文件: cert.go 项目: skycoin/skycoin

func certKeyXor(certFile, keyFile string) (bool, []error) {
	certInfo, err := os.Stat(certFile)
	certExists := !os.IsNotExist(err)
	certIsFile := certExists && certInfo.Mode().IsRegular()

	keyInfo, err := os.Stat(keyFile)
	keyExists := !os.IsNotExist(err)
	keyIsFile := keyExists && keyInfo.Mode().IsRegular()

	errors := make([]error, 0)
	if certExists && certIsFile && keyExists && keyIsFile {
		return true, errors
	}
	if !certExists && !keyExists {
		return false, errors
	}
	if !certExists {
		errors = append(errors, fmt.Errorf("Cert %s does not exist", certFile))
	} else if !certIsFile {
		errors = append(errors, fmt.Errorf("Cert %s is not a file", certFile))
	}
	if !keyExists {
		errors = append(errors, fmt.Errorf("Key %s does not exist", keyFile))
	} else if !keyIsFile {
		errors = append(errors, fmt.Errorf("Key %s is not a file", keyFile))
	}
	return false, errors
}

示例#6
文件: server.go 项目: md14454/kapacitor

func (s *Server) setupIDs() error {
	clusterIDPath := filepath.Join(s.dataDir, clusterIDFilename)
	clusterID, err := s.readID(clusterIDPath)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	if clusterID == "" {
		clusterID = uuid.NewV4().String()
		s.writeID(clusterIDPath, clusterID)
	}
	s.ClusterID = clusterID

	serverIDPath := filepath.Join(s.dataDir, serverIDFilename)
	serverID, err := s.readID(serverIDPath)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	if serverID == "" {
		serverID = uuid.NewV4().String()
		s.writeID(serverIDPath, serverID)
	}
	s.ServerID = serverID

	return nil
}

示例#7
文件: aufs_test.go 项目: m1911/hyper

func TestTempDirCreate(t *testing.T) {
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}
	if _, err := os.Stat(aufsTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}
	if _, err := os.Stat(testFile3); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}

}

示例#8
文件: volume_test.go 项目: ericcapricorn/kubernetes

func TestSetUpAndTearDown(t *testing.T) {
	tempDir, err := ioutil.TempDir("", "CreateVolumes")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
	defer os.RemoveAll(tempDir)
	fakeID := "my-id"
	type VolumeTester interface {
		Builder
		Cleaner
	}
	volumes := []VolumeTester{
		&EmptyDir{"empty", fakeID, tempDir},
		&GCEPersistentDisk{"pd", fakeID, tempDir, "pd-disk", "ext4", "", false, &MockDiskUtil{}, &MockMounter{}},
	}

	for _, vol := range volumes {
		err = vol.SetUp()
		path := vol.GetPath()
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		if _, err := os.Stat(path); os.IsNotExist(err) {
			t.Errorf("SetUp() failed, volume path not created: %v", path)
		}
		err = vol.TearDown()
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		if _, err := os.Stat(path); !os.IsNotExist(err) {
			t.Errorf("TearDown() failed, original volume path not properly removed: %v", path)
		}
	}
}

示例#9
文件: index_test.go 项目: alexsaveliev/vcsstore

func TestIndexOpen(t *testing.T) {
	repo := createTestRepo(t)
	defer cleanupTestRepo(t, repo)

	path := repo.Workdir() + "/heyindex"

	_, err := os.Stat(path)
	if !os.IsNotExist(err) {
		t.Fatal("new index file already exists")
	}

	idx, err := OpenIndex(path)
	checkFatal(t, err)

	if path != idx.Path() {
		t.Fatalf("mismatched index paths, expected %v, got %v", path, idx.Path())
	}

	err = idx.Write()
	checkFatal(t, err)

	_, err = os.Stat(path)
	if os.IsNotExist(err) {
		t.Fatal("new index file did not get written")
	}
}

示例#10
文件: alloc_dir_test.go 项目: PagerDuty/nomad

// Test that given a set of tasks, each task gets a directory and that directory
// has the shared alloc dir inside of it.
func TestAllocDir_BuildAlloc(t *testing.T) {
	tmp, err := ioutil.TempDir("", "AllocDir")
	if err != nil {
		t.Fatalf("Couldn't create temp dir: %v", err)
	}
	defer os.RemoveAll(tmp)

	d := NewAllocDir(tmp)
	defer d.Destroy()
	tasks := []*structs.Task{t1, t2}
	if err := d.Build(tasks); err != nil {
		t.Fatalf("Build(%v) failed: %v", tasks, err)
	}

	// Check that the AllocDir and each of the task directories exist.
	if _, err := os.Stat(d.AllocDir); os.IsNotExist(err) {
		t.Fatalf("Build(%v) didn't create AllocDir %v", tasks, d.AllocDir)
	}

	for _, task := range tasks {
		tDir, ok := d.TaskDirs[task.Name]
		if !ok {
			t.Fatalf("Task directory not found for %v", task.Name)
		}

		if _, err := os.Stat(tDir); os.IsNotExist(err) {
			t.Fatalf("Build(%v) didn't create TaskDir %v", tasks, tDir)
		}
	}
}

示例#11
文件: main.go 项目: rajasec/ocitools

func loadSpecConfig() (spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec, err error) {
	cPath := "config.json"
	cf, err := os.Open(cPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("config.json not found")
		}
	}
	defer cf.Close()

	rPath := "runtime.json"
	rf, err := os.Open(rPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("runtime.json not found")
		}
	}
	defer rf.Close()

	if err = json.NewDecoder(cf).Decode(&spec); err != nil {
		return
	}
	if err = json.NewDecoder(rf).Decode(&rspec); err != nil {
		return
	}
	return spec, rspec, nil
}

示例#12
文件: main.go 项目: cross-dev/arch-repo-server

func get(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	log.Println("Serving ", r.URL.String())
	repo := p.ByName("repo")
	repoStat, err := os.Stat(repo)
	if os.IsNotExist(err) || !repoStat.IsDir() {
		http.Error(w, "Repo not found", 404)
		return
	}
	arch := p.ByName("arch")
	archStat, err := os.Stat(path.Join(repo, "os", arch))
	if os.IsNotExist(err) || !archStat.IsDir() {
		http.Error(w, "Arch not found", 404)
		return
	}
	name := p.ByName("name")
	finalPath := path.Join(repo, "os", arch, name)
	nameExt := path.Ext(name)
	if nameExt == ".xz" {
		getXz(w, finalPath)
	} else if nameExt == ".db" {
		if fmt.Sprint(repo, ".db") == name {
			getDb(w, finalPath)
		} else {
			http.Error(w, "Database not available", 404)
		}
	} else {
		http.Error(w, "Name not found", 404)
	}
}

示例#13
文件: flexvolume_test.go 项目: ethernetdan/kubernetes

func doTestPluginMountUnmount(t *testing.T, spec *volume.Spec, tmpDir string) {
	tmpDir, err := utiltesting.MkTmpdir("flexvolume_test")
	if err != nil {
		t.Fatalf("error creating temp dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)

	plugMgr := volume.VolumePluginMgr{}
	installPluginUnderTest(t, "kubernetes.io", "fakeMounter", tmpDir, execScriptTempl2, nil)
	plugMgr.InitPlugins(ProbeVolumePlugins(tmpDir), volume.NewFakeVolumeHost(tmpDir, nil, nil))
	plugin, err := plugMgr.FindPluginByName("kubernetes.io/fakeMounter")
	if err != nil {
		t.Errorf("Can't find the plugin by name")
	}
	fake := &mount.FakeMounter{}
	pod := &api.Pod{ObjectMeta: api.ObjectMeta{UID: types.UID("poduid")}}
	builder, err := plugin.(*flexVolumePlugin).newBuilderInternal(spec, pod, &flexVolumeUtil{}, fake, exec.New(), "")
	volumePath := builder.GetPath()
	if err != nil {
		t.Errorf("Failed to make a new Builder: %v", err)
	}
	if builder == nil {
		t.Errorf("Got a nil Builder")
	}
	path := builder.GetPath()
	expectedPath := fmt.Sprintf("%s/pods/poduid/volumes/kubernetes.io~fakeMounter/vol1", tmpDir)
	if path != expectedPath {
		t.Errorf("Unexpected path, expected %q, got: %q", expectedPath, path)
	}
	if err := builder.SetUp(nil); err != nil {
		t.Errorf("Expected success, got: %v", err)
	}
	if _, err := os.Stat(volumePath); err != nil {
		if os.IsNotExist(err) {
			t.Errorf("SetUp() failed, volume path not created: %s", volumePath)
		} else {
			t.Errorf("SetUp() failed: %v", err)
		}
	}
	t.Logf("Setup successful")
	if builder.(*flexVolumeBuilder).readOnly {
		t.Errorf("The volume source should not be read-only and it is.")
	}

	cleaner, err := plugin.(*flexVolumePlugin).newCleanerInternal("vol1", types.UID("poduid"), &flexVolumeUtil{}, fake, exec.New())
	if err != nil {
		t.Errorf("Failed to make a new Cleaner: %v", err)
	}
	if cleaner == nil {
		t.Errorf("Got a nil Cleaner")
	}
	if err := cleaner.TearDown(); err != nil {
		t.Errorf("Expected success, got: %v", err)
	}
	if _, err := os.Stat(volumePath); err == nil {
		t.Errorf("TearDown() failed, volume path still exists: %s", volumePath)
	} else if !os.IsNotExist(err) {
		t.Errorf("SetUp() failed: %v", err)
	}
}

示例#14
文件: pod_test.go 项目: tomzhang/p2

func TestUninstall(t *testing.T) {
	fakeSB := runit.FakeServiceBuilder()
	defer fakeSB.Cleanup()
	serviceBuilder := &fakeSB.ServiceBuilder

	testPodDir, err := ioutil.TempDir("", "testPodDir")
	Assert(t).IsNil(err, "Got an unexpected error creating a temp directory")
	pod := Pod{
		Id:             "testPod",
		path:           testPodDir,
		ServiceBuilder: serviceBuilder,
	}
	manifest := getTestPodManifest(t)
	manifestContent, err := manifest.Marshal()
	Assert(t).IsNil(err, "couldn't get manifest bytes")
	err = ioutil.WriteFile(pod.currentPodManifestPath(), manifestContent, 0744)
	Assert(t).IsNil(err, "should have written current manifest")

	serviceBuilderFilePath := filepath.Join(serviceBuilder.ConfigRoot, "testPod.yaml")
	err = ioutil.WriteFile(serviceBuilderFilePath, []byte("stuff"), 0744)
	Assert(t).IsNil(err, "Error writing fake servicebuilder file")

	err = pod.Uninstall()
	Assert(t).IsNil(err, "Error uninstalling pod")
	_, err = os.Stat(serviceBuilderFilePath)
	Assert(t).IsTrue(os.IsNotExist(err), "Expected file to not exist after uninstall")
	_, err = os.Stat(pod.currentPodManifestPath())
	Assert(t).IsTrue(os.IsNotExist(err), "Expected file to not exist after uninstall")
}

示例#15
文件: linux.go 项目: spheromak/containerd

// loadSpec loads the specification from the provided path.
// If the path is empty then the default path will be "config.json"
func (r *libcontainerRuntime) loadSpec(cPath, rPath string) (spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec, err error) {
	cf, err := os.Open(cPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("JSON specification file at %s not found", cPath)
		}
		return spec, rspec, err
	}
	defer cf.Close()

	rf, err := os.Open(rPath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil, fmt.Errorf("JSON runtime config file at %s not found", rPath)
		}
		return spec, rspec, err
	}
	defer rf.Close()

	if err = json.NewDecoder(cf).Decode(&spec); err != nil {
		return spec, rspec, fmt.Errorf("unmarshal %s: %v", cPath, err)
	}
	if err = json.NewDecoder(rf).Decode(&rspec); err != nil {
		return spec, rspec, fmt.Errorf("unmarshal %s: %v", rPath, err)
	}
	return spec, rspec, r.checkSpecVersion(spec)
}

示例#16
文件: lazyweb.go 项目: lazypic/web

func www_coffeecat_page(w http.ResponseWriter, r *http.Request, i int) {
	img := fmt.Sprintf("images/coffeecat/%02d.png", i)
	_, err := os.Stat(img)
	if err != nil {
		if os.IsNotExist(err) {
			http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
			return
		} else {
			log.Print(err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
	}
	prev := fmt.Sprintf("coffeecat/%d", i-1)
	_, err = os.Stat(fmt.Sprintf("images/coffeecat/%02d.png", i-1))
	if err != nil {
		if os.IsNotExist(err) {
			prev = ""
		} else {
			log.Print(err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
	}
	next := fmt.Sprintf("coffeecat/%d", i+1)
	_, err = os.Stat(fmt.Sprintf("images/coffeecat/%02d.png", i+1))
	if err != nil {
		if os.IsNotExist(err) {
			next = ""
		} else {
			log.Print(err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
	}
	fmap := template.FuncMap{
		"lower": strings.ToLower,
	}
	t, err := template.New("coffeecat_page.html").Funcs(fmap).ParseFiles("template/coffeecat_page.html", "template/head.html", "template/menu.html", "template/footer.html")
	if err != nil {
		log.Fatal(err)
	}
	info := struct {
		Menus  []string
		MenuOn string
		Image  string
		Prev   string
		Next   string
	}{
		Menus:  Menus,
		MenuOn: "CoffeeCat",
		Image:  img,
		Prev:   prev,
		Next:   next,
	}
	err = t.Execute(w, info)
	if err != nil {
		log.Fatal(err)
	}
}

示例#17
文件: build_test.go 项目: rangilin/glowing-dangerzone

func TestBuildShouldCopyPostFiles(t *testing.T) {
	t.Parallel()

	testDataDir := testDataPath("build", "test_generate_posts")
	output := createTmpFolder(t)

	err := NewBlogBuilder(newTestPostParser(), fakeConfiguration(), testDataDir).Build(output)
	if err != nil {
		t.Fatal(err)
	}

	file := filepath.Join(output, "test-post", "test.txt")
	if _, err := os.Stat(file); os.IsNotExist(err) {
		t.Errorf("File in post folder should be copied to build result")
	}

	fileInSubDir := filepath.Join(output, "test-post", "test", "test.txt")
	if _, err := os.Stat(fileInSubDir); os.IsNotExist(err) {
		t.Errorf("File in sub folder of post folder should be copied to the build result")
	}

	markdown := filepath.Join(output, "test-post", "post.md")
	if _, err := os.Stat(markdown); !os.IsNotExist(err) {
		t.Errorf("Post markdown file should not be copied to the built result")
	}

}

示例#18
文件: driver.go 项目: Gandi/docker

func (d *driver) Terminate(p *execdriver.Command) error {
	// lets check the start time for the process
	state, err := libcontainer.GetState(filepath.Join(d.root, p.ID))
	if err != nil {
		if !os.IsNotExist(err) {
			return err
		}
		// TODO: Remove this part for version 1.2.0
		// This is added only to ensure smooth upgrades from pre 1.1.0 to 1.1.0
		data, err := ioutil.ReadFile(filepath.Join(d.root, p.ID, "start"))
		if err != nil {
			// if we don't have the data on disk then we can assume the process is gone
			// because this is only removed after we know the process has stopped
			if os.IsNotExist(err) {
				return nil
			}
			return err
		}
		state = &libcontainer.State{InitStartTime: string(data)}
	}

	currentStartTime, err := system.GetProcessStartTime(p.ProcessConfig.Process.Pid)
	if err != nil {
		return err
	}

	if state.InitStartTime == currentStartTime {
		err = syscall.Kill(p.ProcessConfig.Process.Pid, 9)
		syscall.Wait4(p.ProcessConfig.Process.Pid, nil, 0, nil)
	}
	d.removeContainerRoot(p.ID)

	return err

}

示例#19
文件: tree.go 项目: klizhentas/acbuild

// Remove cleans the directory for the specified key
func (ts *TreeStore) Remove(key string) error {
	treepath := filepath.Join(ts.path, key)
	// If tree path doesn't exist we're done
	_, err := os.Stat(treepath)
	if err != nil && os.IsNotExist(err) {
		return nil
	}
	if err != nil {
		return fmt.Errorf("treestore: failed to open tree store directory: %v", err)
	}

	renderedFilePath := filepath.Join(treepath, renderedfilename)
	// The "rendered" flag file should be the firstly removed file. So if
	// the removal ends with some error leaving some stale files IsRendered()
	// will return false.
	_, err = os.Stat(renderedFilePath)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	if !os.IsNotExist(err) {
		err := os.Remove(renderedFilePath)
		// Ensure that the treepath directory is fsynced after removing the
		// "rendered" flag file
		f, err := os.Open(treepath)
		if err != nil {
			return fmt.Errorf("treestore: failed to open tree store directory: %v", err)
		}
		defer f.Close()
		err = f.Sync()
		if err != nil {
			return fmt.Errorf("treestore: failed to sync tree store directory: %v", err)
		}
	}
	return os.RemoveAll(treepath)
}

示例#20
文件: config.go 项目: RichardLitt/gx

func LoadConfigFrom(paths ...string) (*Config, error) {
	if len(paths) == 0 {
		return nil, fmt.Errorf("no path specified!")
	}

	base := paths[0]
	paths = paths[1:]

	cfg, err := loadFile(base)
	if err != nil {
		if !os.IsNotExist(err) {
			return nil, err
		}
	}

	for _, np := range paths {
		next, err := loadFile(np)
		if err != nil {
			if !os.IsNotExist(err) {
				return nil, err
			}
		}

		cfg = mergeConfigs(cfg, next)
	}

	rcfg, err := mapToCfg(cfg)
	if err != nil {
		return nil, err
	}

	sanityFill(rcfg)
	return rcfg, nil
}

示例#21
文件: sysinfo.go 项目: pbx0/docker

// New returns a new SysInfo, using the filesystem to detect which features the kernel supports.
func New(quiet bool) *SysInfo {
	sysInfo := &SysInfo{}
	if cgroupMemoryMountpoint, err := cgroups.FindCgroupMountpoint("memory"); err != nil {
		if !quiet {
			logrus.Warnf("Your kernel does not support cgroup memory limit: %v", err)
		}
	} else {
		// If memory cgroup is mounted, MemoryLimit is always enabled.
		sysInfo.MemoryLimit = true

		_, err1 := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.memsw.limit_in_bytes"))
		sysInfo.SwapLimit = err1 == nil
		if !sysInfo.SwapLimit && !quiet {
			logrus.Warn("Your kernel does not support swap memory limit.")
		}

		_, err = ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.oom_control"))
		sysInfo.OomKillDisable = err == nil
		if !sysInfo.OomKillDisable && !quiet {
			logrus.Warnf("Your kernel does not support oom control.")
		}
	}

	if cgroupCpuMountpoint, err := cgroups.FindCgroupMountpoint("cpu"); err != nil {
		if !quiet {
			logrus.Warnf("%v", err)
		}
	} else {
		_, err1 := ioutil.ReadFile(path.Join(cgroupCpuMountpoint, "cpu.cfs_quota_us"))
		sysInfo.CpuCfsQuota = err1 == nil
		if !sysInfo.CpuCfsQuota && !quiet {
			logrus.Warn("Your kernel does not support cgroup cfs quotas")
		}
	}

	// Checek if ipv4_forward is disabled.
	if data, err := ioutil.ReadFile("/proc/sys/net/ipv4/ip_forward"); os.IsNotExist(err) {
		sysInfo.IPv4ForwardingDisabled = true
	} else {
		if enabled, _ := strconv.Atoi(strings.TrimSpace(string(data))); enabled == 0 {
			sysInfo.IPv4ForwardingDisabled = true
		} else {
			sysInfo.IPv4ForwardingDisabled = false
		}
	}

	// Check if AppArmor is supported.
	if _, err := os.Stat("/sys/kernel/security/apparmor"); os.IsNotExist(err) {
		sysInfo.AppArmor = false
	} else {
		sysInfo.AppArmor = true
	}

	// Check if Devices cgroup is mounted, it is hard requirement for container security.
	if _, err := cgroups.FindCgroupMountpoint("devices"); err != nil {
		logrus.Fatalf("Error mounting devices cgroup: %v", err)
	}

	return sysInfo
}

示例#22
文件: config.go 项目: RichardLitt/gx

func LoadConfig() (*Config, error) {
	// first check $HOME/.gxrc
	cfg, err := loadFile(path.Join(os.Getenv("HOME"), CfgFileName))
	if err != nil {
		if !os.IsNotExist(err) {
			return nil, err
		}
	}

	cwd, err := os.Getwd()
	if err != nil {
		return nil, err
	}

	local, err := loadFile(path.Join(cwd, CfgFileName))
	if err != nil {
		if !os.IsNotExist(err) {
			return nil, err
		}
	}

	if local == nil {
		return mapToCfg(cfg)
	}

	if cfg == nil {
		return mapToCfg(local)
	}

	merged := mergeConfigs(cfg, local)

	return mapToCfg(merged)
}

示例#23
文件: multiple_servers_test.go 项目: kennylixi/influxdb

func (self *ServerSuite) TestRelogging(c *C) {
	// write data and confirm that it went to all three servers
	data := `
  [{
    "points": [
        [1]
    ],
    "name": "test_relogging",
    "columns": ["val"]
  }]`

	self.serverProcesses[0].Post("/db/full_rep/series?u=paul&p=pass", data, c)

	self.serverProcesses[0].WaitForServerToSync()

	self.serverProcesses[0].Query("full_rep", "delete from test_relogging", false, c)

	for _, server := range self.serverProcesses[1:] {
		err := server.DoesWalExist()
		c.Assert(os.IsNotExist(err), Equals, true)
		server.Stop()
		server.Start()
	}

	for _, server := range self.serverProcesses[1:] {
		server.WaitForServerToStart()
		err := server.DoesWalExist()
		c.Assert(os.IsNotExist(err), Equals, true)
	}
}

示例#24
文件: reservation.go 项目: rajatchopra/geard

func ReleaseExternalPorts(ports PortPairs) error {
	var err error
	for i := range ports {
		_, direct := ports[i].External.PortPathsFor()
		path, errl := os.Readlink(direct)
		if errl != nil {
			if !os.IsNotExist(errl) {
				// REPAIR: link can't be checked, may be broken
				log.Printf("ports: Path cannot be checked: %v", errl)
				err = errl
			}
			// the port is no longer reserved (link does not exist)
			continue
		}
		if _, errs := os.Stat(path); errs != nil {
			if os.IsNotExist(errs) {
				// referenced container does not exist, remove the link
				os.Remove(direct)
				continue
			}
			// REPAIR: can't read the referenced container
			err = errs
			continue
		}
		if errr := os.Remove(direct); errr != nil {
			log.Printf("ports: Unable to remove symlink %v", errr)
			err = errr
			// REPAIR: reserved ports may not be properly released
			continue
		}
	}
	return err
}

示例#25
文件: tempfile.go 项目: achanda/go

// TempDir creates a new temporary directory in the directory dir
// with a name beginning with prefix and returns the path of the
// new directory. If dir is the empty string, TempDir uses the
// default directory for temporary files (see os.TempDir).
// Multiple programs calling TempDir simultaneously
// will not choose the same directory. It is the caller's responsibility
// to remove the directory when no longer needed.
func TempDir(dir, prefix string) (name string, err error) {
	if dir == "" {
		dir = os.TempDir()
	}

	nconflict := 0
	for i := 0; i < 10000; i++ {
		try := filepath.Join(dir, prefix+nextSuffix())
		err = os.Mkdir(try, 0700)
		if os.IsExist(err) {
			if nconflict++; nconflict > 10 {
				randmu.Lock()
				rand = reseed()
				randmu.Unlock()
			}
			continue
		}
		if os.IsNotExist(err) {
			if _, err := os.Stat(dir); os.IsNotExist(err) {
				return "", err
			}
		}
		if err == nil {
			name = try
		}
		break
	}
	return
}

示例#26
文件: driver_fusion5.go 项目: Nitron/packer

func (d *Fusion5Driver) Verify() error {
	if _, err := os.Stat(d.AppPath); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("Fusion application not found at path: %s", d.AppPath)
		}

		return err
	}

	if _, err := os.Stat(d.vmrunPath()); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf(
				"Critical application 'vmrun' not found at path: %s", d.vmrunPath())
		}

		return err
	}

	if _, err := os.Stat(d.vdiskManagerPath()); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf(
				"Critical application vdisk manager not found at path: %s",
				d.vdiskManagerPath())
		}

		return err
	}

	return nil
}

示例#27
文件: main.go 项目: kookxiang/Git-Deploy

func updateGitFolder(path string) {
	fmt.Println()
	fmt.Println("Path: " + path)
	if _, err := os.Stat(path); os.IsNotExist(err) {
		fmt.Println("Not exists! Ignored")
		return
	}
	if err := os.Chdir(path); err != nil {
		fmt.Println("Access denied")
		return
	}
	if _, err := os.Stat(".git"); os.IsNotExist(err) {
		fmt.Println("Not a GIT folder! Ignored")
		return
	}
	fmt.Println("Revert all changes...")
	runCommand(exec.Command("git", "reset", "--hard", "HEAD"))
	fmt.Println("Pulling...")
	runCommand(exec.Command("git", "pull"))

	if _, err := os.Stat("deploy.sh"); err == nil {
		fmt.Println("Running external deploy.sh script...")
		runCommand(exec.Command("./deploy.sh"))
	}

	if _, err := os.Stat("build.sh"); err == nil {
		fmt.Println("Running external build.sh script...")
		runCommand(exec.Command("./build.sh"))
	}

	fmt.Println("Done")
}

示例#28
文件: whisper.go 项目: RogerBai/heka

// Creates or opens the relevant whisper db file, and returns running
// WhisperRunner that will write to that file.
func NewWhisperRunner(path_ string, archiveInfo []whisper.ArchiveInfo,
	aggMethod whisper.AggregationMethod, folderPerm os.FileMode,
	wg *sync.WaitGroup) (wr WhisperRunner, err error) {

	var db *whisper.Whisper
	if db, err = whisper.Open(path_); err != nil {
		if !os.IsNotExist(err) {
			// A real error.
			err = fmt.Errorf("Error opening whisper db: %s", err)
			return
		}

		// First make sure the folder is there.
		dir := filepath.Dir(path_)
		if _, err = os.Stat(dir); os.IsNotExist(err) {
			if err = os.MkdirAll(dir, folderPerm); err != nil {
				err = fmt.Errorf("Error creating whisper db folder '%s': %s", dir, err)
				return
			}
		} else if err != nil {
			err = fmt.Errorf("Error opening whisper db folder '%s': %s", dir, err)
		}
		createOptions := whisper.CreateOptions{0.1, aggMethod, false}
		if db, err = whisper.Create(path_, archiveInfo, createOptions); err != nil {
			err = fmt.Errorf("Error creating whisper db: %s", err)
			return
		}
	}
	inChan := make(chan *whisper.Point, 10)
	realWr := &wRunner{path_, db, inChan, wg}
	realWr.start()
	wr = realWr
	return
}

示例#29
文件: certificates.go 项目: yugongpeng/swarmkit

// GetLocalRootCA validates if the contents of the file are a valid self-signed
// CA certificate, and returns the PEM-encoded Certificate if so
func GetLocalRootCA(baseDir string) (RootCA, error) {
	paths := NewConfigPaths(baseDir)

	// Check if we have a Certificate file
	cert, err := ioutil.ReadFile(paths.RootCA.Cert)
	if err != nil {
		if os.IsNotExist(err) {
			err = ErrNoLocalRootCA
		}

		return RootCA{}, err
	}

	key, err := ioutil.ReadFile(paths.RootCA.Key)
	if err != nil {
		if !os.IsNotExist(err) {
			return RootCA{}, err
		}
		// There may not be a local key. It's okay to pass in a nil
		// key. We'll get a root CA without a signer.
		key = nil
	}

	rootCA, err := NewRootCA(cert, key, DefaultNodeCertExpiration)
	if err == nil {
		log.Debugf("successfully loaded the signer for the Root CA: %s", paths.RootCA.Cert)
	}

	return rootCA, err
}

示例#30
文件: watcher.go 项目: btfidelis/gync

func (w *Watcher) sync(path string) {
	fmt.Println("syncing: ", path)

	i, err := os.Stat(path)

	if err != nil {
		log.Println("Error Sync: ", err)
	}

	if i.IsDir() {

		if _, err = os.Stat(w.getDestinationPath(path)); os.IsNotExist(err) {

			fmt.Println("new directory: ", path)
			w.ModFiles[path] = NEWDIR
		}

		for dir, _ := range w.ModTimes {

			if _, err := os.Stat(dir); os.IsNotExist(err) {
				fmt.Println("moved or renamed or deleted: ", dir)
				delete(w.ModTimes, dir)
				w.ModFiles[dir] = DELETED
			}
		}
	} else {
		fmt.Println(w.ModFiles, "modified: ", path)
		w.ModFiles[path] = MODIFIED
	}

	go w.copy()

}

展开阅读全文