This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 62
/
filters.go
271 lines (240 loc) · 9.04 KB
/
filters.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// Util around parsing request filters
package util
import (
"context"
"regexp"
"strconv"
"strings"
"time"
"github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/core"
"github.com/flyteorg/flytestdlib/logger"
"github.com/flyteorg/flyteadmin/pkg/errors"
"google.golang.org/grpc/codes"
"fmt"
"github.com/flyteorg/flyteadmin/pkg/common"
"github.com/flyteorg/flyteadmin/pkg/manager/impl/shared"
)
const (
filterExpressionSeperator = "+"
listValueSeparator = ";"
)
// Matches filters of the form `func(field,value)` or `func(field, value)`
var filterRegex = regexp.MustCompile(`(.+)\((.+),\s?(.+)\)`)
// InlineFilter parsing consts. For example, matching on the filter string "contains(Name, foo)"
// will return a slice consisting of: ["contains(Name, foo)", "contains", "Name", "foo"]
const (
funcMatchIndex = 1
fieldMatchIndex = 2
valueMatchIndex = 3
expectedMatchGroupLength = 4
)
var timestampFields = map[string]bool{
"CreatedAt": true,
"UpdatedAt": true,
"DeletedAt": true,
"StartedAt": true,
}
var durationFields = map[string]bool{
"duration": true,
}
const filterFieldEntityPrefixFmt = "%s."
const secondsFormat = "%vs"
var filterFieldEntityPrefix = map[string]common.Entity{
"task": common.Task,
"workflow": common.Workflow,
"launch_plan": common.LaunchPlan,
"execution": common.Execution,
"node_execution": common.NodeExecution,
"task_execution": common.TaskExecution,
"entities": common.NamedEntity,
"named_entity_metadata": common.NamedEntityMetadata,
"project": common.Project,
}
func parseField(field string, primaryEntity common.Entity) (common.Entity, string) {
for prefix, entity := range filterFieldEntityPrefix {
otherEntityPrefix := fmt.Sprintf(filterFieldEntityPrefixFmt, prefix)
if strings.HasPrefix(field, otherEntityPrefix) {
// Strip the referenced entity prefix from the field name.
// e.g. workflow_name becomes simply "name"
return entity, field[len(otherEntityPrefix):]
}
}
return primaryEntity, field
}
func parseRepeatedValues(parsedValues string) []string {
return strings.Split(parsedValues, listValueSeparator)
}
// Handles parsing repeated values and non-string values such as time fields.
func prepareValues(field string, values []string) (interface{}, error) {
preparedValues := make([]interface{}, len(values))
if isTimestampField := timestampFields[field]; isTimestampField {
for idx, value := range values {
timestamp, err := time.Parse(time.RFC3339Nano, value)
if err != nil {
return nil, errors.NewFlyteAdminErrorf(codes.InvalidArgument,
"Timestamp %s must conform to RFC3339 Nano spec", value)
}
preparedValues[idx] = timestamp
}
} else if isDurationField := durationFields[strings.ToLower(field)]; isDurationField {
for idx, value := range values {
floatValue, err := strconv.ParseFloat(value, 64)
if err == nil {
// The value is an float. By default purely float values are assumed to represent durations in seconds.
value = fmt.Sprintf(secondsFormat, floatValue)
}
duration, err := time.ParseDuration(value)
if err != nil {
return nil, errors.NewFlyteAdminErrorf(codes.InvalidArgument,
"Failed to parse duration [%s]", value)
}
preparedValues[idx] = duration
}
} else {
for idx, value := range values {
preparedValues[idx] = value
}
}
if len(preparedValues) == 1 {
return preparedValues[0], nil
}
return preparedValues, nil
}
func ParseFilters(filterParams string, primaryEntity common.Entity) ([]common.InlineFilter, error) {
// Multiple filters can be appended as URI-escaped strings joined by filterExpressionSeperator
filterExpressions := strings.Split(filterParams, filterExpressionSeperator)
parsedFilters := make([]common.InlineFilter, 0)
for _, filterExpression := range filterExpressions {
// Parse string expression
matches := filterRegex.FindStringSubmatch(filterExpression)
if len(matches) != expectedMatchGroupLength {
// Poorly formatted filter string doesn't match expected regex.
return nil, shared.GetInvalidArgumentError(shared.Filters)
}
referencedEntity, field := parseField(matches[fieldMatchIndex], primaryEntity)
// Parse and transform values
parsedValues := parseRepeatedValues(matches[valueMatchIndex])
preparedValues, err := prepareValues(field, parsedValues)
if err != nil {
return nil, err
}
// Create InlineFilter object.
filter, err := common.NewInlineFilter(referencedEntity, matches[funcMatchIndex], field, preparedValues)
if err != nil {
return nil, err
}
parsedFilters = append(parsedFilters, filter)
}
return parsedFilters, nil
}
func GetSingleValueEqualityFilter(entity common.Entity, field, value string) (common.InlineFilter, error) {
return common.NewSingleValueFilter(entity, common.Equal, field, value)
}
type FilterSpec struct {
// All of these fields are optional (although they should not *all* be empty).
Project string
Domain string
Name string
RequestFilters string
}
// Returns equality filters initialized for identifier attributes (project, domain & name)
// which can be optionally specified in requests.
func getIdentifierFilters(entity common.Entity, spec FilterSpec) ([]common.InlineFilter, error) {
filters := make([]common.InlineFilter, 0)
if spec.Project != "" {
projectFilter, err := GetSingleValueEqualityFilter(entity, shared.Project, spec.Project)
if err != nil {
return nil, err
}
filters = append(filters, projectFilter)
}
if spec.Domain != "" {
domainFilter, err := GetSingleValueEqualityFilter(entity, shared.Domain, spec.Domain)
if err != nil {
return nil, err
}
filters = append(filters, domainFilter)
}
if spec.Name != "" {
nameFilter, err := GetSingleValueEqualityFilter(entity, shared.Name, spec.Name)
if err != nil {
return nil, err
}
filters = append(filters, nameFilter)
}
return filters, nil
}
func AddRequestFilters(requestFilters string, primaryEntity common.Entity, existingFilters []common.InlineFilter) (
[]common.InlineFilter, error) {
if requestFilters == "" {
return existingFilters, nil
}
var additionalFilters []common.InlineFilter
additionalFilters, err := ParseFilters(requestFilters, primaryEntity)
if err != nil {
return nil, err
}
updatedFilters := append(existingFilters, additionalFilters...)
return updatedFilters, nil
}
// Consolidates request params and filters to a single list of filters. This consolidation is necessary since the db is
// agnostic to required request parameters and additional filter arguments.
func GetDbFilters(spec FilterSpec, primaryEntity common.Entity) ([]common.InlineFilter, error) {
filters, err := getIdentifierFilters(primaryEntity, spec)
if err != nil {
return nil, err
}
// Append any request filters.
if spec.RequestFilters != "" {
filters, err = AddRequestFilters(spec.RequestFilters, primaryEntity, filters)
if err != nil {
return nil, err
}
}
return filters, nil
}
func GetWorkflowExecutionIdentifierFilters(
ctx context.Context, workflowExecutionIdentifier core.WorkflowExecutionIdentifier) ([]common.InlineFilter, error) {
identifierFilters := make([]common.InlineFilter, 3)
identifierProjectFilter, err := GetSingleValueEqualityFilter(
common.Execution, shared.Project, workflowExecutionIdentifier.Project)
if err != nil {
logger.Warningf(ctx, "Failed to create execution identifier filter for project: %s with identifier [%+v]",
workflowExecutionIdentifier.Project, workflowExecutionIdentifier)
return nil, err
}
identifierFilters[0] = identifierProjectFilter
identifierDomainFilter, err := GetSingleValueEqualityFilter(
common.Execution, shared.Domain, workflowExecutionIdentifier.Domain)
if err != nil {
logger.Warningf(ctx, "Failed to create execution identifier filter for domain: %s with identifier [%+v]",
workflowExecutionIdentifier.Domain, workflowExecutionIdentifier)
return nil, err
}
identifierFilters[1] = identifierDomainFilter
identifierNameFilter, err := GetSingleValueEqualityFilter(
common.Execution, shared.Name, workflowExecutionIdentifier.Name)
if err != nil {
logger.Warningf(ctx, "Failed to create execution identifier filter for domain: %s with identifier [%+v]",
workflowExecutionIdentifier.Name, workflowExecutionIdentifier)
return nil, err
}
identifierFilters[2] = identifierNameFilter
return identifierFilters, nil
}
// All inputs to this function must be validated.
func GetNodeExecutionIdentifierFilters(
ctx context.Context, nodeExecutionIdentifier core.NodeExecutionIdentifier) ([]common.InlineFilter, error) {
workflowExecutionIdentifierFilters, err :=
GetWorkflowExecutionIdentifierFilters(ctx, *nodeExecutionIdentifier.ExecutionId)
if err != nil {
return nil, err
}
nodeIDFilter, err := GetSingleValueEqualityFilter(
common.NodeExecution, shared.NodeID, nodeExecutionIdentifier.NodeId)
if err != nil {
logger.Warningf(ctx, "Failed to create node execution identifier filter for node id: %s with identifier [%+v]",
nodeExecutionIdentifier.NodeId, nodeExecutionIdentifier)
}
return append(workflowExecutionIdentifierFilters, nodeIDFilter), nil
}