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
|
package mapr
import (
"context"
"errors"
"fmt"
"os"
"sort"
"strconv"
"strings"
"github.com/mimecast/dtail/internal/color"
"github.com/mimecast/dtail/internal/config"
"github.com/mimecast/dtail/internal/io/dlog"
"github.com/mimecast/dtail/internal/io/pool"
"github.com/mimecast/dtail/internal/protocol"
)
// GroupSet represents a map of aggregate sets. The group sets
// are requierd by the "group by" mapr clause, whereas the
// group set map keys are the values of the "group by" arguments.
// E.g. "group by $cid" would create one aggregate set and one map
// entry per customer id.
type GroupSet struct {
sets map[string]*AggregateSet
}
// Internal helper type
type result struct {
groupKey string
values []string
widths []int
orderBy float64
}
// NewGroupSet returns a new empty group set.
func NewGroupSet() *GroupSet {
g := GroupSet{}
g.InitSet()
return &g
}
// String representation of the group set.
func (g *GroupSet) String() string {
return fmt.Sprintf("GroupSet(%v)", g.sets)
}
// InitSet makes the group set empty (initialize).
func (g *GroupSet) InitSet() {
g.sets = make(map[string]*AggregateSet)
}
// GetSet gets a specific aggregate set from the group set.
func (g *GroupSet) GetSet(groupKey string) *AggregateSet {
set, ok := g.sets[groupKey]
if !ok {
set = NewAggregateSet()
g.sets[groupKey] = set
}
return set
}
// Serialize the group set (e.g. to send it over the wire).
func (g *GroupSet) Serialize(ctx context.Context, ch chan<- string) {
for groupKey, set := range g.sets {
set.Serialize(ctx, groupKey, ch)
}
}
// Result returns a nicely formated result of the query from the group set.
func (g *GroupSet) Result(query *Query, rowsLimit int) (string, int, error) {
rows, widths, err := g.result(query, true)
if err != nil {
return "", 0, err
}
if query.Limit != -1 {
rowsLimit = query.Limit
}
sb := pool.BuilderBuffer.Get().(*strings.Builder)
defer pool.RecycleBuilderBuffer(sb)
// Generate header now
lastIndex := len(query.Select) - 1
for i, sc := range query.Select {
format := fmt.Sprintf(" %%%ds ", widths[i])
str := fmt.Sprintf(format, sc.FieldStorage)
if config.Client.TermColorsEnable {
attrs := []color.Attribute{config.Client.TermColors.MaprTable.HeaderAttr}
if sc.FieldStorage == query.OrderBy {
attrs = append(attrs, config.Client.TermColors.MaprTable.HeaderSortKeyAttr)
}
for _, groupBy := range query.GroupBy {
if sc.FieldStorage == groupBy {
attrs = append(attrs, config.Client.TermColors.MaprTable.HeaderGroupKeyAttr)
break
}
}
color.PaintWithAttrs(sb, str,
config.Client.TermColors.MaprTable.HeaderFg,
config.Client.TermColors.MaprTable.HeaderBg,
attrs)
} else {
sb.WriteString(str)
}
if i == lastIndex {
continue
}
if config.Client.TermColorsEnable {
color.PaintWithAttr(sb, protocol.FieldDelimiter,
config.Client.TermColors.MaprTable.HeaderDelimiterFg,
config.Client.TermColors.MaprTable.HeaderDelimiterBg,
config.Client.TermColors.MaprTable.HeaderDelimiterAttr)
} else {
sb.WriteString(protocol.FieldDelimiter)
}
}
sb.WriteString("\n")
for i := 0; i < len(query.Select); i++ {
str := fmt.Sprintf("-%s-", strings.Repeat("-", widths[i]))
if config.Client.TermColorsEnable {
color.PaintWithAttr(sb, str,
config.Client.TermColors.MaprTable.HeaderDelimiterFg,
config.Client.TermColors.MaprTable.HeaderDelimiterBg,
config.Client.TermColors.MaprTable.HeaderDelimiterAttr)
} else {
sb.WriteString(str)
}
if i == lastIndex {
continue
}
if config.Client.TermColorsEnable {
color.PaintWithAttr(sb, protocol.FieldDelimiter,
config.Client.TermColors.MaprTable.HeaderDelimiterFg,
config.Client.TermColors.MaprTable.HeaderDelimiterBg,
config.Client.TermColors.MaprTable.HeaderDelimiterAttr)
} else {
sb.WriteString(protocol.FieldDelimiter)
}
}
sb.WriteString("\n")
// And now write the data
for i, r := range rows {
if i == rowsLimit {
break
}
for j, value := range r.values {
format := fmt.Sprintf(" %%%ds ", widths[j])
str := fmt.Sprintf(format, value)
if config.Client.TermColorsEnable {
color.PaintWithAttr(sb, str,
config.Client.TermColors.MaprTable.DataFg,
config.Client.TermColors.MaprTable.DataBg,
config.Client.TermColors.MaprTable.DataAttr)
} else {
sb.WriteString(str)
}
if j == lastIndex {
continue
}
if config.Client.TermColorsEnable {
color.PaintWithAttr(sb, protocol.FieldDelimiter,
config.Client.TermColors.MaprTable.DelimiterFg,
config.Client.TermColors.MaprTable.DelimiterBg,
config.Client.TermColors.MaprTable.DelimiterAttr)
} else {
sb.WriteString(protocol.FieldDelimiter)
}
}
sb.WriteString("\n")
}
return sb.String(), len(rows), nil
}
func (*GroupSet) writeQueryFile(query *Query) error {
queryFile := fmt.Sprintf("%s.query", query.Outfile)
tmpQueryFile := fmt.Sprintf("%s.tmp", queryFile)
dlog.Common.Debug("Writing query file", queryFile)
fd, err := os.Create(tmpQueryFile)
if err != nil {
return err
}
defer fd.Close()
fd.WriteString(query.RawQuery)
os.Rename(tmpQueryFile, queryFile)
return nil
}
// WriteResult writes the result to an CSV outfile.
func (g *GroupSet) WriteResult(query *Query) error {
if !query.HasOutfile() {
return errors.New("No outfile specified")
}
if err := g.writeQueryFile(query); err != nil {
return err
}
rows, _, err := g.result(query, false)
if err != nil {
return err
}
dlog.Common.Info("Writing outfile", query.Outfile)
tmpOutfile := fmt.Sprintf("%s.tmp", query.Outfile)
fd, err := os.Create(tmpOutfile)
if err != nil {
return err
}
defer fd.Close()
// Generate header now
lastIndex := len(query.Select) - 1
for i, sc := range query.Select {
fd.WriteString(sc.FieldStorage)
if i == lastIndex {
continue
}
fd.WriteString(protocol.CSVDelimiter)
}
fd.WriteString("\n")
// And now write the data
for i, r := range rows {
if i == query.Limit {
break
}
for j, value := range r.values {
fd.WriteString(value)
if j == lastIndex {
continue
}
fd.WriteString(protocol.CSVDelimiter)
}
fd.WriteString("\n")
}
if err := os.Rename(tmpOutfile, query.Outfile); err != nil {
os.Remove(tmpOutfile)
return err
}
return nil
}
// Return a sorted result slice of the query from the group set.
func (g *GroupSet) result(query *Query, gatherWidths bool) ([]result, []int, error) {
var rows []result
widths := make([]int, len(query.Select))
var valueStr string
var value float64
for groupKey, set := range g.sets {
r := result{groupKey: groupKey}
for i, sc := range query.Select {
switch sc.Operation {
case Count:
value = set.FValues[sc.FieldStorage]
valueStr = fmt.Sprintf("%d", int(value))
case Len:
fallthrough
case Sum:
fallthrough
case Min:
fallthrough
case Max:
value = set.FValues[sc.FieldStorage]
valueStr = fmt.Sprintf("%f", value)
case Last:
valueStr = set.SValues[sc.FieldStorage]
value, _ = strconv.ParseFloat(valueStr, 64)
case Avg:
value = set.FValues[sc.FieldStorage] / float64(set.Samples)
valueStr = fmt.Sprintf("%f", value)
default:
return rows, widths, fmt.Errorf("Unknown aggregation method '%v'", sc.Operation)
}
if sc.FieldStorage == query.OrderBy {
r.orderBy = value
}
r.values = append(r.values, valueStr)
if !gatherWidths {
continue
}
if widths[i] < len(sc.FieldStorage) {
widths[i] = len(sc.FieldStorage)
}
if widths[i] < len(valueStr) {
widths[i] = len(valueStr)
}
}
rows = append(rows, r)
}
if query.OrderBy != "" {
if query.ReverseOrder {
sort.SliceStable(rows, func(i, j int) bool {
return rows[i].orderBy < rows[j].orderBy
})
} else {
sort.SliceStable(rows, func(i, j int) bool {
return rows[i].orderBy > rows[j].orderBy
})
}
}
return rows, widths, nil
}
|