Golang Fields示例

说明

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

编程语言: Golang

命名空间/包名称: strings

示例#1
文件: combine.go 项目: roundbrackets/quiz

// Reads a log file.
func (c *combiner) read(fileName string) error {
	fh, err := os.Open(fileName)
	if err != nil {
		return err
	}
	defer fh.Close()

	scanner := bufio.NewScanner(fh)
	for j := 0; scanner.Scan(); j++ {
		line := scanner.Text()
		if j == 0 {
			fields := strings.Fields(string(line))
			if len(c.headers) == 0 {
				c.ts = fields[0]
				c.headers = fields[1:]
			} else if len(c.headers) > len(fields[1:]) {
				c.headers = fields[1:]
			}
		} else if j > 1 {
			fields := strings.Fields(line)
			ts, _ := strconv.ParseInt(fields[0], 10, 64)
			c.entries[int(ts)] = fields[1:]
		}
	}
	// check for scanner errors
	return nil
}

示例#2
文件: procfs.go 项目: bytbox/procfs.go

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"))
	}
}

示例#3
文件: snmp.go 项目: bountylabs/goprocinfo

func ReadSNMP(path string) (*Snmp, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	lines := strings.Split(string(data), "\n")

	// Maps a netstat metric to its value (i.e. SyncookiesSent --> 0)
	statMap := make(map[string]string)

	// patterns
	// TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed... <-- header
	// TcpExt: 0 0 1764... <-- values
	for i := 1; i < len(lines); i = i + 2 {
		headers := strings.Fields(lines[i-1][strings.Index(lines[i-1], ":")+1:])
		values := strings.Fields(lines[i][strings.Index(lines[i], ":")+1:])
		for j, header := range headers {
			statMap[header] = values[j]
		}
	}

	out := Snmp{}
	elem := reflect.ValueOf(&out.TCP).Elem()
	typeOfElem := elem.Type()

	for i := 0; i < elem.NumField(); i++ {
		if val, ok := statMap[typeOfElem.Field(i).Name]; ok {
			parsedVal, _ := strconv.ParseUint(val, 10, 64)
			elem.Field(i).SetUint(parsedVal)
		}
	}

	return &out, nil
}

示例#4
文件: parser.go 项目: alexsaveliev/makex

// Parse parses a Makefile into a *Makefile struct.
//
// TODO(sqs): super hacky.
func Parse(data []byte) (*Makefile, error) {
	var mf Makefile

	lines := bytes.Split(data, []byte{'\n'})
	var rule *BasicRule
	for lineno, lineBytes := range lines {
		line := string(lineBytes)
		if strings.HasPrefix(line, "\t") {
			if rule == nil {
				return nil, fmt.Errorf("line %d: indented recipe not inside a rule", lineno)
			}
			recipe := strings.TrimPrefix(line, "\t")
			recipe = ExpandAutoVars(rule, recipe)
			rule.RecipeCmds = append(rule.RecipeCmds, recipe)
		} else if strings.Contains(line, ":") {
			sep := strings.Index(line, ":")
			targets := strings.Fields(line[:sep])
			if len(targets) > 1 {
				return nil, errMultipleTargetsUnsupported(lineno)
			}
			target := targets[0]
			prereqs := strings.Fields(line[sep+1:])
			prereqs = uniqAndSort(prereqs)
			rule = &BasicRule{TargetFile: target, PrereqFiles: prereqs}
			mf.Rules = append(mf.Rules, rule)
		} else {
			rule = nil
		}
	}

	return &mf, nil
}

示例#5
文件: parser.go 项目: korroktheslavemaster/jee

func GetStudent(d *goquery.Document, rollno int) (s Student, ok bool) {
	//sanity on document
	// if v := d.Find(".titlehead").Children().Text(); v != "JEE (Advanced) - 2013 Result" {
	// 	return Student{}, false
	// }
	dtext := strings.Trim(d.Text(), " ")
	dfields := strings.Fields(dtext)
	for _, v := range dfields {
		s.Plaintext += v + " "
	}
	s.Plaintext = strings.Trim(s.Plaintext, " ")
	if isInvalid(dtext) {
		return s, false
	}
	ok = true
	s.Rollno = rollno
	s.Region = s.Rollno / 10000
	if !isSelected(dtext) {
		return
	}
	s.Selected = true
	s.Rank, _ = strconv.Atoi(d.Find(".style7").First().Text())
	text, _ := d.Find(".titlehead").First().Parent().Next().Children().Children().First().Html()
	tokens := strings.Split(text, "<br/>")
	nameToks := strings.Fields(tokens[1])
	nameToks = nameToks[2:len(nameToks)]
	for _, v := range nameToks {
		s.Name += v + " "
	}
	s.Name = strings.Trim(s.Name, " ")
	s.Q = GetQuota(dtext)
	return
}

示例#6
文件: docker_cli_events_test.go 项目: nicholaskh/docker

func TestEventsImageUntagDelete(t *testing.T) {
	name := "testimageevents"
	defer deleteImages(name)
	_, err := buildImage(name,
		`FROM scratch
		MAINTAINER "docker"`,
		true)
	if err != nil {
		t.Fatal(err)
	}
	if err := deleteImages(name); err != nil {
		t.Fatal(err)
	}
	eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(t).Unix()))
	out, exitCode, err := runCommandWithOutput(eventsCmd)
	if exitCode != 0 || err != nil {
		t.Fatalf("Failed to get events with exit code %d: %s", exitCode, err)
	}
	events := strings.Split(out, "\n")

	events = events[:len(events)-1]
	if len(events) < 2 {
		t.Fatalf("Missing expected event")
	}
	untagEvent := strings.Fields(events[len(events)-2])
	deleteEvent := strings.Fields(events[len(events)-1])
	if untagEvent[len(untagEvent)-1] != "untag" {
		t.Fatalf("untag should be untag, not %#v", untagEvent)
	}
	if deleteEvent[len(deleteEvent)-1] != "delete" {
		t.Fatalf("delete should be delete, not %#v", deleteEvent)
	}
	logDone("events - image untag, delete is logged")
}

示例#7
文件: docker_cli_events_test.go 项目: nicholaskh/docker

func TestEventsContainerEvents(t *testing.T) {
	dockerCmd(t, "run", "--rm", "busybox", "true")
	eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(t).Unix()))
	out, exitCode, err := runCommandWithOutput(eventsCmd)
	if exitCode != 0 || err != nil {
		t.Fatalf("Failed to get events with exit code %d: %s", exitCode, err)
	}
	events := strings.Split(out, "\n")
	events = events[:len(events)-1]
	if len(events) < 4 {
		t.Fatalf("Missing expected event")
	}
	createEvent := strings.Fields(events[len(events)-4])
	startEvent := strings.Fields(events[len(events)-3])
	dieEvent := strings.Fields(events[len(events)-2])
	destroyEvent := strings.Fields(events[len(events)-1])
	if createEvent[len(createEvent)-1] != "create" {
		t.Fatalf("event should be create, not %#v", createEvent)
	}
	if startEvent[len(startEvent)-1] != "start" {
		t.Fatalf("event should be start, not %#v", startEvent)
	}
	if dieEvent[len(dieEvent)-1] != "die" {
		t.Fatalf("event should be die, not %#v", dieEvent)
	}
	if destroyEvent[len(destroyEvent)-1] != "destroy" {
		t.Fatalf("event should be destroy, not %#v", destroyEvent)
	}

	logDone("events - container create, start, die, destroy is logged")
}

示例#8
文件: blkio.go 项目: TencentSA/kubernetes-0.5

func getRootfsDM(containerID string) (string, error) {
	var (
		rootfs string
		major  string
		minor  string
	)
	out, err := exec.Command("ls", "-lh", "/dev/mapper").CombinedOutput()
	if err != nil {
		return "", err
	}
	for _, line := range strings.Split(string(out), "\n") {
		fields := strings.Fields(line)
		if strings.Contains(line, containerID) {
			if len(fields) < 10 {
				return "", fmt.Errorf("Failed to get /dev/mapper info")
			}
			rootfs = filepath.Base(fields[10])
			break
		}
	}

	out, err = exec.Command("ls", "-lh", filepath.Join("/dev", rootfs)).CombinedOutput()
	if err != nil {
		return "", err
	}
	fields := strings.Fields(string(out))
	if len(fields) < 5 {
		return "", fmt.Errorf("Failed to get /dev/%s info", rootfs)
	}
	major = strings.Replace(fields[4], ",", "", -1)
	minor = fields[5]
	return fmt.Sprintf("%s:%s", major, minor), nil
}

示例#9
文件: bonding_linux.go 项目: prometheus/node_exporter

func readBondingStats(root string) (status map[string][2]int, err error) {
	status = map[string][2]int{}
	masters, err := ioutil.ReadFile(path.Join(root, "bonding_masters"))
	if err != nil {
		return nil, err
	}
	for _, master := range strings.Fields(string(masters)) {
		slaves, err := ioutil.ReadFile(path.Join(root, master, "bonding", "slaves"))
		if err != nil {
			return nil, err
		}
		sstat := [2]int{0, 0}
		for _, slave := range strings.Fields(string(slaves)) {
			state, err := ioutil.ReadFile(path.Join(root, master, fmt.Sprintf("lower_%s", slave), "operstate"))
			if os.IsNotExist(err) {
				// some older? kernels use slave_ prefix
				state, err = ioutil.ReadFile(path.Join(root, master, fmt.Sprintf("slave_%s", slave), "operstate"))
			}
			if err != nil {
				return nil, err
			}
			sstat[0]++
			if strings.TrimSpace(string(state)) == "up" {
				sstat[1]++
			}
		}
		status[master] = sstat
	}
	return status, err
}

示例#10
文件: irc.go 项目: lyuyun/loggregator

func parseIrcLine(line string) (prefix, command string, args []string) {
	if line == "" {
		logger.Printf("cannot parse %q", line)
		return
	}
	var hasPrefix bool
	if line[0] == ':' {
		hasPrefix = true
	}
	var items []string
	colon := strings.Index(line[1:], ":")
	if colon >= 0 {
		// long arg
		items = strings.Fields(line[:colon+1])
		items = append(items, line[colon+2:])
	} else {
		items = strings.Fields(line)
	}
	if len(items) < 2 {
		logger.Printf("cannot parse %q", line)
		return
	}
	if hasPrefix {
		return items[0][1:], items[1], items[2:]
	}
	return "", items[0], items[1:]
}

示例#11
文件: sigar_linux.go 项目: rasputnik/gosigar

func (self *ProcMem) Get(pid int) error {
	contents, err := readProcFile(pid, "statm")
	if err != nil {
		return err
	}

	fields := strings.Fields(string(contents))

	size, _ := strtoull(fields[0])
	self.Size = size << 12

	rss, _ := strtoull(fields[1])
	self.Resident = rss << 12

	share, _ := strtoull(fields[2])
	self.Share = share << 12

	contents, err = readProcFile(pid, "stat")
	if err != nil {
		return err
	}

	fields = strings.Fields(string(contents))

	self.MinorFaults, _ = strtoull(fields[10])
	self.MajorFaults, _ = strtoull(fields[12])
	self.PageFaults = self.MinorFaults + self.MajorFaults

	return nil
}

示例#12
文件: vipr.go 项目: ozym/dmc

func (v *ViPR) discover(cli *http.Client, url string) (map[string]string, error) {

	user := env(v.Username, "VIPR_USERNAME", "Admin")
	password := env(v.Password, "VIPR_PASSWORD", "ADMINISTRATOR")

	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	request.SetBasicAuth(user, password)

	resp, err := cli.Do(request)
	if resp == nil || err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	doc, err := goquery.NewDocumentFromResponse(resp)
	if doc == nil || err != nil {
		return nil, err
	}

	results := make(map[string]string)

	// mac address is hidden in javascript and non changeable
	doc.Find("td").Each(func(i int, s *goquery.Selection) {
		p := strings.Fields(s.Text())
		if len(p) > 0 && s.Next() != nil {
			r := strings.Fields(strings.Replace(s.Next().Text(), "\"", "", -1))
			if strings.HasPrefix(s.Text(), "Dataradio") {
				results["version"] = strings.Join(p, " ")
			}
			if strings.HasPrefix(s.Text(), "MAC") {
				if _, ok := results["macaddr"]; !ok && len(r) > 10 {
					results["macaddr"] = strings.Join(r[5:10], ":")
				}
			}
			if strings.HasPrefix(s.Text(), "RSSI") {
				if len(r) > 1 {
					results["signal"] = r[0]
				}
			}

			switch strings.Join(p, " ") {
			case "Modem Firmware Version":
				results["firmware"] = strings.Replace(strings.Replace(strings.Join(r, " "), "(", "", -1), ")", "", -1)
			case "Station Name":
				results["name"] = strings.Join(r, " ")
			case "Unit Status":
				results["status"] = strings.Join(r, " ")
			case "DC Input Voltage":
				results["supply"] = strings.Join(r, " ")
			case "Transceiver Temperature":
				results["temperature"] = strings.Join(r, " ")
			}
		}
	})

	return results, nil
}

示例#13
文件: docker_cli_events_test.go 项目: baoruxing/docker

func TestEventsPause(t *testing.T) {
	out, _, _ := cmd(t, "images", "-q")
	image := strings.Split(out, "\n")[0]
	cmd(t, "run", "-d", "--name", "testeventpause", image, "sleep", "2")
	cmd(t, "pause", "testeventpause")
	cmd(t, "unpause", "testeventpause")
	eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", time.Now().Unix()))
	out, _, _ = runCommandWithOutput(eventsCmd)
	events := strings.Split(out, "\n")
	if len(events) <= 1 {
		t.Fatalf("Missing expected event")
	}

	pauseEvent := strings.Fields(events[len(events)-3])
	unpauseEvent := strings.Fields(events[len(events)-2])

	if pauseEvent[len(pauseEvent)-1] != "pause" {
		t.Fatalf("event should be pause, not %#v", pauseEvent)
	}
	if unpauseEvent[len(unpauseEvent)-1] != "unpause" {
		t.Fatalf("event should be pause, not %#v", unpauseEvent)
	}

	logDone("events - pause/unpause is logged")
}

示例#14
文件: commands.go 项目: wjlroe/gocampfire

func Command(cmd string) []string {
	command := []byte(strings.ToLower(cmd))
	if what_time.Match(command) {
		current_time := time.LocalTime()
		formatted_time := current_time.Format(time.Kitchen)
		return []string{formatted_time}
	} else if who_are_you.Match(command) {
		return []string{"I am Gopher, I'm here to help."}
	} else if cmd == "gopher quit" {
		os.Exit(0)
	} else if matches := gist.FindSubmatch(command); matches != nil {
		for _, match := range matches {
			fmt.Printf("Match: %s\n", string(match))
		}

		if len(matches) > 1 {
			gist_id, err := strconv.Atoui(string(matches[1]))
			if err != nil {
				fmt.Printf("Could not parse the gist_id: %s\n", string(matches[1]))
				return []string{}
			}
			gist_file := strings.TrimSpace(string(matches[2]))
			fmt.Printf("Gist file: %s\n", gist_file)
			gist_content := GetGist(gist_id, gist_file)
			fmt.Printf("Gist Content: %s\n", gist_content)
			return gist_content
		}
		return []string{}
	} else if matches := hoogle.FindSubmatch([]byte(cmd)); matches != nil {
		return Hoogle(strings.Fields(string(matches[1])))
	} else if matches := man_page.FindSubmatch([]byte(cmd)); matches != nil {
		return Manpage(strings.Fields(string(matches[1])))
	}
	return []string{"Dunno what you are asking me. WTF dude?"}
}

示例#15
文件: docker_cli_pull_test.go 项目: rzzdy/docker

// TestPullAllTagsFromCentralRegistry pulls using `all-tags` for a given image and verifies that it
// results in more images than a naked pull.
func (s *DockerHubPullSuite) TestPullAllTagsFromCentralRegistry(c *check.C) {
	testRequires(c, DaemonIsLinux)
	s.Cmd(c, "pull", "busybox")
	outImageCmd := s.Cmd(c, "images", "busybox")
	splitOutImageCmd := strings.Split(strings.TrimSpace(outImageCmd), "\n")
	c.Assert(splitOutImageCmd, checker.HasLen, 2, check.Commentf("expected a single entry in images\n%v", outImageCmd))

	s.Cmd(c, "pull", "--all-tags=true", "busybox")
	outImageAllTagCmd := s.Cmd(c, "images", "busybox")
	if linesCount := strings.Count(outImageAllTagCmd, "\n"); linesCount <= 2 {
		c.Fatalf("pulling all tags should provide more images, got %d", linesCount-1)
	}

	// Verify that the line for 'busybox:latest' is left unchanged.
	var latestLine string
	for _, line := range strings.Split(outImageAllTagCmd, "\n") {
		if strings.HasPrefix(line, "busybox") && strings.Contains(line, "latest") {
			latestLine = line
			break
		}
	}
	c.Assert(latestLine, checker.Not(checker.Equals), "", check.Commentf("no entry for busybox:latest found after pulling all tags"))
	splitLatest := strings.Fields(latestLine)
	splitCurrent := strings.Fields(splitOutImageCmd[1])
	c.Assert(splitLatest, checker.DeepEquals, splitCurrent, check.Commentf("busybox:latest was changed after pulling all tags"))
}

示例#16
文件: docker_cli_events_test.go 项目: waterytowers/global-hack-day-3

func (s *DockerSuite) TestEventsContainerEvents(c *check.C) {
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "--rm", "busybox", "true")
	out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
	events := strings.Split(out, "\n")
	events = events[:len(events)-1]
	if len(events) < 5 {
		c.Fatalf("Missing expected event")
	}
	createEvent := strings.Fields(events[len(events)-5])
	attachEvent := strings.Fields(events[len(events)-4])
	startEvent := strings.Fields(events[len(events)-3])
	dieEvent := strings.Fields(events[len(events)-2])
	destroyEvent := strings.Fields(events[len(events)-1])
	if createEvent[len(createEvent)-1] != "create" {
		c.Fatalf("event should be create, not %#v", createEvent)
	}
	if attachEvent[len(createEvent)-1] != "attach" {
		c.Fatalf("event should be attach, not %#v", attachEvent)
	}
	if startEvent[len(startEvent)-1] != "start" {
		c.Fatalf("event should be start, not %#v", startEvent)
	}
	if dieEvent[len(dieEvent)-1] != "die" {
		c.Fatalf("event should be die, not %#v", dieEvent)
	}
	if destroyEvent[len(destroyEvent)-1] != "destroy" {
		c.Fatalf("event should be destroy, not %#v", destroyEvent)
	}

}

示例#17
文件: service_test.go 项目: imoapps/juju

func (s *serviceSuite) TestNewConf(c *gc.C) {
	dataDir := "/var/lib/juju"
	dbDir := dataDir + "/db"
	mongodPath := "/mgo/bin/mongod"
	port := 12345
	oplogSizeMB := 10
	conf := mongo.NewConf(dataDir, dbDir, mongodPath, port, oplogSizeMB, false)

	expected := common.Conf{
		Desc: "juju state database",
		Limit: map[string]int{
			"nofile": 65000,
			"nproc":  20000,
		},
		Timeout: 300,
		ExecStart: "/mgo/bin/mongod" +
			" --auth" +
			" --dbpath '/var/lib/juju/db'" +
			" --sslOnNormalPorts" +
			" --sslPEMKeyFile '/var/lib/juju/server.pem'" +
			" --sslPEMKeyPassword ignored" +
			" --port 12345" +
			" --noprealloc" +
			" --syslog" +
			" --smallfiles" +
			" --journal" +
			" --keyFile '/var/lib/juju/shared-secret'" +
			" --replSet juju" +
			" --ipv6" +
			" --oplogSize 10",
	}
	c.Check(conf, jc.DeepEquals, expected)
	c.Check(strings.Fields(conf.ExecStart), jc.DeepEquals, strings.Fields(expected.ExecStart))
}

示例#18
文件: docker_cli_events_test.go 项目: waterytowers/global-hack-day-3

func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *check.C) {
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "--rm", "busybox", "true")
	timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano)
	timeBeginning = strings.Replace(timeBeginning, "Z", ".000000000Z", -1)
	out, _ := dockerCmd(c, "events", fmt.Sprintf("--since='%s'", timeBeginning),
		fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
	events := strings.Split(out, "\n")
	events = events[:len(events)-1]
	if len(events) < 5 {
		c.Fatalf("Missing expected event")
	}
	createEvent := strings.Fields(events[len(events)-5])
	attachEvent := strings.Fields(events[len(events)-4])
	startEvent := strings.Fields(events[len(events)-3])
	dieEvent := strings.Fields(events[len(events)-2])
	destroyEvent := strings.Fields(events[len(events)-1])
	if createEvent[len(createEvent)-1] != "create" {
		c.Fatalf("event should be create, not %#v", createEvent)
	}
	if attachEvent[len(attachEvent)-1] != "attach" {
		c.Fatalf("event should be attach, not %#v", attachEvent)
	}
	if startEvent[len(startEvent)-1] != "start" {
		c.Fatalf("event should be start, not %#v", startEvent)
	}
	if dieEvent[len(dieEvent)-1] != "die" {
		c.Fatalf("event should be die, not %#v", dieEvent)
	}
	if destroyEvent[len(destroyEvent)-1] != "destroy" {
		c.Fatalf("event should be destroy, not %#v", destroyEvent)
	}

}

示例#19
文件: docker_cli_events_test.go 项目: nicholaskh/docker

func TestEventsContainerFailStartDie(t *testing.T) {
	defer deleteAllContainers()

	out, _, _ := dockerCmd(t, "images", "-q")
	image := strings.Split(out, "\n")[0]
	eventsCmd := exec.Command(dockerBinary, "run", "--name", "testeventdie", image, "blerg")
	_, _, err := runCommandWithOutput(eventsCmd)
	if err == nil {
		t.Fatalf("Container run with command blerg should have failed, but it did not")
	}

	eventsCmd = exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(t).Unix()))
	out, _, _ = runCommandWithOutput(eventsCmd)
	events := strings.Split(out, "\n")
	if len(events) <= 1 {
		t.Fatalf("Missing expected event")
	}

	startEvent := strings.Fields(events[len(events)-3])
	dieEvent := strings.Fields(events[len(events)-2])

	if startEvent[len(startEvent)-1] != "start" {
		t.Fatalf("event should be start, not %#v", startEvent)
	}
	if dieEvent[len(dieEvent)-1] != "die" {
		t.Fatalf("event should be die, not %#v", dieEvent)
	}

	logDone("events - container unwilling to start logs die")
}

示例#20
文件: docker_cli_events_test.go 项目: waterytowers/global-hack-day-3

func (s *DockerSuite) TestEventsImageUntagDelete(c *check.C) {
	testRequires(c, DaemonIsLinux)
	name := "testimageevents"
	_, err := buildImage(name,
		`FROM scratch
		MAINTAINER "docker"`,
		true)
	if err != nil {
		c.Fatal(err)
	}
	if err := deleteImages(name); err != nil {
		c.Fatal(err)
	}
	out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
	events := strings.Split(out, "\n")

	events = events[:len(events)-1]
	if len(events) < 2 {
		c.Fatalf("Missing expected event")
	}
	untagEvent := strings.Fields(events[len(events)-2])
	deleteEvent := strings.Fields(events[len(events)-1])
	if untagEvent[len(untagEvent)-1] != "untag" {
		c.Fatalf("untag should be untag, not %#v", untagEvent)
	}
	if deleteEvent[len(deleteEvent)-1] != "delete" {
		c.Fatalf("delete should be delete, not %#v", deleteEvent)
	}
}

示例#21
文件: interrupts_linux.go 项目: juergenhoetzel/node_exporter

func parseInterrupts(r io.Reader) (map[string]interrupt, error) {
	var (
		interrupts = map[string]interrupt{}
		scanner    = bufio.NewScanner(r)
	)

	if !scanner.Scan() {
		return nil, errors.New("interrupts empty")
	}
	cpuNum := len(strings.Fields(string(scanner.Text()))) // one header per cpu

	for scanner.Scan() {
		line := scanner.Text()
		parts := strings.Fields(string(line))
		if len(parts) < cpuNum+2 { // irq + one column per cpu + details,
			continue // we ignore ERR and MIS for now
		}
		intName := parts[0][:len(parts[0])-1] // remove trailing :
		intr := interrupt{
			values: parts[1:cpuNum],
		}

		if _, err := strconv.Atoi(intName); err == nil { // numeral interrupt
			intr.info = parts[cpuNum+1]
			intr.devices = strings.Join(parts[cpuNum+2:], " ")
		} else {
			intr.info = strings.Join(parts[cpuNum+1:], " ")
		}
		interrupts[intName] = intr
	}

	return interrupts, nil
}

示例#22
文件: docker_cli_events_test.go 项目: swak/docker

func (s *DockerSuite) TestEventsContainerEvents(c *check.C) {
	dockerCmd(c, "run", "--rm", "busybox", "true")
	eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
	out, exitCode, err := runCommandWithOutput(eventsCmd)
	if exitCode != 0 || err != nil {
		c.Fatalf("Failed to get events with exit code %d: %s", exitCode, err)
	}
	events := strings.Split(out, "\n")
	events = events[:len(events)-1]
	if len(events) < 5 {
		c.Fatalf("Missing expected event")
	}
	createEvent := strings.Fields(events[len(events)-5])
	attachEvent := strings.Fields(events[len(events)-4])
	startEvent := strings.Fields(events[len(events)-3])
	dieEvent := strings.Fields(events[len(events)-2])
	destroyEvent := strings.Fields(events[len(events)-1])
	if createEvent[len(createEvent)-1] != "create" {
		c.Fatalf("event should be create, not %#v", createEvent)
	}
	if attachEvent[len(createEvent)-1] != "attach" {
		c.Fatalf("event should be attach, not %#v", attachEvent)
	}
	if startEvent[len(startEvent)-1] != "start" {
		c.Fatalf("event should be start, not %#v", startEvent)
	}
	if dieEvent[len(dieEvent)-1] != "die" {
		c.Fatalf("event should be die, not %#v", dieEvent)
	}
	if destroyEvent[len(destroyEvent)-1] != "destroy" {
		c.Fatalf("event should be destroy, not %#v", destroyEvent)
	}

}

示例#23
文件: docker_cli_pause_test.go 项目: nickschuch/kube-haproxy

func (s *DockerSuite) TestPause(c *check.C) {
	testRequires(c, DaemonIsLinux)
	defer unpauseAllContainers()

	name := "testeventpause"
	dockerCmd(c, "run", "-d", "--name", name, "busybox", "top")

	dockerCmd(c, "pause", name)
	pausedContainers, err := getSliceOfPausedContainers()
	c.Assert(err, checker.IsNil)
	c.Assert(len(pausedContainers), checker.Equals, 1)

	dockerCmd(c, "unpause", name)

	out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
	events := strings.Split(out, "\n")
	c.Assert(len(events) > 1, checker.Equals, true)

	pauseEvent := strings.Fields(events[len(events)-3])
	unpauseEvent := strings.Fields(events[len(events)-2])

	c.Assert(pauseEvent[len(pauseEvent)-1], checker.Equals, "pause")
	c.Assert(unpauseEvent[len(unpauseEvent)-1], checker.Equals, "unpause")

}

示例#24
文件: docker_cli_events_test.go 项目: swak/docker

func (s *DockerSuite) TestEventsContainerFailStartDie(c *check.C) {

	out, _ := dockerCmd(c, "images", "-q")
	image := strings.Split(out, "\n")[0]
	if err := exec.Command(dockerBinary, "run", "--name", "testeventdie", image, "blerg").Run(); err == nil {
		c.Fatalf("Container run with command blerg should have failed, but it did not")
	}

	eventsCmd := exec.Command(dockerBinary, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
	out, _, _ = runCommandWithOutput(eventsCmd)
	events := strings.Split(out, "\n")
	if len(events) <= 1 {
		c.Fatalf("Missing expected event")
	}

	startEvent := strings.Fields(events[len(events)-3])
	dieEvent := strings.Fields(events[len(events)-2])

	if startEvent[len(startEvent)-1] != "start" {
		c.Fatalf("event should be start, not %#v", startEvent)
	}
	if dieEvent[len(dieEvent)-1] != "die" {
		c.Fatalf("event should be die, not %#v", dieEvent)
	}

}

示例#25
文件: cgo.go 项目: nakalsio/gb

// call pkg-config and return the cflags and ldflags.
func pkgconfig(p *Package) ([]string, []string, error) {
	if len(p.CgoPkgConfig) == 0 {
		return nil, nil, nil // nothing to do
	}
	args := []string{
		"--cflags",
	}
	args = append(args, p.CgoPkgConfig...)
	var out bytes.Buffer
	err := p.runOut(&out, p.Dir, nil, "pkg-config", args...)
	if err != nil {
		return nil, nil, err
	}
	cflags := strings.Fields(out.String())

	args = []string{
		"--libs",
	}
	args = append(args, p.CgoPkgConfig...)
	out.Reset()
	err = p.runOut(&out, p.Dir, nil, "pkg-config", args...)
	if err != nil {
		return nil, nil, err
	}
	ldflags := strings.Fields(out.String())
	return cflags, ldflags, nil
}

示例#26
文件: event.go 项目: strogo/newshound

// checks if partial is any of the words or phrases within whole
func phrasesMatch(partial, whole string) bool {
	// create words of whole
	words := strings.Fields(whole)
	// tag partial apart and put it back together with standard space
	partials := strings.Fields(partial)
	partialWords := len(partials)
	partial = strings.Join(partials, " ")
	// check if partial matches any of whole's phrases
	for i := 0; (i + partialWords) <= len(words); i++ {

		slidingBit := strings.Join(words[i:(i+partialWords)], " ")

		if strings.EqualFold(slidingBit, partial) {
			return true
		}

		if strings.HasSuffix(slidingBit, "'s") {
			if strings.EqualFold(strings.TrimSuffix(slidingBit, "'s"), partial) {
				return true
			}
		}
	}

	return false
}

示例#27
文件: cpu.go 项目: intelsdi-x/snap-plugin-collector-cpu

//getInitialProcStatData gets number of CPUs and number of metrics available in /proc/stat output
func getInitialProcStatData(path string) (cpuMetricsNumber int, procStatMetricNumber int, err error) {
	fh, err := os.Open(path)
	if err != nil {
		return cpuMetricsNumber, procStatMetricNumber, err
	}
	defer fh.Close()

	scanner := bufio.NewScanner(fh)
	//read the first line to start the loop
	scanErr := scanner.Scan()
	if scanErr != true {
		return cpuMetricsNumber, procStatMetricNumber, fmt.Errorf("Cannot read from %s", path)
	}

	procStatLine := strings.Fields(scanner.Text())
	procStatMetricNumber = len(procStatLine) - 1 //without cpu identifier (e.g. cpu or cpu0)

	cpuMetricsNumber = 0
	for strings.Contains(procStatLine[0], cpuStr) {
		//check line length, compare current length with length of the first line
		//length of the first line = len(procStatMetricNumber) + CPU identifier
		if len(procStatLine) != (procStatMetricNumber + 1) {
			return cpuMetricsNumber, procStatMetricNumber, fmt.Errorf("Incorrect %s output", path)
		}
		cpuMetricsNumber++
		//read the next line to be able to check loop condition
		scanErr = scanner.Scan()
		if scanErr != true {
			break //no more lines to read
		}
		procStatLine = strings.Fields(scanner.Text())
	}
	return cpuMetricsNumber, procStatMetricNumber, err
}

示例#28
文件: core_test.go 项目: CyCoreSystems/coreos-kubernetes

// TestBidiCore performs the tests in BidiTest.txt.
// See http://www.unicode.org/Public/UCD/latest/ucd/BidiTest.txt.
func TestBidiCore(t *testing.T) {
	testtext.SkipIfNotLong(t)

	r := gen.OpenUCDFile("BidiTest.txt")
	defer r.Close()

	var wantLevels, wantOrder []string
	p := ucd.New(r, ucd.Part(func(p *ucd.Parser) {
		s := strings.Split(p.String(0), ":")
		switch s[0] {
		case "Levels":
			wantLevels = strings.Fields(s[1])
		case "Reorder":
			wantOrder = strings.Fields(s[1])
		default:
			log.Fatalf("Unknown part %q.", s[0])
		}
	}))

	for p.Next() {
		types := []class{}
		for _, s := range p.Strings(0) {
			types = append(types, bidiClass[s])
		}
		// We ignore the bracketing part of the algorithm.
		pairTypes := make([]bracketType, len(types))
		pairValues := make([]rune, len(types))

		for i := uint(0); i < 3; i++ {
			if p.Uint(1)&(1<<i) == 0 {
				continue
			}
			lev := level(int(i) - 1)
			par := newParagraph(types, pairTypes, pairValues, lev)

			if *testLevels {
				levels := par.resultLevels
				for i, s := range wantLevels {
					if s == "x" {
						continue
					}
					l, _ := strconv.ParseUint(s, 10, 8)
					if level(l)&1 != levels[i]&1 {
						t.Errorf("%s:%d:levels: got %v; want %v", p.String(0), lev, levels, wantLevels)
						break
					}
				}
			}

			order := par.getReordering([]int{len(types)})
			gotOrder := filterOrder(types, order)
			if got, want := fmt.Sprint(gotOrder), fmt.Sprint(wantOrder); got != want {
				t.Errorf("%s:%d:order: got %v; want %v\noriginal %v", p.String(0), lev, got, want, order)
			}
		}
	}
	if err := p.Err(); err != nil {
		log.Fatal(err)
	}
}

示例#29
文件: keys_test.go 项目: sillydong/gogs

func TestMarshalParsePublicKey(t *testing.T) {
	pub, pubSerialized := getTestKey()
	line := fmt.Sprintf("%s %s [email protected]", pub.Type(), pubSerialized)

	authKeys := MarshalAuthorizedKey(pub)
	actualFields := strings.Fields(string(authKeys))
	if len(actualFields) == 0 {
		t.Fatalf("failed authKeys: %v", authKeys)
	}

	// drop the comment
	expectedFields := strings.Fields(line)[0:2]

	if !reflect.DeepEqual(actualFields, expectedFields) {
		t.Errorf("got %v, expected %v", actualFields, expectedFields)
	}

	actPub, _, _, _, err := ParseAuthorizedKey([]byte(line))
	if err != nil {
		t.Fatalf("cannot parse %v: %v", line, err)
	}
	if !reflect.DeepEqual(actPub, pub) {
		t.Errorf("got %v, expected %v", actPub, pub)
	}
}

示例#30
文件: pangolin-api.go 项目: gitter-badger/pangolin

func killGotty(instanceid string) {
	cmd := exec.Command("sudo", "ps", "auxww")
	stdout, err := cmd.Output()
	if err != nil {
		return
	}

	lines := strings.Split(string(stdout), "\n")
	var recpid string

	for _, line := range lines {
		if strings.Contains(line, instanceid) {
			sudo := strings.Contains(line, "sudo")
			if !sudo {
				bhyve := strings.Contains(line, "bhyve")
				if !bhyve {
					recpid = strings.Fields(line)[1]
					cmd = exec.Command("sudo", "kill", recpid)
					cmd.Output()
				}
			}
		}
	}
	for _, line := range lines {
		if strings.Contains(line, instanceid) {
			gotty := strings.Contains(line, "gotty")
			if gotty {
				recpid = strings.Fields(line)[1]
				cmd = exec.Command("sudo", "kill", recpid)
				cmd.Output()
			}
		}
	}
}

展开阅读全文