-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcluster_query.go
370 lines (339 loc) · 10.1 KB
/
cluster_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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package zenodb
import (
"bytes"
"context"
"errors"
"fmt"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/getlantern/bytemap"
"github.com/getlantern/mtime"
"github.com/getlantern/zenodb/common"
"github.com/getlantern/zenodb/core"
"github.com/getlantern/zenodb/planner"
)
var (
ErrMissingQueryHandler = errors.New("Missing query handler for partition")
)
func (db *DB) RegisterQueryHandler(partition int, query planner.QueryClusterFN) {
db.tablesMutex.Lock()
handlersCh := db.remoteQueryHandlers[partition]
if handlersCh == nil {
handlersCh = make(chan planner.QueryClusterFN, db.opts.ClusterQueryConcurrency)
}
db.remoteQueryHandlers[partition] = handlersCh
db.tablesMutex.Unlock()
handlersCh <- query
}
func (db *DB) remoteQueryHandlerForPartition(partition int) planner.QueryClusterFN {
db.tablesMutex.RLock()
defer db.tablesMutex.RUnlock()
select {
case handler := <-db.remoteQueryHandlers[partition]:
return handler
default:
return nil
}
}
func (db *DB) queryForRemote(ctx context.Context, sqlString string, isSubQuery bool, subQueryResults [][]interface{}, unflat bool, onFields core.OnFields, onRow core.OnRow, onFlatRow core.OnFlatRow) (result interface{}, err error) {
source, prepareErr := db.Query(sqlString, isSubQuery, subQueryResults, common.ShouldIncludeMemStore(ctx))
if prepareErr != nil {
db.log.Errorf("Error on preparing query for remote: %v", prepareErr)
return nil, prepareErr
}
elapsed := mtime.Stopwatch()
defer func() {
db.log.Debugf("Processed query in %v, error?: %v : %v", elapsed(), err, sqlString)
}()
if unflat {
result, err = core.UnflattenOptimized(source).Iterate(ctx, onFields, onRow)
} else {
result, err = source.Iterate(ctx, onFields, onFlatRow)
}
return
}
type remoteResult struct {
partition int
fields core.Fields
key bytemap.ByteMap
vals core.Vals
flatRow *core.FlatRow
totalRows int
elapsed time.Duration
highWaterMark int64
err error
}
func (db *DB) queryCluster(ctx context.Context, sqlString string, isSubQuery bool, subQueryResults [][]interface{}, includeMemStore bool, unflat bool, onFields core.OnFields, onRow core.OnRow, onFlatRow core.OnFlatRow) (interface{}, error) {
ctx = common.WithIncludeMemStore(ctx, includeMemStore)
numPartitions := db.opts.NumPartitions
results := make(chan *remoteResult, numPartitions*100000) // TODO: make this tunable
resultsByPartition := make(map[int]*int64)
stats := &common.QueryStats{NumPartitions: numPartitions}
missingPartitions := make(map[int]bool, numPartitions)
var _finalErr error
var finalMx sync.RWMutex
finalStats := func() *common.QueryStats {
finalMx.RLock()
defer finalMx.RUnlock()
mps := make([]int, 0, len(missingPartitions))
for partition := range missingPartitions {
mps = append(mps, partition)
}
sort.Ints(mps)
stats.MissingPartitions = mps
return stats
}
finalErr := func() error {
finalMx.RLock()
defer finalMx.RUnlock()
result := _finalErr
return result
}
fail := func(partition int, err error) {
finalMx.Lock()
defer finalMx.Unlock()
if _finalErr != nil {
_finalErr = err
}
missingPartitions[partition] = true
}
finish := func(result *remoteResult) {
finalMx.Lock()
defer finalMx.Unlock()
if result.err == nil {
stats.NumSuccessfulPartitions++
if stats.LowestHighWaterMark == 0 || stats.LowestHighWaterMark > result.highWaterMark {
stats.LowestHighWaterMark = result.highWaterMark
}
if stats.HighestHighWaterMark < result.highWaterMark {
stats.HighestHighWaterMark = result.highWaterMark
}
}
}
_stopped := int64(0)
stopped := func() bool {
return atomic.LoadInt64(&_stopped) == 1
}
stop := func() {
atomic.StoreInt64(&_stopped, 1)
}
subCtx := ctx
ctxDeadline, ctxHasDeadline := subCtx.Deadline()
if ctxHasDeadline {
// Halve timeout for sub-contexts
now := time.Now()
timeout := ctxDeadline.Sub(now)
var cancel context.CancelFunc
ctxDeadline = now.Add(timeout / 2)
subCtx, cancel = context.WithDeadline(subCtx, ctxDeadline)
defer cancel()
}
for i := 0; i < numPartitions; i++ {
partition := i
_resultsForPartition := int64(0)
resultsForPartition := &_resultsForPartition
resultsByPartition[partition] = resultsForPartition
go func() {
for {
elapsed := mtime.Stopwatch()
query := db.remoteQueryHandlerForPartition(partition)
if query == nil {
db.log.Errorf("No query handler for partition %d, ignoring", partition)
results <- &remoteResult{
partition: partition,
totalRows: 0,
elapsed: elapsed(),
err: ErrMissingQueryHandler,
}
break
}
var partOnRow func(key bytemap.ByteMap, vals core.Vals) (bool, error)
var partOnFlatRow func(row *core.FlatRow) (bool, error)
if unflat {
partOnRow = func(key bytemap.ByteMap, vals core.Vals) (bool, error) {
err := finalErr()
if err != nil {
return false, err
}
if stopped() {
return false, nil
}
results <- &remoteResult{
partition: partition,
key: key,
vals: vals,
}
atomic.AddInt64(resultsForPartition, 1)
return true, nil
}
} else {
partOnFlatRow = func(row *core.FlatRow) (bool, error) {
err := finalErr()
if err != nil {
return false, err
}
if stopped() {
return false, nil
}
results <- &remoteResult{
partition: partition,
flatRow: row,
}
atomic.AddInt64(resultsForPartition, 1)
return true, nil
}
}
qstats, err := query(subCtx, sqlString, isSubQuery, subQueryResults, unflat, func(fields core.Fields) error {
results <- &remoteResult{
partition: partition,
fields: fields,
}
return nil
}, partOnRow, partOnFlatRow)
if err != nil {
switch err.(type) {
case common.Retriable:
db.log.Debugf("Failed on partition %d but error is retriable, continuing: %v", partition, err)
continue
default:
db.log.Debugf("Failed on partition %d and error is not retriable, will abort: %v", partition, err)
}
}
var highWaterMark int64
qs, ok := qstats.(*common.QueryStats)
if ok && qs != nil {
highWaterMark = qs.HighestHighWaterMark
}
results <- &remoteResult{
partition: partition,
totalRows: int(atomic.LoadInt64(resultsForPartition)),
elapsed: elapsed(),
highWaterMark: highWaterMark,
err: err,
}
break
}
}()
}
start := time.Now()
deadline := start.Add(db.opts.ClusterQueryTimeout)
if ctxHasDeadline {
deadline = ctxDeadline
}
db.log.Debugf("Deadline for results from partitions: %v (T - %v)", deadline, deadline.Sub(time.Now()))
timeout := deadline.Sub(time.Now())
timeoutTimer := time.NewTimer(timeout)
defer timeoutTimer.Stop()
var canonicalFields core.Fields
fieldsByPartition := make([]core.Fields, db.opts.NumPartitions)
partitionRowMappers := make([]func(core.Vals) core.Vals, db.opts.NumPartitions)
resultCount := 0
for pendingPartitions := numPartitions; pendingPartitions > 0; {
select {
case result := <-results:
// first handle fields
partitionFields := result.fields
if partitionFields != nil {
if canonicalFields == nil {
db.log.Debugf("fields: %v", partitionFields)
err := onFields(partitionFields)
if err != nil {
fail(result.partition, err)
}
canonicalFields = partitionFields
}
// Each partition can theoretically have different field definitions.
// To accomodate this, we track the fields separate for each partition
// and convert into the canonical form before sending onward.
fieldsByPartition[result.partition] = partitionFields
partitionRowMappers[result.partition] = partitionRowMapper(canonicalFields, partitionFields)
continue
}
// handle unflat rows
if result.key != nil {
if stopped() || finalErr() != nil {
continue
}
more, err := onRow(result.key, partitionRowMappers[result.partition](result.vals))
if err == nil && !more {
fail(result.partition, err)
stop()
}
continue
}
// handle flat rows
flatRow := result.flatRow
if flatRow != nil {
if stopped() || finalErr() != nil {
continue
}
flatRow.SetFields(fieldsByPartition[result.partition])
more, err := onFlatRow(flatRow)
if err != nil {
fail(result.partition, err)
return finalStats(), err
} else if !more {
stop()
}
continue
}
// final results for partition
resultCount++
pendingPartitions--
if result.err != nil {
db.log.Errorf("Error from partition %d: %v", result.partition, result.err)
fail(result.partition, result.err)
}
finish(result)
db.log.Debugf("%d/%d got %d results from partition %d in %v", resultCount, db.opts.NumPartitions, result.totalRows, result.partition, result.elapsed)
delete(resultsByPartition, result.partition)
case <-timeoutTimer.C:
db.log.Errorf("Failed to get results by within %v, %d of %d partitions reporting", timeout, resultCount, numPartitions)
msg := bytes.NewBuffer([]byte("Missing partitions: "))
first := true
for partition, results := range resultsByPartition {
if !first {
msg.WriteString(" | ")
}
first = false
msg.WriteString(fmt.Sprintf("%d (%d)", partition, results))
fail(partition, core.ErrDeadlineExceeded)
}
db.log.Debug(msg.String())
return finalStats(), finalErr()
}
}
return finalStats(), finalErr()
}
func partitionRowMapper(canonicalFields core.Fields, partitionFields core.Fields) func(core.Vals) core.Vals {
if canonicalFields.Equals(partitionFields) {
return func(vals core.Vals) core.Vals { return vals }
}
scratch := make(core.Vals, len(canonicalFields))
idxs := make([]int, 0, len(canonicalFields))
for _, canonicalField := range canonicalFields {
i := -1
for _i, partitionField := range partitionFields {
if canonicalField.Equals(partitionField) {
i = _i
break
}
}
idxs = append(idxs, i)
}
return func(vals core.Vals) core.Vals {
for o, i := range idxs {
if i < 0 || i >= len(vals) {
scratch[o] = nil
} else {
scratch[o] = vals[i]
}
}
for i := range vals {
vals[i] = scratch[i]
}
return vals
}
}