Ejemplo n.º 1
1
func GetChain(ctx *cli.Context) (*core.ChainManager, common.Database, common.Database) {
	dataDir := ctx.GlobalString(DataDirFlag.Name)

	blockDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "blockchain"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	stateDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "state"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	extraDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "extra"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	eventMux := new(event.TypeMux)
	chainManager := core.NewChainManager(blockDb, stateDb, eventMux)
	pow := ethash.New()
	txPool := core.NewTxPool(eventMux, chainManager.State, chainManager.GasLimit)
	blockProcessor := core.NewBlockProcessor(stateDb, extraDb, pow, txPool, chainManager, eventMux)
	chainManager.SetProcessor(blockProcessor)

	return chainManager, blockDb, stateDb
}
Ejemplo n.º 2
0
Archivo: flatfs.go Proyecto: rht/bssim
func (fs *Datastore) encode(key datastore.Key) (dir, file string) {
	safe := hex.EncodeToString(key.Bytes()[1:])
	prefix := (safe + padding)[:fs.hexPrefixLen]
	dir = path.Join(fs.path, prefix)
	file = path.Join(dir, safe+extension)
	return dir, file
}
Ejemplo n.º 3
0
func (n *Node) DownloadByGoGet(ctx *cli.Context, u *url.URL) error {
	baseDir := path.Join(setting.HomeDir, ".gopm/temp/goget")
	os.MkdirAll(baseDir, os.ModePerm)
	defer func() {
		os.RemoveAll(baseDir)
	}()

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

	log.Debug("RUN 'go get %s'", n.RootPath)
	_, stderr, err := base.ExecCmdDir(baseDir, "go", "get", n.RootPath)
	if err != nil {
		log.Error("Error occurs when 'go get" + n.RootPath + "'")
		log.Error("\t" + stderr)
		return errors.New(stderr)
	}
	tmpPath := path.Join(baseDir, "src", n.RootPath)
	if !n.IsEmptyVal() {
		base.ExecCmdDir(tmpPath, "git", "checkout", n.Value)
		if err != nil {
			log.Error("Error occurs when 'git checkout" + n.Value + "'")
			log.Error("\t" + stderr)
			return errors.New(stderr)
		}
	}
	os.MkdirAll(path.Dir(n.InstallPath), os.ModePerm)
	os.Rename(tmpPath, n.InstallPath)
	return nil
}
Ejemplo n.º 4
0
// listChart enumerates all of the relevant files in a chart
func listChart(chartDir string) ([]string, error) {

	var files []string

	metadataFile := path.Join(chartDir, "Chart.yaml")
	manifestDir := path.Join(chartDir, "manifests")

	// check for existence of important files and directories
	for _, path := range []string{chartDir, metadataFile, manifestDir} {
		if _, err := os.Stat(path); os.IsNotExist(err) {
			return nil, err
		}
	}

	// add metadata file to front of list
	files = append(files, metadataFile)

	// add manifest files
	walker := func(fname string, fi os.FileInfo, e error) error {
		if e != nil {
			log.Warn("Encounter error walking %q: %s", fname, e)
			return nil
		}

		if filepath.Ext(fname) == ".yaml" {
			files = append(files, fname)
		}

		return nil
	}
	filepath.Walk(manifestDir, walker)

	return files, nil
}
Ejemplo n.º 5
0
// Lists all directories under "path" and outputs the results as children of "parent".
func listDirectories(dirpath string, parent string, recursive bool, output map[string]struct{}) error {
	// Ignore if this hierarchy does not exist.
	if !utils.FileExists(dirpath) {
		return nil
	}

	entries, err := ioutil.ReadDir(dirpath)
	if err != nil {
		return err
	}
	for _, entry := range entries {
		// We only grab directories.
		if entry.IsDir() {
			name := path.Join(parent, entry.Name())
			output[name] = struct{}{}

			// List subcontainers if asked to.
			if recursive {
				err := listDirectories(path.Join(dirpath, entry.Name()), name, true, output)
				if err != nil {
					return err
				}
			}
		}
	}
	return nil
}
Ejemplo n.º 6
0
// goListPkg takes one package name, and computes all the files it needs to build,
// seperating them into Go tree files and uroot files. For now we just 'go list'
// but hopefully later we can do this programatically.
func goListPkg(name string) (*GoDirs, error) {
	cmd := exec.Command("go", "list", "-json", name)
	cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
	debug("Run %v @ %v", cmd, cmd.Dir)
	j, err := cmd.CombinedOutput()
	if err != nil {
		return nil, err
	}

	var p GoDirs
	if err := json.Unmarshal([]byte(j), &p); err != nil {
		return nil, err
	}

	debug("%v, %v %v %v", p, p.GoFiles, p.SFiles, p.HFiles)
	for _, v := range append(append(p.GoFiles, p.SFiles...), p.HFiles...) {
		if p.Goroot {
			GorootFiles[path.Join(p.ImportPath, v)] = true
		} else {
			UrootFiles[path.Join(p.ImportPath, v)] = true
		}
	}

	return &p, nil
}
Ejemplo n.º 7
0
// Return the rootfs path for the id
// This will mount the dir at it's given path
func (a *Driver) Get(id, mountLabel string) (string, error) {
	ids, err := getParentIds(a.rootPath(), id)
	if err != nil {
		if !os.IsNotExist(err) {
			return "", err
		}
		ids = []string{}
	}

	// Protect the a.active from concurrent access
	a.Lock()
	defer a.Unlock()

	count := a.active[id]

	// If a dir does not have a parent ( no layers )do not try to mount
	// just return the diff path to the data
	out := path.Join(a.rootPath(), "diff", id)
	if len(ids) > 0 {
		out = path.Join(a.rootPath(), "mnt", id)

		if count == 0 {
			if err := a.mount(id, mountLabel); err != nil {
				return "", err
			}
		}
	}

	a.active[id] = count + 1

	return out, nil
}
Ejemplo n.º 8
0
func createMigration(name string) string {
	if name == "" {
		return "invalid migration name"
	}
	wd, err := os.Getwd()
	if err != nil {
		return err.Error()
	}
	err = os.MkdirAll(path.Join(wd, kDbDir, kMgrDir), 0777)
	if err != nil {
		panic(err)
	}
	ts := time.Now().Unix()
	fileName := path.Join(kDbDir, kMgrDir, fmt.Sprintf("%d_%s.go", ts, name))
	f, err := os.OpenFile(path.Join(wd, fileName), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	err = migrationTemplate.Execute(f, &Migration{
		Timestamp: ts,
		Name:      name,
	})
	if err != nil {
		panic(err)
	}
	return fmt.Sprintf("created migration '%s'", fileName)
}
Ejemplo n.º 9
0
// Inject the io.Reader at the given path. Note: do not close the reader
func (container *Container) Inject(file io.Reader, pth string) error {
	// Return error if path exists
	if _, err := os.Stat(path.Join(container.rwPath(), pth)); err == nil {
		// Since err is nil, the path could be stat'd and it exists
		return fmt.Errorf("%s exists", pth)
	} else if !os.IsNotExist(err) {
		// Expect err might be that the file doesn't exist, so
		// if it's some other error, return that.

		return err
	}

	// Make sure the directory exists
	if err := os.MkdirAll(path.Join(container.rwPath(), path.Dir(pth)), 0755); err != nil {
		return err
	}

	dest, err := os.Create(path.Join(container.rwPath(), pth))
	if err != nil {
		return err
	}
	if _, err := io.Copy(dest, file); err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 10
0
// genSource renders the given template to produce source code, which it writes
// to the given directory and file.
func genSource(dir, filename, templateSource string, args map[string]interface{}) {
	sourceCode := revel.ExecuteTemplate(
		template.Must(template.New("").Parse(templateSource)),
		args)

	// Create a fresh dir.
	tmpPath := path.Join(revel.AppPath, dir)
	err := os.RemoveAll(tmpPath)
	if err != nil {
		revel.ERROR.Println("Failed to remove dir:", err)
	}
	err = os.Mkdir(tmpPath, 0777)
	if err != nil {
		revel.ERROR.Fatalf("Failed to make tmp directory: %v", err)
	}

	// Create the file
	file, err := os.Create(path.Join(tmpPath, filename))
	defer file.Close()
	if err != nil {
		revel.ERROR.Fatalf("Failed to create file: %v", err)
	}
	_, err = file.WriteString(sourceCode)
	if err != nil {
		revel.ERROR.Fatalf("Failed to write to file: %v", err)
	}
}
Ejemplo n.º 11
0
func dictionary(file string) {

	f, _ := os.OpenFile(path.Join(".", "data", file), os.O_SYNC|os.O_APPEND|os.O_RDWR, 0755)
	defer f.Close()

	scanner := bufio.NewScanner(f)
	scanner.Split(bufio.ScanLines)

	var n []string

	for scanner.Scan() {

		n = append(n, scanner.Text())

		if len(n) == 0 {
			break
		}

	}

	w, _ := os.Create(path.Join(".", "data", file))
	defer w.Close()

	for i := 0; i < len(n); i++ {
		f.WriteString(n[i] + "\n")
	}

	line := " this is the APPENDED text"

	f.WriteString(line)

}
Ejemplo n.º 12
0
Archivo: run.go Proyecto: krieg/rkt
// overlayRender renders the image that corresponds to the given hash using the
// overlay filesystem.
// It writes the manifest in the specified directory and mounts an overlay
// filesystem from the cached tree of the image as rootfs.
func overlayRender(cfg RunConfig, img types.Hash, cdir string, dest string) error {
	if err := writeManifest(cfg.CommonConfig, img, dest); err != nil {
		return err
	}

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

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

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

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

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

	return nil
}
Ejemplo n.º 13
0
func (r Renderer) RenderPost(pc *PostContext, templates *template.Template) error {
	err := os.MkdirAll(path.Join(r.OutputPath, pc.Slug), 0755)
	if err != nil {
		log.Panicf(err.Error())
	}

	outfile, err := os.Create(path.Join(r.OutputPath, pc.Slug, "index.html"))
	if err != nil {
		log.Panicf(err.Error())
	}

	err = templates.ExecuteTemplate(outfile, "post.html", pc)
	if err != nil {
		log.Panicf(err.Error())
	}

	// copy images
	log.Printf("\"%s\": Using %d %s", pc.Slug, len(pc.Images), pluralize("image", len(pc.Images)))
	for _, image := range pc.Images {
		err = cp(image.SrcAbsPath, path.Join(r.OutputPath, pc.Slug, image.Filename))
		if err != nil {
			log.Panicf(err.Error())
		}
	}

	log.Printf("\"%s\": Done rendering", pc.Slug)
	return nil
}
Ejemplo n.º 14
0
func (r Renderer) RenderAll(site *SiteContext, posts []*Post) error {
	templates := template.Must(
		template.ParseGlob(path.Join(r.TemplatePath, "*.html")))

	// ensure the output directory exists
	err := os.MkdirAll(path.Join(r.OutputPath), 0755)
	if err != nil {
		return err
	}

	// copy assets
	cpDir(path.Join(r.TemplatePath, "assets"), path.Join(r.OutputPath, "assets"))

	// make the index page
	index, err := os.Create(path.Join(r.OutputPath, "index.html"))
	if err != nil {
		log.Panicf(err.Error())
	}
	err = templates.ExecuteTemplate(index, "index.html", &IndexContext{site, posts, "Home", ""})

	// gratuitous use of goroutines
	// use a WaitGroup to ensure all goroutines get access to STDOUT
	var wg sync.WaitGroup
	for _, post := range posts {
		wg.Add(1)
		go func(site *SiteContext, post *Post) {
			defer wg.Done()
			pc := &PostContext{site, post, "../"}
			r.RenderPost(pc, templates)
		}(site, post)
	}
	wg.Wait()

	return nil
}
Ejemplo n.º 15
0
func (pfs *ProcFS) Get(k string) {
	var uf = path.Join(procfsdir, "uptime")
	switch k {
	case PROCFS_SELF:
		var selfdir = path.Join(procfsdir, "self")
		if !exists(selfdir) {
			return
		}
		fi, _ := os.Readlink(selfdir)
		pfs.Self = fi
	case PROCFS_UPTIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[0], 64)
				pfs.Uptime = int(it)
			}
		}
	case PROCFS_IDLETIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[1], 64)
				pfs.Idletime = int(it)
			}
		}
	case PROCFS_MOUNTS:
		pfs.Mounts = getMounts(path.Join(procfsdir, "mounts"))
	}
}
Ejemplo n.º 16
0
func TestBindMounts(t *testing.T) {
	eng := NewTestEngine(t)
	r := mkDaemonFromEngine(eng, t)
	defer r.Nuke()

	tmpDir := tempDir(t)
	defer os.RemoveAll(tmpDir)
	writeFile(path.Join(tmpDir, "touch-me"), "", t)

	// Test reading from a read-only bind mount
	stdout, _ := runContainer(eng, r, []string{"-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "_", "ls", "/tmp"}, t)
	if !strings.Contains(stdout, "touch-me") {
		t.Fatal("Container failed to read from bind mount")
	}

	// test writing to bind mount
	runContainer(eng, r, []string{"-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "_", "touch", "/tmp/holla"}, t)
	readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist

	// test mounting to an illegal destination directory
	if _, err := runContainer(eng, r, []string{"-v", fmt.Sprintf("%s:.", tmpDir), "_", "ls", "."}, nil); err == nil {
		t.Fatal("Container bind mounted illegal directory")
	}

	// test mount a file
	runContainer(eng, r, []string{"-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "_", "sh", "-c", "echo -n 'yotta' > /tmp/holla"}, t)
	content := readFile(path.Join(tmpDir, "holla"), t) // Will fail if the file doesn't exist
	if content != "yotta" {
		t.Fatal("Container failed to write to bind mount file")
	}
}
Ejemplo n.º 17
0
// Inject the io.Reader at the given path. Note: do not close the reader
func (container *Container) Inject(file io.Reader, pth string) error {
	if err := container.Mount(); err != nil {
		return fmt.Errorf("inject: error mounting container %s: %s", container.ID, err)
	}
	defer container.Unmount()

	// Return error if path exists
	destPath := path.Join(container.RootfsPath(), pth)
	if _, err := os.Stat(destPath); err == nil {
		// Since err is nil, the path could be stat'd and it exists
		return fmt.Errorf("%s exists", pth)
	} else if !os.IsNotExist(err) {
		// Expect err might be that the file doesn't exist, so
		// if it's some other error, return that.

		return err
	}

	// Make sure the directory exists
	if err := os.MkdirAll(path.Join(container.RootfsPath(), path.Dir(pth)), 0755); err != nil {
		return err
	}

	dest, err := os.Create(destPath)
	if err != nil {
		return err
	}
	defer dest.Close()

	if _, err := io.Copy(dest, file); err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 18
0
func (context *Context) loadActions(action string) template.HTML {
	var actions = map[string]string{}
	var actionKeys = []string{}
	var viewPaths = context.getViewPaths()

	for j := len(viewPaths); j > 0; j-- {
		view := viewPaths[j-1]
		globalfiles, _ := filepath.Glob(path.Join(view, "actions/*.tmpl"))
		files, _ := filepath.Glob(path.Join(view, "actions", action, "*.tmpl"))

		for _, file := range append(globalfiles, files...) {
			if _, ok := actions[path.Base(file)]; !ok {
				actionKeys = append(actionKeys, path.Base(file))
			}
			base := regexp.MustCompile("^\\d+\\.").ReplaceAllString(path.Base(file), "")
			actions[base] = file
		}
	}

	sort.Strings(actionKeys)

	var result = bytes.NewBufferString("")
	for _, key := range actionKeys {
		base := regexp.MustCompile("^\\d+\\.").ReplaceAllString(key, "")
		file := actions[base]
		if tmpl, err := template.New(path.Base(file)).Funcs(context.FuncMap()).ParseFiles(file); err == nil {
			if err := tmpl.Execute(result, context); err != nil {
				panic(err)
			}
		}
	}
	return template.HTML(strings.TrimSpace(result.String()))
}
Ejemplo n.º 19
0
func main() {
	flag.Parse()
	ZellijTilings, reset = zellij.TileSkeleton(skeleton, tileSymmetry, false)
	Frame := zellij.SkeletonFrame(skeleton)
	symmetryCounts := make(map[string]int)
	for T := range ZellijTilings {
		symmetryGroup := zellij.DetectSymmetryGroup(T)
		filename := fmt.Sprintf("%v-%v-%d", skeleton, symmetryGroup, symmetryCounts[symmetryGroup]+1)
		symmetryCounts[symmetryGroup]++
		save, err := os.Create(path.Join(dir, filename+".zellij"))
		if err != nil {
			panic("file error")
		}
		enc := json.NewEncoder(save)
		enc.Encode([]*quadratic.Map{Frame, T})
		save.Close()
		image := cairo.NewSurface(path.Join(dir, "svg", filename+".svg"), 72*5, 72*5)
		image.SetSourceRGB(0., 0., 0.)
		image.SetLineWidth(.1)
		image.Translate(72*2.5, 72*2.5)
		image.Scale(4., 4.)
		T.ColourFaces(image, zellij.PlainBrush)
		image.Finish()
	}
}
Ejemplo n.º 20
0
func (context *Context) newResourcePath(value interface{}) string {
	if res, ok := value.(*Resource); ok {
		return path.Join(context.Admin.router.Prefix, res.ToParam(), "new")
	} else {
		return path.Join(context.Admin.router.Prefix, context.Resource.ToParam(), "new")
	}
}
Ejemplo n.º 21
0
func (d *Driver) Create(id, parent string) error {
	if err := d.DeviceSet.AddDevice(id, parent); err != nil {
		return err
	}

	mp := path.Join(d.home, "mnt", id)
	if err := d.mount(id, mp); err != nil {
		return err
	}

	if err := osMkdirAll(path.Join(mp, "rootfs"), 0755); err != nil && !osIsExist(err) {
		return 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(path.Join(mp, "id"), []byte(id), 0600); err != nil {
		return err
	}

	// We float this reference so that the next Get call can
	// steal it, so we don't have to unmount
	if err := d.DeviceSet.UnmountDevice(id, UnmountFloat); err != nil {
		return err
	}

	return nil
}
Ejemplo n.º 22
0
func (tmpl *Template) parsePartial(name string) (*Template, error) {
	filenames := []string{
		path.Join(tmpl.dir, name),
		path.Join(tmpl.dir, name+".mustache"),
		path.Join(tmpl.dir, name+".stache"),
		name,
		name + ".mustache",
		name + ".stache",
	}
	var filename string
	for _, name := range filenames {
		f, err := os.Open(name)
		if err == nil {
			filename = name
			f.Close()
			break
		}
	}
	if filename == "" {
		return nil, errors.New(fmt.Sprintf("Could not find partial %q", name))
	}

	partial, err := ParseFile(filename)

	if err != nil {
		return nil, err
	}

	return partial, nil
}
Ejemplo n.º 23
0
func (imp Importer) ImportDir(dirType string, dir string) error {

	dir = path.Join(dir, dirType)

	// check if the directory exists
	if _, err := os.Stat(dir); err != nil {
		// nothing to import
		fmt.Println("No directory", dir)
		return nil
	}

	fmt.Println("Import directory ", dir)
	errors := []string{}

	files, err := filepath.Glob(path.Join(dir, "*.json"))
	if err != nil {
		return fmt.Errorf("fail to read directory %s. Error: %s", dir, err)
	}
	if len(files) == 0 {
		return fmt.Errorf("empty directory %s", dir)
	}
	for _, file := range files {

		err = imp.ImportFile(dirType, file)
		if err != nil {
			fmt.Println("ERROR: ", err)
			errors = append(errors, fmt.Sprintf("error loading %s: %s\n", file, err))
		}
	}
	if len(errors) > 0 {
		return fmt.Errorf("fail to load directory %s: %s", dir, strings.Join(errors, ", "))
	}
	return nil

}
Ejemplo n.º 24
0
// Save stores the session back to the same location it was loaded from
func (s *Session) Save() error {
	sessPath := path.Join(s.SessionDir, SESSION_FILE)

	if _, err := os.Stat(sessPath); err == nil {
		// If the session file already exists then back it up first
		backupPath := path.Join(s.SessionDir, SESSION_FILE_BCK)

		if err := fs.CopyFileContents(sessPath, backupPath); err != nil {
			return err
		}
	}

	fd, err := os.Create(sessPath)
	if err != nil {
		return err
	}
	defer fd.Close()

	if jsonData, err := json.Marshal(*s); err != nil {
		return err
	} else {
		if _, err := fd.Write(jsonData); err != nil {
			return err
		}
	}

	return nil
}
// Suffix appends segments to the end of the path. These items will be placed after the prefix and optional
// Namespace, Resource, or Name sections.
func (r *Request) Suffix(segments ...string) *Request {
	if r.err != nil {
		return r
	}
	r.subpath = path.Join(r.subpath, path.Join(segments...))
	return r
}
Ejemplo n.º 26
0
func NewLolReplayLauncher(basepath string) (LolReplayLauncher, error) {
	if len(basepath) == 0 {
		basepath = path.Join("/Applications", "League Of Legends.app")
	}

	info, err := os.Stat(basepath)
	if err != nil {
		return nil, fmt.Errorf("Could not check for League Of Legend application in %s:  %s", basepath, err)
	}

	if info.IsDir() == false {
		return nil, fmt.Errorf("%s is not a directory/App Bundle, please check your LoL installation", basepath)
	}

	res := &darwinLauncher{}
	res.launcherPath, err = res.lookForExecutableReleases(path.Join(basepath, launcherReleasesBasepath), launcherPath)
	if err != nil {
		return nil, fmt.Errorf("Could not find LoL launcher: %s", err)
	}

	res.clientPath, err = res.lookForExecutableReleases(path.Join(basepath, clientReleasesBasepath), clientPath)
	if err != nil {
		return nil, fmt.Errorf("Could not find LoL Client: %s", err)
	}

	return res, nil
}
Ejemplo n.º 27
0
// Get returns the rootfs path for the id.
// This will mount the dir at it's given path
func (a *Driver) Get(id, mountLabel string) (string, error) {
	ids, err := getParentIds(a.rootPath(), id)
	if err != nil {
		if !os.IsNotExist(err) {
			return "", err
		}
		ids = []string{}
	}

	// Protect the a.active from concurrent access
	a.Lock()
	defer a.Unlock()

	m := a.active[id]
	if m == nil {
		m = &data{}
		a.active[id] = m
	}

	// If a dir does not have a parent ( no layers )do not try to mount
	// just return the diff path to the data
	m.path = path.Join(a.rootPath(), "diff", id)
	if len(ids) > 0 {
		m.path = path.Join(a.rootPath(), "mnt", id)
		if m.referenceCount == 0 {
			if err := a.mount(id, m, mountLabel); err != nil {
				return "", err
			}
		}
	}
	m.referenceCount++
	return m.path, nil
}
Ejemplo n.º 28
0
func (l *Layer0) Remove(id string) error {
	if !l.isLayer0(id) {
		return l.Driver.Remove(l.realID(id))
	}
	l.Lock()
	defer l.Unlock()
	var err error
	v, ok := l.volumes[id]

	if ok {
		atomic.AddInt32(&v.ref, -1)
		if v.ref == 0 {
			// Save the upper dir and blow away the rest.
			upperDir := path.Join(path.Join(l.home, l.realID(id)), "upper")
			err := os.Rename(upperDir, path.Join(v.path, "upper"))
			if err != nil {
				log.Warnf("Failed in rename(%v): %v", id, err)
			}
			l.Driver.Remove(l.realID(id))
			err = l.volDriver.Unmount(v.volumeID, v.path)
			if l.volDriver.Type()&api.Block != 0 {
				_ = l.volDriver.Detach(v.volumeID)
			}
			err = os.RemoveAll(v.path)
			delete(l.volumes, v.id)
		}
	} else {
		log.Warnf("Failed to find layer0 vol for id %v", id)
	}
	return err
}
Ejemplo n.º 29
0
func TestMountMoreThan42Layers(t *testing.T) {
	d := newDriver(t)
	defer os.RemoveAll(tmp)
	defer d.Cleanup()
	var last string
	var expected int

	for i := 1; i < 127; i++ {
		expected++
		var (
			parent  = fmt.Sprintf("%d", i-1)
			current = fmt.Sprintf("%d", i)
		)

		if parent == "0" {
			parent = ""
		} else {
			parent = hash(parent)
		}
		current = hash(current)

		if err := d.Create(current, parent); err != nil {
			t.Logf("Current layer %d", i)
			t.Fatal(err)
		}
		point, err := d.Get(current)
		if err != nil {
			t.Logf("Current layer %d", i)
			t.Fatal(err)
		}
		f, err := os.Create(path.Join(point, current))
		if err != nil {
			t.Logf("Current layer %d", i)
			t.Fatal(err)
		}
		f.Close()

		if i%10 == 0 {
			if err := os.Remove(path.Join(point, parent)); err != nil {
				t.Logf("Current layer %d", i)
				t.Fatal(err)
			}
			expected--
		}
		last = current
	}

	// Perform the actual mount for the top most image
	point, err := d.Get(last)
	if err != nil {
		t.Fatal(err)
	}
	files, err := ioutil.ReadDir(point)
	if err != nil {
		t.Fatal(err)
	}
	if len(files) != expected {
		t.Fatalf("Expected %d got %d", expected, len(files))
	}
}
Ejemplo n.º 30
0
// 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
}