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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
|
package server
import (
"context"
"strings"
"sync"
"time"
"github.com/mimecast/dtail/internal"
"github.com/mimecast/dtail/internal/config"
"github.com/mimecast/dtail/internal/io/dlog"
"github.com/mimecast/dtail/internal/io/line"
"github.com/mimecast/dtail/internal/mapr"
"github.com/mimecast/dtail/internal/mapr/logformat"
"github.com/mimecast/dtail/internal/protocol"
)
// Aggregate is for aggregating mapreduce data on the DTail server side.
type Aggregate struct {
done *internal.Done
// NextLinesCh can be used to use a new line ch.
NextLinesCh chan chan *line.Line
linesCh chan *line.Line
// Hostname of the current server (used to populate $hostname field).
hostname string
// Signals to serialize data.
serialize chan struct{}
// The mapr query
query *mapr.Query
// The mapr log format parser
parser logformat.Parser
// mu protects concurrent access to channel switching
mu sync.Mutex
}
// NewAggregate return a new server side aggregator.
func NewAggregate(queryStr string) (*Aggregate, error) {
query, err := mapr.NewQuery(queryStr)
if err != nil {
return nil, err
}
fqdn, err := config.Hostname()
if err != nil {
dlog.Server.Error(err)
}
s := strings.Split(fqdn, ".")
var parserName string
switch query.LogFormat {
case "":
parserName = config.Server.MapreduceLogFormat
if query.Table == "" {
parserName = "generic"
}
default:
parserName = query.LogFormat
}
dlog.Server.Info("Creating log format parser", parserName)
logParser, err := logformat.NewParser(parserName, query)
if err != nil {
dlog.Server.Error("Could not create log format parser. Falling back to 'generic'", err)
if logParser, err = logformat.NewParser("generic", query); err != nil {
dlog.Server.FatalPanic("Could not create log format parser", err)
}
}
return &Aggregate{
done: internal.NewDone(),
NextLinesCh: make(chan chan *line.Line, 10000), // Increased buffer for high concurrency
serialize: make(chan struct{}),
hostname: s[0],
query: query,
parser: logParser,
}, nil
}
// Shutdown the aggregation engine.
func (a *Aggregate) Shutdown() {
a.done.Shutdown()
}
// Start an aggregation.
func (a *Aggregate) Start(ctx context.Context, maprMessages chan<- string) {
myCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
select {
case <-myCtx.Done():
a.done.Shutdown()
case <-a.done.Done():
cancel()
}
}()
fieldsCh := a.fieldsFromLines(myCtx)
// Add fields (e.g. via 'set' clause)
if len(a.query.Set) > 0 {
fieldsCh = a.setAdditionalFields(myCtx, fieldsCh)
}
// Periodically pre-aggregate data every a.query.Interval seconds.
go a.aggregateTimer(myCtx)
a.aggregateAndSerialize(myCtx, fieldsCh, maprMessages)
}
func (a *Aggregate) aggregateTimer(ctx context.Context) {
interval := a.query.Interval
if interval <= 0 {
interval = time.Second
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
a.Serialize(ctx)
case <-ctx.Done():
return
}
}
}
func (a *Aggregate) nextLine() (l *line.Line, ok bool, noMoreChannels bool) {
dlog.Server.Trace("nextLine.enter", l, ok, noMoreChannels)
// Protect channel operations with mutex to prevent race conditions
a.mu.Lock()
defer a.mu.Unlock()
select {
case l, ok = <-a.linesCh:
if !ok {
// Channel is closed, go to next channel.
select {
case a.linesCh = <-a.NextLinesCh:
default:
noMoreChannels = true
}
}
default:
// No new line from current lines channel. Try next one.
select {
case newLinesCh := <-a.NextLinesCh:
oldLinesCh := a.linesCh
a.linesCh = newLinesCh
// Ensure the old channel is fully drained before recycling to prevent data mixing
go func(oldCh chan *line.Line) {
// First, drain any remaining lines from the old channel
drained := 0
drainLoop:
for {
select {
case l, ok := <-oldCh:
if !ok {
// Channel is closed, safe to recycle
break drainLoop
}
if l != nil {
l.Recycle()
drained++
}
default:
// No more lines to drain immediately
break drainLoop
}
}
if drained > 0 {
dlog.Server.Debug("Drained", drained, "lines from recycled channel")
}
// Now safely recycle the drained channel
timer := time.NewTimer(5 * time.Second)
defer timer.Stop()
select {
case a.NextLinesCh <- oldCh:
case <-timer.C:
dlog.Server.Warn("Timeout: failed to put channel back, NextLinesCh might be full")
}
}(oldLinesCh)
default:
// No new lines channel found.
}
}
dlog.Server.Trace("nextLine.exit", l, ok, noMoreChannels)
return
}
func (a *Aggregate) fieldsFromLines(ctx context.Context) <-chan map[string]string {
fieldsCh := make(chan map[string]string)
go func() {
defer close(fieldsCh)
// Gather first lines channel (first input file)
a.mu.Lock()
select {
case a.linesCh = <-a.NextLinesCh:
case <-ctx.Done():
a.mu.Unlock()
return
}
a.mu.Unlock()
for {
select {
case <-ctx.Done():
return
default:
}
// Gather first lines channel (first input file)
line, ok, noMoreChannels := a.nextLine()
if !ok {
if noMoreChannels {
return
}
time.Sleep(time.Millisecond * 100)
continue
}
if err := a.fieldFromLine(ctx, line, fieldsCh); err != nil {
dlog.Server.Error(err)
}
}
}()
return fieldsCh
}
func (a *Aggregate) fieldFromLine(ctx context.Context, line *line.Line,
fieldsCh chan<- map[string]string) error {
maprLine := strings.TrimSpace(line.Content.String())
// after recycling it, don't use line object anymore!!!
line.Recycle()
fields, err := a.parser.MakeFields(maprLine)
if err != nil {
// Should fields be ignored anyway?
if err != logformat.ErrIgnoreFields {
return err
}
return nil
}
if !a.query.WhereClause(fields) {
return nil
}
select {
case fieldsCh <- fields:
case <-ctx.Done():
}
return nil
}
func (a *Aggregate) setAdditionalFields(ctx context.Context,
fieldsCh <-chan map[string]string) <-chan map[string]string {
newFieldsCh := make(chan map[string]string)
go func() {
defer close(newFieldsCh)
for {
fields, ok := <-fieldsCh
if !ok {
return
}
if err := a.query.SetClause(fields); err != nil {
dlog.Server.Error(err)
}
select {
case newFieldsCh <- fields:
case <-ctx.Done():
}
}
}()
return newFieldsCh
}
func (a *Aggregate) aggregateAndSerialize(ctx context.Context,
fieldsCh <-chan map[string]string, maprMessages chan<- string) {
group := mapr.NewGroupSet()
serialize := func() {
dlog.Server.Info("Serializing mapreduce result")
group.Serialize(ctx, maprMessages)
group = mapr.NewGroupSet()
}
for {
select {
case fields, ok := <-fieldsCh:
if !ok {
serialize()
return
}
a.aggregate(group, fields)
case <-a.serialize:
serialize()
case <-ctx.Done():
return
}
}
}
func (a *Aggregate) aggregate(group *mapr.GroupSet, fields map[string]string) {
var sb strings.Builder
for i, field := range a.query.GroupBy {
if i > 0 {
sb.WriteString(protocol.AggregateGroupKeyCombinator)
}
if val, ok := fields[field]; ok {
sb.WriteString(val)
}
}
groupKey := sb.String()
set := group.GetSet(groupKey)
var addedSample bool
for _, sc := range a.query.Select {
if val, ok := fields[sc.Field]; ok {
if err := set.Aggregate(sc.FieldStorage, sc.Operation, val, false); err != nil {
dlog.Server.Error(err)
continue
}
addedSample = true
}
}
if addedSample {
set.Samples++
return
}
dlog.Server.Trace("Aggregated data locally without adding new samples")
}
// Serialize all the aggregated data.
func (a *Aggregate) Serialize(ctx context.Context) {
select {
case a.serialize <- struct{}{}:
case <-time.After(time.Minute):
dlog.Server.Warn("Starting to serialize mapredice data takes over a minute")
case <-ctx.Done():
}
}
|