示例#1
2
func main() {
	filecsv := `C:\Users\yejianfeng\Desktop\mxm\skill.csv`
	file, err := os.Open(filecsv)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	roleFolder := `C:\Users\yejianfeng\Desktop\mxm\skill\`
	reader.Read()
	for {
		fields, err := reader.Read()
		if err == io.EOF {
			break
		}

		picurl := fields[15]

		jpg := roleFolder + picurl + ".jpg"
		_, err = os.Open(jpg)
		if err == nil || os.IsExist(err) {
			continue
		}

		png := roleFolder + picurl + ".png"
		_, err = os.Open(png)
		if err == nil || os.IsExist(err) {
			continue
		}

		fmt.Println(fields[0])
	}
}
示例#2
0
文件: main.go 项目: uiri/coreutils
func createParents(dir string, verbose bool) bool {
	error := false
	dirs := strings.Split(dir, "/")
	base := ""
	for i := range dirs {
		if dirs[i] == "" {
			base = "/"
			continue
		}
		base = base + dirs[i] + string(os.PathSeparator)
		_, err := os.Stat(base)
		if err == nil || os.IsExist(err) {
			continue
		}
		if verbose {
			fmt.Printf("Creating directory %s\n", base)
		}
		err = os.Mkdir(base, coreutils.Mode)
		if err != nil && !os.IsExist(err) {
			fmt.Fprintf(os.Stderr, "Error while creating directory '%s': %v\n", base, err)
			error = true
		}
	}
	return error
}
示例#3
0
文件: main.go 项目: wenxiaoyu/traffic
func RenderDetail(shdarray []*DP, t *template.Template, sh string) error {
	var hisName = time.Now().Format("2006-01-02")
	dshfilename := homeDir + "/changshi/today/detail_" + sh + ".html"
	if _, err := os.Stat(dshfilename); os.IsExist(err) {
		os.Remove(dshfilename)
	}
	dshf, _ := os.Create(dshfilename)
	dshfbw := bufio.NewWriter(dshf)
	err := t.ExecuteTemplate(dshfbw, "detail.tmpl", shdarray)
	if err != nil {
		return err
	}
	dshfbw.Flush()
	dshf.Close()

	dshhfilename := homeDir + "/changshi/his/d_" + sh + "_" + hisName + ".html"
	if _, err := os.Stat(dshhfilename); os.IsExist(err) {
		os.Remove(dshhfilename)
	}
	dshhf, _ := os.Create(dshhfilename)
	dshhfbw := bufio.NewWriter(dshhf)
	err1 := t.ExecuteTemplate(dshhfbw, "detail.tmpl", shdarray)
	if err1 != nil {
		return err
	}
	dshhfbw.Flush()
	dshhf.Close()
	return nil
}
示例#4
0
func copyDir(srcDir, destDir string) (fileCount int, err error) {
	fileCount = 0
	err = os.MkdirAll(destDir, 0777)
	if err != nil && !os.IsExist(err) {
		return fileCount, err
	}
	err = filepath.Walk(srcDir, func(path string, fi os.FileInfo, err error) error {
		fileCount++
		base := strings.Replace(path, srcDir, "", 1)
		dest := filepath.Join(destDir, base)
		if fi.IsDir() {
			err := os.Mkdir(dest, 0777)
			if os.IsExist(err) {
				return nil
			} else {
				return err
			}
		} else {
			log.Printf("path: %s, base: %s", path, base)
			_, err := copyFile(path, dest)
			return err
		}
	})
	return
}
示例#5
0
文件: dirs.go 项目: jfindley/testfs
func (i *inode) mkdirAll(terms []string, perm os.FileMode) error {
	if len(terms) == 0 {
		return nil
	}

	err := i.new(terms[0], Uid, Gid, perm)
	if len(terms) == 1 {
		if os.IsExist(err) {
			return nil
		}
		return err
	}

	dir := i.children[terms[0]]

	switch {

	case err == nil:
		return dir.mkdirAll(terms[1:], perm)

	case os.IsExist(err):
		// If the child is not a directory, fail
		if !i.children[terms[0]].IsDir() {
			return err
		}
		// If it is a directory, just continue
		return dir.mkdirAll(terms[1:], perm)

	default:
		// Some other error
		return err

	}

}
示例#6
0
func runTaskCopyResources(tp TaskParams) error {
	resources := core.ParseIncludeResources(tp.WorkingDirectory, tp.Settings.ResourcesInclude, tp.Settings.ResourcesExclude, tp.Settings.IsVerbose())
	destFolder := filepath.Join(tp.OutDestRoot, tp.Settings.GetFullVersionName())
	log.Printf("resources: %v", resources)
	for _, resource := range resources {
		if strings.HasPrefix(resource, tp.WorkingDirectory) {
			resource = resource[len(tp.WorkingDirectory)+1:]
		}
		//_, resourcebase := filepath.Split(resource)
		sourcePath := filepath.Join(tp.WorkingDirectory, resource)
		destPath := filepath.Join(destFolder, resource)
		finfo, err := os.Lstat(sourcePath)
		if err != nil {
			return err
		}
		if finfo.IsDir() {
			err = os.MkdirAll(destPath, 0777)
			if err != nil && !os.IsExist(err) {
				return err
			}
		} else {
			err = os.MkdirAll(filepath.Dir(destPath), 0777)
			if err != nil && !os.IsExist(err) {
				return err
			}
			_, err = copyFile(sourcePath, destPath)
		}
		if err != nil {
			return err
		}
	}
	return nil
}
示例#7
0
//Called to create the database for the first time
func (sp *FileStorageProvider) CreateDatabase(opts map[string]string) error {
	for i := 0; i < NUMFILES; i++ {
		//Open file
		dbpath, ok := opts["dbpath"]
		if !ok {
			log.Panicf("Expected dbpath")
		}
		fname := fmt.Sprintf("%s/blockstore.%02x.db", dbpath, i)
		//write file descriptor
		{
			f, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
			if err != nil && !os.IsExist(err) {
				log.Panicf("Problem with blockstore DB: ", err)
			} else if os.IsExist(err) {
				return bprovider.ErrExists
			}
			//Add a file tag
			//An exercise left for the reader: if you remove this, everything breaks :-)
			//Hint: what is the physical address of the first byte of file zero?
			_, err = f.Write([]byte("QUASARDB"))
			if err != nil {
				log.Panicf("Could not write to blockstore:", err)
			}

			err = f.Close()
			if err != nil {
				log.Panicf("Error on close %v", err)
			}
		}
	}
	return nil
}
示例#8
0
// ServeHTTP determines if the request is for this plugin, and if all prerequisites are met.
// If so, control is handed over to ServeListing.
func (b Browse) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	var bc *Config
	// See if there's a browse configuration to match the path
	for i := range b.Configs {
		if httpserver.Path(r.URL.Path).Matches(b.Configs[i].PathScope) {
			bc = &b.Configs[i]
			goto inScope
		}
	}
	return b.Next.ServeHTTP(w, r)
inScope:

	// Browse works on existing directories; delegate everything else
	requestedFilepath, err := bc.Root.Open(r.URL.Path)
	if err != nil {
		switch {
		case os.IsPermission(err):
			return http.StatusForbidden, err
		case os.IsExist(err):
			return http.StatusNotFound, err
		default:
			return b.Next.ServeHTTP(w, r)
		}
	}
	defer requestedFilepath.Close()

	info, err := requestedFilepath.Stat()
	if err != nil {
		switch {
		case os.IsPermission(err):
			return http.StatusForbidden, err
		case os.IsExist(err):
			return http.StatusGone, err
		default:
			return b.Next.ServeHTTP(w, r)
		}
	}
	if !info.IsDir() {
		return b.Next.ServeHTTP(w, r)
	}

	// Do not reply to anything else because it might be nonsensical
	switch r.Method {
	case http.MethodGet, http.MethodHead:
		// proceed, noop
	case "PROPFIND", http.MethodOptions:
		return http.StatusNotImplemented, nil
	default:
		return b.Next.ServeHTTP(w, r)
	}

	// Browsing navigation gets messed up if browsing a directory
	// that doesn't end in "/" (which it should, anyway)
	if !strings.HasSuffix(r.URL.Path, "/") {
		staticfiles.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
		return 0, nil
	}

	return b.ServeListing(w, r, requestedFilepath, bc)
}
示例#9
0
// Mount maps an RBD image and mount it on /mnt/ceph/<datastore>/<volume> directory
// FIXME: Figure out how to use rbd locks
func (cv *CephVolume) Mount() error {
	cd := cv.driver
	// Directory to mount the volume
	dataStoreDir := filepath.Join(cd.mountBase, cv.PoolName)
	volumeDir := filepath.Join(dataStoreDir, cv.VolumeName)

	devName, err := cv.mapImage()
	if err != nil {
		return err
	}

	// Create directory to mount
	if err := os.MkdirAll(cd.mountBase, 0700); err != nil && !os.IsExist(err) {
		return fmt.Errorf("error creating %q directory: %v", cd.mountBase, err)
	}

	if err := os.MkdirAll(dataStoreDir, 0700); err != nil && !os.IsExist(err) {
		return fmt.Errorf("error creating %q directory: %v", dataStoreDir)
	}

	if err := os.MkdirAll(volumeDir, 0777); err != nil && !os.IsExist(err) {
		return fmt.Errorf("error creating %q directory: %v", volumeDir)
	}

	// Mount the RBD
	if err := syscall.Mount(devName, volumeDir, "ext4", 0, ""); err != nil && err != syscall.EBUSY {
		return fmt.Errorf("Failed to mount RBD dev %q: %v", devName, err.Error())
	}

	return nil
}
示例#10
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
}
示例#11
0
func (i *indexMeta) Save(path string) (err error) {
	indexMetaPath := indexMetaPath(path)
	// ensure any necessary parent directories exist
	err = os.MkdirAll(path, 0700)
	if err != nil {
		if os.IsExist(err) {
			return ErrorIndexPathExists
		}
		return err
	}
	metaBytes, err := json.Marshal(i)
	if err != nil {
		return err
	}
	indexMetaFile, err := os.OpenFile(indexMetaPath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
	if err != nil {
		if os.IsExist(err) {
			return ErrorIndexPathExists
		}
		return err
	}
	defer func() {
		if ierr := indexMetaFile.Close(); err == nil && ierr != nil {
			err = ierr
		}
	}()
	_, err = indexMetaFile.Write(metaBytes)
	if err != nil {
		return err
	}
	return nil
}
示例#12
0
// Creates the device node in the rootfs of the container.
func createDeviceNode(rootfs string, node *configs.Device) error {
	dest := filepath.Join(rootfs, node.Path)
	if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
		return err
	}
	if err := mknodDevice(dest, node); err != nil {
		if os.IsExist(err) {
			return nil
		}
		if err != syscall.EPERM {
			return err
		}
		// containers running in a user namespace are not allowed to mknod
		// devices so we can just bind mount it from the host.
		f, err := os.Create(dest)
		if err != nil && !os.IsExist(err) {
			return err
		}
		if f != nil {
			f.Close()
		}
		return syscall.Mount(node.Path, dest, "bind", syscall.MS_BIND, "")
	}
	return nil
}
示例#13
0
// MakeLocalCasTable returns a CasTable rooted at rootDir.
func MakeLocalCasTable(rootDir string) (CasTable, error) {
	// Creates 16^3 (4096) directories. Preferable values are 2 or 3.
	prefixLength := 3
	// Currently hardcoded for SHA-1 but could be used for any length.
	hashLength := sha1.Size * 2

	if !filepath.IsAbs(rootDir) {
		return nil, fmt.Errorf("MakeCasTable(%s) is not valid", rootDir)
	}
	rootDir = filepath.Clean(rootDir)
	casDir := filepath.Join(rootDir, casName)
	if err := os.MkdirAll(casDir, 0750); err != nil && !os.IsExist(err) {
		return nil, fmt.Errorf("MakeCasTable(%s): failed to create the directory: %s", casDir, err)
	} else if !os.IsExist(err) {
		// Create all the prefixes at initialization time so they don't need to be
		// tested all the time.
		for i := 0; i < prefixSpace(uint(prefixLength)); i++ {
			prefix := fmt.Sprintf("%0*x", prefixLength, i)
			if err := os.Mkdir(filepath.Join(casDir, prefix), 0750); err != nil && !os.IsExist(err) {
				return nil, fmt.Errorf("Failed to create %s: %s\n", prefix, err)
			}
		}
	}
	return &casTable{
		rootDir,
		casDir,
		prefixLength,
		hashLength,
		regexp.MustCompile(fmt.Sprintf("^([a-f0-9]{%d})$", hashLength)),
		makeTrash(casDir),
	}, nil
}
示例#14
0
func (b *basedir) Init(path string) error {
	var err error
	b.path, err = filepath.Abs(path)
	if err != nil {
		return err
	}

	if err := MakeDir(b.path); err != nil && !os.IsExist(err) {
		return err
	}

	b.configDir = filepath.Join(b.path, CONFIG_DIR)
	if err := MakeDir(b.configDir); err != nil && !os.IsExist(err) {
		return err
	}
	if err := os.Chmod(b.configDir, 0700); err != nil {
		return err
	}

	b.dataDir = filepath.Join(b.path, DATA_DIR)
	if err := MakeDir(b.dataDir); err != nil && !os.IsExist(err) {
		return err
	}

	b.binDir = filepath.Join(b.path, BIN_DIR)
	if err := MakeDir(b.binDir); err != nil && !os.IsExist(err) {
		return err
	}

	return nil
}
示例#15
0
文件: test.go 项目: contiv/volplugin
// Mount records mounted volume
func (d *Driver) Mount(do storage.DriverOptions) (*storage.Mount, error) {
	d.logStat(getFunctionName())
	if err := os.MkdirAll(d.BaseMountPath, 0700); err != nil && !os.IsExist(err) {
		return nil, errored.Errorf("error creating %q directory: %v", d.BaseMountPath, err)
	}

	volumePath := filepath.Join(d.BaseMountPath, do.Volume.Params["pool"], do.Volume.Name)
	if err := os.MkdirAll(volumePath, 0700); err != nil && !os.IsExist(err) {
		return nil, errored.Errorf("error creating %q directory: %v", volumePath, err)
	}

	mount := &storage.Mount{
		Path:   volumePath,
		Volume: do.Volume,
	}

	content, err := json.Marshal(mount)
	if err != nil {
		return nil, err
	}

	_, err = d.client.Set(context.Background(), path.Join(mountedPrefix, do.Volume.Name), string(content), &client.SetOptions{PrevExist: client.PrevNoExist})
	logrus.Infof("%v %v", path.Join(mountedPrefix, do.Volume.Name), err)
	if err != nil {
		return nil, err
	}

	return mount, nil
}
示例#16
0
文件: daemon.go 项目: gnawux/hyper
func NewDaemon(cfg *apitypes.HyperConfig) (*Daemon, error) {
	var tempdir = path.Join(utils.HYPER_ROOT, "run")
	os.Setenv("TMPDIR", tempdir)
	if err := os.MkdirAll(tempdir, 0755); err != nil && !os.IsExist(err) {
		return nil, err
	}

	var realRoot = path.Join(utils.HYPER_ROOT, "lib")
	// Create the root directory if it doesn't exists
	if err := os.MkdirAll(realRoot, 0755); err != nil && !os.IsExist(err) {
		return nil, err
	}

	var (
		db_file = fmt.Sprintf("%s/hyper.db", realRoot)
	)
	db, err := daemondb.NewDaemonDB(db_file)
	if err != nil {
		return nil, err
	}

	daemon := &Daemon{
		ID:      fmt.Sprintf("%d", os.Getpid()),
		db:      db,
		PodList: pod.NewPodList(),
		Host:    cfg.Host,
	}

	daemon.Daemon, err = docker.NewDaemon(dockerCfg, registryCfg)
	if err != nil {
		return nil, err
	}

	// Get the docker daemon info
	sysinfo, err := daemon.Daemon.SystemInfo()
	if err != nil {
		return nil, err
	}
	stor, err := StorageFactory(sysinfo, daemon.db)
	if err != nil {
		return nil, err
	}
	daemon.Storage = stor
	daemon.Storage.Init()

	err = daemon.initRunV(cfg)
	if err != nil {
		return nil, err
	}

	err = daemon.initNetworks(cfg)
	if err != nil {
		return nil, err
	}

	daemon.initDefaultLog(cfg)

	return daemon, nil
}
示例#17
0
func printRules(wordFileName, ruleFileName string, words chan []Word) {
	var wordFile *os.File
	var ruleFile *os.File

	// may not even need to stat it.
	// os.create will just overwrite the file

	// we remove the old files so we can write the new contents
	if _, err := os.Stat(wordFileName); err != nil {
		if os.IsExist(err) {
			err = os.Remove(wordFileName)
			if err != nil {
				log.Println(err.Error())
			}

		}
	}
	wordFile, err := os.Create(wordFileName)
	if err != nil {
		log.Println("cannot open file to write to:" + err.Error())
	}

	if _, err := os.Stat(ruleFileName); err != nil {
		if os.IsExist(err) {
			err = os.Remove(ruleFileName)
			if err != nil {
				log.Println(err.Error())
			}

		}
	}
	ruleFile, err = os.Create(ruleFileName)
	if err != nil {
		log.Println("cannot open file to write to:" + err.Error())
	}

	defer wordFile.Close()
	defer ruleFile.Close()

	wordbuf := bufio.NewWriter(wordFile)
	rulebuf := bufio.NewWriter(ruleFile)

	for word := range words {
		for _, a := range word {
			fmt.Fprintln(wordbuf, a.suggestion)
			fmt.Fprintf(rulebuf, "%v", a.hashcatRules)
			// try to flush right before the buffer gets filled
			if wordbuf.Buffered() >= 4000 {
				wordbuf.Flush()
			}
			if rulebuf.Buffered() >= 4000 {
				rulebuf.Flush()
			}
		}
	}
	// make sure that everything is flushed
	rulebuf.Flush()
	wordbuf.Flush()
}
示例#18
0
文件: store.go 项目: niallo/docker
func (mp *Mountpoint) createFolders() error {
	if err := os.Mkdir(mp.Root, 0755); err != nil && !os.IsExist(err) {
		return err
	}
	if err := os.Mkdir(mp.Rw, 0755); err != nil && !os.IsExist(err) {
		return err
	}
	return nil
}
示例#19
0
func linkAlreadyExists(err error) bool {
	if os.IsExist(err) {
		return true
	}
	if le, ok := err.(*os.LinkError); ok && os.IsExist(le.Err) {
		return true
	}
	return false
}
示例#20
0
文件: main.go 项目: sparks/genarthack
func main() {
	err := os.Mkdir(uploadPath, os.ModeDir|0755)
	if err != nil && !os.IsExist(err) {
		panic(err)
	}

	err = os.Mkdir(livePath, os.ModeDir|0755)
	if err != nil && !os.IsExist(err) {
		panic(err)
	}

	// Read the secret
	file, err := os.Open("secret.txt")
	if err == nil {
		reader := bufio.NewReader(file)
		line, err := reader.ReadString('\n')
		if err != nil {
			log.Fatal("Failed to read secret file")
		}
		secret = strings.TrimSpace(line)
		log.Println("Set the secret to: " + secret)
	} else {
		log.Println("Warning: No secret specified, defaulting to: " + secret)
	}

	// Create a random value for the cookies
	bytes := make([]byte, 4)
	n, err := rand.Read(bytes)
	if err != nil || n != cap(bytes) {
		log.Fatal("Failed to initalize random session value")
	}
	secretVal = hex.EncodeToString(bytes)

	RebuildPieceMap()

	http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {}) //Prevent favicon unserved error

	http.HandleFunc("/auth", AuthHandler)
	http.HandleFunc("/submit", SubmitHandler)

	http.Handle("/uploads/", http.StripPrefix("/uploads", http.FileServer(http.Dir(uploadPath))))
	http.HandleFunc("/live/", LiveHandler)
	http.Handle("/resources/", http.StripPrefix("/resources", http.FileServer(http.Dir(resourcePath))))

	http.HandleFunc("/nominate", NominateHandler)
	http.HandleFunc("/nominees", NomineeHandler)
	http.HandleFunc("/random", RandomHandler)
	http.HandleFunc("/cycler", CyclerHandler)

	http.HandleFunc("/rebuild", RebuildHandler)

	http.HandleFunc("/", MainHandler)

	log.Fatal(http.ListenAndServe(":8080", nil))
}
示例#21
0
// EnsurePaths ensures that all paths necessary for proper host functioning exist.
func (c *Config) EnsurePaths(path string) error {
	if err := os.MkdirAll(filepath.Dir(path), 0770); !os.IsExist(err) {
		return err
	}

	if err := os.MkdirAll(filepath.Join(c.Home, "db"), 0770); !os.IsExist(err) {
		return err
	}

	return nil
}
示例#22
0
文件: sequins.go 项目: delkyd/sequins
func (s *sequins) refresh() error {
	s.reloadLock.Lock()
	defer s.reloadLock.Unlock()

	version, err := s.backend.LatestVersion(s.options.CheckForSuccessFile)
	if err != nil {
		return err
	}

	// We can use unsafe ref, since closing the index would not affect the version string
	var currentVersion string
	currentIndex := s.indexReference.UnsafeGet()
	if currentIndex != nil {
		currentVersion = currentIndex.Version
	}

	if version != currentVersion {
		path := filepath.Join(s.options.LocalPath, version)

		err := os.Mkdir(path, 0700|os.ModeDir)
		if err != nil && !os.IsExist(err) {
			return err
		}

		if os.IsExist(err) {
			log.Printf("Version %s is already downloaded", version)
		} else {
			log.Printf("Downloading version %s from %s", version, s.backend.DisplayPath(version))
			err = s.download(version, path)
			if err != nil {
				return err
			}
		}

		log.Printf("Preparing version %s at %s", version, path)
		index := index.New(path, version)
		err = index.Load()
		if err != nil {
			return fmt.Errorf("Error while indexing: %s", err)
		}

		log.Printf("Switching to version %s!", version)

		oldIndex := s.indexReference.Replace(index)
		if oldIndex != nil {
			oldIndex.Close()
		}
	} else {
		log.Printf("%s is already the newest version, so not reloading.", version)
	}

	return nil
}
示例#23
0
文件: ceph.go 项目: contiv/volplugin
// Mount a volume. Returns the rbd device and mounted filesystem path.
// If you pass in the params what filesystem to use as `filesystem`, it will
// prefer that to `ext4` which is the default.
func (c *Driver) Mount(do storage.DriverOptions) (*storage.Mount, error) {
	intName, err := c.internalName(do.Volume.Name)
	if err != nil {
		return nil, err
	}

	poolName := do.Volume.Params["pool"]

	volumePath, err := c.mkMountPath(poolName, intName)
	if err != nil {
		return nil, err
	}

	devName, err := c.mapImage(do)
	if err != nil {
		return nil, err
	}

	// Create directory to mount
	if err := os.MkdirAll(c.mountpath, 0700); err != nil && !os.IsExist(err) {
		return nil, errored.Errorf("error creating %q directory: %v", c.mountpath, err)
	}

	if err := os.MkdirAll(volumePath, 0700); err != nil && !os.IsExist(err) {
		return nil, errored.Errorf("error creating %q directory: %v", volumePath, err)
	}

	// Obtain the major and minor node information about the device we're mounting.
	// This is critical for tuning cgroups and obtaining metrics for this device only.
	fi, err := os.Stat(devName)
	if err != nil {
		return nil, errored.Errorf("Failed to stat rbd device %q: %v", devName, err)
	}

	rdev := fi.Sys().(*syscall.Stat_t).Rdev

	major := rdev >> 8
	minor := rdev & 0xFF

	// Mount the RBD
	if err := unix.Mount(devName, volumePath, do.FSOptions.Type, 0, ""); err != nil {
		return nil, errored.Errorf("Failed to mount RBD dev %q: %v", devName, err)
	}

	return &storage.Mount{
		Device:   devName,
		Path:     volumePath,
		Volume:   do.Volume,
		DevMajor: uint(major),
		DevMinor: uint(minor),
	}, nil
}
示例#24
0
文件: main.go 项目: Varjelus/nwbob
// Copy NW.js files
func copyWalk(path string, info os.FileInfo, err error) error {
	if err != nil {
		return err
	}

	fileName := strings.TrimPrefix(path, *nwDir)
	if len(fileName) < 1 {
		return nil
	}
	dstPath := filepath.Join(*outDir, fileName)

	// Check if the destination file exists
	dstInfo, err := os.Stat(dstPath)
	// If it does exist and it errors, return
	if err != nil && os.IsExist(err) {
		return err
	}
	// If it does exist and it's the same file, return nil
	if os.IsExist(err) && os.SameFile(info, dstInfo) {
		return nil
	}

	if info.IsDir() {
		if err := os.Mkdir(dstPath, info.Mode()); err != nil {
			return err
		}
		return nil
	}

	// Keep only regular, nonempty files
	if !info.Mode().IsRegular() || info.Size() == 0 {
		return nil
	}

	// Omit pdf.dll unless otherwise specified
	if info.Name() == "pdf.dll" && !*usePdf {
		return nil
	}

	// Omit specified files
	for _, e := range NW_OMIT {
		if e == info.Name() {
			return nil
		}
	}

	if _, err = kopsa.Copy(dstPath, path); err != nil {
		return err
	}

	return nil
}
示例#25
0
// makePodDataDirs creates the dirs for the pod datas.
func (kl *Kubelet) makePodDataDirs(pod *api.Pod) error {
	uid := pod.UID
	if err := os.MkdirAll(kl.getPodDir(uid), 0750); err != nil && !os.IsExist(err) {
		return err
	}
	if err := os.MkdirAll(kl.getPodVolumesDir(uid), 0750); err != nil && !os.IsExist(err) {
		return err
	}
	if err := os.MkdirAll(kl.getPodPluginsDir(uid), 0750); err != nil && !os.IsExist(err) {
		return err
	}
	return nil
}
示例#26
0
文件: options.go 项目: pmezard/exp
func (o *Options) check(dbname string, new, lock bool) (err error) {
	var lname string
	if lock {
		lname = o.lockName(dbname)
		if o.lock, err = os.OpenFile(lname, os.O_CREATE|os.O_EXCL|os.O_RDONLY, 0666); err != nil {
			if os.IsExist(err) {
				err = fmt.Errorf("cannot access DB %q: lock file %q exists", dbname, lname)
			}
			return
		}
	}

	switch o.ACID {
	default:
		return fmt.Errorf("Unsupported Options.ACID: %d", o.ACID)
	case ACIDNone, ACIDTransactions:
	case ACIDFull:
		o.WAL = o.walName(dbname, o.WAL)
		if lname == o.WAL {
			panic("internal error")
		}

		switch new {
		case true:
			if o.wal, err = os.OpenFile(o.WAL, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err != nil {
				if os.IsExist(err) {
					fi, e := os.Stat(o.WAL)
					if e != nil {
						return e
					}

					if sz := fi.Size(); sz != 0 {
						return fmt.Errorf("cannot create DB %q: non empty WAL file %q (size %d) exists", dbname, o.WAL, sz)
					}

					o.wal, err = os.OpenFile(o.WAL, os.O_RDWR, 0666)
				}
				return
			}
		case false:
			if o.wal, err = os.OpenFile(o.WAL, os.O_RDWR, 0666); err != nil {
				if os.IsNotExist(err) {
					err = fmt.Errorf("cannot open DB %q: WAL file %q doesn't exist", dbname, o.WAL)
				}
				return
			}
		}
	}

	return
}
示例#27
0
func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error {
	// make an array containing the original path asked for, plus (for mkAll == true)
	// all path components leading up to the complete path that don't exist before we MkdirAll
	// so that we can chown all of them properly at the end.  If chownExisting is false, we won't
	// chown the full directory path if it exists
	var paths []string
	if _, err := os.Stat(path); err != nil && os.IsNotExist(err) {
		paths = []string{path}
	} else if err == nil && chownExisting {
		if err := os.Chown(path, ownerUID, ownerGID); err != nil {
			return err
		}
		// short-circuit--we were called with an existing directory and chown was requested
		return nil
	} else if err == nil {
		// nothing to do; directory path fully exists already and chown was NOT requested
		return nil
	}

	if mkAll {
		// walk back to "/" looking for directories which do not exist
		// and add them to the paths array for chown after creation
		dirPath := path
		for {
			dirPath = filepath.Dir(dirPath)
			if dirPath == "/" {
				break
			}
			if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) {
				paths = append(paths, dirPath)
			}
		}
		if err := system.MkdirAll(path, mode); err != nil && !os.IsExist(err) {
			return err
		}
	} else {
		if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) {
			return err
		}
	}
	// even if it existed, we will chown the requested path + any subpaths that
	// didn't exist when we called MkdirAll
	for _, pathComponent := range paths {
		if err := os.Chown(pathComponent, ownerUID, ownerGID); err != nil {
			return err
		}
	}
	return nil
}
示例#28
0
文件: driver.go 项目: harche/docker
// Get mounts a device with given id into the root filesystem
func (d *Driver) Get(id, mountLabel string) (string, error) {
	mp := path.Join(d.home, "mnt", id)
	rootFs := path.Join(mp, "rootfs")
	if count := d.ctr.Increment(mp); count > 1 {
		return rootFs, nil
	}

	uid, gid, err := idtools.GetRootUIDGID(d.uidMaps, d.gidMaps)
	if err != nil {
		d.ctr.Decrement(mp)
		return "", err
	}

	// Create the target directories if they don't exist
	if err := idtools.MkdirAllAs(path.Join(d.home, "mnt"), 0755, uid, gid); err != nil && !os.IsExist(err) {
		d.ctr.Decrement(mp)
		return "", err
	}
	if err := idtools.MkdirAs(mp, 0755, uid, gid); err != nil && !os.IsExist(err) {
		d.ctr.Decrement(mp)
		return "", err
	}

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

	if err := idtools.MkdirAllAs(rootFs, 0755, uid, gid); err != nil && !os.IsExist(err) {
		d.ctr.Decrement(mp)
		d.DeviceSet.UnmountDevice(id, mp)
		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 reconstruct this in case
		// of later problems
		if err := ioutil.WriteFile(idFile, []byte(id), 0600); err != nil {
			d.ctr.Decrement(mp)
			d.DeviceSet.UnmountDevice(id, mp)
			return "", err
		}
	}

	return rootFs, nil
}
示例#29
0
文件: fs.go 项目: DirkZhao/pproxy
func File_exists(file_path string) bool {
	_, err := os.Stat(file_path)
	if err == nil {
		return true
	}
	return os.IsExist(err)
}
示例#30
0
//判断文件是否存在
//判断文件是否存在
func isExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	return os.IsExist(err)
}