func testFindAllIndex(t *testing.T, tc *testCase, x *Index, rx *regexp.Regexp, n int) {
	res := x.FindAllIndex(rx, n)
	exp := rx.FindAllStringIndex(tc.source, n)

	// check that the lengths match
	if len(res) != len(exp) {
		t.Errorf("test %q, FindAllIndex %q (n = %d): expected %d results; got %d", tc.name, rx, n, len(exp), len(res))
	}

	// if n >= 0 the number of results is limited --- unless n >= all results,
	// we may obtain different positions from the Index and from regexp (because
	// Index may not find the results in the same order as regexp) => in general
	// we cannot simply check that the res and exp lists are equal

	// check that each result is in fact a correct match and the result is sorted
	for i, r := range res {
		if r[0] < 0 || r[0] > r[1] || len(tc.source) < r[1] {
			t.Errorf("test %q, FindAllIndex %q, result %d (n == %d): illegal match [%d, %d]", tc.name, rx, i, n, r[0], r[1])
		} else if !rx.MatchString(tc.source[r[0]:r[1]]) {
			t.Errorf("test %q, FindAllIndex %q, result %d (n = %d): [%d, %d] not a match", tc.name, rx, i, n, r[0], r[1])
		}
	}

	if n < 0 {
		// all results computed - sorted res and exp must be equal
		for i, r := range res {
			e := exp[i]
			if r[0] != e[0] || r[1] != e[1] {
				t.Errorf("test %q, FindAllIndex %q, result %d: expected match [%d, %d]; got [%d, %d]",
					tc.name, rx, i, e[0], e[1], r[0], r[1])
			}
		}
	}
}
Example #2
0
File: pprof.go Project: Mokolea/go
func (f *file) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
	if f.sym == nil {
		sym, err := f.file.Symbols()
		if err != nil {
			return nil, err
		}
		f.sym = sym
	}
	var out []*plugin.Sym
	for _, s := range f.sym {
		// Ignore a symbol with address 0 and size 0.
		// An ELF STT_FILE symbol will look like that.
		if s.Addr == 0 && s.Size == 0 {
			continue
		}
		if (r == nil || r.MatchString(s.Name)) && (addr == 0 || s.Addr <= addr && addr < s.Addr+uint64(s.Size)) {
			out = append(out, &plugin.Sym{
				Name:  []string{s.Name},
				File:  f.name,
				Start: s.Addr,
				End:   s.Addr + uint64(s.Size) - 1,
			})
		}
	}
	return out, nil
}
Example #3
0
// list is a subcommand to list up snippets.
// It just finds snippet files in the snippet directory and listed them.
func list(c *cli.Context) {
	var pattern *regexp.Regexp
	var err error
	query := c.Args().First()
	if len(query) > 0 {
		pattern, err = regexp.Compile(fmt.Sprintf(".*%s.*", query))
		if err != nil {
			log.Fatal(err)
		}
	}

	err = filepath.Walk(
		conf.SnippetDirectory,
		func(path string, info os.FileInfo, err error) error {
			if info.IsDir() {
				return nil
			}
			rel, err := filepath.Rel(conf.SnippetDirectory, path)

			if pattern != nil {
				if pattern.MatchString(rel) {
					fmt.Println(rel)
				}
				return nil
			}

			fmt.Println(rel)
			return nil
		},
	)

	if err != nil {
		log.Fatal(err)
	}
}
Example #4
0
File: auth.go Project: kamaln7/nbnc
func checkAuth(client <-chan string, result chan<- bool) {
	var (
		attempt int
		data    string

		pass *regexp.Regexp
	)

	pass = regexp.MustCompile(`^(?i)PASS(?-i) ` + opt.Password + `\r?\n?$`)

	attempt = 0
	for data = range client {
		if attempt > AuthAttempts {
			log.Print("Authentication bad, tearing down.")
			result <- false
			return
		}

		if pass.MatchString(data) {
			log.Print("Authentication good, open sesame.")
			result <- true
			return
		}

		attempt++
	}
}
Example #5
0
func parseNetDevStats(r io.Reader, ignore *regexp.Regexp) (map[string]map[string]string, error) {
	scanner := bufio.NewScanner(r)
	scanner.Scan() // skip first header
	scanner.Scan()
	parts := strings.Split(string(scanner.Text()), "|")
	if len(parts) != 3 { // interface + receive + transmit
		return nil, fmt.Errorf("invalid header line in net/dev: %s",
			scanner.Text())
	}

	header := strings.Fields(parts[1])
	netDev := map[string]map[string]string{}
	for scanner.Scan() {
		line := strings.TrimLeft(string(scanner.Text()), " ")
		parts := procNetDevFieldSep.Split(line, -1)
		if len(parts) != 2*len(header)+1 {
			return nil, fmt.Errorf("invalid line in net/dev: %s", scanner.Text())
		}

		dev := parts[0][:len(parts[0])]
		if ignore.MatchString(dev) {
			log.Debugf("Ignoring device: %s", dev)
			continue
		}
		netDev[dev] = map[string]string{}
		for i, v := range header {
			netDev[dev]["receive_"+v] = parts[i+1]
			netDev[dev]["transmit_"+v] = parts[i+1+len(header)]
		}
	}
	return netDev, scanner.Err()
}
Example #6
0
// PruneFrom removes all nodes beneath the lowest node matching dropRx, not including itself.
//
// Please see the example below to understand this method as well as
// the difference from Prune method.
//
// A sample contains Location of [A,B,C,B,D] where D is the top frame and there's no inline.
//
// PruneFrom(A) returns [A,B,C,B,D] because there's no node beneath A.
// Prune(A, nil) returns [B,C,B,D] by removing A itself.
//
// PruneFrom(B) returns [B,C,B,D] by removing all nodes beneath the first B when scanning from the bottom.
// Prune(B, nil) returns [D] because a matching node is found by scanning from the root.
func (p *Profile) PruneFrom(dropRx *regexp.Regexp) {
	pruneBeneath := make(map[uint64]bool)

	for _, loc := range p.Location {
		for i := 0; i < len(loc.Line); i++ {
			if fn := loc.Line[i].Function; fn != nil && fn.Name != "" {
				// Account for leading '.' on the PPC ELF v1 ABI.
				funcName := strings.TrimPrefix(fn.Name, ".")
				// Account for unsimplified names -- trim starting from the first '('.
				if index := strings.Index(funcName, "("); index > 0 {
					funcName = funcName[:index]
				}
				if dropRx.MatchString(funcName) {
					// Found matching entry to prune.
					pruneBeneath[loc.ID] = true
					loc.Line = loc.Line[i:]
					break
				}
			}
		}
	}

	// Prune locs from each Sample
	for _, sample := range p.Sample {
		// Scan from the bottom leaf to the root to find the prune location.
		for i, loc := range sample.Location {
			if pruneBeneath[loc.ID] {
				sample.Location = sample.Location[i:]
				break
			}
		}
	}
}
Example #7
0
func getSuffixMatches(req *http.Request, pattern *regexp.Regexp) bool {
	if httputil.IsGet(req) {
		suffix := httputil.PathSuffix(req)
		return pattern.MatchString(suffix)
	}
	return false
}
Example #8
0
func TestIntegration(t *testing.T) {

	flag.Parse()

	bleve.Config.DefaultIndexType = *indexType
	t.Logf("using index type %s", *indexType)

	var err error
	var datasetRegexp *regexp.Regexp
	if *dataset != "" {
		datasetRegexp, err = regexp.Compile(*dataset)
		if err != nil {
			t.Fatal(err)
		}
	}

	fis, err := ioutil.ReadDir("tests")
	if err != nil {
		t.Fatal(err)
	}
	for _, fi := range fis {
		if datasetRegexp != nil {
			if !datasetRegexp.MatchString(fi.Name()) {
				continue
			}
		}
		if fi.IsDir() {
			t.Logf("Running test: %s", fi.Name())
			runTestDir(t, "tests"+string(filepath.Separator)+fi.Name(), fi.Name())
		}
	}
}
Example #9
0
func validateField(name, cont string, whitelist *regexp.Regexp) error {
	if !whitelist.MatchString(cont) {
		return fmt.Errorf("app description field '%s' contains illegal %q (legal: '%s')", name, cont, whitelist)

	}
	return nil
}
Example #10
0
func (rules *Rules) matches(u string, options map[string]interface{}, generalRe *re.Regexp, domainRequiredRules map[string][]*Rule, rulesWithOptions []*Rule) bool {
	if generalRe != nil && generalRe.MatchString(u) {
		return true
	}

	rls := []*Rule{}
	isrcDomain, ok := options["domain"]
	srcDomain, ok2 := isrcDomain.(string)
	if ok && ok2 && len(domainRequiredRules) > 0 {
		for _, domain := range DomainVariants(srcDomain) {
			if vs, ok := domainRequiredRules[domain]; ok {
				rls = append(rls, vs...)
			}
		}
	}

	rls = append(rls, rulesWithOptions...)

	if !rules.opt.CheckUnsupportedRules {
		for _, rule := range rls {
			if rule.MatchingSupported(options) {
				if rule.MatchURL(u, options) {
					return true
				}
			}
		}
	}

	return false
}
Example #11
0
// Err ensures the error satisfies the given regular expression.
func Err(t Fataler, err error, re *regexp.Regexp, a ...interface{}) {
	if err == nil && re == nil {
		return
	}

	if err == nil && re != nil {
		fatal(cond{
			Fataler:    t,
			Format:     `expected error: "%s" but got a nil error`,
			FormatArgs: []interface{}{re},
			Extra:      a,
		})
		return
	}

	if err != nil && re == nil {
		fatal(cond{
			Fataler:    t,
			Format:     `unexpected error: %s`,
			FormatArgs: []interface{}{err},
			Extra:      a,
		})
		return
	}

	if !re.MatchString(err.Error()) {
		fatal(cond{
			Fataler:    t,
			Format:     `expected error: "%s" but got "%s"`,
			FormatArgs: []interface{}{re, err},
			Extra:      a,
		})
	}
}
func (fc *AfmFontCollection) Select(family, weight, style string, ranges []string) (fontMetrics FontMetrics, err error) {
	if len(ranges) > 0 {
		return nil, errors.New("Named ranges not supported for Type1 fonts.")
	}
	var re *regexp.Regexp
	if re, err = makeFontSelectRegexp(family, weight, style); err != nil {
		return
	}
	if fc.Fonts == nil {
		fc.Fonts = make(map[string]*afm.Font)
	}
	for _, f := range fc.FontInfos {
		if re.MatchString(f.PostScriptName()) {
			font := fc.Fonts[f.Filename]
			if font == nil {
				font, err = afm.LoadFont(f.Filename)
				fc.Fonts[f.Filename] = font
			}
			fontMetrics = font
			return
		}
	}
	err = fmt.Errorf("Font '%s %s %s' not found", family, weight, style)
	return
}
Example #13
0
// Given an IP address and a port number, this function creates a transport address.
//
// INPUT
// - in_ip: IP address.
// - in_port: port number.
//
// OUTPUT
// - The transport address.
// - The error flag.
func MakeTransportAddress(in_ip string, in_port int) (string, error) {
	var ipv4, ipv6 *regexp.Regexp
	var err error

	ipv4, err = regexp.Compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")
	if nil != err {
		panic("Internal error.")
	}

	ipv6, err = regexp.Compile("^[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}$")
	if nil != err {
		panic("Internal error.")
	}

	// Is it IPV4?
	if ipv4.MatchString(in_ip) {
		return fmt.Sprintf("%s:%d", in_ip, in_port), nil
	}

	// Is it IPV6?
	if ipv6.MatchString(in_ip) {
		return fmt.Sprintf("[%s]:%d", in_ip, in_port), nil
	}

	return "", errors.New(fmt.Sprintf("Invalid IP address \"%s\"!", in_ip))
}
Example #14
0
func newWatcher(path string, include, exclude *regexp.Regexp) (*watcher, error) {
	events := make(chan notify.EventInfo, 10)
	ops := make(chan Operation, 10)

	if err := notify.Watch(path+"/...", events, notify.All); err != nil {
		return nil, err
	}

	go func() {
		for ev := range events {
			if include.MatchString(ev.Path()) == false {
				debug(fmt.Sprintf("Skipping: does not match include path: %s", ev.Path()))
				continue
			}

			if exclude.MatchString(ev.Path()) == true {
				debug(fmt.Sprintf("Skipping: does match exclude path: %s", ev.Path()))
				continue
			}

			ops <- Operation{
				Path:      ev.Path(),
				EventInfo: ev,
			}
		}
	}()

	return &watcher{ops: ops, events: events}, nil
}
Example #15
0
func re(ctx *ScalarContext, nArg int) {
	ad := ctx.GetAuxData(0)
	var re *regexp.Regexp
	if ad == nil {
		reused = false
		//println("Compile")
		var err error
		re, err = regexp.Compile(ctx.Text(0))
		if err != nil {
			ctx.ResultError(err.Error())
			return
		}
		ctx.SetAuxData(0, re)
	} else {
		reused = true
		//println("Reuse")
		var ok bool
		if re, ok = ad.(*regexp.Regexp); !ok {
			println(ad)
			ctx.ResultError("AuxData not a regexp")
			return
		}
	}
	m := re.MatchString(ctx.Text(1))
	ctx.ResultBool(m)
}
Example #16
0
func getSuitableAddrs(addrs []*address, v4, v6, linklocal, loopback bool, re *regexp.Regexp, mask *net.IPNet) ([]*address, error) {
	ret := []*address{}
	for _, a := range addrs {
		if a.IsLoopback() && !loopback {
			continue
		}
		if !v6 && a.IsV6() {
			continue
		}
		if !v4 && a.IsV4() {
			continue
		}
		if !linklocal && a.IsLinkLocalUnicast() {
			continue
		}
		if !loopback && a.IsLoopback() {
			continue
		}
		if re != nil {
			if !re.MatchString(a.String()) {
				continue
			}
		}
		if mask != nil {
			if !mask.Contains(a.IP) {
				continue
			}
		}
		ret = append(ret, a)
	}
	if len(ret) == 0 {
		return nil, errors.New("unable to find suitable address")
	}
	return ret, nil
}
Example #17
0
func search(c chan *Trial, target *regexp.Regexp) {
	sequence := uint32(0)
	batch := make([]byte, 1024*4)
	for {
		_, err := rand.Read(batch)
		checkErr(err)
		for i := 0; i < len(batch)-16; i++ {
			trial := &Trial{
				Seed: make([]byte, 16),
			}
			copy(trial.Seed, batch[i:])
			if *ed25519key {
				trial.Key, err = crypto.NewEd25519Key(trial.Seed)
			} else {
				trial.Key, err = crypto.NewECDSAKey(trial.Seed)
			}
			checkErr(err)
			if *ed25519key {
				trial.Id, err = crypto.AccountId(trial.Key, nil)
			} else {
				trial.Id, err = crypto.AccountId(trial.Key, &sequence)
			}
			checkErr(err)
			atomic.AddUint64(&count, 1)
			if target.MatchString(trial.Id.String()) {
				c <- trial
			}
		}
	}
}
Example #18
0
func reduceWithRepoFilters(c *clif.Command, allRepos []*common.Info) ([]*common.Info, error) {

	// determine repo name pattern
	includeRx := regexp.MustCompile(`.`)
	if pattern := c.Option("include").String(); pattern != "" {
		var err error
		if includeRx, err = regexp.Compile(pattern); err != nil {
			return nil, fmt.Errorf("Failed to compile include pattern: %s", err)
		}
	}
	var excludeRx *regexp.Regexp
	if pattern := c.Option("exclude").String(); pattern != "" {
		var err error
		if excludeRx, err = regexp.Compile(pattern); err != nil {
			return nil, fmt.Errorf("Failed to compile exclude pattern: %s", err)
		}
	}

	repos := make([]*common.Info, 0)
	for _, repo := range allRepos {
		if !includeRx.MatchString(repo.Name) {
			Debug(DEBUG3, "Exclude repo %s since not matching include", repo.Name)
			continue
		} else if excludeRx != nil && excludeRx.MatchString(repo.Name) {
			Debug(DEBUG3, "Exclude repo %s since match exclude", repo.Name)
			continue
		}
		repos = append(repos, repo)
	}

	return repos, nil
}
Example #19
0
//broker.handleMessage() gets messages from broker.This() and handles them according
// to the user-provided plugins currently loaded.
func (b *Broker) handleMessage(thingy map[string]interface{}) {
	if b.cbIndex[M] == nil {
		return
	}
	message := new(Event)
	jthingy, _ := json.Marshal(thingy)
	json.Unmarshal(jthingy, message)
	message.Broker = b
	botNamePat := fmt.Sprintf(`^(?:@?%s[:,]?)\s+(?:${1})`, b.Config.Name)
	for _, cbInterface := range b.cbIndex[M] {
		callback := cbInterface.(*MessageCallback)

		Logger.Debug(`Broker:: checking callback: `, callback.ID)
		if callback.SlackChan != `` {
			if callback.SlackChan != message.Channel {
				Logger.Debug(`Broker:: dropping message because chan mismatch: `, callback.ID)
				continue //skip this message because it doesn't match the cb's channel filter
			} else {
				Logger.Debug(`Broker:: channel filter match for: `, callback.ID)
			}
		}
		var r *regexp.Regexp
		if callback.Respond {
			r = regexp.MustCompile(strings.Replace(botNamePat, "${1}", callback.Pattern, 1))
		} else {
			r = regexp.MustCompile(callback.Pattern)
		}
		if r.MatchString(message.Text) {
			match := r.FindAllStringSubmatch(message.Text, -1)[0]
			Logger.Debug(`Broker:: firing callback: `, callback.ID)
			callback.Chan <- PatternMatch{Event: message, Match: match}
		}
	}
}
Example #20
0
// Expand '~'-based homedif from the given path
func ExpandHomedir(s string) (string, error) {
	const (
		slash = string(os.PathSeparator)
		re1   = "~%s"            // regex: /~\//
		re2   = "~([\\w\\-]+)%s" // regex: /~([\w\-]+)\//
	)
	var (
		err error
		re  *regexp.Regexp
		u   *user.User
		rv  string
	)

	if strings.HasPrefix(s, fmt.Sprintf(re1, slash)) {
		u, _ = user.Current()
		rv = fmt.Sprintf("%s", u.HomeDir+s[1:])
		err = nil
	} else if re = regexp.MustCompile(fmt.Sprintf(re2, slash)); re.MatchString(s) {
		uname := re.FindStringSubmatch(s)[0]
		uname = uname[1 : len(uname)-1]
		if u, _ = user.Lookup(uname); u == nil {
			rv = s
			err = nil
		} else {
			rv = u.HomeDir + slash + strings.Join(strings.Split(s, slash)[1:], slash)
			err = nil
		}
	} else if err != nil {
		rv = s
	} else {
		rv = s
		err = nil
	}
	return rv, err
}
Example #21
0
func TestMatchResourceAttr(name, key string, r *regexp.Regexp) TestCheckFunc {
	return func(s *terraform.State) error {
		ms := s.RootModule()
		rs, ok := ms.Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		is := rs.Primary
		if is == nil {
			return fmt.Errorf("No primary instance: %s", name)
		}

		if !r.MatchString(is.Attributes[key]) {
			return fmt.Errorf(
				"%s: Attribute '%s' didn't match %q, got %#v",
				name,
				key,
				r.String(),
				is.Attributes[key])
		}

		return nil
	}
}
Example #22
0
func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) {
	s := GetParam(r, param)
	if !re.MatchString(s) {
		return "", fmt.Errorf(param, "Did not match regular expression %v", re.String())
	}
	return s, nil
}
Example #23
0
// RequireHeader requires a request header to match a value pattern. If the
// header is missing or does not match then the failureStatus is the response
// (e.g. http.StatusUnauthorized). If pathPattern is nil then any path is
// included. If requiredHeaderValue is nil then any value is accepted so long as
// the header is non-empty.
func RequireHeader(
	pathPattern *regexp.Regexp,
	requiredHeaderName string,
	requiredHeaderValue *regexp.Regexp,
	failureStatus int) goa.Middleware {

	return func(h goa.Handler) goa.Handler {
		return func(ctx *goa.Context) (err error) {
			if pathPattern == nil || pathPattern.MatchString(ctx.Request().URL.Path) {
				matched := false
				header := ctx.Request().Header
				headerValue := header.Get(requiredHeaderName)
				if len(headerValue) > 0 {
					if requiredHeaderValue == nil {
						matched = true
					} else {
						matched = requiredHeaderValue.MatchString(headerValue)
					}
				}
				if matched {
					err = h(ctx)
				} else {
					err = ctx.RespondBytes(failureStatus, []byte(http.StatusText(failureStatus)))
				}
			} else {
				err = h(ctx)
			}
			return
		}
	}
}
Example #24
0
// FIXME: too much magic, just do explicit validation of the few
//        fields we have
// verifyStructStringsAgainstWhitelist takes a struct and ensures that
// the given whitelist regexp matches all string fields of the struct
func verifyStructStringsAgainstWhitelist(s interface{}, whitelist *regexp.Regexp) error {
	// check all members of the services struct against our whitelist
	t := reflect.TypeOf(s)
	v := reflect.ValueOf(s)
	for i := 0; i < t.NumField(); i++ {

		// PkgPath means its a unexported field and we can ignore it
		if t.Field(i).PkgPath != "" {
			continue
		}
		if v.Field(i).Kind() == reflect.Ptr {
			vi := v.Field(i).Elem()
			if vi.Kind() == reflect.Struct {
				return verifyStructStringsAgainstWhitelist(vi.Interface(), whitelist)
			}
		}
		if v.Field(i).Kind() == reflect.Struct {
			vi := v.Field(i).Interface()
			return verifyStructStringsAgainstWhitelist(vi, whitelist)
		}
		if v.Field(i).Kind() == reflect.String {
			key := t.Field(i).Name
			value := v.Field(i).String()
			if !whitelist.MatchString(value) {
				return &ErrStructIllegalContent{
					Field:     key,
					Content:   value,
					Whitelist: whitelist.String(),
				}
			}
		}
	}

	return nil
}
Example #25
0
func (g unitGenerator) units(name string, types map[string]typeDef) ([]unitDef, error) {
	var r *regexp.Regexp
	var err error

	t, ok := types[g.From]
	if !ok {
		return nil, fmt.Errorf(".from: '%s' not found in type lookup", g.From)
	}
	if g.Pattern != "" {
		r, err = regexp.Compile(g.Pattern)
		if err != nil {
			return nil, fmt.Errorf(".pattern: %s", err.Error())
		}
	}
	units := make([]unitDef, 0, len(t.Units))
	for _, from := range t.Units {
		if r != nil && !r.MatchString(from.Name) {
			continue
		}
		units = append(units, unitDef{
			Name:       from.Name + g.NameSuffix,
			NamePlural: from.NamePlural + g.NameSuffix,
			Value:      fmt.Sprintf("%s(%s)%s", name, from.Name, g.ValueSuffix),
		})
	}
	return units, nil
}
Example #26
0
func removeTimestampAndRequestIdFromLogLine(line, requestId string, requestIdRegexp *regexp.Regexp) (string, bool) {
	sep := "\t"
	parts := strings.Split(line, sep)

	// assume timestamp is before request_id
	for i, p := range parts {
		if p == requestId {
			hasTimeStamp := i > 0 && timestampRegexp.MatchString(parts[i-1])
			if hasTimeStamp {
				parts = append(parts[:i-1], parts[i+1:]...)
			} else {
				parts = append(parts[:i], parts[i+1:]...)
			}
			return strings.Join(parts, sep), true
		}
	}

	//remove a log line from another request_id
	for _, p := range parts {
		if requestIdRegexp.MatchString(p) {
			return "", false
		}
	}
	return line, true
}
Example #27
0
func (d *xtremIODriver) getLocalDeviceByID() (map[string]string, error) {
	mapDiskByID := make(map[string]string)
	diskIDPath := "/dev/disk/by-id"
	files, err := ioutil.ReadDir(diskIDPath)
	if err != nil {
		return nil, err
	}

	var match1 *regexp.Regexp
	var match2 string

	if d.r.Config.XtremIODeviceMapper || d.r.Config.XtremIOMultipath {
		match1, _ = regexp.Compile(`^dm-name-\w*$`)
		match2 = `^dm-name-\d+`
	} else {
		match1, _ = regexp.Compile(`^wwn-0x\w*$`)
		match2 = `^wwn-0x`
	}

	for _, f := range files {
		if match1.MatchString(f.Name()) {
			naaName := strings.Replace(f.Name(), match2, "", 1)
			naaName = naaName[len(naaName)-16:]
			devPath, _ := filepath.EvalSymlinks(fmt.Sprintf("%s/%s", diskIDPath, f.Name()))
			mapDiskByID[naaName] = devPath
		}
	}
	return mapDiskByID, nil
}
func getNetDevStats(ignore *regexp.Regexp) (map[string]map[string]string, error) {
	netDev := map[string]map[string]string{}

	var ifap, ifa *C.struct_ifaddrs
	if C.getifaddrs(&ifap) == -1 {
		return nil, errors.New("getifaddrs() failed")
	}
	defer C.freeifaddrs(ifap)

	for ifa = ifap; ifa != nil; ifa = ifa.ifa_next {
		if ifa.ifa_addr.sa_family == C.AF_LINK {
			dev := C.GoString(ifa.ifa_name)
			if ignore.MatchString(dev) {
				log.Debugf("Ignoring device: %s", dev)
				continue
			}

			devStats := map[string]string{}
			data := (*C.struct_if_data)(ifa.ifa_data)

			devStats["receive_packets"] = strconv.Itoa(int(data.ifi_ipackets))
			devStats["transmit_packets"] = strconv.Itoa(int(data.ifi_opackets))
			devStats["receive_errs"] = strconv.Itoa(int(data.ifi_ierrors))
			devStats["transmit_errs"] = strconv.Itoa(int(data.ifi_oerrors))
			devStats["receive_bytes"] = strconv.Itoa(int(data.ifi_ibytes))
			devStats["transmit_bytes"] = strconv.Itoa(int(data.ifi_obytes))
			devStats["receive_multicast"] = strconv.Itoa(int(data.ifi_imcasts))
			devStats["transmit_multicast"] = strconv.Itoa(int(data.ifi_omcasts))
			devStats["receive_drop"] = strconv.Itoa(int(data.ifi_iqdrops))
			netDev[dev] = devStats
		}
	}

	return netDev, nil
}
Example #29
0
// RequireHeader requires a request header to match a value pattern. If the
// header is missing or does not match then the failureStatus is the response
// (e.g. http.StatusUnauthorized). If pathPattern is nil then any path is
// included. If requiredHeaderValue is nil then any value is accepted so long as
// the header is non-empty.
func RequireHeader(
	service *goa.Service,
	pathPattern *regexp.Regexp,
	requiredHeaderName string,
	requiredHeaderValue *regexp.Regexp,
	failureStatus int) goa.Middleware {

	return func(h goa.Handler) goa.Handler {
		return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) (err error) {
			if pathPattern == nil || pathPattern.MatchString(req.URL.Path) {
				matched := false
				headerValue := req.Header.Get(requiredHeaderName)
				if len(headerValue) > 0 {
					if requiredHeaderValue == nil {
						matched = true
					} else {
						matched = requiredHeaderValue.MatchString(headerValue)
					}
				}
				if matched {
					err = h(ctx, rw, req)
				} else {
					err = service.Send(ctx, failureStatus, http.StatusText(failureStatus))
				}
			} else {
				err = h(ctx, rw, req)
			}
			return
		}
	}
}
Example #30
0
func (m *Module) AddResponse(reg *regexp.Regexp, f func(*Response), permission permissions.Permission) error {
	name := reg.String()
	wrap := func(message *irc.Message) {
		switch message.Command {
		case "PRIVMSG", "NOTICE":
			nick := message.Server.CurrentNick()
			text := strings.Join(message.Arguments[1:], " ")
			if message.Arguments[0] == nick { //direct privmsg
				if reg.MatchString(strings.Trim(text, " ")) {
					f(&Response{message, text, reg.FindStringSubmatch(text)})
				}
			} else { //asked from channel
				current, err := regexp.Compile("^" + nick + "[ ,;:]")
				if err != nil {
					log.Error("Failed to compile nick regexp: ", err)
				} else if current.MatchString(text) {
					nl := len(nick) + 1
					if len(text) > nl {
						just_text := strings.Trim(text[nl:], " ")
						if reg.MatchString(just_text) {
							f(&Response{message, text, reg.FindStringSubmatch(just_text)})
						}
					}
				}
			}
		}
	}

	if _, ok := m.handlers[name]; ok {
		return errors.New("Response with same regexp already exist's!")
	}

	m.handlers[name] = m.connection.AddHandler(wrap, permission)
	return nil
}