-
Notifications
You must be signed in to change notification settings - Fork 8
/
aggregates.go
337 lines (283 loc) · 8.71 KB
/
aggregates.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// VQL functions to deal with aggregates. This is mostly useful with
// group by clause.
// Aggregate functions store state between invocations in a way that
// is compatible with the GROUP BY clause. The state is stored in the
// scope but it is unique to the specific instance of the aggregate
// function. For example consider:
//
// SELECT sum(item=X), sum(item=Y) FROM ... GROUP BY ...
//
// Each instance of sum() will keep its own aggregate constant within
// the scope. Similarly the group by clause will force different
// aggregates to use a different scope context, therefore the result
// will be the sum over each group.
// There are several parts to aggregate support:
// 1. Each aggregate function instance in the AST carries a unique
// ID. This allows the function to store its own state in the
// aggregate context without interference from other instances of
// the same function (e.g. having two count() instaces is OK)
// 2. The scope may contain a reference to an AggregatorCtx
// object. This object manages access to the aggregate
// context. The main method that should be used is Modify() which
// mofidies the context under lock.
// 3. When the scope spawns a child scope, the child scope does not
// have its own AggregatorCtx, instead chasing its parent to find
// one. This allows aggregate functions within the scope to see
// the wider AggregatorCtx which controls the entire query clause.
// 4. When the query runs in an isolated context, the AggregatorCtx
// is recreated at the calling scope. This allows isolated scopes
// to reset the AggregatorCtx. For example, when calling a LET
// defined function, a new context is created.
// 5. If a GROUP BY query, the Grouper will create a new
// AggregatorCtx for each bin. This allows aggregate functions to
// apply on each group separately.
package functions
import (
"context"
"fmt"
"sync/atomic"
"github.com/Velocidex/ordereddict"
"www.velocidex.com/golang/vfilter/arg_parser"
"www.velocidex.com/golang/vfilter/types"
)
var (
// Atomically incremented global id to give aggregate
// functions.
id uint64
)
// All aggregate functions need to embed the Aggregator. Aggregators
// store their state in the scope context so they can retrieve it next
// time they are evaluated.
type Aggregator struct {
id string
}
func (self Aggregator) GetContext(scope types.Scope) (res types.Any, res_pres bool) {
return scope.GetAggregatorCtx().Modify(self.id,
func(previous_value_any types.Any, pres bool) types.Any {
res_pres = pres
return previous_value_any
}), res_pres
}
func (self Aggregator) SetContext(scope types.Scope, value types.Any) {
scope.GetAggregatorCtx().Modify(self.id,
func(previous_value_any types.Any, pres bool) types.Any {
return value
})
}
// Sets a new aggregator if possible
func NewAggregator() Aggregator {
new_id := atomic.AddUint64(&id, 1)
return Aggregator{
id: fmt.Sprintf("id_%v", new_id),
}
}
type _CountFunctionArgs struct {
Items types.Any `vfilter:"optional,field=items,doc=Not used anymore"`
}
type _CountFunction struct {
Aggregator
}
func (self _CountFunction) Info(scope types.Scope, type_map *types.TypeMap) *types.FunctionInfo {
return &types.FunctionInfo{
Name: "count",
Doc: "Counts the items.",
ArgType: type_map.AddType(scope, _CountFunctionArgs{}),
IsAggregate: true,
}
}
// Aggregate functions must be copiable.
func (self _CountFunction) Copy() types.FunctionInterface {
return _CountFunction{
Aggregator: NewAggregator(),
}
}
func (self _CountFunction) Call(
ctx context.Context,
scope types.Scope,
args *ordereddict.Dict) types.Any {
arg := &_CountFunctionArgs{}
err := arg_parser.ExtractArgs(scope, args, arg)
if err != nil {
scope.Log("count: %s", err.Error())
return types.Null{}
}
// Modify the aggregator under lock
return scope.GetAggregatorCtx().Modify(self.id,
func(previous_value_any types.Any, pres bool) types.Any {
count := uint64(0)
if pres {
var ok bool
count, ok = previous_value_any.(uint64)
if !ok {
scope.Log("count: unexpected previous value type %T",
previous_value_any)
return types.Null{}
}
}
return count + 1
})
}
type _SumFunctionArgs struct {
Item int64 `vfilter:"required,field=item"`
}
type _SumFunction struct {
Aggregator
}
// Aggregate functions must be copiable.
func (self _SumFunction) Copy() types.FunctionInterface {
return _SumFunction{
Aggregator: NewAggregator(),
}
}
func (self _SumFunction) Info(scope types.Scope, type_map *types.TypeMap) *types.FunctionInfo {
return &types.FunctionInfo{
Name: "sum",
Doc: "Sums the items.",
ArgType: type_map.AddType(scope, _SumFunctionArgs{}),
IsAggregate: true,
}
}
func (self _SumFunction) Call(
ctx context.Context,
scope types.Scope,
args *ordereddict.Dict) types.Any {
arg := &_SumFunctionArgs{}
err := arg_parser.ExtractArgs(scope, args, arg)
if err != nil {
scope.Log("sum: %s", err.Error())
return types.Null{}
}
return scope.GetAggregatorCtx().Modify(self.id,
func(previous_value_any types.Any, pres bool) types.Any {
sum := int64(0)
if pres {
var ok bool
sum, ok = previous_value_any.(int64)
if !ok {
scope.Log("sum: unexpected previous value type %T", previous_value_any)
return types.Null{}
}
}
sum += arg.Item
return sum
})
}
type _MinFunctionArgs struct {
Item types.LazyExpr `vfilter:"required,field=item"`
}
type _MinFunction struct {
Aggregator
}
// Aggregate functions must be copiable.
func (self _MinFunction) Copy() types.FunctionInterface {
return &_MinFunction{
Aggregator: NewAggregator(),
}
}
func (self _MinFunction) Info(scope types.Scope, type_map *types.TypeMap) *types.FunctionInfo {
return &types.FunctionInfo{
Name: "min",
Doc: "Finds the smallest item in the aggregate.",
ArgType: type_map.AddType(scope, _MinFunctionArgs{}),
IsAggregate: true,
}
}
func (self _MinFunction) Call(
ctx context.Context,
scope types.Scope,
args *ordereddict.Dict) types.Any {
arg := &_MinFunctionArgs{}
err := arg_parser.ExtractArgs(scope, args, arg)
if err != nil {
scope.Log("min: %s", err.Error())
return types.Null{}
}
var min_value types.Any = arg.Item.Reduce(ctx)
return scope.GetAggregatorCtx().Modify(self.id,
func(previous_value_any types.Any, pres bool) types.Any {
if pres && !scope.Lt(min_value, previous_value_any) {
min_value = previous_value_any
}
return min_value
})
}
type _MaxFunction struct {
Aggregator
}
// Aggregate functions must be copiable.
func (self _MaxFunction) Copy() types.FunctionInterface {
return _MaxFunction{
Aggregator: NewAggregator(),
}
}
func (self _MaxFunction) Info(scope types.Scope, type_map *types.TypeMap) *types.FunctionInfo {
return &types.FunctionInfo{
Name: "max",
Doc: "Finds the largest item in the aggregate.",
ArgType: type_map.AddType(scope, _MinFunctionArgs{}),
IsAggregate: true,
}
}
func (self _MaxFunction) Call(
ctx context.Context,
scope types.Scope,
args *ordereddict.Dict) types.Any {
arg := &_MinFunctionArgs{}
err := arg_parser.ExtractArgs(scope, args, arg)
if err != nil {
scope.Log("min: %s", err.Error())
return types.Null{}
}
var max_value types.Any = arg.Item.Reduce(ctx)
return scope.GetAggregatorCtx().Modify(self.id,
func(previous_value_any types.Any, pres bool) types.Any {
if pres && scope.Lt(max_value, previous_value_any) {
max_value = previous_value_any
}
return max_value
})
}
type _EnumeateFunctionArgs struct {
Items types.Any `vfilter:"optional,field=items,doc=The items to enumerate"`
}
type _EnumerateFunction struct {
Aggregator
}
// Aggregate functions must be copiable.
func (self _EnumerateFunction) Copy() types.FunctionInterface {
return _EnumerateFunction{
Aggregator: NewAggregator(),
}
}
func (self _EnumerateFunction) Info(scope types.Scope, type_map *types.TypeMap) *types.FunctionInfo {
return &types.FunctionInfo{
Name: "enumerate",
Doc: "Collect all the items in each group by bin.",
ArgType: type_map.AddType(scope, _EnumeateFunctionArgs{}),
IsAggregate: true,
}
}
func (self _EnumerateFunction) Call(
ctx context.Context,
scope types.Scope,
args *ordereddict.Dict) types.Any {
arg := &_EnumeateFunctionArgs{}
err := arg_parser.ExtractArgs(scope, args, arg)
if err != nil {
scope.Log("enumerate: %s", err.Error())
return types.Null{}
}
return scope.GetAggregatorCtx().Modify(self.id,
func(previous_value_any types.Any, pres bool) types.Any {
var value types.Any
if pres {
previous_value_array, ok := previous_value_any.([]types.Any)
if ok {
value = append(previous_value_array, arg.Items)
}
} else {
value = []types.Any{arg.Items}
}
return value
})
}