2019-12-30 17:08:50 -08:00
|
|
|
package context
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2020-01-09 12:23:05 -08:00
|
|
|
"fmt"
|
2020-05-06 00:29:40 +05:30
|
|
|
"strings"
|
2019-12-30 17:08:50 -08:00
|
|
|
|
2020-01-09 12:23:05 -08:00
|
|
|
jmespath "github.com/jmespath/go-jmespath"
|
2019-12-30 17:08:50 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
//Query the JSON context with JMESPATH search path
|
|
|
|
func (ctx *Context) Query(query string) (interface{}, error) {
|
2020-11-24 17:53:19 -08:00
|
|
|
query = strings.TrimSpace(query)
|
|
|
|
if query == "" {
|
|
|
|
return nil, fmt.Errorf("invalid query (nil)")
|
|
|
|
}
|
|
|
|
|
2019-12-30 17:08:50 -08:00
|
|
|
var emptyResult interface{}
|
2020-02-14 11:59:28 -08:00
|
|
|
// check for white-listed variables
|
2020-11-24 17:53:19 -08:00
|
|
|
if !ctx.isBuiltInVariable(query) {
|
2020-02-14 11:59:28 -08:00
|
|
|
return emptyResult, fmt.Errorf("variable %s cannot be used", query)
|
|
|
|
}
|
|
|
|
|
2019-12-30 17:08:50 -08:00
|
|
|
// compile the query
|
|
|
|
queryPath, err := jmespath.Compile(query)
|
|
|
|
if err != nil {
|
2020-03-17 11:05:20 -07:00
|
|
|
ctx.log.Error(err, "incorrect query", "query", query)
|
2020-01-09 12:23:05 -08:00
|
|
|
return emptyResult, fmt.Errorf("incorrect query %s: %v", query, err)
|
2019-12-30 17:08:50 -08:00
|
|
|
}
|
|
|
|
// search
|
2021-02-01 23:22:19 -08:00
|
|
|
ctx.mutex.RLock()
|
|
|
|
defer ctx.mutex.RUnlock()
|
2019-12-30 17:08:50 -08:00
|
|
|
|
|
|
|
var data interface{}
|
|
|
|
if err := json.Unmarshal(ctx.jsonRaw, &data); err != nil {
|
2020-03-17 11:05:20 -07:00
|
|
|
ctx.log.Error(err, "failed to unmarshal context")
|
2020-01-09 12:23:05 -08:00
|
|
|
return emptyResult, fmt.Errorf("failed to unmarshall context: %v", err)
|
2019-12-30 17:08:50 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
result, err := queryPath.Search(data)
|
|
|
|
if err != nil {
|
2020-03-17 11:05:20 -07:00
|
|
|
ctx.log.Error(err, "failed to search query", "query", query)
|
2020-01-09 12:23:05 -08:00
|
|
|
return emptyResult, fmt.Errorf("failed to search query %s: %v", query, err)
|
2019-12-30 17:08:50 -08:00
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|
2020-02-14 11:59:28 -08:00
|
|
|
|
2020-11-24 17:53:19 -08:00
|
|
|
func (ctx *Context) isBuiltInVariable(variable string) bool {
|
2020-11-24 17:48:54 -08:00
|
|
|
if len(ctx.builtInVars) == 0 {
|
2020-05-06 01:08:49 +05:30
|
|
|
return true
|
|
|
|
}
|
2020-11-24 17:48:54 -08:00
|
|
|
for _, wVar := range ctx.builtInVars {
|
2020-05-06 00:29:40 +05:30
|
|
|
if strings.HasPrefix(variable, wVar) {
|
2020-02-14 11:59:28 -08:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|