Example #1
0
func (group *TailGroup) activate(match string) {
	tail, ok := group.Tails[match]
	if !ok {
		fi, _ := os.Stat(match)
		for _, tail = range group.Tails {
			tfi, _ := tail.Stat()
			if os.SameFile(fi, tfi) {
				tail.Close()
				delete(group.Tails, tail.Path)
				off := tail.Offset()
				tail.SetOffset(0)
				tail.WriteOffset()
				base := path.Base(match)
				offset := path.Join(group.OffsetDir, base+".ptr")
				tail = NewTail(group.NewParser(base), group.maxBackfill, match, offset, off)
				group.Tails[match] = tail
				return
			}
		}
		base := path.Base(match)
		offset := path.Join(group.OffsetDir, base+".ptr")
		tail = NewTail(group.NewParser(base), group.maxBackfill, match, offset, 0)
		group.Tails[match] = tail

	}
}
Example #2
0
func (fs *FileSystemImporter) importSingle(scan *ScanResult, opts *ImportOptions) error {
	//process is now:
	// find mime type.
	// inspect, which gives us the item.
	// look up existing, merge tags
	// overwrite added if needed
	// if created.isZero() then use file mtime
	// set in store
	// index
	// see if exportable -> export
	prefixError := func(e error) error {
		return fmt.Errorf("error importing `%s`: %s", path.Base(scan.Path), e)
	}

	rd, err := os.Open(scan.Path)
	if err != nil {
		return prefixError(err)
	}
	defer rd.Close()
	item, err := Inspect(NewInspectableFile(rd, scan.Mime, path.Base(scan.Path)))
	if err != nil {
		return prefixError(err)
	}

	//check for existing
	if existing, err := fs.service.store.Meta(item.Hash); err == nil {
		//merge!
		mergeItemData(item, existing)
		//we just need to update!
		err = fs.service.store.Update(item)
		if err != nil {
			return prefixError(err)
		}
	} else {
		//new item
		rd.Seek(0, 0) //rewind
		err = fs.service.store.Set(item, rd)
		if err != nil {
			return prefixError(err)
		}
		//generate thumbnail now! saves load time later...
		getItemThumbnail(fs.service, item, THUMBNAIL_LARGE)
	}
	//(re)index
	if err = fs.service.indexer.Index(item); err != nil {
		return prefixError(err)
	}
	// if err = fs.service.exporter.ExportItem(item, store); err != nil {
	//  errs <- err
	//  //we don't need to continue here. We rebuild the index occasionally,
	//  //so we'll pick it up.
	// }
	if opts.DeleteAfterImport {
		if err = os.Remove(scan.Path); err != nil {
			return prefixError(err)
		}
	}
	log.Printf("Import success: %s (%s)\n", item.Name, item.Type)
	return nil
}
Example #3
0
func (d *discovery) waitNodes(nodes []*client.Node, size int, index uint64) ([]*client.Node, error) {
	if len(nodes) > size {
		nodes = nodes[:size]
	}
	// watch from the next index
	w := d.c.Watcher(d.cluster, &client.WatcherOptions{AfterIndex: index, Recursive: true})
	all := make([]*client.Node, len(nodes))
	copy(all, nodes)
	for _, n := range all {
		if path.Base(n.Key) == path.Base(d.selfKey()) {
			plog.Noticef("found self %s in the cluster", path.Base(d.selfKey()))
		} else {
			plog.Noticef("found peer %s in the cluster", path.Base(n.Key))
		}
	}

	// wait for others
	for len(all) < size {
		plog.Noticef("found %d peer(s), waiting for %d more", len(all), size-len(all))
		resp, err := w.Next(context.Background())
		if err != nil {
			if ce, ok := err.(*client.ClusterError); ok {
				plog.Error(ce.Detail())
				return d.waitNodesRetry()
			}
			return nil, err
		}
		plog.Noticef("found peer %s in the cluster", path.Base(resp.Node.Key))
		all = append(all, resp.Node)
	}
	plog.Noticef("found %d needed peer(s)", len(all))
	return all, nil
}
Example #4
0
File: dir.go Project: ncw/rclone
// ReadDirAll reads the contents of the directory
func (d *Dir) ReadDirAll(ctx context.Context) (dirents []fuse.Dirent, err error) {
	fs.Debug(d.path, "Dir.ReadDirAll")
	err = d.readDir()
	if err != nil {
		fs.Debug(d.path, "Dir.ReadDirAll error: %v", err)
		return nil, err
	}
	d.mu.RLock()
	defer d.mu.RUnlock()
	for _, item := range d.items {
		var dirent fuse.Dirent
		switch x := item.o.(type) {
		case fs.Object:
			dirent = fuse.Dirent{
				// Inode FIXME ???
				Type: fuse.DT_File,
				Name: path.Base(x.Remote()),
			}
		case *fs.Dir:
			dirent = fuse.Dirent{
				// Inode FIXME ???
				Type: fuse.DT_Dir,
				Name: path.Base(x.Remote()),
			}
		default:
			err = errors.Errorf("unknown type %T", item)
			fs.ErrorLog(d.path, "Dir.ReadDirAll error: %v", err)
			return nil, err
		}
		dirents = append(dirents, dirent)
	}
	fs.Debug(d.path, "Dir.ReadDirAll OK with %d entries", len(dirents))
	return dirents, nil
}
Example #5
0
// load a PCM from <<pathTo>>, which if not explicitly pointing into a folder with the <<Sample Rate>>, numerically as its name, will look into a sub-folder with the sampleRate indicated by the PCM parameter, and if that's zero will load any samplerate available. Also adds extension ".pcm".
func LoadPCM(pathTo string, p *PCM) (err error) {
	sampleRate, err := strconv.ParseUint(path.Base(path.Dir(pathTo)), 10, 32)
	if err != nil {
		if p.samplePeriod == 0 {
			var files []os.FileInfo
			files, err = ioutil.ReadDir(path.Dir(pathTo))
			if err != nil {
				return
			}
			for _, file := range files {
				if file.IsDir() && file.Size() > 0 {
					sampleRate, err = strconv.ParseUint(file.Name(), 10, 32)
					if err == nil {
						pathTo = path.Join(path.Dir(pathTo), file.Name(), path.Base(pathTo))
						break
					}
				}
			}
		} else {
			pathTo = path.Join(path.Dir(pathTo), strconv.FormatInt(int64(unitX/x(p.samplePeriod)), 10), path.Base(pathTo))
		}
	} else {
		p.samplePeriod = X(1 / float32(sampleRate))
	}
	p.Data, err = ioutil.ReadFile(pathTo + ".pcm")
	return
}
Example #6
0
func fileCp(srcPath, dstPath string) error {
	dstIsDir := dstPath[len(dstPath)-1] == '/'
	srcPath = fixZkPath(srcPath)
	dstPath = fixZkPath(dstPath)

	if !isZkFile(srcPath) && !isZkFile(dstPath) {
		return fmt.Errorf("cp: neither src nor dst is a /zk file: exitting")
	}

	data, err := getPathData(srcPath)
	if err != nil {
		return fmt.Errorf("cp: cannot read %v: %v", srcPath, err)
	}

	// If we are copying to a local directory - say '.', make the filename
	// the same as the source.
	if !isZkFile(dstPath) {
		fileInfo, err := os.Stat(dstPath)
		if err != nil {
			if err.(*os.PathError).Err != syscall.ENOENT {
				return fmt.Errorf("cp: cannot stat %v: %v", dstPath, err)
			}
		} else if fileInfo.IsDir() {
			dstPath = path.Join(dstPath, path.Base(srcPath))
		}
	} else if dstIsDir {
		// If we are copying into zk, interpret trailing slash as treating the
		// dstPath as a directory.
		dstPath = path.Join(dstPath, path.Base(srcPath))
	}
	if err := setPathData(dstPath, data); err != nil {
		return fmt.Errorf("cp: cannot write %v: %v", dstPath, err)
	}
	return nil
}
Example #7
0
// syncFile syncs the given file
func syncFile(file string) {
	// Read file
	buf, err := ioutil.ReadFile(file)
	if err != nil {
		cli.LogErr.Fatal(err)
	}

	syncIt := true

	// Pull docker images
	if dockerPullFlag {
		cli.LogOut.Printf("syncing %s\n", path.Base(file))
		if err := findAndPullDockerImages(string(buf)); err != nil {
			cli.LogErr.Println("failed to sync " + path.Base(file) + " due to " + err.Error())
			syncIt = false
		}
	}

	// Add the job
	if syncIt {
		if err := nomadClient.AddJob(string(buf)); err != nil {
			cli.LogErr.Fatal(err)
		} else {
			cli.LogOut.Printf("%s is synced\n", path.Base(file))
		}
	}
}
Example #8
0
func buildName(dstPath string) (relpath string, author string, err error) {
	fname := path.Base(dstPath)
	curPath := path.Dir(dstPath)
	parts := []string{}

	for !fileExists(path.Join(curPath, configFile)) {
		parts = append([]string{path.Base(curPath)}, parts...)
		newCurPath := path.Dir(curPath)

		if newCurPath == curPath {
			fail("Couldn't find %s. Did you create it?", configFile)
		}

		curPath = newCurPath
	}

	// TODO: This is ugly. Fix by making a real config file.
	bs, err := ioutil.ReadFile(path.Join(curPath, configFile))
	if err != nil {
		return "", "", err
	}

	parts = append([]string{path.Base(curPath)}, parts...)
	parts = append(parts, fname)
	return path.Join(parts...), string(bs), nil
}
Example #9
0
func main() {
	flag.Parse()

	if flags.Help {
		flag.Usage()
		os.Exit(2)
	}

	if flags.Version {
		fmt.Printf("%s main: %s, data: %s\n",
			path.Base(os.Args[0]), cbgt.VERSION, cbgt.VERSION)
		os.Exit(0)
	}

	cmd.MainCommon(cbgt.VERSION, flagAliases)

	cfg, err := cmd.MainCfgClient(path.Base(os.Args[0]), flags.CfgConnect)
	if err != nil {
		log.Fatalf("%v", err)
		return
	}

	if flags.IndexTypes != "" {
		cmd.RegisterIndexTypes(strings.Split(flags.IndexTypes, ","))
	}

	nodesToRemove := []string(nil)
	if len(flags.RemoveNodes) > 0 {
		nodesToRemove = strings.Split(flags.RemoveNodes, ",")
	}

	var steps map[string]bool
	if flags.Steps != "" {
		steps = cbgt.StringsToMap(strings.Split(flags.Steps, ","))
	}

	// ------------------------------------------------

	if steps == nil || steps["rebalance"] {
		log.Printf("main: step rebalance")

		err := runRebalance(cfg, flags.Server, nodesToRemove,
			flags.FavorMinNodes, flags.DryRun, flags.Verbose)
		if err != nil {
			log.Fatalf("%v", err)
			return
		}
	}

	// ------------------------------------------------

	err = cmd.PlannerSteps(steps, cfg, cbgt.VERSION,
		flags.Server, nodesToRemove, flags.DryRun)
	if err != nil {
		log.Fatalf("%v", err)
		return
	}

	log.Printf("main: done")
}
func handleTestRequest(rw http.ResponseWriter, req *http.Request) {
	file := path.Base(req.URL.Path) + ".html"
	if strings.HasPrefix(req.URL.Path, "/importers/") {
		file = path.Base(req.URL.Path) + "-importers.json"
	}
	http.ServeFile(rw, req, path.Join("testdata", file))
}
Example #11
0
func TestConfigsUsed(t *testing.T) {
	defer restoreDflts(dfltFiles, dfltDirs)
	tmpdir, err := ioutil.TempDir("", "tmp1")
	assert.NoError(t, err)
	defer os.Remove(tmpdir)

	cntFile, err := ioutil.TempFile(tmpdir, "nf_conntrack_count")
	maxFile, err := ioutil.TempFile(tmpdir, "nf_conntrack_max")
	assert.NoError(t, err)

	dfltDirs = []string{tmpdir}
	cntFname := path.Base(cntFile.Name())
	maxFname := path.Base(maxFile.Name())
	dfltFiles = []string{cntFname, maxFname}

	count := 1234321
	max := 9999999
	ioutil.WriteFile(cntFile.Name(), []byte(strconv.Itoa(count)), 0660)
	ioutil.WriteFile(maxFile.Name(), []byte(strconv.Itoa(max)), 0660)
	c := &Conntrack{}
	acc := &testutil.Accumulator{}

	c.Gather(acc)

	fix := func(s string) string {
		return strings.Replace(s, "nf_", "ip_", 1)
	}

	acc.AssertContainsFields(t, inputName,
		map[string]interface{}{
			fix(cntFname): float64(count),
			fix(maxFname): float64(max),
		})
}
Example #12
0
func handleUnmarshalError(f string, content []byte, err error) error {
	switch e := err.(type) {
	case *json.SyntaxError:
		line, ctx, off := getContext(content, e.Offset)

		if off <= 1 {
			return fmt.Errorf("Error: No policy")
		}

		preoff := off - 1
		pre := make([]byte, preoff)
		copy(pre, ctx[:preoff])
		for i := 0; i < preoff && i < len(pre); i++ {
			if pre[i] != '\t' {
				pre[i] = ' '
			}
		}

		return fmt.Errorf("Error: %s:%d: Syntax error at offset %d:\n%s\n%s^",
			path.Base(f), line, off, ctx, pre)
	case *json.UnmarshalTypeError:
		line, ctx, off := getContext(content, e.Offset)
		return fmt.Errorf("Error: %s:%d: Unable to assign value '%s' to type '%v':\n%s\n%*c",
			path.Base(f), line, e.Value, e.Type, ctx, off, '^')
	default:
		return fmt.Errorf("Error: %s: Unknown error:%s", path.Base(f), err)
	}
}
Example #13
0
func Prettify(logMessage *events.LogMessage) string {
	entry := chug.ChugLogMessage(logMessage)

	var sourceType, sourceTypeColorized, sourceInstance, sourceInstanceColorized string

	sourceType = path.Base(entry.LogMessage.GetSourceType())
	sourceInstance = entry.LogMessage.GetSourceInstance()

	// TODO: Or, do we use GetSourceType() for raw and Json source for pretty?
	color, ok := colorLookup[path.Base(strings.Split(sourceType, ":")[0])]
	if ok {
		sourceTypeColorized = colors.Colorize(color, sourceType)
		sourceInstanceColorized = colors.Colorize(color, sourceInstance)
	} else {
		sourceTypeColorized = sourceType
		sourceInstanceColorized = sourceInstance
	}

	prefix := fmt.Sprintf("[%s|%s]", sourceTypeColorized, sourceInstanceColorized)

	colorWidth := len(sourceTypeColorized+sourceInstanceColorized) - len(sourceType+sourceInstance)

	components := append([]string(nil), fmt.Sprintf("%-"+strconv.Itoa(34+colorWidth)+"s", prefix))

	var whichFunc func(chug.Entry) []string
	if entry.IsLager {
		whichFunc = prettyPrintLog
	} else {
		whichFunc = prettyPrintRaw
	}

	components = append(components, whichFunc(entry)...)
	return strings.Join(components, " ")
}
Example #14
0
func TestTransactionCommands(t *testing.T) {
	// add two blobs, and then delete one
	blob1 := uploadstring(t, "POST", "/upload", "hello world")
	t.Log("blob1 =", blob1)
	blob2 := uploadstring(t, "POST", "/upload", "delete me")
	t.Log("blob2 =", blob2)

	itemid := "zxcvbnm" + randomid()
	checkStatus(t, "GET", "/item/"+itemid, 404)
	txpath := sendtransaction(t, "/item/"+itemid+"/transaction",
		[][]string{{"add", path.Base(blob1)},
			{"add", path.Base(blob2)}}, 202)
	t.Log("got tx path", txpath)
	// tx is processed async from the commit above.
	waitTransaction(t, txpath)
	checkStatus(t, "GET", "/item/"+itemid, 200)
	text := getbody(t, "GET", "/blob/"+itemid+"/2", 200)
	if text != "delete me" {
		t.Errorf("Received %#v, expected %#v", text, "delete me")
	}
	// now delete blob 2
	txpath = sendtransaction(t, "/item/"+itemid+"/transaction",
		[][]string{{"delete", "2"}}, 202)
	t.Log("got tx path", txpath)
	waitTransaction(t, txpath)
	text = getbody(t, "GET", "/blob/"+itemid+"/1", 200)
	if text != "hello world" {
		t.Errorf("Received %#v, expected %#v", text, "hello world")
	}
	text = getbody(t, "GET", "/blob/"+itemid+"/2", 404)
	if text != "Blob has been deleted\n" {
		t.Errorf("Received %#v, expected %#v", text, "Blob has been deleted\n")
	}
}
Example #15
0
func uploadFiles(client *github.Client, owner string, repo string, id int, files []string) error {
	assets, _, err := client.Repositories.ListReleaseAssets(owner, repo, id, &github.ListOptions{})
	if err != nil {
		return fmt.Errorf("Failed to fetch existing assets: %s", err)
	}

	for _, file := range files {
		handle, err := os.Open(file)
		if err != nil {
			return fmt.Errorf("Failed to read %s artifact: %s", file, err)
		}

		for _, asset := range assets {
			if *asset.Name == path.Base(file) {
				if _, err := client.Repositories.DeleteReleaseAsset(owner, repo, *asset.ID); err != nil {
					return fmt.Errorf("Failed to delete %s artifact: %s", file, err)
				}
				fmt.Printf("Successfully deleted old %s artifact\n", *asset.Name)
			}
		}

		uo := &github.UploadOptions{Name: path.Base(file)}
		if _, _, err = client.Repositories.UploadReleaseAsset(owner, repo, id, uo, handle); err != nil {
			return fmt.Errorf("Failed to upload %s artifact: %s", file, err)
		}

		fmt.Printf("Successfully uploaded %s artifact\n", file)
	}

	return nil
}
Example #16
0
// Some logic to guess the application name
func guessApplicationName(c util.Settings, e *util.Environment) (string, error) {
	applicationName, _ := c.String("application-name")
	if applicationName != "" {
		return applicationName, nil
	}

	// Otherwise, check our build target, it can be a url...
	target, _ := c.String("target")
	projectURL := ""
	if strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://") {
		projectURL = target
		base := path.Base(projectURL)
		// Special handling for github tarballs
		if base == "tarball" {
			base = path.Base(path.Dir(projectURL))
		}
		ext := path.Ext(base)
		base = base[:len(ext)]
		return base, nil
	}

	// ... or a file path
	if target == "" {
		target = "."
	}
	stat, err := os.Stat(target)
	if err != nil || !stat.IsDir() {
		return "", fmt.Errorf("target '%s' is not a directory", target)
	}
	abspath, err := filepath.Abs(target)
	if err != nil {
		return "", err
	}
	return filepath.Base(abspath), nil
}
Example #17
0
// NewParser creates a new parser. It uses os.Args[0] as the application
// name and then calls Parser.NewNamedParser (see Parser.NewNamedParser for
// more details). The provided data is a pointer to a struct representing the
// default option group (named "Application Options"), or nil if the default
// group should not be added. The options parameter specifies a set of options
// for the parser.
func NewParser(data interface{}, options Options) *Parser {
	if data == nil {
		return NewNamedParser(path.Base(os.Args[0]), options)
	}

	return NewNamedParser(path.Base(os.Args[0]), options, NewGroup("Application Options", data))
}
Example #18
0
// MWErrorPanic wraps MWError and recovers from panic.
func (sm *ServeMux) MWErrorPanic(handler HandlerFunc) http.HandlerFunc {
	return sm.MWError(func(w http.ResponseWriter, req *http.Request) (err error) {
		defer func() {
			if e1 := recover(); e1 != nil {
				var name string
				skip := 0
			begin:
				pc, file, line, ok := runtime.Caller(3 + skip)
				if ok {
					name = runtime.FuncForPC(pc).Name()
					name = path.Base(name)
					file = path.Base(file)
					// If there is a runtime panic (nil dereference or other) we endup with a runtime callstack. Skip until out of it.
					if len(name) > 7 && name[:7] == "runtime" {
						skip++
						goto begin
					}
				}
				err = sm.HandlePanic(err, e1)
				if e2, ok := err.(*Error); ok {
					e2.error = fmt.Errorf("[%s %s:%d] %s", name, file, line, e2.error)
				} else {
					err = fmt.Errorf("[%s %s:%d] %s", name, file, line, err)
				}
			}
		}()
		return handler(w, req)
	})
}
Example #19
0
func (gce *GCECloud) ListRoutes(clusterName string) ([]*cloudprovider.Route, error) {
	listCall := gce.service.Routes.List(gce.projectID)

	prefix := truncateClusterName(clusterName)
	listCall = listCall.Filter("name eq " + prefix + "-.*")

	res, err := listCall.Do()
	if err != nil {
		return nil, err
	}
	var routes []*cloudprovider.Route
	for _, r := range res.Items {
		if path.Base(r.Network) != gce.networkName {
			continue
		}
		// Not managed if route description != "k8s-node-route"
		if r.Description != k8sNodeRouteTag {
			continue
		}
		// Not managed if route name doesn't start with <clusterName>
		if !strings.HasPrefix(r.Name, prefix) {
			continue
		}

		target := path.Base(r.NextHopInstance)
		routes = append(routes, &cloudprovider.Route{r.Name, target, r.DestRange})
	}
	return routes, nil
}
// NewTemplateFromFileNames creates and returns a new template whose content
// and imported files are read from the supplied file names.
func NewTemplateFromFileNames(
	templateFileName string,
	importFileNames []string,
) (*Template, error) {
	name := path.Base(templateFileName)
	content, err := ioutil.ReadFile(templateFileName)
	if err != nil {
		return nil, fmt.Errorf("cannot read template file (%s): %s", err, templateFileName)
	}

	imports := []*ImportFile{}
	for _, importFileName := range importFileNames {
		importFileData, err := ioutil.ReadFile(importFileName)
		if err != nil {
			return nil, fmt.Errorf("cannot read import file (%s): %s", err, importFileName)
		}

		imports = append(imports,
			&ImportFile{
				Name:    path.Base(importFileName),
				Content: string(importFileData),
			})
	}

	return &Template{
		Name:    name,
		Content: string(content),
		Imports: imports,
	}, nil
}
Example #21
0
func (d *discovery) waitNodes(nodes client.Nodes, size int, index uint64) (client.Nodes, error) {
	if len(nodes) > size {
		nodes = nodes[:size]
	}
	// watch from the next index
	w := d.c.RecursiveWatch(d.cluster, index+1)
	all := make(client.Nodes, len(nodes))
	copy(all, nodes)
	for _, n := range all {
		if path.Base(n.Key) == path.Base(d.selfKey()) {
			log.Printf("discovery: found self %s in the cluster", path.Base(d.selfKey()))
		} else {
			log.Printf("discovery: found peer %s in the cluster", path.Base(n.Key))
		}
	}

	// wait for others
	for len(all) < size {
		log.Printf("discovery: found %d peer(s), waiting for %d more", len(all), size-len(all))
		resp, err := w.Next(context.Background())
		if err != nil {
			if err == client.ErrTimeout {
				return d.waitNodesRetry()
			}
			return nil, err
		}
		log.Printf("discovery: found peer %s in the cluster", path.Base(resp.Node.Key))
		all = append(all, resp.Node)
	}
	log.Printf("discovery: found %d needed peer(s)", len(all))
	return all, nil
}
Example #22
0
func getListDetail(m string, s []byte) []string {
	r := bytes.NewReader(s)
	doc, err := goquery.NewDocumentFromReader(r)
	checkError(err)

	arr := []string{}

	dir := "./detail/" + m
	err0 := os.MkdirAll(dir, 0777)
	checkError(err0)

	doc.Find("div.cont dl").Each(func(i int, s *goquery.Selection) {
		title := s.Find("dt a").Text()
		link, _ := s.Find("dt a").Attr("href")

		url := "http://www.safe10000.com" + link

		file := dir + "/" + path.Base(url)
		//desc := s.Find("dd").Text()
		arr = append(arr, url)
		c := getContent(url, file)

		fmt.Printf("Review %d: %s - %s - %s\n", i, url, title, file)
		parseDetailHtml(m, c, path.Base(url))
	})
	return arr
}
Example #23
0
func loadEnvironment(node *etcd.Node) (Environment, error) {
	env := Environment{
		Name:   path.Base(node.Key),
		Branch: "master",
	}
	for _, n := range node.Nodes {
		switch path.Base(n.Key) {
		case "branch":
			env.Branch = n.Value
		case "deploy":
			env.Deploy = n.Value
		case "repo_path":
			env.RepoPath = n.Value
		case "locked":
			locked, err := strconv.ParseBool(n.Value)
			if err != nil {
				glog.Errorf("Failed to parse 'locked' field %q. Assuming unlocked: %v", n.Value, err)
				continue
			}
			env.IsLocked = locked
		case "comment":
			env.Comment = n.Value
		case "hosts":
			if err := loadHosts(n, &env); err != nil {
				return Environment{}, err
			}
		}
	}
	return env, nil
}
Example #24
0
func (b *BuiltPkg) String() string {
	if b.Signature != "" {
		return fmt.Sprintf("%s (%s)", path.Base(b.Package), path.Base(b.Signature))
	}

	return path.Base(b.Package)
}
Example #25
0
func (s *environSuite) TestDestroyController(c *gc.C) {
	groups := []resources.ResourceGroup{{
		Name: to.StringPtr("group1"),
	}, {
		Name: to.StringPtr("group2"),
	}}
	result := resources.ResourceGroupListResult{Value: &groups}

	env := s.openEnviron(c)
	s.sender = azuretesting.Senders{
		s.makeSender(".*/resourcegroups", result),        // GET
		s.makeSender(".*/resourcegroups/group[12]", nil), // DELETE
		s.makeSender(".*/resourcegroups/group[12]", nil), // DELETE
	}
	err := env.DestroyController(s.controllerUUID)
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(s.requests, gc.HasLen, 3)
	c.Assert(s.requests[0].Method, gc.Equals, "GET")
	c.Assert(s.requests[0].URL.Query().Get("$filter"), gc.Equals, fmt.Sprintf(
		"tagname eq 'juju-controller-uuid' and tagvalue eq '%s'",
		testing.ControllerTag.Id(),
	))
	c.Assert(s.requests[1].Method, gc.Equals, "DELETE")
	c.Assert(s.requests[2].Method, gc.Equals, "DELETE")

	// Groups are deleted concurrently, so there's no known order.
	groupsDeleted := []string{
		path.Base(s.requests[1].URL.Path),
		path.Base(s.requests[2].URL.Path),
	}
	c.Assert(groupsDeleted, jc.SameContents, []string{"group1", "group2"})
}
Example #26
0
func (h *H) Generate(w http.ResponseWriter, req *http.Request) {
	opts := &generateReq{}
	if errs := binding.Bind(req, opts); errs.Handle(w) {
		return
	}
	vopts := []string{}
	for _, o := range opts.Options {
		vopts = append(vopts, fmt.Sprintf("%s=%s", o.Key, o.Value))
	}
	var paths string
	err := h.C.Call("generate", vopts, &paths)
	if err != nil {
		h.JSON400(w, errors.New("could not parse the response from veil, likely no options or an invalid payload"))
		return
	}
	if paths == "" {
		h.JSON400(w, errors.New("no payload was generated"))
		return
	}
	fullDir := path.Dir(paths)
	rootDir := path.Base(fullDir)
	f := path.Base(paths)
	httpath := path.Join(rootDir, f)
	h.JSON(w, map[string]string{"result": httpath})
}
Example #27
0
func (c *Context) lookupProjectName() (string, error) {
	if c.ProjectName != "" {
		return c.ProjectName, nil
	}

	if envProject := os.Getenv("COMPOSE_PROJECT_NAME"); envProject != "" {
		return envProject, nil
	}

	file := "."
	if len(c.ComposeFiles) > 0 {
		file = c.ComposeFiles[0]
	}

	f, err := filepath.Abs(file)
	if err != nil {
		logrus.Errorf("Failed to get absolute directory for: %s", file)
		return "", err
	}

	f = toUnixPath(f)

	parent := path.Base(path.Dir(f))
	if parent != "" && parent != "." {
		return parent, nil
	} else if wd, err := os.Getwd(); err != nil {
		return "", err
	} else {
		return path.Base(toUnixPath(wd)), nil
	}
}
Example #28
0
func TestCut(t *testing.T) {
	p, err := ioutil.TempDir(os.TempDir(), "waltest")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(p)

	w, err := Create(p)
	if err != nil {
		t.Fatal(err)
	}
	defer w.Close()

	if err := w.Cut(0); err != nil {
		t.Fatal(err)
	}
	wname := fmt.Sprintf("%016x-%016x.wal", 1, 1)
	if g := path.Base(w.f.Name()); g != wname {
		t.Errorf("name = %s, want %s", g, wname)
	}

	e := &raftpb.Entry{Index: 1, Term: 1, Data: []byte{1}}
	if err := w.SaveEntry(e); err != nil {
		t.Fatal(err)
	}
	if err := w.Cut(1); err != nil {
		t.Fatal(err)
	}
	wname = fmt.Sprintf("%016x-%016x.wal", 2, 2)
	if g := path.Base(w.f.Name()); g != wname {
		t.Errorf("name = %s, want %s", g, wname)
	}
}
Example #29
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()))
}
Example #30
0
func (m *Model) RLock() {
	_, file, line, _ := runtime.Caller(1)
	log.Printf("%s:%d: RLock()...", path.Base(file), line)
	blockTime := time.Now()
	m.RWMutex.RLock()
	log.Printf("%s:%d: ...RLock() [%.04f ms]", path.Base(file), line, time.Since(blockTime).Seconds()*1000)
}