forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster_configuration.go
1357 lines (1200 loc) · 40.3 KB
/
cluster_configuration.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cluster
import (
"bytes"
"crypto/sha1"
"encoding/binary"
"encoding/gob"
"errors"
"fmt"
"math"
"math/rand"
"regexp"
"sort"
"sync"
"time"
log "code.google.com/p/log4go"
"github.com/influxdb/influxdb/common"
"github.com/influxdb/influxdb/configuration"
"github.com/influxdb/influxdb/metastore"
"github.com/influxdb/influxdb/parser"
"github.com/influxdb/influxdb/protocol"
"github.com/influxdb/influxdb/wal"
)
// defined by cluster config (in cluster package)
type QuerySpec interface {
GetStartTime() time.Time
GetEndTime() time.Time
Database() string
TableNames() []string
TableNamesAndRegex() ([]string, *regexp.Regexp)
GetGroupByInterval() *time.Duration
AllShardsQuery() bool
IsRegex() bool
}
type WAL interface {
AssignSequenceNumbersAndLog(request *protocol.Request, shard wal.Shard) (uint32, error)
AssignSequenceNumbers(request *protocol.Request) error
Commit(requestNumber uint32, serverId uint32) error
CreateCheckpoint() error
RecoverServerFromRequestNumber(requestNumber uint32, shardIds []uint32, yield func(request *protocol.Request, shardId uint32) error) error
RecoverServerFromLastCommit(serverId uint32, shardIds []uint32, yield func(request *protocol.Request, shardId uint32) error) error
}
type ShardCreator interface {
// the shard creator expects all shards to be of the same type (long term or short term) and have the same
// start and end times. This is called to create the shard set for a given duration.
CreateShards(shards []*NewShardData) ([]*ShardData, error)
CreateShardSpace(shardSpace *ShardSpace) error
}
const (
DEFAULT_SHARD_SPACE_NAME = "default"
)
/*
This struct stores all the metadata confiugration information about a running cluster. This includes
the servers in the cluster and their state, databases, users, and which continuous queries are running.
*/
type ClusterConfiguration struct {
createDatabaseLock sync.RWMutex
DatabaseReplicationFactors map[string]struct{}
usersLock sync.RWMutex
clusterAdmins map[string]*ClusterAdmin
dbUsers map[string]map[string]*DbUser
servers []*ClusterServer
serversLock sync.RWMutex
continuousQueries map[string][]*ContinuousQuery
continuousQueriesLock sync.RWMutex
ParsedContinuousQueries map[string]map[uint32]*parser.SelectQuery
continuousQueryTimestamp time.Time
LocalServer *ClusterServer
config *configuration.Configuration
addedLocalServerWait chan bool
addedLocalServer bool
connectionCreator func(string) ServerConnection
shardStore LocalShardStore
wal WAL
lastShardIdUsed uint32
random *rand.Rand
lastServerToGetShard *ClusterServer
shardCreator ShardCreator
shardLock sync.RWMutex
shardsById map[uint32]*ShardData
LocalRaftName string
writeBuffers []*WriteBuffer
MetaStore *metastore.Store
// these are just the spaces organized by db and default to make write lookups faster
databaseShardSpaces map[string][]*ShardSpace
}
type ContinuousQuery struct {
Id uint32
Query string
}
type Database struct {
Name string `json:"name"`
}
func NewClusterConfiguration(
config *configuration.Configuration,
wal WAL,
shardStore LocalShardStore,
connectionCreator func(string) ServerConnection,
metaStore *metastore.Store) *ClusterConfiguration {
return &ClusterConfiguration{
DatabaseReplicationFactors: make(map[string]struct{}),
clusterAdmins: make(map[string]*ClusterAdmin),
dbUsers: make(map[string]map[string]*DbUser),
continuousQueries: make(map[string][]*ContinuousQuery),
ParsedContinuousQueries: make(map[string]map[uint32]*parser.SelectQuery),
servers: make([]*ClusterServer, 0),
config: config,
addedLocalServerWait: make(chan bool, 1),
connectionCreator: connectionCreator,
shardStore: shardStore,
wal: wal,
random: rand.New(rand.NewSource(time.Now().UnixNano())),
shardsById: make(map[uint32]*ShardData, 0),
MetaStore: metaStore,
databaseShardSpaces: make(map[string][]*ShardSpace),
}
}
func (self *ClusterConfiguration) DoesShardSpaceExist(space *ShardSpace) error {
self.shardLock.RLock()
defer self.shardLock.RUnlock()
dbSpaces := self.databaseShardSpaces[space.Database]
for _, s := range dbSpaces {
if s.Name == space.Name {
return fmt.Errorf("Shard space %s exists", space.Name)
}
}
return nil
}
func (self *ClusterConfiguration) SetShardCreator(shardCreator ShardCreator) {
self.shardCreator = shardCreator
}
func (self *ClusterConfiguration) GetShards() []*ShardData {
self.shardLock.RLock()
defer self.shardLock.RUnlock()
shards := make([]*ShardData, 0, len(self.shardsById))
for _, shard := range self.shardsById {
shards = append(shards, shard)
}
return shards
}
func (self *ClusterConfiguration) GetShardSpaces() []*ShardSpace {
self.shardLock.RLock()
defer self.shardLock.RUnlock()
spaces := make([]*ShardSpace, 0)
for _, databaseSpaces := range self.databaseShardSpaces {
spaces = append(spaces, databaseSpaces...)
}
return spaces
}
// called by the server, this will wake up every 10 mintues to see if it should
// create a shard for the next window of time. This way shards get created before
// a bunch of writes stream in and try to create it all at the same time.
func (self *ClusterConfiguration) CreateFutureShardsAutomaticallyBeforeTimeComes() {
go func() {
for {
time.Sleep(time.Minute * 10)
log.Debug("Checking to see if future shards should be created")
spaces := self.allSpaces()
for _, s := range spaces {
self.automaticallyCreateFutureShard(s)
}
}
}()
}
func (self *ClusterConfiguration) allSpaces() []*ShardSpace {
self.shardLock.RLock()
defer self.shardLock.RUnlock()
spaces := make([]*ShardSpace, 0)
for _, s := range self.databaseShardSpaces {
spaces = append(s)
}
return spaces
}
func (self *ClusterConfiguration) GetExpiredShards() []*ShardData {
self.shardLock.RLock()
defer self.shardLock.RUnlock()
shards := make([]*ShardData, 0)
for _, space := range self.allSpaces() {
if space.ParsedRetentionPeriod() == time.Duration(uint64(0)) {
continue
}
expiredTime := time.Now().Add(-space.ParsedRetentionPeriod())
for _, shard := range space.shards {
if shard.endTime.Before(expiredTime) {
shards = append(shards, shard)
}
}
}
return shards
}
func (self *ClusterConfiguration) automaticallyCreateFutureShard(shardSpace *ShardSpace) {
if len(shardSpace.shards) == 0 {
// don't automatically create shards if they haven't created any yet.
return
}
latestShard := shardSpace.shards[0]
if latestShard.endTime.Add(-15*time.Minute).Unix() < time.Now().Unix() {
newShardTime := latestShard.endTime.Add(time.Second)
microSecondEpochForNewShard := newShardTime.Unix() * 1000 * 1000
log.Info("Automatically creating shard for %s", newShardTime.Format("Mon Jan 2 15:04:05 -0700 MST 2006"))
self.createShards(microSecondEpochForNewShard, shardSpace)
}
}
func (self *ClusterConfiguration) ServerId() uint32 {
return self.LocalServer.Id
}
func (self *ClusterConfiguration) IsSingleServer() bool {
return len(self.servers) < 2
}
func (self *ClusterConfiguration) Servers() []*ClusterServer {
return self.servers
}
// This function will wait until the configuration has received an addPotentialServer command for
// this local server.
func (self *ClusterConfiguration) WaitForLocalServerLoaded() {
// It's possible during initialization if Raft hasn't finished relpaying the log file or joining
// the cluster that the cluster config won't have any servers. Wait for a little bit and retry, but error out eventually.
<-self.addedLocalServerWait
}
func (self *ClusterConfiguration) GetServerByRaftName(name string) *ClusterServer {
for _, server := range self.servers {
if server.RaftName == name {
return server
}
}
return nil
}
func (self *ClusterConfiguration) GetServerById(id *uint32) *ClusterServer {
for _, server := range self.servers {
if server.Id == *id {
return server
}
}
log.Warn("Couldn't find server with id %d. Cluster servers: %#v", *id, self.servers)
return nil
}
func (self *ClusterConfiguration) GetServerByProtobufConnectionString(connectionString string) *ClusterServer {
for _, server := range self.servers {
if server.ProtobufConnectionString == connectionString {
return server
}
}
return nil
}
// Return per shard request numbers for the local server and all remote servers
func (self *ClusterConfiguration) HasUncommitedWrites() bool {
for _, buffer := range self.writeBuffers {
if buffer.HasUncommitedWrites() {
return true
}
}
return false
}
func (self *ClusterConfiguration) ChangeProtobufConnectionString(server *ClusterServer) {
if server.connection != nil {
server.connection.Close()
}
server.connection = self.connectionCreator(server.ProtobufConnectionString)
server.Connect()
}
func (self *ClusterConfiguration) RemoveServer(server *ClusterServer) error {
server.connection.Close()
i := 0
l := len(self.servers)
for i = 0; i < l; i++ {
if self.servers[i].Id == server.Id {
log.Debug("Found server %d at index %d", server.Id, i)
break
}
}
if i == l {
return fmt.Errorf("Cannot find server %d", server.Id)
}
self.servers[i], self.servers = self.servers[l-1], self.servers[:l-1]
log.Debug("Removed server %d", server.Id)
return nil
}
func (self *ClusterConfiguration) AddPotentialServer(server *ClusterServer) {
self.serversLock.Lock()
defer self.serversLock.Unlock()
server.State = Potential
self.servers = append(self.servers, server)
server.Id = uint32(len(self.servers))
log.Info("Added server to cluster config: %d, %s, %s", server.Id, server.RaftConnectionString, server.ProtobufConnectionString)
log.Info("Checking whether this is the local server local: %s, new: %s", self.config.ProtobufConnectionString(), server.ProtobufConnectionString)
if server.RaftName == self.LocalRaftName && self.addedLocalServer {
panic("how did we add the same server twice ?")
}
// if this is the local server unblock WaitForLocalServerLoaded()
// and set the local connection string and id
if server.RaftName == self.LocalRaftName {
log.Info("Added the local server")
self.LocalServer = server
self.addedLocalServerWait <- true
self.addedLocalServer = true
return
}
// if this isn't the local server, connect to it
log.Info("Connecting to ProtobufServer: %s from %s", server.ProtobufConnectionString, self.config.ProtobufConnectionString())
if server.connection == nil {
server.connection = self.connectionCreator(server.ProtobufConnectionString)
server.Connect()
}
writeBuffer := NewWriteBuffer(fmt.Sprintf("%d", server.GetId()), server, self.wal, server.Id, self.config.PerServerWriteBufferSize)
self.writeBuffers = append(self.writeBuffers, writeBuffer)
server.SetWriteBuffer(writeBuffer)
server.StartHeartbeat()
return
}
func (self *ClusterConfiguration) DatabasesExists(db string) bool {
self.createDatabaseLock.RLock()
defer self.createDatabaseLock.RUnlock()
_, ok := self.DatabaseReplicationFactors[db]
return ok
}
func (self *ClusterConfiguration) GetDatabases() []*Database {
self.createDatabaseLock.RLock()
defer self.createDatabaseLock.RUnlock()
dbs := make([]*Database, 0, len(self.DatabaseReplicationFactors))
for name := range self.DatabaseReplicationFactors {
dbs = append(dbs, &Database{Name: name})
}
return dbs
}
func (self *ClusterConfiguration) DatabaseExists(name string) bool {
if _, ok := self.DatabaseReplicationFactors[name]; ok {
return true
} else {
return false
}
}
func (self *ClusterConfiguration) CreateDatabase(name string) error {
self.createDatabaseLock.Lock()
defer self.createDatabaseLock.Unlock()
if _, ok := self.DatabaseReplicationFactors[name]; ok {
return common.NewDatabaseExistsError(name)
}
self.DatabaseReplicationFactors[name] = struct{}{}
return nil
}
func (self *ClusterConfiguration) DropDatabase(name string) error {
self.createDatabaseLock.Lock()
defer self.createDatabaseLock.Unlock()
if _, ok := self.DatabaseReplicationFactors[name]; !ok {
return fmt.Errorf("Database %s doesn't exist", name)
}
delete(self.DatabaseReplicationFactors, name)
self.continuousQueriesLock.Lock()
defer self.continuousQueriesLock.Unlock()
delete(self.continuousQueries, name)
delete(self.ParsedContinuousQueries, name)
self.usersLock.Lock()
defer self.usersLock.Unlock()
delete(self.dbUsers, name)
_, err := self.MetaStore.DropDatabase(name)
if err != nil {
return err
}
self.shardLock.Lock()
defer self.shardLock.Unlock()
shardSpaces := self.databaseShardSpaces[name]
delete(self.databaseShardSpaces, name)
if shardSpaces == nil {
return nil
}
for _, space := range shardSpaces {
for _, shard := range space.shards {
delete(self.shardsById, shard.id)
}
}
go func() {
for _, s := range shardSpaces {
for _, sh := range s.shards {
self.shardStore.DeleteShard(sh.id)
}
}
}()
return nil
}
func (self *ClusterConfiguration) CreateContinuousQuery(db string, query string) error {
self.continuousQueriesLock.Lock()
defer self.continuousQueriesLock.Unlock()
maxId := uint32(0)
for _, query := range self.continuousQueries[db] {
if query.Id > maxId {
maxId = query.Id
}
}
return self.addContinuousQuery(db, &ContinuousQuery{maxId + 1, query})
}
func (self *ClusterConfiguration) addContinuousQuery(db string, query *ContinuousQuery) error {
if self.continuousQueries == nil {
self.continuousQueries = map[string][]*ContinuousQuery{}
}
if self.ParsedContinuousQueries == nil {
self.ParsedContinuousQueries = map[string]map[uint32]*parser.SelectQuery{}
}
selectQuery, err := parser.ParseSelectQuery(query.Query)
if err != nil {
return fmt.Errorf("Failed to parse continuous query: %s", query.Query)
}
if self.ParsedContinuousQueries[db] == nil {
self.ParsedContinuousQueries[db] = map[uint32]*parser.SelectQuery{query.Id: selectQuery}
} else {
self.ParsedContinuousQueries[db][query.Id] = selectQuery
}
self.continuousQueries[db] = append(self.continuousQueries[db], query)
return nil
}
func (self *ClusterConfiguration) SetContinuousQueryTimestamp(timestamp time.Time) error {
self.continuousQueriesLock.Lock()
defer self.continuousQueriesLock.Unlock()
self.continuousQueryTimestamp = timestamp
return nil
}
func (self *ClusterConfiguration) DeleteContinuousQuery(db string, id uint32) error {
self.continuousQueriesLock.Lock()
defer self.continuousQueriesLock.Unlock()
for i, query := range self.continuousQueries[db] {
if query.Id == id {
q := self.continuousQueries[db]
q[len(q)-1], q[i], q = nil, q[len(q)-1], q[:len(q)-1]
self.continuousQueries[db] = q
delete(self.ParsedContinuousQueries[db], id)
break
}
}
return nil
}
func (self *ClusterConfiguration) GetContinuousQueries(db string) []*ContinuousQuery {
self.continuousQueriesLock.Lock()
defer self.continuousQueriesLock.Unlock()
return self.continuousQueries[db]
}
func (self *ClusterConfiguration) GetLocalConfiguration() *configuration.Configuration {
return self.config
}
func (self *ClusterConfiguration) GetDbUsers(db string) []common.User {
self.usersLock.RLock()
defer self.usersLock.RUnlock()
dbUsers := self.dbUsers[db]
users := make([]common.User, 0, len(dbUsers))
for name := range dbUsers {
dbUser := dbUsers[name]
users = append(users, dbUser)
}
return users
}
func (self *ClusterConfiguration) GetDbUser(db, username string) *DbUser {
self.usersLock.RLock()
defer self.usersLock.RUnlock()
dbUsers := self.dbUsers[db]
if dbUsers == nil {
return nil
}
return dbUsers[username]
}
func (self *ClusterConfiguration) SaveDbUser(u *DbUser) {
self.usersLock.Lock()
defer self.usersLock.Unlock()
db := u.GetDb()
dbUsers := self.dbUsers[db]
if u.IsDeleted() {
if dbUsers == nil {
return
}
delete(dbUsers, u.GetName())
return
}
if dbUsers == nil {
dbUsers = map[string]*DbUser{}
self.dbUsers[db] = dbUsers
}
dbUsers[u.GetName()] = u
}
func (self *ClusterConfiguration) ChangeDbUserPassword(db, username, hash string) error {
self.usersLock.Lock()
defer self.usersLock.Unlock()
dbUsers := self.dbUsers[db]
if dbUsers == nil {
return fmt.Errorf("Invalid database name %s", db)
}
if dbUsers[username] == nil {
return fmt.Errorf("Invalid username %s", username)
}
dbUsers[username].ChangePassword(hash)
return nil
}
func (self *ClusterConfiguration) ChangeDbUserPermissions(db, username, readPermissions, writePermissions string) error {
self.usersLock.Lock()
defer self.usersLock.Unlock()
dbUsers := self.dbUsers[db]
if dbUsers == nil {
return fmt.Errorf("Invalid database name %s", db)
}
if dbUsers[username] == nil {
return fmt.Errorf("Invalid username %s", username)
}
dbUsers[username].ChangePermissions(readPermissions, writePermissions)
return nil
}
func (self *ClusterConfiguration) GetClusterAdmins() (names []string) {
self.usersLock.RLock()
defer self.usersLock.RUnlock()
clusterAdmins := self.clusterAdmins
for name := range clusterAdmins {
names = append(names, name)
}
return
}
func (self *ClusterConfiguration) GetClusterAdmin(username string) *ClusterAdmin {
self.usersLock.RLock()
defer self.usersLock.RUnlock()
return self.clusterAdmins[username]
}
func (self *ClusterConfiguration) SaveClusterAdmin(u *ClusterAdmin) {
self.usersLock.Lock()
defer self.usersLock.Unlock()
if u.IsDeleted() {
delete(self.clusterAdmins, u.GetName())
return
}
self.clusterAdmins[u.GetName()] = u
u.ChangePassword(u.Hash)
}
type SavedConfiguration struct {
Databases map[string]uint8
Admins map[string]*ClusterAdmin
DbUsers map[string]map[string]*DbUser
Servers []*ClusterServer
ContinuousQueries map[string][]*ContinuousQuery
MetaStore *metastore.Store
LastShardIdUsed uint32
DatabaseShardSpaces map[string][]*ShardSpace
Shards []*NewShardData
}
func (self *ClusterConfiguration) Save() ([]byte, error) {
log.Debug("Dumping the cluster configuration")
data := &SavedConfiguration{
Databases: make(map[string]uint8, len(self.DatabaseReplicationFactors)),
Admins: self.clusterAdmins,
DbUsers: self.dbUsers,
Servers: self.servers,
ContinuousQueries: self.continuousQueries,
LastShardIdUsed: self.lastShardIdUsed,
MetaStore: self.MetaStore,
DatabaseShardSpaces: self.databaseShardSpaces,
Shards: self.convertShardsToNewShardData(self.GetShards()),
}
for k := range self.DatabaseReplicationFactors {
data.Databases[k] = 0
}
b := bytes.NewBuffer(nil)
err := gob.NewEncoder(b).Encode(&data)
if err != nil {
return nil, err
}
return b.Bytes(), nil
}
func (self *ClusterConfiguration) convertShardsToNewShardData(shards []*ShardData) []*NewShardData {
newShardData := make([]*NewShardData, len(shards), len(shards))
for i, shard := range shards {
newShardData[i] = &NewShardData{
Id: shard.id,
Database: shard.Database,
SpaceName: shard.SpaceName,
StartTime: shard.startTime,
EndTime: shard.endTime,
ServerIds: shard.serverIds}
}
return newShardData
}
func (self *ClusterConfiguration) convertNewShardDataToShards(newShards []*NewShardData) []*ShardData {
shards := make([]*ShardData, len(newShards), len(newShards))
for i, newShard := range newShards {
shard := NewShard(newShard.Id, newShard.StartTime, newShard.EndTime, newShard.Database, newShard.SpaceName, self.wal)
servers := make([]*ClusterServer, 0)
for _, serverId := range newShard.ServerIds {
if serverId == self.LocalServer.Id {
err := shard.SetLocalStore(self.shardStore, self.LocalServer.Id)
if err != nil {
log.Error("CliusterConfig convertNewShardDataToShards: ", err)
}
} else {
server := self.GetServerById(&serverId)
servers = append(servers, server)
}
}
shard.SetServers(servers)
shards[i] = shard
}
return shards
}
func (self *ClusterConfiguration) Recovery(b []byte) error {
log.Info("Recovering the cluster configuration")
data := &SavedConfiguration{}
err := gob.NewDecoder(bytes.NewReader(b)).Decode(&data)
if err != nil {
log.Error("Error while decoding snapshot: %s", err)
return err
}
self.DatabaseReplicationFactors = make(map[string]struct{}, len(data.Databases))
for k := range data.Databases {
self.DatabaseReplicationFactors[k] = struct{}{}
}
self.clusterAdmins = data.Admins
self.dbUsers = data.DbUsers
self.servers = data.Servers
self.MetaStore.UpdateFromSnapshot(data.MetaStore)
for _, server := range self.servers {
log.Info("Checking whether %s is the local server %s", server.RaftName, self.LocalRaftName)
if server.RaftName == self.LocalRaftName {
self.LocalServer = server
self.addedLocalServerWait <- true
self.addedLocalServer = true
continue
}
server.connection = self.connectionCreator(server.ProtobufConnectionString)
writeBuffer := NewWriteBuffer(fmt.Sprintf("server: %d", server.GetId()), server, self.wal, server.Id, self.config.PerServerWriteBufferSize)
self.writeBuffers = append(self.writeBuffers, writeBuffer)
server.SetWriteBuffer(writeBuffer)
server.Connect()
server.StartHeartbeat()
}
shards := self.convertNewShardDataToShards(data.Shards)
highestShardId := uint32(0)
for _, s := range shards {
shard := s
self.shardsById[s.id] = shard
if s.id > highestShardId {
highestShardId = s.id
}
}
if data.LastShardIdUsed == 0 {
self.lastShardIdUsed = highestShardId
} else {
self.lastShardIdUsed = data.LastShardIdUsed
}
// map the shards to their spaces
self.databaseShardSpaces = data.DatabaseShardSpaces
for _, spaces := range self.databaseShardSpaces {
for _, space := range spaces {
spaceShards := make([]*ShardData, 0)
for _, s := range shards {
if s.Database == space.Database && s.SpaceName == space.Name {
spaceShards = append(spaceShards, s)
}
}
SortShardsByTimeDescending(spaceShards)
space.shards = spaceShards
}
}
for db, queries := range data.ContinuousQueries {
for _, query := range queries {
self.addContinuousQuery(db, query)
}
}
return nil
}
func (self *ClusterConfiguration) AuthenticateDbUser(db, username, password string) (common.User, error) {
dbUsers := self.dbUsers[db]
if dbUsers == nil || dbUsers[username] == nil {
return nil, common.NewAuthorizationError("Invalid username/password")
}
user := dbUsers[username]
if user.isValidPwd(password) {
return user, nil
}
return nil, common.NewAuthorizationError("Invalid username/password")
}
func (self *ClusterConfiguration) AuthenticateClusterAdmin(username, password string) (common.User, error) {
user := self.clusterAdmins[username]
if user == nil {
return nil, common.NewAuthorizationError("Invalid username/password")
}
if user.isValidPwd(password) {
return user, nil
}
return nil, common.NewAuthorizationError("Invalid username/password")
}
func (self *ClusterConfiguration) HasContinuousQueries() bool {
return self.continuousQueries != nil && len(self.continuousQueries) > 0
}
func (self *ClusterConfiguration) LastContinuousQueryRunTime() time.Time {
return self.continuousQueryTimestamp
}
func (self *ClusterConfiguration) SetLastContinuousQueryRunTime(t time.Time) {
self.continuousQueryTimestamp = t
}
func (self *ClusterConfiguration) GetMapForJsonSerialization() map[string]interface{} {
jsonObject := make(map[string]interface{})
dbs := make([]string, 0)
for db := range self.DatabaseReplicationFactors {
dbs = append(dbs, db)
}
jsonObject["databases"] = dbs
jsonObject["cluster_admins"] = self.clusterAdmins
jsonObject["database_users"] = self.dbUsers
return jsonObject
}
func (self *ClusterConfiguration) createDefaultShardSpace(database string) (*ShardSpace, error) {
space := NewShardSpace(database, DEFAULT_SHARD_SPACE_NAME)
err := self.shardCreator.CreateShardSpace(space)
if err != nil {
return nil, err
}
return space, nil
}
func (self *ClusterConfiguration) GetShardToWriteToBySeriesAndTime(db, series string, microsecondsEpoch int64) (*ShardData, error) {
shardSpace := self.getShardSpaceToMatchSeriesName(db, series)
if shardSpace == nil {
var err error
shardSpace, err = self.createDefaultShardSpace(db)
if err != nil {
return nil, err
}
}
matchingShards := make([]*ShardData, 0)
for _, s := range shardSpace.shards {
if s.IsMicrosecondInRange(microsecondsEpoch) {
matchingShards = append(matchingShards, s)
} else if len(matchingShards) > 0 {
// shards are always in time descending order. If we've already found one and the next one doesn't match, we can ignore the rest
break
}
}
var err error
if len(matchingShards) == 0 {
log.Info("No matching shards for write at time %du, creating...", microsecondsEpoch)
matchingShards, err = self.createShards(microsecondsEpoch, shardSpace)
if err != nil {
return nil, err
}
}
if len(matchingShards) == 1 {
return matchingShards[0], nil
}
index := HashDbAndSeriesToInt(db, series)
index = index % len(matchingShards)
return matchingShards[index], nil
}
func (self *ClusterConfiguration) createShards(microsecondsEpoch int64, shardSpace *ShardSpace) ([]*ShardData, error) {
startIndex := 0
if self.lastServerToGetShard != nil {
for i, server := range self.servers {
if server == self.lastServerToGetShard {
startIndex = i + 1
}
}
}
shards := make([]*NewShardData, 0)
startTime, endTime := self.getStartAndEndBasedOnDuration(microsecondsEpoch, shardSpace.SecondsOfDuration())
log.Info("createShards for space %s: start: %s. end: %s",
shardSpace.Name,
startTime.Format("Mon Jan 2 15:04:05 -0700 MST 2006"), endTime.Format("Mon Jan 2 15:04:05 -0700 MST 2006"))
for i := shardSpace.Split; i > 0; i-- {
serverIds := make([]uint32, 0)
// if they have the replication factor set higher than the number of servers in the cluster, limit it
rf := int(shardSpace.ReplicationFactor)
if rf > len(self.servers) {
rf = len(self.servers)
}
for ; rf > 0; rf-- {
if startIndex >= len(self.servers) {
startIndex = 0
}
server := self.servers[startIndex]
self.lastServerToGetShard = server
serverIds = append(serverIds, server.Id)
startIndex += 1
}
shards = append(shards, &NewShardData{
StartTime: *startTime,
EndTime: *endTime,
ServerIds: serverIds,
Database: shardSpace.Database,
SpaceName: shardSpace.Name})
}
// call out to rafter server to create the shards (or return shard objects that the leader already knows about)
createdShards, err := self.shardCreator.CreateShards(shards)
if err != nil {
return nil, err
}
return createdShards, nil
}
func (self *ClusterConfiguration) CreateCheckpoint() error {
return self.wal.CreateCheckpoint()
}
func (self *ClusterConfiguration) getStartAndEndBasedOnDuration(microsecondsEpoch int64, duration float64) (*time.Time, *time.Time) {
startTimeSeconds := math.Floor(float64(microsecondsEpoch)/1000.0/1000.0/duration) * duration
startTime := time.Unix(int64(startTimeSeconds), 0)
endTime := time.Unix(int64(startTimeSeconds+duration), 0)
return &startTime, &endTime
}
func (self *ClusterConfiguration) GetShardsForQuery(querySpec *parser.QuerySpec) []*ShardData {
shards := self.getShardsToMatchQuery(querySpec)
shards = self.getShardRange(querySpec, shards)
if querySpec.IsAscending() {
SortShardsByTimeAscending(shards)
}
return shards
}
func (self *ClusterConfiguration) getShardsToMatchQuery(querySpec *parser.QuerySpec) []*ShardData {
self.shardLock.RLock()
defer self.shardLock.RUnlock()
seriesNames, fromRegex := querySpec.TableNamesAndRegex()
if fromRegex != nil {
seriesNames = self.MetaStore.GetSeriesForDatabaseAndRegex(querySpec.Database(), fromRegex)
}
uniqueShards := make(map[uint32]*ShardData)
for _, name := range seriesNames {
space := self.getShardSpaceToMatchSeriesName(querySpec.Database(), name)
if space == nil {
continue
}
for _, shard := range space.shards {
uniqueShards[shard.id] = shard
}
}
shards := make([]*ShardData, 0, len(uniqueShards))
for _, shard := range uniqueShards {
shards = append(shards, shard)
}
SortShardsByTimeDescending(shards)
return shards
}
func (self *ClusterConfiguration) getShardSpaceToMatchSeriesName(database, name string) *ShardSpace {
// order of matching for any series. First look at the database specific shard
// spaces. Then look at the defaults.
databaseSpaces := self.databaseShardSpaces[database]
if databaseSpaces == nil {
return nil
}
for _, s := range databaseSpaces {
if s.MatchesSeries(name) {
return s
}
}
return nil
}
func (self *ClusterConfiguration) GetShard(id uint32) *ShardData {
self.shardLock.RLock()
shard := self.shardsById[id]
self.shardLock.RUnlock()
if shard != nil {
return shard
}
return nil
}
func (self *ClusterConfiguration) getShardRange(querySpec QuerySpec, shards []*ShardData) []*ShardData {
if querySpec.AllShardsQuery() {
return shards
}
startTime := common.TimeToMicroseconds(querySpec.GetStartTime())
endTime := common.TimeToMicroseconds(querySpec.GetEndTime())
// the shards are always in descending order, if we have the following shards
// [t + 20, t + 30], [t + 10, t + 20], [t, t + 10]
// if we are querying [t + 5, t + 15], we have to find the first shard whose
// startMicro is less than the end time of the query,
// which is the second shard [t + 10, t + 20], then
// start searching from this shard for the shard that has
// endMicro less than the start time of the query, which is
// no entry (sort.Search will return the length of the slice
// in this case) so we return [t + 10, t + 20], [t, t + 10]
// as expected
startIndex := sort.Search(len(shards), func(n int) bool {
return shards[n].startMicro < endTime
})
if startIndex == len(shards) {
return nil
}
endIndex := sort.Search(len(shards)-startIndex, func(n int) bool {
return shards[n+startIndex].endMicro <= startTime
})
return shards[startIndex : endIndex+startIndex]
}
func HashDbAndSeriesToInt(database, series string) int {