| // Copyright 2016 Google LLC | |
| // | |
| // Use of this source code is governed by a BSD-style license that can be | |
| // found in the LICENSE file. | |
| // Package query provides tools for searching over structured keys. | |
| // | |
| // One example of such a structured key is a Trace id. A key is simply a | |
| // string, but with a very specific format. The parameters are serialized so | |
| // that the parameter names appear in alphabetical order, and each name=value | |
| // pair is delimited by a comma. For example, this map: | |
| // | |
| // a := map[string]string{"d": "w", "a": "b", "c": "d"} | |
| // | |
| // Would be serialized as this key: | |
| // | |
| // ,a=b,c=d,d=w, | |
| // | |
| // Structured keys are a serialization of a map[string]string, so duplicate | |
| // parameter names are not allowed. | |
| // | |
| // Structured key parameter names and values are restricted to the following | |
| // chars: | |
| // | |
| // [a-zA-Z0-9._-] | |
| package query | |
| import ( | |
| "errors" | |
| "fmt" | |
| "net/url" | |
| "regexp" | |
| "sort" | |
| "strconv" | |
| "strings" | |
| "go.skia.org/infra/go/paramtools" | |
| "go.skia.org/infra/go/skerr" | |
| "go.skia.org/infra/go/util" | |
| ) | |
| var ( | |
| InvalidChar = regexp.MustCompile(`([^a-zA-Z0-9\._\-])`) | |
| // For trace name format check, and avoid SQL injection attacks. | |
| keyRe = regexp.MustCompile(`^,([^,=;]+=[^,=;]+,)+$`) | |
| // To avoid SQL injection attacks. | |
| paramRe = regexp.MustCompile(`^[^,=;]+$`) | |
| QueryWillNeverMatch = errors.New("Query will never match.") | |
| ) | |
| func cleanWithRegex(s string, regexp *regexp.Regexp) string { | |
| ret := regexp.ReplaceAllLiteralString(s, "_") | |
| if ret == "" { | |
| return "_" | |
| } | |
| return ret | |
| } | |
| // ForceValid ensures that the resulting map will make a valid structured key. | |
| func ForceValid(m map[string]string) map[string]string { | |
| return ForceValidWithRegex(m, InvalidChar) | |
| } | |
| // ForceValidWithRegex ensures that the resulting map will make a valid | |
| // structured key with the given regex. | |
| func ForceValidWithRegex(m map[string]string, regexp *regexp.Regexp) map[string]string { | |
| ret := make(map[string]string, len(m)) | |
| for key, value := range m { | |
| ret[cleanWithRegex(key, regexp)] = cleanWithRegex(value, regexp) | |
| } | |
| return ret | |
| } | |
| // ValidateParamSet validates that all the keys and values in a ParamSet are | |
| // restricted to the right subset of characters. | |
| func ValidateParamSet(ps paramtools.ParamSet) error { | |
| for key, values := range ps { | |
| if !paramRe.MatchString(key) { | |
| return skerr.Fmt("Invalid key in ParamSet: %q", key) | |
| } | |
| for _, value := range values { | |
| if !paramRe.MatchString(value) { | |
| return skerr.Fmt("Invalid value in ParamSet: %q", value) | |
| } | |
| } | |
| } | |
| return nil | |
| } | |
| // IsValid returns true if a key is valid, i.e. if the parameter names are | |
| // in alphabetical order and if the param names and values are restricted to | |
| // valid values. | |
| func IsValid(key string) bool { | |
| if !keyRe.MatchString(key) { | |
| return false | |
| } | |
| parts := strings.Split(key, ",") | |
| if len(parts) < 3 { | |
| return true | |
| } | |
| parts = parts[1 : len(parts)-1] | |
| lastName := "" | |
| keys := []string{} | |
| for _, s := range parts { | |
| pair := strings.Split(s, "=") | |
| if len(pair) != 2 { | |
| return false | |
| } | |
| if lastName == pair[0] { | |
| return false | |
| } | |
| lastName = pair[0] | |
| keys = append(keys, pair[0]) | |
| } | |
| return sort.IsSorted(sort.StringSlice(keys)) | |
| } | |
| // MakeKey returns a structured key from the given map[string]string, or a | |
| // non-nil error if the parameter names or values violate the structured key | |
| // restrictions. | |
| func MakeKey(m map[string]string) (string, error) { | |
| if len(m) == 0 { | |
| return "", fmt.Errorf("Map must have at least one entry.") | |
| } | |
| keys := make([]string, 0, len(m)) | |
| for k := range m { | |
| if !paramRe.MatchString(k) { | |
| return "", fmt.Errorf("Key contains invalid characters: %q", k) | |
| } | |
| keys = append(keys, k) | |
| } | |
| sort.Strings(keys) | |
| ret := "," | |
| for _, k := range keys { | |
| if !paramRe.MatchString(m[k]) { | |
| return "", fmt.Errorf("Value contains invalid characters: %q", m[k]) | |
| } | |
| ret += fmt.Sprintf("%s=%s,", k, m[k]) | |
| } | |
| return ret, nil | |
| } | |
| // MakeKeyFast returns a structured key from the given map[string]string. It | |
| // does no validation on names or values. This is important if you are making | |
| // keys from a large number of go routines, as regexp doesn't handle that case | |
| // very well. See https://github.com/golang/go/issues/8232. | |
| func MakeKeyFast(m map[string]string) (string, error) { | |
| if len(m) == 0 { | |
| return "", skerr.Fmt("Map must have at least one entry.") | |
| } | |
| ret := strings.Builder{} | |
| // Give a heuristic for the size based on the number of entries | |
| // most real-world entries are tens of bytes long, but this is a good | |
| // starting point. | |
| ret.Grow(len(m) * 20) | |
| ret.WriteRune(',') | |
| keys := make([]string, 0, len(m)) | |
| for k := range m { | |
| keys = append(keys, k) | |
| } | |
| sort.Strings(keys) | |
| for _, k := range keys { | |
| ret.WriteString(k) | |
| ret.WriteRune('=') | |
| ret.WriteString(m[k]) | |
| ret.WriteRune(',') | |
| } | |
| return ret.String(), nil | |
| } | |
| // ParseKey parses the structured key, and if valid, returns the parsed values | |
| // as a map[string]string, otherwise is returns a non-nil error. | |
| func ParseKey(key string) (map[string]string, error) { | |
| if !keyRe.MatchString(key) { | |
| return nil, fmt.Errorf("Key is not valid, fails to match regex: %s", key) | |
| } | |
| ret := map[string]string{} | |
| parts := strings.Split(key, ",") | |
| if len(parts) < 3 { | |
| // Maybe should be an error? | |
| return map[string]string{}, nil | |
| } | |
| parts = parts[1 : len(parts)-1] | |
| lastName := "" | |
| keys := []string{} | |
| for _, s := range parts { | |
| pair := strings.Split(s, "=") | |
| if len(pair) != 2 { | |
| return nil, fmt.Errorf("Invalid key=value pair: %s", s) | |
| } | |
| if lastName == pair[0] { | |
| return nil, fmt.Errorf("Duplicate key: %s", s) | |
| } | |
| ret[pair[0]] = pair[1] | |
| lastName = pair[0] | |
| keys = append(keys, pair[0]) | |
| } | |
| if !sort.IsSorted(sort.StringSlice(keys)) { | |
| return nil, fmt.Errorf("Key is not valid, params are unsorted: %v", parts) | |
| } | |
| return ret, nil | |
| } | |
| // ParseKeyFast is like ParseKey but omits much of the validation portions | |
| func ParseKeyFast(key string) (map[string]string, error) { | |
| ret := map[string]string{} | |
| parts := strings.Split(key, ",") | |
| if len(parts) < 3 { | |
| return map[string]string{}, nil | |
| } | |
| parts = parts[1 : len(parts)-1] | |
| for _, s := range parts { | |
| pair := strings.SplitN(s, "=", 2) | |
| if len(pair) != 2 { | |
| return nil, fmt.Errorf("Invalid key=value pair: %s", s) | |
| } | |
| ret[pair[0]] = pair[1] | |
| } | |
| return ret, nil | |
| } | |
| // queryParam represents a query on a particular parameter in a key. | |
| type QueryParam struct { | |
| KeyMatch string // The param key, including the leading "," and trailing "=". | |
| KeyMatchLen int // The length of keyMatch. | |
| MatchAny bool // MatchAny is true if the query matches any value for this key. | |
| Values []string // The potential matches for the value. | |
| Reg *regexp.Regexp // The regexp to match against, if a regexp search. | |
| NegativeValues []string // The potential negative matches for the value. | |
| NegativeReg *regexp.Regexp // The regexp to match against for negative exclusions. | |
| } | |
| // Key returns the parameter key, removing the leading "," and trailing "=". | |
| func (q QueryParam) Key() string { | |
| if len(q.KeyMatch) <= 2 { | |
| return "" | |
| } | |
| return q.KeyMatch[1 : len(q.KeyMatch)-1] | |
| } | |
| // MatchesValue returns true if the given value matches the QueryParam constraints. | |
| func (q QueryParam) MatchesValue(value string) bool { | |
| // 1. Check exclusions (Negative) | |
| if len(q.NegativeValues) > 0 { | |
| if util.In(value, q.NegativeValues) { | |
| return false | |
| } | |
| } | |
| if q.NegativeReg != nil { | |
| if q.NegativeReg.MatchString(value) { | |
| return false | |
| } | |
| } | |
| if q.MatchAny { | |
| return true | |
| } | |
| // 2. Check inclusions (Positive) | |
| // If there are ANY positive constraints (literal or regex), the value must match one of them. | |
| hasPositiveConstraints := len(q.Values) > 0 || q.Reg != nil | |
| if hasPositiveConstraints { | |
| isLiteralMatch := len(q.Values) > 0 && util.In(value, q.Values) | |
| isRegexMatch := q.Reg != nil && q.Reg.MatchString(value) | |
| if !isLiteralMatch && !isRegexMatch { | |
| return false | |
| } | |
| } | |
| return true | |
| } | |
| // Query represents a query against a key, i.e. Query.Matches can return true | |
| // or false if a given key matches the query. For example, this query will find all | |
| // keys that have a value of 565 for 'config' and true for 'debug': | |
| // | |
| // q := New(url.Values{"config": []string{"565"}, "debug": []string{"true"}}) | |
| // | |
| // This will find all keys that have a value of '565' or '8888': | |
| // | |
| // q := New(url.Values{"config": []string{"565", "8888"}}) | |
| // | |
| // If the first parameter value is preceeded with an '!' then the match is negated, | |
| // i.e. this query will match all keys that have a 'config' param, but whose value | |
| // is not '565'. | |
| // | |
| // q := New(url.Values{"config": []string{"!565"}}) | |
| // | |
| // If the parameter value is '*' then the match will match all keys that have | |
| // that parameter name. I.e. this will match all keys that have a parameter | |
| // named 'config', regardless of the value: | |
| // | |
| // q := New(url.Values{"config": []string{"*"}}) | |
| // | |
| // If the parameter value begins with '~' then the rest of the value is interpreted | |
| // as a regular expression. I.e. this will match all keys that have a parameter | |
| // named 'arch' that begin with 'x': | |
| // | |
| // q := New(url.Values{"arch": []string{"~^x"}}) | |
| // | |
| // Here is more complex example that matches all tests that have the 'name' | |
| // parameter with a value of 'desk_nytimes.skp', a 'config' param that does not | |
| // equal '565' or '8888', and has an 'extra_config' parameter of any value. | |
| // | |
| // q := New(url.Values{ | |
| // "name": "desk_nytimes.skp", | |
| // "config": []string{"!565", "8888"}, | |
| // "extra_config": []string{"*"}}) | |
| type Query struct { | |
| // These are in alphabetical order of parameter name. | |
| Params []QueryParam | |
| } | |
| // String returns a minimal string representation of the Query. | |
| func (q *Query) String() string { | |
| ret := []string{} | |
| for _, p := range q.Params { | |
| ret = append(ret, p.Values...) | |
| ret = append(ret, " ") | |
| } | |
| return strings.Join(ret, "") | |
| } | |
| // KeyValueString returns a string in the form of key=[v1, v2] | |
| // representing the query. | |
| func (q *Query) KeyValueString() string { | |
| sb := strings.Builder{} | |
| for _, p := range q.Params { | |
| sb.WriteString(fmt.Sprintf("%s%s", p.KeyMatch[1:], p.Values)) | |
| } | |
| return sb.String() | |
| } | |
| // NewFromString creates a Query from the given string, which is formatted as a URL query. | |
| func NewFromString(s string) (*Query, error) { | |
| values, err := url.ParseQuery(s) | |
| if err != nil { | |
| return nil, err | |
| } | |
| return New(values) | |
| } | |
| // New creates a Query from the given url.Values. It represents a query to be | |
| // used against keys. | |
| func New(q url.Values) (*Query, error) { | |
| keys := make([]string, 0, len(q)) | |
| for k := range q { | |
| keys = append(keys, k) | |
| } | |
| sort.Strings(keys) | |
| params := make([]QueryParam, 0, len(q)) | |
| for _, key := range keys { | |
| param, err := parseQueryParam(key, q[key]) | |
| if err != nil { | |
| return nil, err | |
| } | |
| params = append(params, param) | |
| } | |
| return &Query{Params: params}, nil | |
| } | |
| func parseQueryParam(key string, keyValues []string) (QueryParam, error) { | |
| keyMatch := "," + key + "=" | |
| matchAny := false | |
| values := []string{} | |
| negativeValues := []string{} | |
| var posRegs []string | |
| var negRegs []string | |
| for _, v := range keyValues { | |
| if v == "" { | |
| return QueryParam{}, fmt.Errorf("Invalid query") | |
| } | |
| if v == "*" { | |
| matchAny = true | |
| continue | |
| } | |
| isNeg := strings.HasPrefix(v, "!") | |
| clean := v | |
| if isNeg { | |
| clean = v[1:] | |
| } | |
| if strings.HasPrefix(clean, "~") { | |
| regexBody := clean[1:] | |
| if _, err := regexp.Compile(regexBody); err != nil { | |
| return QueryParam{}, fmt.Errorf("Error compiling regexp %q: %s", regexBody, err) | |
| } | |
| if isNeg { | |
| negRegs = append(negRegs, regexBody) | |
| } else { | |
| posRegs = append(posRegs, regexBody) | |
| } | |
| } else { | |
| if isNeg { | |
| negativeValues = append(negativeValues, clean) | |
| } else { | |
| values = append(values, clean) | |
| } | |
| } | |
| } | |
| var reg *regexp.Regexp | |
| if len(posRegs) > 0 { | |
| var err error | |
| reg, err = regexp.Compile("(" + strings.Join(posRegs, ")|(") + ")") | |
| if err != nil { | |
| return QueryParam{}, fmt.Errorf("Error compiling combined positive regex: %s", err) | |
| } | |
| } | |
| var negativeReg *regexp.Regexp | |
| if len(negRegs) > 0 { | |
| var err error | |
| negativeReg, err = regexp.Compile("(" + strings.Join(negRegs, ")|(") + ")") | |
| if err != nil { | |
| return QueryParam{}, fmt.Errorf("Error compiling combined negative regex: %s", err) | |
| } | |
| } | |
| return QueryParam{ | |
| KeyMatch: keyMatch, | |
| KeyMatchLen: len(keyMatch), | |
| MatchAny: matchAny, | |
| Values: values, | |
| Reg: reg, | |
| NegativeValues: negativeValues, | |
| NegativeReg: negativeReg, | |
| }, nil | |
| } | |
| // Empty returns true of the Query is empty, i.e. it will match any trace. | |
| func (q *Query) Empty() bool { | |
| return len(q.Params) == 0 | |
| } | |
| // Matches returns true if the given structured key matches the query. | |
| func (q *Query) Matches(s string) bool { | |
| // Search forward in the given structured key. Since q.params are in | |
| // alphabetical order and structured keys have their params in alphabetical | |
| // order we can always search forward in the structured key, i.e. once | |
| // we've matched to a certain index in the string we can shorten the string | |
| // and only search the remaining chars. | |
| for _, part := range q.Params { | |
| // First find the key. | |
| keyIndex := strings.Index(s, part.KeyMatch) | |
| if keyIndex == -1 { | |
| // If there is no key, check if there are any positive constraints. | |
| // If there are none, then this key is not required and the query | |
| // still matches. Otherwise, it doesn't match (note: it means missing key | |
| // does NOT match the wildcard '*'). | |
| hasPositiveConstraints := len(part.Values) > 0 || part.Reg != nil || part.MatchAny | |
| if !hasPositiveConstraints { | |
| continue | |
| } | |
| return false | |
| } | |
| // Truncate to the key. | |
| s = s[keyIndex+part.KeyMatchLen:] | |
| // Extract the value string. | |
| valueIndex := strings.Index(s, ",") | |
| value := s[:valueIndex] | |
| if !part.MatchesValue(value) { | |
| return false | |
| } | |
| // Truncate to the value. | |
| s = s[valueIndex:] | |
| } | |
| return true | |
| } | |
| // appendRegexForFilter will attach a regex to 'ret' for every value in | |
| // 'values' that matches the given 'filter'. | |
| func appendRegexForFilter(keyIndex string, values []string, part QueryParam, ret *[]string, filter func(string) bool) error { | |
| toBeORd := []string{} | |
| for index, value := range values { | |
| if filter(value) { | |
| toBeORd = append(toBeORd, fmt.Sprintf(`(,%s=%s\b)`, keyIndex, strconv.Itoa(index))) | |
| } | |
| } | |
| if len(toBeORd) == 0 { | |
| return QueryWillNeverMatch | |
| } | |
| *ret = append(*ret, "(", strings.Join(toBeORd, "|"), ").*") | |
| return nil | |
| } | |
| // appendValueForFilter will return the values that matches the given 'filter'. | |
| func appendValueForFilter(key string, values []string, part QueryParam, ret *paramtools.ParamSet, filter func(string) bool) error { | |
| toBeORd := []string{} | |
| for _, value := range values { | |
| if filter(value) { | |
| toBeORd = append(toBeORd, value) | |
| } | |
| } | |
| if len(toBeORd) == 0 { | |
| return QueryWillNeverMatch | |
| } | |
| (*ret)[key] = toBeORd | |
| return nil | |
| } | |
| // QueryPlan returns a paramtools.ParamSet that can be used run a query using | |
| // trace indices. | |
| // | |
| // That is, if you have a Params: | |
| // | |
| // Params{"config":"8888", "arch":"x86"} | |
| // | |
| // And a ParamSet: | |
| // | |
| // ps := ¶mtools.ParamSet{ | |
| // ParamSet: paramtools.ParamSet{ | |
| // "config": []string{"565", "8888", "gpu"}, | |
| // "arch": []string{"x86", "arm", "riscv"}, | |
| // "foo": []string{"bar"}, | |
| // }, | |
| // } | |
| // | |
| // It would return the ParamSet: | |
| // | |
| // ParamSet{ | |
| // "config": ["8888"], | |
| // "arch": ["x86"], | |
| // } | |
| // | |
| // Then a query of the form: | |
| // | |
| // url.Values{"arch": []string{"x86", "risc-v"}, "config": []string{"*"}} | |
| // | |
| // Would return: | |
| // | |
| // ParamSet{ | |
| // "arch": ["x86", "risc-v"], | |
| // "config": ["8888", "565", "gpu"], | |
| // } | |
| func (q *Query) QueryPlan(ps paramtools.ReadOnlyParamSet) (paramtools.ParamSet, error) { | |
| ret := paramtools.NewParamSet() | |
| for _, part := range q.Params { | |
| partKey := part.Key() | |
| values, ok := ps[partKey] | |
| if !ok { | |
| return nil, skerr.Fmt("Unknown key for paramset: %s", partKey) | |
| } | |
| var err error = nil | |
| // Filter logic must match Matches() | |
| err = appendValueForFilter(partKey, values, part, &ret, func(value string) bool { | |
| return part.MatchesValue(value) | |
| }) | |
| if err != nil { | |
| return nil, err | |
| } | |
| continue | |
| } | |
| return ret, nil | |
| } |