/
parse_query.go
202 lines (172 loc) · 5.57 KB
/
parse_query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package native
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/m3db/m3/src/query/api/v1/handler"
"github.com/m3db/m3/src/query/api/v1/options"
"github.com/m3db/m3/src/query/executor"
"github.com/m3db/m3/src/query/models"
"github.com/m3db/m3/src/query/parser"
"github.com/m3db/m3/src/query/parser/promql"
"github.com/m3db/m3/src/x/instrument"
xhttp "github.com/m3db/m3/src/x/net/http"
"go.uber.org/zap"
)
const (
// PromParseURL is the url for native prom parse handler, this parses out the
// query and returns a JSON representation of the execution DAG.
PromParseURL = handler.RoutePrefixV1 + "/parse"
// PromParseHTTPMethod is the HTTP method used with this resource.
PromParseHTTPMethod = http.MethodGet
)
// PromParseHandler represents a handler for prometheus parse endpoint.
type promParseHandler struct {
engine executor.Engine
instrumentOpts instrument.Options
}
// NewPromParseHandler returns a new instance of handler.
func NewPromParseHandler(opts options.HandlerOptions) http.Handler {
return &promParseHandler{
engine: opts.Engine(),
instrumentOpts: opts.InstrumentOpts(),
}
}
// FunctionNode is a JSON representation of a function.
type FunctionNode struct {
// Name is the name of the function node.
Name string `json:"name,omitempty"`
// Children are any children this function node has.
Children []FunctionNode `json:"children,omitempty"`
// parents are any parents this node has; this is private since it is only
// used to construct the function node map.
parents []FunctionNode
// node is the actual execution node.
node parser.Node
}
// String prints the string representation of a function node.
func (n FunctionNode) String() string {
var sb strings.Builder
sb.WriteString(n.Name)
if len(n.Children) > 0 {
sb.WriteString(": ")
sb.WriteString(fmt.Sprint(n.Children))
}
return sb.String()
}
type nodeMap map[string]FunctionNode
func (n nodeMap) rootNode() (FunctionNode, error) {
var (
found bool
node FunctionNode
)
for _, v := range n {
if len(v.parents) == 0 {
if found {
return node, fmt.Errorf(
"multiple roots found for map: %s",
fmt.Sprint(n),
)
}
found = true
node = v
}
}
if !found {
return node, fmt.Errorf("no root found for map: %s", fmt.Sprint(n))
}
return node, nil
}
func constructNodeMap(nodes parser.Nodes, edges parser.Edges) (nodeMap, error) {
nodeMap := make(map[string]FunctionNode, len(nodes))
for _, node := range nodes {
name := node.Op.OpType()
nodeMap[string(node.ID)] = FunctionNode{
Name: name,
node: node,
}
}
for _, edge := range edges {
// NB: due to how execution occurs, `parent` and `child` have the opposite
// meaning in the `edge` context compared to the expected lexical reading,
// so they should be swapped here.
parent := string(edge.ChildID)
child := string(edge.ParentID)
parentNode, ok := nodeMap[parent]
if !ok {
return nil, fmt.Errorf("parent node with ID %s not found", parent)
}
childNode, ok := nodeMap[child]
if !ok {
return nil, fmt.Errorf("child node with ID %s not found", child)
}
parentNode.Children = append(parentNode.Children, childNode)
childNode.parents = append(childNode.parents, parentNode)
nodeMap[parent] = parentNode
nodeMap[child] = childNode
}
return nodeMap, nil
}
func parseRootNode(
r *http.Request,
engine executor.Engine,
logger *zap.Logger,
) (FunctionNode, error) {
query, err := parseQuery(r)
if err != nil {
logger.Error("cannot parse query string", zap.Error(err))
return FunctionNode{}, err
}
parseOpts := engine.Options().ParseOptions()
parser, err := promql.Parse(query, time.Second,
models.NewTagOptions(), parseOpts)
if err != nil {
logger.Error("cannot parse query PromQL", zap.Error(err))
return FunctionNode{}, err
}
nodes, edges, err := parser.DAG()
if err != nil {
logger.Error("cannot extract query DAG", zap.Error(err))
return FunctionNode{}, err
}
funcMap, err := constructNodeMap(nodes, edges)
if err != nil {
logger.Error("cannot construct node map", zap.Error(err))
return FunctionNode{}, err
}
root, err := funcMap.rootNode()
if err != nil {
logger.Error("cannot fetch root node", zap.Error(err))
return FunctionNode{}, err
}
return root, nil
}
func (h *promParseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logger := h.instrumentOpts.Logger()
root, err := parseRootNode(r, h.engine, logger)
if err != nil {
xhttp.Error(w, err, http.StatusBadRequest)
return
}
xhttp.WriteJSONResponse(w, root, logger)
}