func isNotXIPIOHostErr(response []byte) bool {
	if !bytes.Contains(response, []byte("no such host")) {
		return true
	}

	return !bytes.Contains(response, []byte("xip.io"))
}
Example #2
0
// TestTags verifies that the -tags argument controls which files to check.
func TestTags(t *testing.T) {
	// go build
	cmd := exec.Command("go", "build", "-o", binary)
	run(cmd, t)

	// defer removal of vet
	defer os.Remove(binary)

	args := []string{
		"-tags=testtag",
		"-v", // We're going to look at the files it examines.
		"testdata/tagtest",
	}
	cmd = exec.Command("./"+binary, args...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatal(err)
	}
	// file1 has testtag and file2 has !testtag.
	if !bytes.Contains(output, []byte(filepath.Join("tagtest", "file1.go"))) {
		t.Error("file1 was excluded, should be included")
	}
	if bytes.Contains(output, []byte(filepath.Join("tagtest", "file2.go"))) {
		t.Error("file2 was included, should be excluded")
	}
}
Example #3
0
// Find one level of whitespace, given indented data
// and a keyword to extract the whitespace in front of
func oneLevelOfIndentation(data *[]byte, keyword string) string {
	whitespace := ""
	kwb := []byte(keyword)
	// If there is a line that contains the given word, extract the whitespace
	if bytes.Contains(*data, kwb) {
		// Find the line that contains they keyword
		var byteline []byte
		found := false
		// Try finding the line with keyword, using \n as the newline
		for _, byteline = range bytes.Split(*data, []byte("\n")) {
			if bytes.Contains(byteline, kwb) {
				found = true
				break
			}
		}
		if found {
			// Find the whitespace in front of the keyword
			whitespaceBytes := byteline[:bytes.Index(byteline, kwb)]
			// Whitespace for one level of indentation
			whitespace = string(whitespaceBytes)
		}
	}
	// Return an empty string, or whitespace for one level of indentation
	return whitespace
}
func slicetest() {
	s := []byte("golang")
	subslice1 := []byte("go")
	subslice2 := []byte("Go")
	fmt.Println(bytes.Contains(s, subslice1))
	fmt.Println(bytes.Contains(s, subslice2))
}
Example #5
0
func ram() interface{} {
	f, err := os.Open("/proc/meminfo")
	if err != nil {
		return "Unsupported"
	}
	defer f.Close()

	bufReader := bufio.NewReader(f)
	b := make([]byte, 0, 100)
	var free, total int

	for line, isPrefix, err := bufReader.ReadLine(); err != io.EOF; line, isPrefix, err = bufReader.ReadLine() {
		if err != nil {
			log.Fatal("bufReader.ReadLine: ", err)
		}
		b = append(b, line...)

		if !isPrefix {
			switch {
			case bytes.Contains(b, []byte("MemFree")):
				free = toInt(bytes.Fields(b)[1])
			case bytes.Contains(b, []byte("MemTotal")):
				total = toInt(bytes.Fields(b)[1])
			}
			b = b[:0]
		}
	}
	return Ram{free, total}
}
Example #6
0
func main() {
	b := []byte("12345678")
	s1 := []byte("456")
	s2 := []byte("789")
	fmt.Println(bytes.Contains(b, s1))
	fmt.Println(bytes.Contains(b, s2))
}
Example #7
0
// Test that timesyncd starts using the local NTP server
func NTP(c platform.TestCluster) error {
	m, err := c.NewMachine("")
	if err != nil {
		return fmt.Errorf("Cluster.NewMachine: %s", err)
	}
	defer m.Destroy()

	out, err := m.SSH("networkctl status eth0")
	if err != nil {
		return fmt.Errorf("networkctl: %v", err)
	}
	if !bytes.Contains(out, []byte("NTP: 10.0.0.1")) {
		return fmt.Errorf("Bad network config:\n%s", out)
	}

	plog.Info("Waiting for systemd-timesyncd.service")
	for i := 0; i < 60; i++ {
		out, err = m.SSH("systemctl status systemd-timesyncd.service")
		if err != nil {
			return fmt.Errorf("systemctl: %v", err)
		}

		if bytes.Contains(out, []byte(`Status: "Using Time Server 10.0.0.1:123 (10.0.0.1)."`)) {
			plog.Info("systemd-timesyncd.service is working!")
			return nil
		}

		time.Sleep(time.Second)
	}

	return fmt.Errorf("Bad status:\n%s", out)
}
Example #8
0
func TestEditVisitPageMissingPathInfo(t *testing.T) {
	inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	url := "/editvisit/"
	req, err := inst.NewRequest("GET", url, nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}

	aetest.Login(&user.User{Email: "*****@*****.**"}, req)

	w := httptest.NewRecorder()
	c := appengine.NewContext(req)

	addTestUser(c, "*****@*****.**", true)

	editvisitpage(c, w, req)

	code := w.Code
	if code != http.StatusBadRequest {
		t.Errorf("got code %v, want %v", code, http.StatusBadRequest)
	}

	body := w.Body.Bytes()
	expected := []byte("id is missing in path for update request /editvisit/")
	if !bytes.Contains(body, expected) {
		t.Errorf("got body %v, did not contain %v", string(body),
			string(expected))
	}

	url += "12345"
	req, err = inst.NewRequest("GET", url, nil)
	if err != nil {
		t.Fatalf("Failed to create req: %v", err)
	}

	aetest.Login(&user.User{Email: "*****@*****.**"}, req)

	w = httptest.NewRecorder()
	c = appengine.NewContext(req)

	editvisitpage(c, w, req)

	code = w.Code
	if code != http.StatusBadRequest {
		t.Errorf("got code %v, want %v", code, http.StatusBadRequest)
	}

	body = w.Body.Bytes()
	expected = []byte("id is missing in path for update request /editvisit/")
	if !bytes.Contains(body, expected) {
		t.Errorf("got body %v, did not contain %v", string(body),
			string(expected))
	}

}
Example #9
0
func isVolatile(flagsRequired bool) bool {
	files, err := ioutil.ReadDir(".")
	if err != nil {
		errorExit("fail reading current directory")
	}

	for _, f := range files {
		if f.IsDir() || filepath.Ext(f.Name()) != ".go" {
			continue
		}

		b, err := ioutil.ReadFile(f.Name())
		if err != nil {
			errorExit("fail reading file " + f.Name())
		}

		if bytes.Contains(b, []byte("\nfunc main() {\n")) && bytes.Contains(b, []byte("core.Run()")) {
			if flagsRequired {
				return bytes.Contains(b, []byte("flag.Parse()"))
			}

			return true
		}
	}

	return false
}
Example #10
0
func TestSetSuperfluousCertTag(t *testing.T) {
	out := tempFileName()

	const expected = "34cf251b916a54dc9351b832bb0ac7ce"
	cmd := exec.Command(tagBinary, "--out", out, "--set-superfluous-cert-tag", expected, sourceExe)
	if err := cmd.Run(); err != nil {
		t.Fatal(err)
	}

	contents, err := ioutil.ReadFile(out)
	if err != nil {
		t.Fatalf("Failed to read output file: %s", err)
	}
	if !bytes.Contains(contents, []byte(expected)) {
		t.Error("Output doesn't contain expected bytes")
	}

	cmd = exec.Command(tagBinary, "--out", out, "--set-superfluous-cert-tag", expected, "--padded-length", "256", sourceExe)
	if err = cmd.Run(); err != nil {
		t.Fatal(err)
	}

	contents, err = ioutil.ReadFile(out)
	if err != nil {
		t.Fatalf("Failed to read output file: %s", err)
	}
	var zeros [16]byte
	if !bytes.Contains(contents, append([]byte(expected), zeros[:]...)) {
		t.Error("Output doesn't contain expected bytes with padding")
	}
}
Example #11
0
func TestNewWriter_1Sample(t *testing.T) {
	t.Parallel()
	is := is.New(t)
	f, err := ioutil.TempFile("", "wavPkgtest")
	is.NoErr(err)
	wr, err := wf.NewWriter(f)
	is.NoErr(err)

	err = wr.WriteSample([]byte{1, 1})
	is.NoErr(err)

	is.Nil(wr.Close())

	f, err = os.Open(f.Name())
	is.NoErr(err)

	b, err := ioutil.ReadAll(f)
	is.NoErr(err)
	is.Equal(len(b), 46)

	is.True(bytes.Contains(b, riff))
	is.True(bytes.Contains(b, wave))
	is.True(bytes.Contains(b, fmt20))

	is.Nil(os.Remove(f.Name()))
}
Example #12
0
func TestQuoteTableNames(t *testing.T) {
	dbmap := initDbMap()
	defer dropAndClose(dbmap)

	quotedTableName := dbmap.Dialect.QuoteField("person_test")

	// Use a buffer to hold the log to check generated queries
	logBuffer := &bytes.Buffer{}
	dbmap.TraceOn("", log.New(logBuffer, "gorptest:", log.Lmicroseconds))

	// Create some rows
	p1 := &Person{0, 0, 0, "bob", "smith", 0}
	errorTemplate := "Expected quoted table name %v in query but didn't find it"

	// Check if Insert quotes the table name
	id := dbmap.Insert(p1)
	if !bytes.Contains(logBuffer.Bytes(), []byte(quotedTableName)) {
		t.Errorf(errorTemplate, quotedTableName)
	}
	logBuffer.Reset()

	// Check if Get quotes the table name
	dbmap.Get(Person{}, id)
	if !bytes.Contains(logBuffer.Bytes(), []byte(quotedTableName)) {
		t.Errorf(errorTemplate, quotedTableName)
	}
	logBuffer.Reset()
}
Example #13
0
func TestDataCopySubscriptionsForUserAsJSON(t *testing.T) {
	pool := newConnPool(t)

	userID, err := data.CreateUser(pool, newUser())
	if err != nil {
		t.Fatal(err)
	}

	buffer := &bytes.Buffer{}
	err = data.CopySubscriptionsForUserAsJSON(pool, buffer, userID)
	if err != nil {
		t.Fatalf("Failed when no subscriptions: %v", err)
	}

	err = data.InsertSubscription(pool, userID, "http://foo")
	if err != nil {
		t.Fatal(err)
	}

	buffer.Reset()
	err = data.CopySubscriptionsForUserAsJSON(pool, buffer, userID)
	if err != nil {
		t.Fatal(err)
	}
	if bytes.Contains(buffer.Bytes(), []byte("foo")) != true {
		t.Errorf("Expected %v, got %v", true, bytes.Contains(buffer.Bytes(), []byte("foo")))
	}
}
Example #14
0
func switchTData(w http.ResponseWriter, r *http.Request) {

	lg, lge := loghttp.Logger(w, r)
	_ = lge

	b := fetch.TestData["test.economist.com"]
	sub1 := []byte(`<li><a href="/sections/newcontinent">xxx</a></li>`)

	sub2 := []byte(`<li><a href="/sections/asia">Asia</a></li>`)
	sub3 := []byte(`<li><a href="/sections/asia">Asia</a></li>
		<li><a href="/sections/newcontinent">xxx</a></li>`)

	if bytes.Contains(b, sub1) {
		b = bytes.Replace(b, sub1, []byte{}, -1)
	} else {
		b = bytes.Replace(b, sub2, sub3, -1)
	}

	if bytes.Contains(b, sub1) {
		lg("now contains %s", sub1)
	} else {
		lg("NOT contains %s", sub1)
	}

	fetch.TestData["test.economist.com"] = b

}
Example #15
0
// escapeControlCharsFromPayload escapes control chars (\n, \t) from a byte slice.
// Context:
// JSON strings are not supposed to contain control characters such as \n, \t,
// ... but some incoming webhooks might still send invalid JSON and we want to
// try to handle that. An example invalid JSON string from an incoming webhook
// might look like this (strings for both "text" and "fallback" attributes are
// invalid JSON strings because they contain unescaped newlines and tabs):
//  `{
//    "text": "this is a test
//						 that contains a newline and tabs",
//    "attachments": [
//      {
//        "fallback": "Required plain-text summary of the attachment
//										that contains a newline and tabs",
//        "color": "#36a64f",
//  			...
//        "text": "Optional text that appears within the attachment
//								 that contains a newline and tabs",
//  			...
//        "thumb_url": "http://example.com/path/to/thumb.png"
//      }
//    ]
//  }`
// This function will search for `"key": "value"` pairs, and escape \n, \t
// from the value.
func escapeControlCharsFromPayload(by []byte) []byte {
	// we'll search for `"text": "..."` or `"fallback": "..."`, ...
	keys := "text|fallback|pretext|author_name|title|value"

	// the regexp reads like this:
	// (?s): this flag let . match \n (default is false)
	// "(keys)": we search for the keys defined above
	// \s*:\s*: followed by 0..n spaces/tabs, a colon then 0..n spaces/tabs
	// ": a double-quote
	// (\\"|[^"])*: any number of times the `\"` string or any char but a double-quote
	// ": a double-quote
	r := `(?s)"(` + keys + `)"\s*:\s*"(\\"|[^"])*"`
	re := regexp.MustCompile(r)

	// the function that will escape \n and \t on the regexp matches
	repl := func(b []byte) []byte {
		if bytes.Contains(b, []byte("\n")) {
			b = bytes.Replace(b, []byte("\n"), []byte("\\n"), -1)
		}
		if bytes.Contains(b, []byte("\t")) {
			b = bytes.Replace(b, []byte("\t"), []byte("\\t"), -1)
		}

		return b
	}

	return re.ReplaceAllFunc(by, repl)
}
Example #16
0
File: whois.go Project: 9uuso/whogo
// Records uses Jaro-Winkler distance to parse WHOIS queries.
// Other than .com domains may not be supported.
func Records(data []byte) record {
	lines := bytes.Split(data, []byte("\n"))
	query := make(map[string]string)
	var record record
	for _, line := range lines {
		if jwd.Calculate(strings.Split(string(line), ":")[0], "Referral") > 0.7 && bytes.Contains(line, []byte(":")) {
			record.Referral = strings.TrimSpace(strings.Split(string(line), ": ")[1])
		}
		if len(line) > 0 && bytes.Contains(line, []byte(":")) && len(bytes.TrimSpace(bytes.Split(line, []byte(":"))[1])) > 0 {
			this := string(line)
			if len(query[strings.TrimSpace(strings.Split(this, ":")[0])]) != 0 {
				n := query[strings.TrimSpace(strings.Split(this, ":")[0])]
				query[strings.TrimSpace(strings.Split(this, ":")[0])] = n + "," + strings.TrimSpace(strings.Split(this, ":")[1])
			} else {
				query[strings.TrimSpace(strings.Split(this, ":")[0])] = strings.TrimSpace(strings.Split(this, ":")[1])
			}
		}
	}
	record.Updated = find(query, "Updated")
	record.Created = find(query, "Created")
	record.Nameservers = strings.Split(find(query, "Nameservers"), ",")
	record.Status = strings.Split(find(query, "Status"), ",")
	record.Expiration = find(query, "Expiration")
	return record
}
// TestCommonKindsRegistered verifies that all group/versions registered with
// the testapi package have the common kinds.
func TestCommonKindsRegistered(t *testing.T) {
	for _, kind := range commonKinds {
		for _, group := range testapi.Groups {
			gv := group.GroupVersion()
			gvk := gv.WithKind(kind)
			obj, err := api.Scheme.New(gvk)
			if err != nil {
				t.Error(err)
			}
			defaults := gv.WithKind("")
			if _, got, err := api.Codecs.LegacyCodec().Decode([]byte(`{"kind":"`+kind+`"}`), &defaults, nil); err != nil || gvk != *got {
				t.Errorf("expected %v: %v %v", gvk, got, err)
			}
			data, err := runtime.Encode(api.Codecs.LegacyCodec(*gv), obj)
			if err != nil {
				t.Errorf("expected %v: %v\n%s", gvk, err, string(data))
				continue
			}
			if !bytes.Contains(data, []byte(`"kind":"`+kind+`","apiVersion":"`+gv.String()+`"`)) {
				if kind != "Status" {
					t.Errorf("expected %v: %v\n%s", gvk, err, string(data))
					continue
				}
				// TODO: this is wrong, but legacy clients expect it
				if !bytes.Contains(data, []byte(`"kind":"`+kind+`","apiVersion":"v1"`)) {
					t.Errorf("expected %v: %v\n%s", gvk, err, string(data))
					continue
				}
			}
		}
	}
}
Example #18
0
func TestHomePage(t *testing.T) {
	inst, err := aetest.NewInstance(&aetest.Options{StronglyConsistentDatastore: true})
	if err != nil {
		t.Fatalf("Failed to create instance: %v", err)
	}
	defer inst.Close()

	req, err := inst.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatalf("Failed to create req1: %v", err)
	}

	aetest.Login(&user.User{Email: "*****@*****.**"}, req)

	w := httptest.NewRecorder()
	c := appengine.NewContext(req)
	addTestUser(c, "*****@*****.**", true)

	homepage(c, w, req)

	code := w.Code
	if code != http.StatusOK {
		t.Errorf("got code %v, want %v", code, http.StatusOK)
	}

	body := w.Body.Bytes()
	expected := []byte("*****@*****.**")
	if !bytes.Contains(body, expected) {
		t.Errorf("got body %v, did not contain %v", string(body), string(expected))
	}
	if !bytes.Contains(body, []byte("Logout")) {
		t.Errorf("got body %v, did not contain %v", body,
			[]byte("Logout"))
	}
}
Example #19
0
// TestTags verifies that the -tags argument controls which files to check.
func TestTags(t *testing.T) {
	t.Parallel()
	Build(t)
	for _, tag := range []string{"testtag", "x testtag y", "x,testtag,y"} {
		tag := tag
		t.Run(tag, func(t *testing.T) {
			t.Parallel()
			t.Logf("-tags=%s", tag)
			args := []string{
				"-tags=" + tag,
				"-v", // We're going to look at the files it examines.
				"testdata/tagtest",
			}
			cmd := exec.Command("./"+binary, args...)
			output, err := cmd.CombinedOutput()
			if err != nil {
				t.Fatal(err)
			}
			// file1 has testtag and file2 has !testtag.
			if !bytes.Contains(output, []byte(filepath.Join("tagtest", "file1.go"))) {
				t.Error("file1 was excluded, should be included")
			}
			if bytes.Contains(output, []byte(filepath.Join("tagtest", "file2.go"))) {
				t.Error("file2 was included, should be excluded")
			}
		})
	}
}
Example #20
0
func computeInsertedDeletedLines(oldCodeR, newCodeR io.Reader) (id InsDel, err error) {
	var i, d int
	// TODO(flowlo): get rid of ReadAll
	var oldCode, newCode []byte
	if oldCode, err = ioutil.ReadAll(oldCodeR); err != nil {
		return
	}

	if newCode, err = ioutil.ReadAll(newCodeR); err != nil {
		return
	}
	currentFields := bytes.Split(newCode, []byte("\n"))
	oldFields := bytes.Split(oldCode, []byte("\n"))
	for _, val := range currentFields {
		if !bytes.Contains(oldCode, val) {
			i++
		}
	}
	for _, val := range oldFields {
		if !bytes.Contains(oldCode, val) {
			d++
		}
	}
	return InsDel{i, d}, nil
}
Example #21
0
func ram() string {
	f, err := os.Open("/proc/meminfo")
	if err != nil {
		return fmt.Sprint(err)
	}
	defer f.Close()

	bufReader := bufio.NewReader(f)
	b := make([]byte, 100)
	var free, total string
	for line, isPrefix, err := bufReader.ReadLine(); err != io.EOF; line, isPrefix, err = bufReader.ReadLine() {
		b = append(b, line...)

		if !isPrefix {
			switch {
			case bytes.Contains(b, []byte("MemFree")):
				s := bytes.Fields(b)
				free = string(s[1])
			case bytes.Contains(b, []byte("MemTotal")):
				s := bytes.Fields(b)
				total = string(s[1])
			}
			b = b[:0]
		}
	}
	return fmt.Sprintf("%s/%s", free, total)
}
Example #22
0
func (p HttpProtocol) Detect(buf []byte) (bool, error) {
	// If it's got "HTTP" in the request, it's HTTP
	if bytes.Contains(buf, []byte("HTTP")) {
		return true, nil
	}

	// Check each of the HTTP methods.  Note that we need to track the number of
	// methods where the buffer isn't long enough - we only return a definitive
	// 'false' if none of the methods result in ErrMoreData.
	var successful int
	for _, method := range httpMethods {
		if len(buf) < len(method) {
			// Not enough data
			continue
		}

		if bytes.Contains(buf, []byte(method)) {
			return true, nil
		}
	}

	// If we get here, then we're not successful.  Return 'ErrMoreData' if not all
	// the above checks succeeded.
	if successful != len(httpMethods) {
		return false, ErrMoreData
	}

	return false, nil
}
Example #23
0
func TestUpdate(t *testing.T) {
	file, err := ioutil.TempFile("", "")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(file.Name())

	if err := Build(file.Name(), "10.11.12.13", "testhostname", "testdomainname", nil); err != nil {
		t.Fatal(err)
	}

	content, err := ioutil.ReadFile(file.Name())
	if err != nil {
		t.Fatal(err)
	}

	if expected := "10.11.12.13\ttesthostname.testdomainname testhostname\n"; !bytes.Contains(content, []byte(expected)) {
		t.Fatalf("Expected to find '%s' got '%s'", expected, content)
	}

	if err := Update(file.Name(), "1.1.1.1", "testhostname"); err != nil {
		t.Fatal(err)
	}

	content, err = ioutil.ReadFile(file.Name())
	if err != nil {
		t.Fatal(err)
	}

	if expected := "1.1.1.1\ttesthostname.testdomainname testhostname\n"; !bytes.Contains(content, []byte(expected)) {
		t.Fatalf("Expected to find '%s' got '%s'", expected, content)
	}
}
Example #24
0
func controlDbStatement(sql []byte, dmlType string) bool {
	sql = bytes.ToLower(sql)
	if bytes.Contains(sql, _VT) || (bytes.Contains(sql, ADMIN) && bytes.Contains(sql, HEARTBEAT)) {
		return true
	}
	return false
}
Example #25
0
func (p *syncthingProcess) stop() error {
	p.cmd.Process.Signal(os.Kill)
	p.cmd.Wait()

	fd, err := os.Open(p.logfd.Name())
	if err != nil {
		return err
	}
	defer fd.Close()

	raceConditionStart := []byte("WARNING: DATA RACE")
	raceConditionSep := []byte("==================")
	sc := bufio.NewScanner(fd)
	race := false
	for sc.Scan() {
		line := sc.Bytes()
		if race {
			fmt.Printf("%s\n", line)
			if bytes.Contains(line, raceConditionSep) {
				race = false
			}
		} else if bytes.Contains(line, raceConditionStart) {
			fmt.Printf("%s\n", raceConditionSep)
			fmt.Printf("%s\n", raceConditionStart)
			race = true
			if err == nil {
				err = errors.New("Race condition detected")
			}
		}
	}
	return err
}
Example #26
0
func TestZipper(t *testing.T) {
	dir := filepath.Join(os.TempDir(), strconv.Itoa(rand.Int()))
	if err := os.Mkdir(dir, 0755); err != nil {
		t.Fatalf("Should have been able to make tempdir: %s", err)
	}
	defer os.Remove(dir)

	fName := "tempfile"
	fullName := filepath.Join(dir, fName)
	data := []byte("\ntest data\n")
	if err := ioutil.WriteFile(fullName, data, 0644); err != nil {
		t.Fatalf("Should have been able to write file: %s", err)
	}
	defer os.Remove(fullName)
	buf, err := Zipper(fullName)
	if err != nil {
		t.Fatalf("Should have been able to zip data: %s", err)
	}
	if len(buf.Bytes()) == 0 {
		t.Fatalf("Expected nonzero length from buffer: %v", buf)
	}
	if !bytes.Contains(buf.Bytes(), []byte(fName)) {
		t.Fatalf("Expected buf %q to contain file name %q", string(buf.Bytes()), fName)
	}
	if !bytes.Contains(buf.Bytes(), data) {
		t.Fatalf("Expected buf %q to contain data %q", string(buf.Bytes()), string(data))
	}
}
Example #27
0
func injectErrors(
	req roachpb.Request,
	hdr roachpb.Header,
	magicVals *filterVals,
) error {
	magicVals.Lock()
	defer magicVals.Unlock()

	switch req := req.(type) {
	case *roachpb.ConditionalPutRequest:
		for key, count := range magicVals.restartCounts {
			checkCorrectTxn(string(req.Value.RawBytes), magicVals, hdr.Txn)
			if count > 0 && bytes.Contains(req.Value.RawBytes, []byte(key)) {
				magicVals.restartCounts[key]--
				err := roachpb.NewReadWithinUncertaintyIntervalError(
					hlc.ZeroTimestamp, hlc.ZeroTimestamp)
				magicVals.failedValues[string(req.Value.RawBytes)] =
					failureRecord{err, hdr.Txn}
				return err
			}
		}
		for key, count := range magicVals.abortCounts {
			checkCorrectTxn(string(req.Value.RawBytes), magicVals, hdr.Txn)
			if count > 0 && bytes.Contains(req.Value.RawBytes, []byte(key)) {
				magicVals.abortCounts[key]--
				err := roachpb.NewTransactionAbortedError()
				magicVals.failedValues[string(req.Value.RawBytes)] =
					failureRecord{err, hdr.Txn}
				return err
			}
		}
		// If we're writing a value that's marked for an EndTransaction failure,
		// keep track of the txn id so we can fail it later on.
		for key, count := range magicVals.endTxnRestartCounts {
			if count > 0 && bytes.Contains(req.Value.RawBytes, []byte(key)) {
				txnID := *hdr.Txn.TxnMeta.ID
				if _, found := magicVals.txnsToFail[txnID]; found {
					continue
				}
				magicVals.endTxnRestartCounts[key]--
				magicVals.txnsToFail[txnID] = true
			}
		}
		return nil
	case *roachpb.EndTransactionRequest:
		txnID := *hdr.Txn.TxnMeta.ID
		if !magicVals.txnsToFail[txnID] {
			return nil
		}
		delete(magicVals.txnsToFail, txnID)
		// Note that we can't return TransactionAborted errors, although those are
		// more representative for the errors that EndTransaction might encounter,
		// because returning those would result in the txn's intents being left
		// around.
		return roachpb.NewTransactionRetryError()
	default:
		return nil
	}
}
Example #28
0
//-----------------------------------------------------------------------------
func (market *Market) checkIfMarketIsOpen(body []byte) []byte {
	start := bytes.Index(body, []byte(`id='yfs_market_time'`))
	finish := start + bytes.Index(body[start:], []byte(`</span>`))
	snippet := body[start:finish]
	market.IsClosed = bytes.Contains(snippet, []byte(`closed`)) || bytes.Contains(snippet, []byte(`open in`))

	return body[finish:]
}
func TestPerRPCCredentials(t *testing.T) {
	l, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	s := grpc.NewServer()
	go func() {
		if err := s.Serve(l); err != nil {
			t.Fatal(err)
		}
	}()
	defer s.TestingCloseConns()

	var ms testMetaServer
	RegisterMetaServer(s, &ms)

	var wg sync.WaitGroup
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()

			time.Sleep(time.Duration(i%10) * 5 * time.Millisecond)

			key := fmt.Sprintf("key%d", i)

			ctx := context.Background()
			ctx = WithGRPCEndpoint(ctx, &url.URL{Host: l.Addr().String()})
			ctx = WithCredentials(ctx, oauth2.StaticTokenSource(&oauth2.Token{TokenType: "x", AccessToken: key}))
			ctx = metadata.NewContext(ctx, metadata.MD{"want-access-token": "x " + key})
			c := NewClientFromContext(ctx)
			if _, err := c.Meta.Status(ctx, &pbtypes.Void{}); err != nil {
				t.Fatal(err)
			}
		}(i)
	}
	wg.Wait()

	out, err := exec.Command("netstat", "-ntap").CombinedOutput()
	if err == nil {
		lines := bytes.Split(out, []byte("\n"))
		var conns, timeWaits int
		addr := strings.Replace(l.Addr().String(), "[::]", "::1", 1)
		for _, line := range lines {
			if bytes.Contains(line, []byte(addr)) {
				conns++
				if bytes.Contains(line, []byte("TIME_WAIT")) {
					timeWaits++
				}
			}
		}
		t.Logf("lingering connections count: %d", conns)
		t.Logf("         in TIME_WAIT state: %d", timeWaits)
		t.Log("(ideally, there should be 0 lingering connections)")
	} else {
		t.Logf("warning: error running `netstat -ntap` to check # of TIME_WAIT conns: %s", err)
	}
}
Example #30
0
// getVersionB is like getVersion but for byte array input.
func GetVersionB(metric_in []byte) metricVersion {
	if bytes.Contains(metric_in, byteEquals) {
		return M20
	}
	if bytes.Contains(metric_in, byteIs) {
		return M20NoEquals
	}
	return Legacy
}