forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
4132 lines (3474 loc) · 111 KB
/
server.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 influxdb
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/influxdb/influxdb/influxql"
"github.com/influxdb/influxdb/messaging"
"golang.org/x/crypto/bcrypt"
)
const (
// DefaultRootPassword is the password initially set for the root user.
// It is also used when reseting the root user's password.
DefaultRootPassword = "root"
// DefaultRetentionPolicyName is the name of a databases's default shard space.
DefaultRetentionPolicyName = "default"
// DefaultSplitN represents the number of partitions a shard is split into.
DefaultSplitN = 1
// DefaultReplicaN represents the number of replicas data is written to.
DefaultReplicaN = 1
// DefaultShardDuration is the time period held by a shard.
DefaultShardDuration = 7 * (24 * time.Hour)
// DefaultShardRetention is the length of time before a shard is dropped.
DefaultShardRetention = 7 * (24 * time.Hour)
// BroadcastTopicID is the topic used for all metadata.
BroadcastTopicID = uint64(0)
// Defines the minimum duration allowed for all retention policies
retentionPolicyMinDuration = time.Hour
// When planning a select statement, passing zero tells it not to chunk results. Only applies to raw queries
NoChunkingSize = 0
)
// Server represents a collection of metadata and raw metric data.
type Server struct {
mu sync.RWMutex
id uint64
path string
done chan struct{} // goroutine close notification
rpDone chan struct{} // retention policies goroutine close notification
sgpcDone chan struct{} // shard group pre-create goroutine close notification
client MessagingClient // broker client
index uint64 // highest broadcast index seen
errors map[uint64]error // message errors
meta *metastore // metadata store
dataNodes map[uint64]*DataNode // data nodes by id
databases map[string]*database // databases by name
users map[string]*User // user by name
shards map[uint64]*Shard // shards by shard id
stats *Stats
Logger *log.Logger
WriteTrace bool // Detailed logging of write path
authenticationEnabled bool
// Retention policy settings
RetentionAutoCreate bool
// continuous query settings
RecomputePreviousN int
RecomputeNoOlderThan time.Duration
ComputeRunsPerInterval int
ComputeNoMoreThan time.Duration
// This is the last time this data node has run continuous queries.
// Keep this state in memory so if a broker makes a request in another second
// to compute, it won't rerun CQs that have already been run. If this data node
// is just getting the request after being off duty for running CQs then
// it will recompute all of them
lastContinuousQueryRun time.Time
// Build information.
Version string
CommitHash string
}
// NewServer returns a new instance of Server.
func NewServer() *Server {
s := Server{
meta: &metastore{},
errors: make(map[uint64]error),
dataNodes: make(map[uint64]*DataNode),
databases: make(map[string]*database),
users: make(map[string]*User),
shards: make(map[uint64]*Shard),
stats: NewStats("server"),
Logger: log.New(os.Stderr, "[server] ", log.LstdFlags),
}
// Server will always return with authentication enabled.
// This ensures that disabling authentication must be an explicit decision.
// To set the server to 'authless mode', call server.SetAuthenticationEnabled(false).
s.authenticationEnabled = true
return &s
}
func (s *Server) BrokerURLs() []url.URL {
return s.client.URLs()
}
// SetAuthenticationEnabled turns on or off server authentication
func (s *Server) SetAuthenticationEnabled(enabled bool) {
s.authenticationEnabled = enabled
}
// ID returns the data node id for the server.
// Returns zero if the server is closed or the server has not joined a cluster.
func (s *Server) ID() uint64 {
s.mu.RLock()
defer s.mu.RUnlock()
return s.id
}
// Index returns the index for the server.
func (s *Server) Index() uint64 {
s.mu.RLock()
defer s.mu.RUnlock()
return s.index
}
// Path returns the path used when opening the server.
// Returns an empty string when the server is closed.
func (s *Server) Path() string {
s.mu.RLock()
defer s.mu.RUnlock()
return s.path
}
// shardPath returns the path for a shard.
func (s *Server) shardPath(id uint64) string {
if s.path == "" {
return ""
}
return filepath.Join(s.path, "shards", strconv.FormatUint(id, 10))
}
// metaPath returns the path for the metastore.
func (s *Server) metaPath() string {
if s.path == "" {
return ""
}
return filepath.Join(s.path, "meta")
}
// Open initializes the server from a given path.
func (s *Server) Open(path string, client MessagingClient) error {
s.mu.Lock()
defer s.mu.Unlock()
// Ensure the server isn't already open and there's a path provided.
if s.opened() {
return ErrServerOpen
} else if path == "" {
return ErrPathRequired
}
// Set the server path.
s.path = path
// Create required directories.
if err := os.MkdirAll(path, 0755); err != nil {
_ = s.close()
return err
}
if err := os.MkdirAll(filepath.Join(path, "shards"), 0755); err != nil {
_ = s.close()
return err
}
// Set the messaging client.
s.client = client
// Open metadata store.
if err := s.meta.open(s.metaPath()); err != nil {
_ = s.close()
return fmt.Errorf("meta: %s", err)
}
// Load state from metastore.
if err := s.load(); err != nil {
_ = s.close()
return fmt.Errorf("load: %s", err)
}
// Create connection for broadcast topic.
conn := client.Conn(BroadcastTopicID)
if err := conn.Open(s.index, true); err != nil {
_ = s.close()
return fmt.Errorf("open conn: %s", err)
}
// Begin streaming messages from broadcast topic.
done := make(chan struct{}, 0)
s.done = done
go s.processor(conn, done)
// TODO: Associate series ids with shards.
return nil
}
// opened returns true when the server is open. Must be called under lock.
func (s *Server) opened() bool { return s.path != "" }
// Close shuts down the server.
func (s *Server) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
return s.close()
}
func (s *Server) close() error {
if !s.opened() {
return ErrServerClosed
}
if s.rpDone != nil {
close(s.rpDone)
s.rpDone = nil
}
if s.sgpcDone != nil {
close(s.sgpcDone)
s.sgpcDone = nil
}
// Remove path.
s.path = ""
s.index = 0
// Stop broadcast topic processing.
if s.done != nil {
close(s.done)
s.done = nil
}
if s.client != nil {
s.client.Close()
s.client = nil
}
// Close metastore.
_ = s.meta.close()
// Close shards.
for _, sh := range s.shards {
_ = sh.close()
}
// Server is closing, empty maps which should be reloaded on open.
s.shards = nil
s.dataNodes = nil
s.databases = nil
s.users = nil
return nil
}
// load reads the state of the server from the metastore.
func (s *Server) load() error {
return s.meta.view(func(tx *metatx) error {
// Read server id & index.
s.id = tx.id()
s.index = tx.index()
// Load data nodes.
s.dataNodes = make(map[uint64]*DataNode)
for _, node := range tx.dataNodes() {
s.dataNodes[node.ID] = node
}
// Load databases.
s.databases = make(map[string]*database)
for _, db := range tx.databases() {
s.databases[db.name] = db
// load the index
log.Printf("Loading metadata index for %s\n", db.name)
err := s.meta.view(func(tx *metatx) error {
tx.indexDatabase(db)
return nil
})
if err != nil {
return err
}
}
// Load shards.
s.shards = make(map[uint64]*Shard)
for _, db := range s.databases {
for _, rp := range db.policies {
for _, g := range rp.shardGroups {
for _, sh := range g.Shards {
// Add to lookups.
s.shards[sh.ID] = sh
// Only open shards owned by the server.
if !sh.HasDataNodeID(s.id) {
continue
}
if err := sh.open(s.shardPath(sh.ID), s.client.Conn(sh.ID)); err != nil {
return fmt.Errorf("cannot open shard store: id=%d, err=%s", sh.ID, err)
}
s.stats.Inc("shardsOpen")
}
}
}
}
// Load users.
s.users = make(map[string]*User)
for _, u := range tx.users() {
s.users[u.Name] = u
}
return nil
})
}
// StartSelfMonitoring starts a goroutine which monitors the InfluxDB server
// itself and stores the results in the specified database at a given interval.
func (s *Server) StartSelfMonitoring(database, retention string, interval time.Duration) error {
if interval == 0 {
return fmt.Errorf("statistics check interval must be non-zero")
}
// Function for local use turns stats into a slice of points
pointsFromStats := func(st *Stats, tags map[string]string) []Point {
var points []Point
now := time.Now()
st.Walk(func(k string, v int64) {
point := Point{
Time: now,
Name: st.name + "_" + k,
Tags: make(map[string]string),
Fields: map[string]interface{}{"value": int(v)},
}
// Specifically create a new map.
for k, v := range tags {
point.Tags[k] = v
}
points = append(points, point)
})
return points
}
go func() {
tick := time.NewTicker(interval)
for {
<-tick.C
// Create the batch and tags
tags := map[string]string{"serverID": strconv.FormatUint(s.ID(), 10)}
if h, err := os.Hostname(); err == nil {
tags["host"] = h
}
batch := pointsFromStats(s.stats, tags)
// Shard-level stats.
tags["shardID"] = strconv.FormatUint(s.id, 10)
for _, sh := range s.shards {
if !sh.HasDataNodeID(s.id) {
// No stats for non-local shards.
continue
}
batch = append(batch, pointsFromStats(sh.stats, tags)...)
}
// Server diagnostics.
for _, row := range s.DiagnosticsAsRows() {
points, err := s.convertRowToPoints(row.Name, row)
if err != nil {
s.Logger.Printf("failed to write diagnostic row for %s: %s", row.Name, err.Error())
continue
}
for _, p := range points {
p.Tags = map[string]string{"serverID": strconv.FormatUint(s.ID(), 10)}
}
batch = append(batch, points...)
}
s.WriteSeries(database, retention, batch)
}
}()
return nil
}
// StartRetentionPolicyEnforcement launches retention policy enforcement.
func (s *Server) StartRetentionPolicyEnforcement(checkInterval time.Duration) error {
if checkInterval == 0 {
return fmt.Errorf("retention policy check interval must be non-zero")
}
rpDone := make(chan struct{}, 0)
s.rpDone = rpDone
go func() {
for {
select {
case <-rpDone:
return
case <-time.After(checkInterval):
s.EnforceRetentionPolicies()
}
}
}()
return nil
}
// EnforceRetentionPolicies ensures that data that is aging-out due to retention policies
// is removed from the server.
func (s *Server) EnforceRetentionPolicies() {
log.Println("retention policy enforcement check commencing")
type group struct {
Database string
Retention string
ID uint64
}
var groups []group
// Only keep the lock while walking the shard groups, so the lock is not held while
// any deletions take place across the cluster.
func() {
s.mu.RLock()
defer s.mu.RUnlock()
// Check all shard groups.
for _, db := range s.databases {
for _, rp := range db.policies {
for _, g := range rp.shardGroups {
if rp.Duration != 0 && g.EndTime.Add(rp.Duration).Before(time.Now().UTC()) {
log.Printf("shard group %d, retention policy %s, database %s due for deletion",
g.ID, rp.Name, db.name)
groups = append(groups, group{Database: db.name, Retention: rp.Name, ID: g.ID})
}
}
}
}
}()
for _, g := range groups {
if err := s.DeleteShardGroup(g.Database, g.Retention, g.ID); err != nil {
log.Printf("failed to request deletion of shard group %d: %s", g.ID, err.Error())
}
}
}
// StartShardGroupsPreCreate launches shard group pre-create to avoid write bottlenecks.
func (s *Server) StartShardGroupsPreCreate(checkInterval time.Duration) error {
if checkInterval == 0 {
return fmt.Errorf("shard group pre-create check interval must be non-zero")
}
sgpcDone := make(chan struct{}, 0)
s.sgpcDone = sgpcDone
go func() {
for {
select {
case <-sgpcDone:
return
case <-time.After(checkInterval):
s.ShardGroupPreCreate(checkInterval)
}
}
}()
return nil
}
// ShardGroupPreCreate ensures that future shard groups and shards are created and ready for writing
// is removed from the server.
func (s *Server) ShardGroupPreCreate(checkInterval time.Duration) {
log.Println("shard group pre-create check commencing")
// For safety, we double the check interval to ensure we have enough time to create all shard groups
// before they are needed, but as close to needed as possible.
// This is a complete punt on optimization
cutoff := time.Now().Add(checkInterval * 2).UTC()
type group struct {
Database string
Retention string
ID uint64
Time time.Time
}
var groups []group
// Only keep the lock while walking the shard groups, so the lock is not held while
// any deletions take place across the cluster.
func() {
s.mu.RLock()
defer s.mu.RUnlock()
// Check all shard groups.
// See if they have a "future" shard group ready to write to
// If not, create the next shard group, as well as each shard for the shardGroup
for _, db := range s.databases {
for _, rp := range db.policies {
for _, g := range rp.shardGroups {
// Check to see if it is going to end before our interval
if g.EndTime.Before(cutoff) {
log.Printf("pre-creating shard group for %d, retention policy %s, database %s", g.ID, rp.Name, db.name)
groups = append(groups, group{Database: db.name, Retention: rp.Name, ID: g.ID, Time: g.EndTime.Add(1 * time.Nanosecond)})
}
}
}
}
}()
for _, g := range groups {
if err := s.CreateShardGroupIfNotExists(g.Database, g.Retention, g.Time); err != nil {
log.Printf("failed to request pre-creation of shard group %d for time %s: %s", g.ID, g.Time, err.Error())
}
}
}
// Client retrieves the current messaging client.
func (s *Server) Client() MessagingClient {
s.mu.RLock()
defer s.mu.RUnlock()
return s.client
}
// broadcast encodes a message as JSON and send it to the broker's broadcast topic.
// This function waits until the message has been processed by the server.
// Returns the broker log index of the message or an error.
func (s *Server) broadcast(typ messaging.MessageType, c interface{}) (uint64, error) {
s.stats.Inc("broadcastMessageTx")
// Encode the command.
data, err := json.Marshal(c)
if err != nil {
return 0, err
}
// Publish the message.
m := &messaging.Message{
Type: typ,
TopicID: BroadcastTopicID,
Data: data,
}
index, err := s.client.Publish(m)
if err != nil {
return 0, err
}
// Wait for the server to receive the message.
err = s.Sync(BroadcastTopicID, index)
return index, err
}
// Sync blocks until a given index (or a higher index) has been applied.
// Returns any error associated with the command.
func (s *Server) Sync(topicID, index uint64) error {
// Sync to the broadcast topic if specified.
if topicID == 0 {
return s.syncBroadcast(index)
}
// Otherwise retrieve shard by id.
s.mu.RLock()
sh := s.shards[topicID]
s.mu.RUnlock()
// Return error if there is no shard.
if sh == nil || sh.store == nil {
return errors.New("shard not owned")
}
return sh.sync(index)
}
// syncBroadcast syncs the broadcast topic.
func (s *Server) syncBroadcast(index uint64) error {
for {
// Check if index has occurred. If so, retrieve the error and return.
s.mu.RLock()
if s.index >= index {
err, ok := s.errors[index]
if ok {
delete(s.errors, index)
}
s.mu.RUnlock()
return err
}
s.mu.RUnlock()
// Otherwise wait momentarily and check again.
time.Sleep(1 * time.Millisecond)
}
}
// Initialize creates a new data node and initializes the server's id to the latest.
func (s *Server) Initialize(u url.URL) error {
// Create a new data node.
if err := s.CreateDataNode(&u); err != nil {
return err
}
// Ensure the data node returns with an ID.
// If it doesn't then something went really wrong. We have to panic because
// the messaging client relies on the first server being assigned ID 1.
n := s.DataNodeByURL(&u)
assert(n != nil, "node not created: %s", u.String())
assert(n.ID > 0, "invalid node id: %d", n.ID)
// Set the ID on the metastore.
if err := s.meta.mustUpdate(0, func(tx *metatx) error {
return tx.setID(n.ID)
}); err != nil {
return err
}
// Set the ID on the server.
s.id = n.ID
return nil
}
// This is the same struct we use in the httpd package, but
// it seems overkill to export it and share it
type dataNodeJSON struct {
ID uint64 `json:"id"`
URL string `json:"url"`
}
// copyURL returns a copy of the the URL.
func copyURL(u *url.URL) *url.URL {
other := &url.URL{}
*other = *u
return other
}
// Join creates a new data node in an existing cluster, copies the metastore,
// and initializes the ID.
func (s *Server) Join(u *url.URL, joinURL *url.URL) error {
s.mu.Lock()
defer s.mu.Unlock()
// Create the initial request. Might get a redirect though depending on
// the nodes role
joinURL = copyURL(joinURL)
joinURL.Path = "/data/data_nodes"
var retries int
var resp *http.Response
var err error
// When POSTing the to the join endpoint, we are manually following redirects
// and not relying on the Go http client redirect policy. The Go http client will convert
// POSTs to GETSs when following redirects which is not what we want when joining.
// (i.e. we want to join a node, not list the nodes) If we receive a redirect response,
// the Location header is where we should resend the POST. We also need to re-encode
// body since the buf was already read.
for {
// Should never get here but bail to avoid a infinite redirect loop to be safe
if retries >= 60 {
return ErrUnableToJoin
}
// Encode data node request.
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(&dataNodeJSON{URL: u.String()}); err != nil {
return err
}
resp, err = http.Post(joinURL.String(), "application/octet-stream", &buf)
if err != nil {
return err
}
defer resp.Body.Close()
// If we get a service unavailable, the other data nodes may still be booting
// so retry again
if resp.StatusCode == http.StatusServiceUnavailable {
s.Logger.Printf("join unavailable, retrying")
retries += 1
time.Sleep(1 * time.Second)
continue
}
// We likely tried to join onto a broker which cannot handle this request. It
// has given us the address of a known data node to join instead.
if resp.StatusCode == http.StatusTemporaryRedirect {
redirectURL, err := url.Parse(resp.Header.Get("Location"))
s.Logger.Printf("redirect join: %s", redirectURL)
// if we happen to get redirected back to ourselves then we'll never join. This
// may because the heartbeater could have already fired once, registering our endpoints
// as a data node and the broker is redirecting data node requests back to us. In
// this case, just re-request the original URL again util we get a different node.
if redirectURL.Host != u.Host {
joinURL = redirectURL
}
if err != nil {
return err
}
retries += 1
resp.Body.Close()
continue
}
// If we are first data node, we can't join anyone and need to initialize
if resp.StatusCode == http.StatusNotFound {
return ErrDataNodeNotFound
}
break
}
// Check if created.
if resp.StatusCode != http.StatusCreated {
return ErrUnableToJoin
}
// Decode response.
var n dataNodeJSON
if err := json.NewDecoder(resp.Body).Decode(&n); err != nil {
return err
}
assert(n.ID > 0, "invalid join node id returned: %d", n.ID)
// Download the metastore from joining server.
joinURL.Path = "/data/metastore"
resp, err = http.Get(joinURL.String())
if err != nil {
return err
}
defer resp.Body.Close()
// Check response & parse content length.
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unsuccessful meta copy: status=%d (%s)", resp.StatusCode, joinURL.String())
}
sz, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
if err != nil {
return fmt.Errorf("cannot parse meta size: %s", err)
}
// Close the metastore.
_ = s.meta.close()
// Overwrite the metastore.
f, err := os.Create(s.metaPath())
if err != nil {
return fmt.Errorf("create meta file: %s", err)
}
// Copy and check size.
if _, err := io.CopyN(f, resp.Body, sz); err != nil {
_ = f.Close()
return fmt.Errorf("copy meta file: %s", err)
}
_ = f.Close()
// Reopen metastore.
s.meta = &metastore{}
if err := s.meta.open(s.metaPath()); err != nil {
return fmt.Errorf("reopen meta: %s", err)
}
// Update the ID on the metastore.
if err := s.meta.mustUpdate(0, func(tx *metatx) error {
return tx.setID(n.ID)
}); err != nil {
return err
}
// Reload the server.
log.Printf("reloading metadata")
if err := s.load(); err != nil {
return fmt.Errorf("reload: %s", err)
}
return nil
}
// CopyMetastore writes the underlying metastore data file to a writer.
func (s *Server) CopyMetastore(w io.Writer) error {
return s.meta.mustView(func(tx *metatx) error {
// Set content lengh if this is a HTTP connection.
if w, ok := w.(http.ResponseWriter); ok {
w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
}
// Write entire database to the writer.
return tx.Copy(w)
})
}
// CopyShard writes the requested shard to a writer.
func (s *Server) CopyShard(w io.Writer, shardID uint64) error {
s.mu.RLock()
// Locate the shard.
sh, ok := s.shards[shardID]
if !ok {
s.mu.RUnlock()
return ErrShardNotFound
}
if sh.store == nil {
s.mu.RUnlock()
return ErrShardNotLocal
}
return sh.view(func(tx *shardtx) error {
s.mu.RUnlock() // Unlock so not held during long read.
sz := int(tx.Size())
// Set content length if this is a HTTP connection.
if w, ok := w.(http.ResponseWriter); ok {
w.Header().Set("Content-Length", strconv.Itoa(sz))
}
// Write entire shard to the writer.
n, err := tx.WriteTo(w)
if n != int64(sz) {
return ErrShardShortRead
}
return err
})
}
// DataNode returns a data node by id.
func (s *Server) DataNode(id uint64) *DataNode {
s.mu.RLock()
defer s.mu.RUnlock()
return s.dataNodes[id]
}
// DataNodesByID returns the data nodes matching the passed ids
func (s *Server) DataNodesByID(ids []uint64) []*DataNode {
s.mu.RLock()
defer s.mu.RUnlock()
var a []*DataNode
for _, id := range ids {
a = append(a, s.dataNodes[id])
}
return a
}
// DataNodeByURL returns a data node by url.
func (s *Server) DataNodeByURL(u *url.URL) *DataNode {
s.mu.RLock()
defer s.mu.RUnlock()
for _, n := range s.dataNodes {
if n.URL.String() == u.String() {
return n
}
}
return nil
}
// DataNodes returns a list of data nodes.
func (s *Server) DataNodes() (a []*DataNode) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, n := range s.dataNodes {
a = append(a, n)
}
sort.Sort(dataNodes(a))
return
}
// CreateDataNode creates a new data node with a given URL.
func (s *Server) CreateDataNode(u *url.URL) error {
c := &createDataNodeCommand{URL: u.String()}
_, err := s.broadcast(createDataNodeMessageType, c)
return err
}
func (s *Server) applyCreateDataNode(m *messaging.Message) (err error) {
var c createDataNodeCommand
mustUnmarshalJSON(m.Data, &c)
// Validate parameters.
if c.URL == "" {
return ErrDataNodeURLRequired
}
// Check that another node with the same URL doesn't already exist.
u, _ := url.Parse(c.URL)
for _, n := range s.dataNodes {
if n.URL.String() == u.String() {
return ErrDataNodeExists
}
}
// Create data node.
n := newDataNode()
n.URL = u
// Persist to metastore.
err = s.meta.mustUpdate(m.Index, func(tx *metatx) error {
n.ID = tx.nextDataNodeID()
return tx.saveDataNode(n)
})
// Add to node on server.
s.dataNodes[n.ID] = n
return
}
// DeleteDataNode deletes an existing data node.
func (s *Server) DeleteDataNode(id uint64) error {
c := &deleteDataNodeCommand{ID: id}
_, err := s.broadcast(deleteDataNodeMessageType, c)
return err
}
func (s *Server) applyDeleteDataNode(m *messaging.Message) (err error) {
var c deleteDataNodeCommand
mustUnmarshalJSON(m.Data, &c)
n := s.dataNodes[c.ID]
if n == nil {
return ErrDataNodeNotFound
}
// Remove from metastore.
err = s.meta.mustUpdate(m.Index, func(tx *metatx) error { return tx.deleteDataNode(c.ID) })
// Delete the node.
delete(s.dataNodes, n.ID)
return
}
// DatabaseExists returns true if a database exists.
func (s *Server) DatabaseExists(name string) bool {
s.mu.RLock()
defer s.mu.RUnlock()
return s.databases[name] != nil
}
// Databases returns a sorted list of all database names.
func (s *Server) Databases() (a []string) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, db := range s.databases {
a = append(a, db.name)
}
sort.Strings(a)
return
}
// CreateDatabase creates a new database.
func (s *Server) CreateDatabase(name string) error {
if name == "" {
return ErrDatabaseNameRequired
}
c := &createDatabaseCommand{Name: name}
_, err := s.broadcast(createDatabaseMessageType, c)
return err
}
// CreateDatabaseIfNotExists creates a new database if, and only if, it does not exist already.
func (s *Server) CreateDatabaseIfNotExists(name string) error {
if s.DatabaseExists(name) {
return nil
}
// Small chance database could have been created even though the check above said it didn't.
if err := s.CreateDatabase(name); err != nil && err != ErrDatabaseExists {
return err
}
return nil
}