forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shard.go
516 lines (453 loc) · 15.3 KB
/
shard.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
package cluster
import (
"common"
"engine"
"fmt"
"parser"
p "protocol"
"sort"
"strings"
"time"
"wal"
log "code.google.com/p/log4go"
)
// A shard imements an interface for writing and querying data.
// It can be copied to multiple servers or the local datastore.
// Shard contains data from [startTime, endTime)
// Ids are unique across the cluster
type Shard interface {
Id() uint32
StartTime() time.Time
EndTime() time.Time
Write(*p.Request) error
Query(querySpec *parser.QuerySpec, response chan *p.Response)
IsMicrosecondInRange(t int64) bool
}
// Passed to a shard (local datastore or whatever) that gets yielded points from series.
type QueryProcessor interface {
// This method returns true if the query should continue. If the query should be stopped,
// like maybe the limit was hit, it should return false
YieldPoint(seriesName *string, columnNames []string, point *p.Point) bool
YieldSeries(seriesIncoming *p.Series) bool
Close()
// Set by the shard, so EXPLAIN query can know query against which shard is being measured
SetShardInfo(shardId int, shardLocal bool)
// Let QueryProcessor identify itself. What if it is a spy and we can't check that?
GetName() string
}
type NewShardData struct {
Id uint32 `json:",omitempty"`
StartTime time.Time
EndTime time.Time
ServerIds []uint32
Type ShardType
DurationSplit bool `json:",omitempty"`
}
type ShardType int
const (
LONG_TERM ShardType = iota
SHORT_TERM
)
type ShardData struct {
id uint32
startTime time.Time
startMicro int64
endMicro int64
endTime time.Time
wal WAL
servers []wal.Server
clusterServers []*ClusterServer
store LocalShardStore
serverIds []uint32
shardType ShardType
durationIsSplit bool
shardDuration time.Duration
localServerId uint32
IsLocal bool
}
func NewShard(id uint32, startTime, endTime time.Time, shardType ShardType, durationIsSplit bool, wal WAL) *ShardData {
return &ShardData{
id: id,
startTime: startTime,
endTime: endTime,
wal: wal,
startMicro: common.TimeToMicroseconds(startTime),
endMicro: common.TimeToMicroseconds(endTime),
serverIds: make([]uint32, 0),
shardType: shardType,
durationIsSplit: durationIsSplit,
shardDuration: endTime.Sub(startTime),
}
}
const (
PER_SERVER_BUFFER_SIZE = 10
LOCAL_WRITE_BUFFER_SIZE = 10
)
var (
queryResponse = p.Response_QUERY
endStreamResponse = p.Response_END_STREAM
accessDeniedResponse = p.Response_ACCESS_DENIED
queryRequest = p.Request_QUERY
dropDatabaseRequest = p.Request_DROP_DATABASE
)
type LocalShardDb interface {
Write(database string, series *p.Series) error
Query(*parser.QuerySpec, QueryProcessor) error
DropDatabase(database string) error
IsClosed() bool
}
type LocalShardStore interface {
Write(request *p.Request) error
SetWriteBuffer(writeBuffer *WriteBuffer)
BufferWrite(request *p.Request)
GetOrCreateShard(id uint32) (LocalShardDb, error)
ReturnShard(id uint32)
DeleteShard(shardId uint32) error
}
func (self *ShardData) Id() uint32 {
return self.id
}
func (self *ShardData) StartMicro() int64 {
return self.startMicro
}
func (self *ShardData) StartTime() time.Time {
return self.startTime
}
func (self *ShardData) EndMicro() int64 {
return self.endMicro
}
func (self *ShardData) EndTime() time.Time {
return self.endTime
}
func (self *ShardData) IsMicrosecondInRange(t int64) bool {
return t >= self.startMicro && t < self.endMicro
}
func (self *ShardData) SetServers(servers []*ClusterServer) {
self.clusterServers = servers
self.servers = make([]wal.Server, len(servers), len(servers))
for i, server := range servers {
self.serverIds = append(self.serverIds, server.Id)
self.servers[i] = server
}
self.sortServerIds()
}
func (self *ShardData) SetLocalStore(store LocalShardStore, localServerId uint32) error {
self.serverIds = append(self.serverIds, localServerId)
self.localServerId = localServerId
self.sortServerIds()
self.store = store
// make sure we can open up the shard
_, err := self.store.GetOrCreateShard(self.id)
if err != nil {
return err
}
self.store.ReturnShard(self.id)
self.IsLocal = true
return nil
}
func (self *ShardData) ServerIds() []uint32 {
return self.serverIds
}
func (self *ShardData) Write(request *p.Request) error {
request.ShardId = &self.id
requestNumber, err := self.wal.AssignSequenceNumbersAndLog(request, self)
if err != nil {
return err
}
request.RequestNumber = &requestNumber
if self.store != nil {
self.store.BufferWrite(request)
}
for _, server := range self.clusterServers {
// we have to create a new reqeust object because the ID gets assigned on each server.
requestWithoutId := &p.Request{Type: request.Type, Database: request.Database, Series: request.Series, ShardId: &self.id, RequestNumber: request.RequestNumber}
server.BufferWrite(requestWithoutId)
}
return nil
}
func (self *ShardData) WriteLocalOnly(request *p.Request) error {
self.store.Write(request)
return nil
}
func (self *ShardData) Query(querySpec *parser.QuerySpec, response chan *p.Response) {
// This is only for queries that are deletes or drops. They need to be sent everywhere as opposed to just the local or one of the remote shards.
// But this boolean should only be set to true on the server that receives the initial query.
if querySpec.RunAgainstAllServersInShard {
if querySpec.IsDeleteFromSeriesQuery() {
self.logAndHandleDeleteQuery(querySpec, response)
} else if querySpec.IsDropSeriesQuery() {
self.logAndHandleDropSeriesQuery(querySpec, response)
}
}
if self.IsLocal {
var processor QueryProcessor
var err error
if querySpec.IsListSeriesQuery() {
processor = engine.NewListSeriesEngine(response)
} else if querySpec.IsDeleteFromSeriesQuery() || querySpec.IsDropSeriesQuery() || querySpec.IsSinglePointQuery() {
maxDeleteResults := 10000
processor = engine.NewPassthroughEngine(response, maxDeleteResults)
} else {
query := querySpec.SelectQuery()
if self.ShouldAggregateLocally(querySpec) {
log.Debug("creating a query engine\n")
processor, err = engine.NewQueryEngine(query, response)
if err != nil {
response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(err.Error())}
log.Error("Error while creating engine: %s", err)
return
}
processor.SetShardInfo(int(self.Id()), self.IsLocal)
} else if query.HasAggregates() {
maxPointsToBufferBeforeSending := 1000
log.Debug("creating a passthrough engine\n")
processor = engine.NewPassthroughEngine(response, maxPointsToBufferBeforeSending)
} else {
maxPointsToBufferBeforeSending := 1000
log.Debug("creating a passthrough engine with limit\n")
processor = engine.NewPassthroughEngineWithLimit(response, maxPointsToBufferBeforeSending, query.Limit)
}
processor = engine.NewFilteringEngine(query, processor)
}
shard, err := self.store.GetOrCreateShard(self.id)
if err != nil {
response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(err.Error())}
log.Error("Error while getting shards: %s", err)
return
}
defer self.store.ReturnShard(self.id)
err = shard.Query(querySpec, processor)
processor.Close()
if err != nil {
response <- &p.Response{Type: &endStreamResponse, ErrorMessage: p.String(err.Error())}
}
response <- &p.Response{Type: &endStreamResponse}
return
}
healthyServers := make([]*ClusterServer, 0, len(self.clusterServers))
for _, s := range self.clusterServers {
if !s.IsUp() {
continue
}
healthyServers = append(healthyServers, s)
}
healthyCount := len(healthyServers)
if healthyCount == 0 {
message := fmt.Sprintf("No servers up to query shard %d", self.id)
response <- &p.Response{Type: &endStreamResponse, ErrorMessage: &message}
log.Error(message)
return
}
randServerIndex := int(time.Now().UnixNano() % int64(healthyCount))
server := healthyServers[randServerIndex]
request := self.createRequest(querySpec)
server.MakeRequest(request, response)
}
func (self *ShardData) DropDatabase(database string, sendToServers bool) {
if self.IsLocal {
if shard, err := self.store.GetOrCreateShard(self.id); err == nil {
defer self.store.ReturnShard(self.id)
shard.DropDatabase(database)
}
}
if !sendToServers {
return
}
responses := make([]chan *p.Response, len(self.clusterServers), len(self.clusterServers))
for i, server := range self.clusterServers {
responseChan := make(chan *p.Response, 1)
responses[i] = responseChan
request := &p.Request{Type: &dropDatabaseRequest, Database: &database, ShardId: &self.id}
go server.MakeRequest(request, responseChan)
}
for _, responseChan := range responses {
// TODO: handle error responses
<-responseChan
}
}
func (self *ShardData) String() string {
serversString := make([]string, 0)
for _, s := range self.servers {
serversString = append(serversString, fmt.Sprintf("%d", s.GetId()))
}
local := "false"
if self.IsLocal {
local = "true"
}
return fmt.Sprintf("[ID: %d, START: %d, END: %d, LOCAL: %s, SERVERS: [%s]]", self.id, self.startMicro, self.endMicro, local, strings.Join(serversString, ","))
}
func (self *ShardData) ShouldAggregateLocally(querySpec *parser.QuerySpec) bool {
if self.durationIsSplit && querySpec.ReadsFromMultipleSeries() {
return false
}
groupByInterval := querySpec.GetGroupByInterval()
if groupByInterval == nil {
if querySpec.HasAggregates() {
return false
}
return true
}
if self.shardDuration%*groupByInterval == 0 {
return true
}
return false
}
func (self *ShardData) logAndHandleDeleteQuery(querySpec *parser.QuerySpec, response chan *p.Response) {
queryString := querySpec.GetQueryStringWithTimeCondition()
request := self.createRequest(querySpec)
request.Query = &queryString
self.LogAndHandleDestructiveQuery(querySpec, request, response, false)
}
func (self *ShardData) logAndHandleDropSeriesQuery(querySpec *parser.QuerySpec, response chan *p.Response) {
self.LogAndHandleDestructiveQuery(querySpec, self.createRequest(querySpec), response, false)
}
func (self *ShardData) LogAndHandleDestructiveQuery(querySpec *parser.QuerySpec, request *p.Request, response chan *p.Response, runLocalOnly bool) {
if runLocalOnly {
self.HandleDestructiveQuery(querySpec, request, response, true)
}
self.HandleDestructiveQuery(querySpec, request, response, false)
}
func (self *ShardData) deleteDataLocally(querySpec *parser.QuerySpec) (<-chan *p.Response, error) {
localResponses := make(chan *p.Response, 1)
// this doesn't really apply at this point since destructive queries don't output anything, but it may later
maxPointsFromDestructiveQuery := 1000
processor := engine.NewPassthroughEngine(localResponses, maxPointsFromDestructiveQuery)
shard, err := self.store.GetOrCreateShard(self.id)
if err != nil {
return nil, err
}
defer self.store.ReturnShard(self.id)
err = shard.Query(querySpec, processor)
processor.Close()
return localResponses, err
}
func (self *ShardData) forwardRequest(request *p.Request) ([]<-chan *p.Response, []uint32, error) {
ids := []uint32{}
responses := []<-chan *p.Response{}
for _, server := range self.clusterServers {
responseChan := make(chan *p.Response, 1)
// do this so that a new id will get assigned
request.Id = nil
log.Debug("Forwarding request %s to %d", request.GetDescription(), server.Id)
server.MakeRequest(request, responseChan)
responses = append(responses, responseChan)
ids = append(ids, server.Id)
}
return responses, ids, nil
}
func (self *ShardData) HandleDestructiveQuery(querySpec *parser.QuerySpec, request *p.Request, response chan *p.Response, runLocalOnly bool) {
if !self.IsLocal && runLocalOnly {
panic("WTF islocal is false and runLocalOnly is true")
}
responseCahnnels := []<-chan *p.Response{}
serverIds := []uint32{}
if self.IsLocal {
channel, err := self.deleteDataLocally(querySpec)
if err != nil {
msg := err.Error()
response <- &p.Response{Type: &endStreamResponse, ErrorMessage: &msg}
log.Error(msg)
return
}
responseCahnnels = append(responseCahnnels, channel)
serverIds = append(serverIds, self.localServerId)
}
log.Debug("request %s, runLocalOnly: %v", request.GetDescription(), runLocalOnly)
if !runLocalOnly {
responses, ids, _ := self.forwardRequest(request)
serverIds = append(serverIds, ids...)
responseCahnnels = append(responseCahnnels, responses...)
}
accessDenied := false
for idx, channel := range responseCahnnels {
serverId := serverIds[idx]
log.Debug("Waiting for response to %s from %d", request.GetDescription(), serverId)
for {
res := <-channel
log.Debug("Received %s response from %d for %s", res.GetType(), serverId, request.GetDescription())
if *res.Type == endStreamResponse {
break
}
// don't send the access denied response until the end so the readers don't close out before the other responses.
// See https://github.com/influxdb/influxdb/issues/316 for more info.
if *res.Type != accessDeniedResponse {
response <- res
} else {
accessDenied = true
}
}
}
if accessDenied {
response <- &p.Response{Type: &accessDeniedResponse}
}
response <- &p.Response{Type: &endStreamResponse}
}
func (self *ShardData) createRequest(querySpec *parser.QuerySpec) *p.Request {
queryString := querySpec.GetQueryString()
user := querySpec.User()
userName := user.GetName()
database := querySpec.Database()
isDbUser := !user.IsClusterAdmin()
return &p.Request{
Type: &queryRequest,
ShardId: &self.id,
Query: &queryString,
UserName: &userName,
Database: &database,
IsDbUser: &isDbUser,
}
}
// used to serialize shards when sending around in raft or when snapshotting in the log
func (self *ShardData) ToNewShardData() *NewShardData {
return &NewShardData{
Id: self.id,
StartTime: self.startTime,
EndTime: self.endTime,
Type: self.shardType,
ServerIds: self.serverIds,
}
}
// server ids should always be returned in sorted order
func (self *ShardData) sortServerIds() {
serverIdInts := make([]int, len(self.serverIds), len(self.serverIds))
for i, id := range self.serverIds {
serverIdInts[i] = int(id)
}
sort.Ints(serverIdInts)
for i, id := range serverIdInts {
self.serverIds[i] = uint32(id)
}
}
func SortShardsByTimeAscending(shards []*ShardData) {
sort.Sort(ByShardTimeAsc{shards})
}
func SortShardsByTimeDescending(shards []*ShardData) {
sort.Sort(ByShardTimeDesc{shards})
}
type ShardCollection []*ShardData
func (s ShardCollection) Len() int { return len(s) }
func (s ShardCollection) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type ByShardTimeDesc struct{ ShardCollection }
type ByShardTimeAsc struct{ ShardCollection }
func (s ByShardTimeAsc) Less(i, j int) bool {
if s.ShardCollection[i] != nil && s.ShardCollection[j] != nil {
iStartTime := s.ShardCollection[i].StartTime().Unix()
jStartTime := s.ShardCollection[j].StartTime().Unix()
if iStartTime == jStartTime {
return s.ShardCollection[i].Id() < s.ShardCollection[j].Id()
}
return iStartTime < jStartTime
}
return false
}
func (s ByShardTimeDesc) Less(i, j int) bool {
if s.ShardCollection[i] != nil && s.ShardCollection[j] != nil {
iStartTime := s.ShardCollection[i].StartTime().Unix()
jStartTime := s.ShardCollection[j].StartTime().Unix()
if iStartTime == jStartTime {
return s.ShardCollection[i].Id() < s.ShardCollection[j].Id()
}
return iStartTime > jStartTime
}
return false
}