Esempio n. 1
1
func xmlToSocketLogWriter(filename string, props []xmlProperty, enabled bool) (SocketLogWriter, bool) {
	endpoint := ""
	protocol := "udp"

	for _, prop := range props {
		switch prop.Name {
		case "endpoint":
			endpoint = strings.Trim(prop.Value, " \r\n")
		case "protocol":
			protocol = strings.Trim(prop.Value, " \r\n")
		default:
			fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for file filter in %s\n", prop.Name, filename)
		}
	}

	if len(endpoint) == 0 {
		fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required property \"%s\" for file filter missing in %s\n", "endpoint", filename)
		return nil, false
	}

	if !enabled {
		return nil, true
	}

	return NewSocketLogWriter(protocol, endpoint), true
}
Esempio n. 2
0
func (p *Problem) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	pp := struct {
		Id                 string       `xml:"id"`
		Name               string       `xml:"name"`
		Available          string       `xml:"available"`
		ProblemTimeLimit   string       `xml:"problemtimelimit"`
		ProblemMemoryLimit string       `xml:"problemmemorylimit"`
		Status             Status       `xml:"status"`
		SolvedList         []SolvedUser `xml:"solved_list>user"`
	}{}
	if err := d.DecodeElement(&pp, &start); err != nil {
		return err
	}

	available, err := strconv.Atoi(strings.Trim(pp.Available, "\n"))
	problemTimeLimit, err := strconv.Atoi(strings.Trim(pp.ProblemTimeLimit, "\n"))
	problemMemoryLimit, err := strconv.Atoi(strings.Trim(pp.ProblemMemoryLimit, "\n"))
	if err != nil {
		return err
	}

	*p = Problem{
		Id:                 strings.Trim(pp.Id, "\n"),
		Name:               strings.Trim(pp.Name, "\n"),
		Available:          available,
		ProblemTimeLimit:   problemTimeLimit,
		ProblemMemoryLimit: problemMemoryLimit,
		Status:             pp.Status,
		SolvedList:         pp.SolvedList,
	}
	return nil
}
Esempio n. 3
0
func cleanRawValue(s string) string {
	s = strings.Trim(s, " \t\n\r")
	if len(s) == 0 {
		return ""
	}

	inString := false
	escape := false
	for i := 0; i < len(s); i++ {
		c := s[i]
		if escape {
			escape = false
			continue
		}
		if c == '"' {
			inString = !inString
			continue
		}
		if inString && c == '\\' {
			escape = true
			continue
		}
		if c == '#' && !inString {
			return strings.Trim(s[0:i], " \t\n\r")
		}
	}

	return s
}
Esempio n. 4
0
func (b *buildFile) Build(context io.Reader) (string, error) {
	// FIXME: @creack "name" is a terrible variable name
	name, err := ioutil.TempDir("", "docker-build")
	if err != nil {
		return "", err
	}
	if err := Untar(context, name); err != nil {
		return "", err
	}
	defer os.RemoveAll(name)
	b.context = name
	filename := path.Join(name, "Dockerfile")
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		return "", fmt.Errorf("Can't build a directory with no Dockerfile")
	}
	fileBytes, err := ioutil.ReadFile(filename)
	if err != nil {
		return "", err
	}
	dockerfile := string(fileBytes)
	dockerfile = lineContinuation.ReplaceAllString(dockerfile, "")
	stepN := 0
	for _, line := range strings.Split(dockerfile, "\n") {
		line = strings.Trim(strings.Replace(line, "\t", " ", -1), " \t\r\n")
		// Skip comments and empty line
		if len(line) == 0 || line[0] == '#' {
			continue
		}
		tmp := strings.SplitN(line, " ", 2)
		if len(tmp) != 2 {
			return "", fmt.Errorf("Invalid Dockerfile format")
		}
		instruction := strings.ToLower(strings.Trim(tmp[0], " "))
		arguments := strings.Trim(tmp[1], " ")

		method, exists := reflect.TypeOf(b).MethodByName("Cmd" + strings.ToUpper(instruction[:1]) + strings.ToLower(instruction[1:]))
		if !exists {
			fmt.Fprintf(b.out, "# Skipping unknown instruction %s\n", strings.ToUpper(instruction))
			continue
		}

		stepN += 1
		fmt.Fprintf(b.out, "Step %d : %s %s\n", stepN, strings.ToUpper(instruction), arguments)

		ret := method.Func.Call([]reflect.Value{reflect.ValueOf(b), reflect.ValueOf(arguments)})[0].Interface()
		if ret != nil {
			return "", ret.(error)
		}

		fmt.Fprintf(b.out, " ---> %v\n", utils.TruncateID(b.image))
	}
	if b.image != "" {
		fmt.Fprintf(b.out, "Successfully built %s\n", utils.TruncateID(b.image))
		if b.rm {
			b.clearTmp(b.tmpContainers)
		}
		return b.image, nil
	}
	return "", fmt.Errorf("An error occurred during the build\n")
}
Esempio n. 5
0
func (p linux) findRootDevicePath() (string, error) {
	mounts, err := p.diskManager.GetMountsSearcher().SearchMounts()

	if err != nil {
		return "", bosherr.WrapError(err, "Searching mounts")
	}

	for _, mount := range mounts {
		if mount.MountPoint == "/" && strings.HasPrefix(mount.PartitionPath, "/dev/") {
			p.logger.Debug(logTag, "Found root partition: `%s'", mount.PartitionPath)

			stdout, _, _, err := p.cmdRunner.RunCommand("readlink", "-f", mount.PartitionPath)
			if err != nil {
				return "", bosherr.WrapError(err, "Shelling out to readlink")
			}
			rootPartition := strings.Trim(stdout, "\n")
			p.logger.Debug(logTag, "Symlink is: `%s'", rootPartition)

			validRootPartition := regexp.MustCompile(`^/dev/[a-z]+1$`)
			if !validRootPartition.MatchString(rootPartition) {
				return "", bosherr.Error("Root partition is not the first partition")
			}

			return strings.Trim(rootPartition, "1"), nil
		}
	}

	return "", bosherr.Error("Getting root partition device")
}
Esempio n. 6
0
// as per http://www.mssqltips.com/sqlservertip/2563/understanding-the-sql-server-select-version-command/
func serverVersion(db *sql.DB) (sqlVersion, sqlPartNumber, osVersion string, err error) {
	var v string
	if err = db.QueryRow("select @@version").Scan(&v); err != nil {
		return "", "", "", err
	}
	a := strings.SplitN(v, "\n", -1)
	if len(a) < 4 {
		return "", "", "", errors.New("SQL Server version string must have at least 4 lines: " + v)
	}
	for i := range a {
		a[i] = strings.Trim(a[i], " \t")
	}
	l1 := strings.SplitN(a[0], "-", -1)
	if len(l1) != 2 {
		return "", "", "", errors.New("SQL Server version first line must have - in it: " + v)
	}
	i := strings.Index(a[3], " on ")
	if i < 0 {
		return "", "", "", errors.New("SQL Server version fourth line must have 'on' in it: " + v)
	}
	sqlVersion = l1[0] + a[3][:i]
	osVersion = a[3][i+4:]
	sqlPartNumber = strings.Trim(l1[1], " ")
	l12 := strings.SplitN(sqlPartNumber, " ", -1)
	if len(l12) < 2 {
		return "", "", "", errors.New("SQL Server version first line must have space after part number in it: " + v)
	}
	sqlPartNumber = l12[0]
	return sqlVersion, sqlPartNumber, osVersion, nil
}
Esempio n. 7
0
File: builder.go Progetto: mmb/boosh
func parsePortRange(ports string) (uint16, uint16, error) {
	segments := strings.Split(ports, "-")

	fromPortStr := ""
	toPortStr := ""

	if len(segments) == 1 {
		fromPortStr = segments[0]
		toPortStr = fromPortStr
	} else if len(segments) == 2 {
		fromPortStr = segments[0]
		toPortStr = segments[1]
	}

	fromPort, err := strconv.Atoi(strings.Trim(fromPortStr, " "))
	if err != nil {
		return 0, 0, err
	}

	toPort, err := strconv.Atoi(strings.Trim(toPortStr, " "))
	if err != nil {
		return 0, 0, err
	}

	return uint16(fromPort), uint16(toPort), nil
}
Esempio n. 8
0
//initial the configure by .properties file.
func (f *Fcfg) InitWithReader(reader *bufio.Reader) error {
	for {
		//read one line
		bys, err := ReadLine(reader, 10000, false)
		if err != nil {
			break
		}
		//
		line := string(bys)
		line = strings.Trim(line, " ")
		if len(line) < 1 {
			continue
		}
		ps := strings.Split(line, "#")
		if len(ps) < 1 || len(ps[0]) < 1 {
			continue
		}
		line = ps[0]
		ps = strings.SplitN(line, "=", 2)
		if len(ps) < 2 {
			fmt.Println(os.Stderr, "found not value key:", ps[0])
			continue
		}
		key := f.EnvReplace(strings.Trim(ps[0], " "))
		val := f.EnvReplace(strings.Trim(ps[1], " "))
		(*f)[key] = val
	}
	return nil
}
Esempio n. 9
0
//连接服务器
func connectServer() {
	//接通
	conn, err := net.Dial("tcp", "localhost:7777")
	checkError(err)
	fmt.Println("连接成功!\n")
	//输入
	inputReader := bufio.NewReader(os.Stdin)
	fmt.Println("你是谁?")
	name, _ := inputReader.ReadString('\n')
	//
	trimName := strings.Trim(name, "\r\n")
	conn.Write([]byte(trimName + " 接入了\n "))
	fmt.Println("我们来聊天吧!按quit退出")
	for {
		//读一行
		input, _ := inputReader.ReadString('\n')
		trimInput := strings.Trim(input, "\r\n")
		//如果quit就退出
		if trimInput == "quit" {
			fmt.Println("再见")
			conn.Write([]byte(trimName + " 退出了 "))
			return
		}
		//写出来
		_, err = conn.Write([]byte(trimName + " says: " + trimInput))
		go doServerStuff(conn)
	}
}
Esempio n. 10
0
func (s systemctl) parseStatus(sData string, err error) (Status, error) {
	var st Status
	lines := strings.Split(sData, "\n")
	if err != nil {
		errString := err.Error()
		idx := strings.LastIndex(errString, " ")
		exitCode, _ := strconv.Atoi(errString[idx+1 : len(errString)])
		// SystemD status is 3 when service is stopped or does not exists
		if exitCode != 3 {
			return st, err
		}
		for _, line := range lines {
			line = strings.Trim(line, " ")
			// When services does not exists then "Loaded" contains "not-found"
			if strings.HasPrefix(line, "Loaded") && strings.Contains(line, "not-found") {
				return st, err
			}
		}
	}
	for _, line := range lines {
		line = strings.Trim(line, " ")
		if strings.HasPrefix(line, "Active") {
			st.Running = strings.Contains(line, "active (running)")
			if !st.Running {
				break
			}
		} else if strings.HasPrefix(line, "Main PID") {
			pid := line[10:len(line)]
			idx := strings.Index(pid, " ")
			pid = pid[0:idx]
			st.PID, _ = strconv.Atoi(pid)
		}
	}
	return st, nil
}
Esempio n. 11
0
// https://www.hackerrank.com/challenges/angry-professor
func angryprof() {
	t, reader := readFirstIntLine()

	for i := 0; i < t; i++ {
		// Read in N and K
		line, _ := reader.ReadString('\n')
		row := strings.Split(strings.Trim(line, "\n"), " ")
		strconv.Atoi(row[0])
		k, _ := strconv.Atoi(row[1])

		// Read in the students
		line, _ = reader.ReadString('\n')
		var nArrived int
		for _, s := range splitInt(strings.Trim(line, "\n")) {
			if s <= 0 {
				nArrived++
			}
		}

		if nArrived >= k {
			fmt.Println("NO")
		} else {
			fmt.Println("YES")
		}
	}
}
Esempio n. 12
0
// Chain performs all the child derivations necessary to end up with the key
// described with BIP32 notations, eg. m/44'/0'/1'/0/3.
func (k *Key) Chain(chain string) (*Key, error) {
	low := strings.ToLower(chain)
	splits := strings.Split(low, "/")
	m := strings.Trim(splits[0], " ")
	if m == "m" {
		if k.depth != 0 {
			return nil, fmt.Errorf("Origin key isn't a master.")
		}
		if len(splits) == 1 {
			return k, nil
		}
		splits = splits[1:]
	}
	key := k
	for i, s := range splits {
		t := strings.Trim(s, " ")
		var harden uint32
		end := t[len(t)-1]
		if end == 'h' || end == '\'' {
			harden = 0x80000000
			t = t[:len(t)-1]
		}
		u, err := strconv.ParseUint(strings.Trim(t, " "), 10, 32)
		if err != nil {
			return nil, fmt.Errorf("Couldn't parse number at position %d (%s): %v",
				i, t, err)
		}
		key, err = key.Child(uint32(u) + harden)
		if err != nil {
			return nil, fmt.Errorf("Couldn't derive child #%d (%s): %v", i, s, err)
		}
	}
	return key, nil
}
Esempio n. 13
0
func (d *pgDataStore) addCertWithTx(tx *pgx.Tx, c *router.Certificate) error {
	c.Cert = strings.Trim(c.Cert, " \n")
	c.Key = strings.Trim(c.Key, " \n")

	if _, err := tls.X509KeyPair([]byte(c.Cert), []byte(c.Key)); err != nil {
		return httphelper.JSONError{
			Code:    httphelper.ValidationErrorCode,
			Message: "Certificate invalid: " + err.Error(),
		}
	}

	tlsCertSHA256 := sha256.Sum256([]byte(c.Cert))
	if err := tx.QueryRow("select_certificate_by_sha", tlsCertSHA256[:]).Scan(&c.ID, &c.CreatedAt, &c.UpdatedAt); err != nil {
		if err := tx.QueryRow("insert_certificate", c.Cert, c.Key, tlsCertSHA256[:]).Scan(&c.ID, &c.CreatedAt, &c.UpdatedAt); err != nil {
			return err
		}
	}
	for _, rid := range c.Routes {
		if _, err := tx.Exec("delete_route_certificate_by_route_id", rid); err != nil {
			return err
		}
		if _, err := tx.Exec("insert_route_certificate", rid, c.ID); err != nil {
			return err
		}
	}
	return nil
}
Esempio n. 14
0
func InspectJson(ins []string) (out []string) {
	var re []string

	for _, in := range ins {
		if JsonPart != "" {
			in = JsonPart + in
		}
		in = strings.Trim(strings.TrimSpace(in), " ,")
		charopen := 0
		charclose := 0
		for i, r := range in {
			c := string(r)
			if c == "{" {
				charopen += 1
			} else if c == "}" {
				charclose += 1
			}

			if charopen == charclose && (charclose != 0 && charopen != 0) {
				if len(in) == i+1 {
					JsonPart = ""
				} else {
					JsonPart = in[i+1:]
				}
				re = append(re, strings.Trim(strings.TrimSpace(in[:i+1]), " ,"))
				break
			}
			if charopen != charclose || (charclose == 0 && charopen == 0) {
				JsonPart = in
			}
		}

	}
	return re
}
Esempio n. 15
0
func SMSHandler(w http.ResponseWriter, r *http.Request) {
	sms := r.URL.Query().Get("Body")
	sms = strings.Trim(sms, "8575-2838")
	if sms == "" {
		log.Println("Blank body.")
		SendSMS(w, r, "Please send a text with: \"Name\" \"email@address\"")
		return
	}
	info := strings.Fields(sms)
	name := strings.Join(info[:len(info)-1], " ")
	email := info[len(info)-1]
	name = strings.Trim(name, "\"")
	if name == "" {
		log.Println("Blank name.")
		SendSMS(w, r, "Please send a text with: \"Name\" \"email@address\"")
		return
	}
	email = strings.Trim(email, "\"")
	address := fmt.Sprintf("%s <%s>", name, email)
	_, err := mail.ParseAddress(address)
	if err != nil {
		SendSMS(w, r, "Please try again with a valid email address.")
		return
	}
	signup := Signup{Name: name, Email: email, Raw: sms, Timestamp: time.Now()}
	log.Println(signup)
	c := mgoSession.DB("sms_signup").C("signups")
	err = c.Insert(signup)
	if err != nil {
		log.Println(err.Error())
	}
	SendSMS(w, r, fmt.Sprintf("Thanks for signing up, %s!", info[0]))
}
Esempio n. 16
0
func decodeCustomValues(incoming reflect.Value, incomingField reflect.StructField, data string) error {
	/* Incoming is a slice */
	underlyingType := incoming.Type().Elem()

	var delim = " "
	if it := incomingField.Tag.Get("delim"); it != "" {
		delim = it
	}

	var strip = ""
	if it := incomingField.Tag.Get("strip"); it != "" {
		strip = it
	}

	if strip != "" {
		data = strings.Trim(data, strip)
	}

	for _, el := range strings.Split(data, delim) {
		if strip != "" {
			el = strings.Trim(el, strip)
		}

		targetValue := reflect.New(underlyingType)
		err := decodeValue(targetValue.Elem(), incomingField, el)
		if err != nil {
			return err
		}
		incoming.Set(reflect.Append(incoming, targetValue.Elem()))
	}
	return nil
}
Esempio n. 17
0
func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
	visited := make(map[string]bool)
	set.Visit(func(f *flag.Flag) {
		visited[f.Name] = true
	})
	for _, f := range flags {
		parts := strings.Split(f.getName(), ",")
		if len(parts) == 1 {
			continue
		}
		var ff *flag.Flag
		for _, name := range parts {
			name = strings.Trim(name, " ")
			if visited[name] {
				if ff != nil {
					return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
				}
				ff = set.Lookup(name)
			}
		}
		if ff == nil {
			continue
		}
		for _, name := range parts {
			name = strings.Trim(name, " ")
			if !visited[name] {
				copyFlag(name, ff, set)
			}
		}
	}
	return nil
}
Esempio n. 18
0
// parseTags parses all individual tags found within a struct tag.
func (mv *Validator) parseTags(t string) ([]tag, error) {
	r := csv.NewReader(strings.NewReader(t))

	records, err := r.ReadAll()
	if err != nil || len(records) != 1 {
		return []tag{}, ErrUnknownTag
	}
	tl := records[0]

	tags := make([]tag, 0, len(tl))
	for _, i := range tl {
		tg := tag{}
		v := strings.SplitN(i, "=", 2)
		tg.Name = strings.Trim(v[0], " ")
		if tg.Name == "" {
			return []tag{}, ErrUnknownTag
		}
		if len(v) > 1 {
			tg.Param = strings.Trim(v[1], " ")
		}
		var found bool
		if tg.Fn, found = mv.validationFuncs[tg.Name]; !found {
			return []tag{}, ErrUnknownTag
		}
		tags = append(tags, tg)

	}
	return tags, nil
}
Esempio n. 19
0
// AreTimeStampsEqual checks whether the TIMESTAMP in the local dir matches the
// TIMESTAMP in the remote Google Storage dir.
func (gs *GsUtil) AreTimeStampsEqual(localDir, gsDir string) (bool, error) {
	// Get timestamp from the local directory.
	localTimestampPath := filepath.Join(localDir, TIMESTAMP_FILE_NAME)
	fileContent, err := ioutil.ReadFile(localTimestampPath)
	if err != nil {
		return false, fmt.Errorf("Could not read %s: %s", localTimestampPath, err)
	}
	localTimestamp := strings.Trim(string(fileContent), "\n")

	// Get timestamp from the Google Storage directory.
	gsTimestampPath := filepath.Join(gsDir, TIMESTAMP_FILE_NAME)
	respBody, err := gs.GetRemoteFileContents(gsTimestampPath)
	if err != nil {
		return false, err
	}
	defer util.Close(respBody)
	resp, err := ioutil.ReadAll(respBody)
	if err != nil {
		return false, err
	}
	gsTimestamp := strings.Trim(string(resp), "\n")

	// Return the comparison of the two timestamps.
	return localTimestamp == gsTimestamp, nil
}
Esempio n. 20
0
// Takes a string and tokenizes it
func GetFlatTokenList(text string) []Token {
	var tokens []Token
	remaining_text := strings.Trim(text, " \n\t\r\u000a")
	last_iteration_text := remaining_text

	for len(remaining_text) > 0 {
		for pattern, converter := range SOURCE_PATTERNS {
			match := pattern.FindIndex([]byte(remaining_text))
			if match == nil || match[0] != 0 {
				continue
			}
			token := converter(remaining_text[match[0]:match[1]])
			//			fmt.Println("appended ", token)
			tokens = append(tokens, token)
			// cut out the regex match
			remaining_text = remaining_text[match[1]:]
			break
		}
		//		println(remaining_text == "\u000a")
		if last_iteration_text == remaining_text {
			panic("loool... we couldn't find any match for the text")
		}
		last_iteration_text = strings.Trim(remaining_text, " \n\t\r\u000a")
	}
	return tokens
}
Esempio n. 21
0
func UpdateInvertebrate(invertebrate *entity.Invertebrate, db *sql.DB, invertebrate_id string) (sql.Result, error) {
	defer recoverDbPanic()

	stmt := getStatement("invertebrate_update", INVERTEBRATE_UPDATE_QUERY, db)

	if stmt == nil {
		return nil, errors.New("Query could not be created.")
	}

	res, err := stmt.Exec(
		strings.Trim(invertebrate.Name, " \t"),
		strings.Trim(invertebrate.Family, " \t"),
		invertebrate.MaxLength,
		invertebrate.WaterConditions.Ph.Min.V,
		invertebrate.WaterConditions.Ph.Max.V,
		invertebrate.WaterConditions.Temperature.Min.V,
		invertebrate.WaterConditions.Temperature.Max.V,
		invertebrate.WaterConditions.TotalHardness.Min.V,
		invertebrate.WaterConditions.TotalHardness.Max.V,
		invertebrate.WaterConditions.CarbonateHardness.Min.V,
		invertebrate.WaterConditions.CarbonateHardness.Max.V,
		invertebrate.WaterType,
		invertebrate_id,
	)

	return res, err
}
Esempio n. 22
0
func parseTrendingRepos(doc *goquery.Document) []GithubRepo {
	var repos []GithubRepo
	var regStars = regexp.MustCompile("[0-9]+")

	doc.Find("li.repo-list-item").Each(func(i int, s *goquery.Selection) {
		title := strings.Trim(s.Find("h3.repo-list-name a").Text(), "\n\t ")
		title = strings.Replace(title, " ", "", -1)
		title = strings.Replace(title, "\n", "", -1)
		description := strings.Trim(s.Find("p.repo-list-description").Text(), "\n\t ")
		url, _ := s.Find("h3.repo-list-name a").Attr("href")
		url = "https://github.com" + url
		starsString := s.Find("p.repo-list-meta").Text()
		starsString = strings.Replace(starsString, ",", "", -1)
		starsString = regStars.FindString(starsString)
		if starsString == "" {
			starsString = "0"
		}
		stars, _ := strconv.Atoi(starsString)

		repo := GithubRepo{
			Title:       title,
			Description: description,
			Url:         url,
			Stars:       stars,
			Forks:       0,
			Date:        time.Now().UTC().Unix(),
		}

		repos = append(repos, repo)
	})

	return repos
}
Esempio n. 23
0
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
}
Esempio n. 24
0
func TestModeHostname(t *testing.T) {
	cmd := exec.Command(dockerBinary, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")

	out, _, err := runCommandWithOutput(cmd)
	if err != nil {
		t.Fatal(err, out)
	}

	if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
		t.Fatalf("expected 'testhostname', but says: '%s'", actual)
	}

	cmd = exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hostname")

	out, _, err = runCommandWithOutput(cmd)
	if err != nil {
		t.Fatal(err, out)
	}
	hostname, err := os.Hostname()
	if err != nil {
		t.Fatal(err)
	}
	if actual := strings.Trim(out, "\r\n"); actual != hostname {
		t.Fatalf("expected '%s', but says: '%s'", hostname, actual)
	}

	deleteAllContainers()

	logDone("run - hostname and several network modes")
}
Esempio n. 25
0
func parseValidatorTags(tag string) ([]validatorTag, error) {
	if tag == "" {
		return nil, nil
	}

	lst := strings.Split(tag, ",")
	if len(lst) == 0 {
		return nil, nil
	}

	tags := make([]validatorTag, 0, len(lst))
	for _, cfg := range lst {
		v := strings.SplitN(cfg, "=", 2)
		name := strings.Trim(v[0], " \t\r\n")
		cb := validators[name]
		if cb == nil {
			return nil, fmt.Errorf("unknown validator '%v'", name)
		}

		param := ""
		if len(v) == 2 {
			param = strings.Trim(v[1], " \t\r\n")
		}

		tags = append(tags, validatorTag{name: name, cb: cb, param: param})
	}

	return tags, nil
}
Esempio n. 26
0
func TestDnsOptions(t *testing.T) {
	cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")

	out, _, err := runCommandWithOutput(cmd)
	if err != nil {
		t.Fatal(err, out)
	}

	actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
	if actual != "nameserver 127.0.0.1 search mydomain" {
		t.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: '%s'", actual)
	}

	cmd = exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf")

	out, _, err = runCommandWithOutput(cmd)
	if err != nil {
		t.Fatal(err, out)
	}

	actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
	if actual != "nameserver 127.0.0.1" {
		t.Fatalf("expected 'nameserver 127.0.0.1', but says: '%s'", actual)
	}

	logDone("run - dns options")
}
Esempio n. 27
0
func drawsOk(t *testing.T, msg string, n tree.Node, s string) {
	got := strings.Trim(n.Draw(), "\n")
	want := strings.Trim(trim.ReplaceAllString(s, ""), "\n")
	if got != want {
		t.Errorf("%s failed\nexpected:\n[%s]\ngot:\n[%s]\n", msg, want, got)
	}
}
Esempio n. 28
0
File: cleaner.go Progetto: ngs/GoOse
func (this *cleaner) cleanDivs(doc *goquery.Document) *goquery.Document {
	frames := make(map[string]int)
	framesNodes := make(map[string]*list.List)
	divs := doc.Find("div")
	divs.Each(func(i int, s *goquery.Selection) {
		children := s.Children()
		if children.Size() == 0 {
			text := s.Text()
			text = strings.Trim(text, " ")
			text = strings.Trim(text, "\t")
			text = strings.ToLower(text)
			frames[text]++
			if framesNodes[text] == nil {
				framesNodes[text] = list.New()
			}
			framesNodes[text].PushBack(s)
		}
	})
	for text, freq := range frames {
		if freq > 1 {
			selections := framesNodes[text]
			for s := selections.Front(); s != nil; s = s.Next() {
				selection := s.Value.(*goquery.Selection)
				this.config.parser.removeNode(selection)
			}
		}
	}
	return doc
}
Esempio n. 29
0
// TestRunDeviceSymlink checks run with device that follows symlink (#13840)
func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
	if _, err := os.Stat("/dev/zero"); err != nil {
		c.Skip("Host does not have /dev/zero")
	}

	// Create a temporary directory to create symlink
	tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
	c.Assert(err, checker.IsNil)

	defer os.RemoveAll(tmpDir)

	// Create a symbolic link to /dev/zero
	symZero := filepath.Join(tmpDir, "zero")
	err = os.Symlink("/dev/zero", symZero)
	c.Assert(err, checker.IsNil)

	// Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
	// then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
	tmpFile := filepath.Join(tmpDir, "temp")
	err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
	c.Assert(err, checker.IsNil)
	symFile := filepath.Join(tmpDir, "file")
	err = os.Symlink(tmpFile, symFile)
	c.Assert(err, checker.IsNil)

	// md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
	out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))

	// symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
	out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
	c.Assert(err, check.NotNil)
	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
}
Esempio n. 30
0
func insert_new_user(user RegisteringUser) (int, []string) {
	db := connect_sql()
	defer db.Close()
	msg_err := make([]string, 10)
	ret := 0
	// TODO : welcom mail to send
	if user_exist(user.InputMail) {
		msg_err[0] = "Email already used"
		ret = 1
	}
	if !strings.Contains(user.InputMail, "@") {
		msg_err[1] = "Incorrect Email"
		ret = 1
	}
	if user.InputPass != user.InputPassVerif {
		msg_err[2] = "Passwords don't match"
		ret = 1
	}
	//TODO : min lenght not max
	if len(user.InputPseudo) > Pref.max_lenght_pseudo {
		msg_err[3] = "Passwords too short"
		ret = 1
	}
	if ret == 0 {
		cleanpseudo := strings.Trim(strings.ToLower(user.InputPseudo), " ")
		cleanmail := strings.Trim(strings.ToLower(user.InputMail), " ")
		cleanpass := strings.Trim(user.InputPass, " ")
		_, err := db.Exec("INSERT INTO users (pseudo, mail, password) VALUES (?, ?, ?)", cleanpseudo, cleanmail, EncryptPass(cleanpass))
		HandleErrorSql(err)
	}
	return ret, msg_err
}