-
Notifications
You must be signed in to change notification settings - Fork 49
/
memberstorage.go
774 lines (531 loc) · 18.4 KB
/
memberstorage.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
/*
* EliasDB
*
* Copyright 2016 Matthias Ladkau. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package cluster
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
"github.com/krotik/common/sortutil"
"github.com/krotik/eliasdb/cluster/manager"
"github.com/krotik/eliasdb/graph/graphstorage"
"github.com/krotik/eliasdb/hash"
"github.com/krotik/eliasdb/storage"
)
/*
ClusterStoragePrefix is the prefix for cluster related storage managers
*/
const ClusterStoragePrefix = "cs_"
/*
LocalStoragePrefix is the prefix for local storage managers
*/
const LocalStoragePrefix = "ls_"
/*
memberStorage models the local storage of a cluster member. This data structure
is the only thing which has access to the wrapped graphstorage.Storage.
*/
type memberStorage struct {
ds *DistributedStorage // Distributed storage which created this member storage
gs graphstorage.Storage // Wrapped graphstorage.Storage
at *memberAddressTable // Address table (cluster location -> local location)
transferLock *sync.Mutex // Lock for the transfer task
transferRunning bool // Flag to indicate that the transfer task is running
rebalanceLock *sync.Mutex // Lock for the rebalance task
rebalanceRunning bool // Flag to indicate that the rebalance task is running
rebalanceCounter int
}
/*
newMemberStorage creates a new memberStorage instance.
*/
func newMemberStorage(ds *DistributedStorage, gs graphstorage.Storage) (*memberStorage, error) {
sm := gs.StorageManager("cluster_translation", true)
at, err := newMemberAddressTable(ds, sm)
if err != nil {
return nil, err
}
return &memberStorage{ds, gs, at, &sync.Mutex{}, false, &sync.Mutex{}, false, 0}, nil
}
/*
handleDataRequest deals with RPC requests. It is the only function which is
called by the RPC server of the member manager.
*/
func (ms *memberStorage) handleDataRequest(request interface{}, response *interface{}) error {
var err error
// Make sure a request can be served
distTable, distTableErr := ms.at.checkState()
if distTableErr != nil {
return distTableErr
}
dr := request.(*DataRequest)
switch dr.RequestType {
case RTGetMain:
*response = ms.gs.MainDB()
case RTSetMain:
err = ms.handleSetMainRequest(distTable, dr, response)
case RTSetRoot:
err = ms.handleSetRootRequest(distTable, dr, response)
case RTGetRoot:
err = ms.handleGetRootRequest(distTable, dr, response)
case RTInsert:
err = ms.handleInsertRequest(distTable, dr, response)
case RTUpdate:
err = ms.handleUpdateRequest(distTable, dr, response)
case RTFree:
err = ms.handleFreeRequest(distTable, dr, response)
case RTExists:
err = ms.handleFetchRequest(distTable, dr, response, false)
case RTFetch:
err = ms.handleFetchRequest(distTable, dr, response, true)
case RTRebalance:
err = ms.handleRebalanceRequest(distTable, dr, response)
default:
err = fmt.Errorf("Unknown request type")
}
manager.LogDebug(ms.ds.MemberManager.Name(), fmt.Sprintf("(Store): Handled: %v %s (Transfer: %v, Error: %v)",
dr.RequestType, dr.Args, dr.Transfer, err))
return err
}
/*
handleSetMainRequest sets the mainDB on the local storage manager.
*/
func (ms *memberStorage) handleSetMainRequest(distTable *DistributionTable, request *DataRequest, response *interface{}) error {
mainDB := ms.gs.MainDB()
newMainDB := request.Value.(map[string]string)
// Update keys and values
for k, v := range newMainDB {
mainDB[k] = v
}
// Check if things should be deleted
var toRemove []string
for k := range mainDB {
if _, ok := newMainDB[k]; !ok {
toRemove = append(toRemove, k)
}
}
for _, k := range toRemove {
delete(mainDB, k)
}
err := ms.gs.FlushMain()
if !request.Transfer {
ms.at.AddTransferRequest(distTable.OtherReplicationMembers(0, ms.ds.MemberManager.Name()),
&DataRequest{RTSetMain, nil, request.Value, true})
}
return err
}
/*
handleGetRootRequest retrieves a root value from a local storage manager.
*/
func (ms *memberStorage) handleGetRootRequest(distTable *DistributionTable, request *DataRequest, response *interface{}) error {
dsname := request.Args[RPStoreName].(string)
root := request.Args[RPRoot].(int)
sm := ms.dataStorage(dsname, false)
if sm != nil {
*response = sm.Root(root)
}
return nil
}
/*
handleSetRootRequest sets a new root value in a local storage manager.
*/
func (ms *memberStorage) handleSetRootRequest(distTable *DistributionTable, request *DataRequest, response *interface{}) error {
dsname := request.Args[RPStoreName].(string)
root := request.Args[RPRoot].(int)
sm := ms.dataStorage(dsname, true)
sm.SetRoot(root, toUInt64(request.Value))
if !request.Transfer {
ms.at.AddTransferRequest(distTable.OtherReplicationMembers(0, ms.ds.MemberManager.Name()),
&DataRequest{RTSetRoot, request.Args, request.Value, true})
}
return sm.Flush()
}
/*
handleInsertRequest inserts an object and return its cluster storage location.
Distribution procedure:
Client -> Cluster Member Request Receiver
Cluster Member Request Receiver -> Cluster Member Primary Storage (chosen round-robin / available)
Cluster Member Primary Storage writes into its Transfer Table
Cluster Member Primary Storage (Transfer worker) -> Replicating Cluster Members
*/
func (ms *memberStorage) handleInsertRequest(distTable *DistributionTable, request *DataRequest, response *interface{}) error {
var err error
var cloc uint64
dsname := request.Args[RPStoreName].(string)
*response = 0
sm := ms.dataStorage(dsname, true)
if !request.Transfer {
// First get a new cluster location (on this member)
cloc, err = ms.at.NewClusterLoc(dsname)
} else {
// If this is a transfer request we know already the cluster location
cloc = toUInt64(request.Args[RPLoc])
}
if err == nil {
var loc uint64
// Insert into the local storage
loc, err = sm.Insert(request.Value)
if err == nil {
// Add a translation
_, _, err = ms.at.SetTransClusterLoc(dsname, cloc, loc, 1)
if err == nil {
if !request.Transfer {
// Add transfer request for replication
// At this point the operation has succeeded. We still need to
// replicate the change to all the replicating members but
// any errors happening during this shall not fail this operation.
// The next rebalancing will then synchronize all members again.
ms.at.AddTransferRequest(distTable.Replicas(ms.ds.MemberManager.Name()),
&DataRequest{RTInsert, map[DataRequestArg]interface{}{
RPStoreName: dsname,
RPLoc: cloc,
}, request.Value, true})
}
*response = cloc
}
}
}
return err
}
/*
handleUpdateRequest updates an object and return its cluster storage location.
There is indeed a chance to produce inconsistencies if members fail in the right
sequence. It is assumed that these will be delt with in the next rebalance.
Distribution procedure:
Client -> Cluster Member Request Receiver
Cluster Member Request Receiver -> Cluster Member Primary Storage or Replicating Cluster Member
Storing Cluster Member does the update and writes into its transfer table
Storing Cluster Member (Transfer worker) -> Replicating / Primary Cluster Members
*/
func (ms *memberStorage) handleUpdateRequest(distTable *DistributionTable, request *DataRequest, response *interface{}) error {
var err error
var newVersion uint64
dsname := request.Args[RPStoreName].(string)
cloc := toUInt64(request.Args[RPLoc])
*response = 0
// Get the translation
transRec, ok, err := ms.at.TransClusterLoc(dsname, cloc)
if ok {
sm := ms.dataStorage(dsname, false)
if sm != nil {
// Update the local storage
if !request.Transfer {
err = sm.Update(transRec.Loc, request.Value)
newVersion = transRec.Ver + 1
} else {
newVersion = toUInt64(request.Args[RPVer])
if newVersion >= transRec.Ver {
err = sm.Update(transRec.Loc, request.Value)
} else {
// Outdated update requests are simply ignored
err = fmt.Errorf("Received outdated update request (%v - Location: %v)",
ms.ds.MemberManager.Name(), cloc)
manager.LogDebug(ms.ds.MemberManager.Name(), err.Error())
// Need to return no error so the transfer worker on the
// other side removes its entry
err = nil
}
}
if err == nil {
// Increase the version of the translation record
_, _, err = ms.at.SetTransClusterLoc(dsname, cloc, transRec.Loc, newVersion)
if err == nil {
if !request.Transfer {
// Add transfer request for replication
// At this point the operation has succeeded. We still need to
// replicate the change to all the replicating members but
// any errors happening during this shall not fail this operation.
// The next rebalancing will then synchronize all members again.
ms.at.AddTransferRequest(distTable.OtherReplicationMembers(cloc, ms.ds.MemberManager.Name()),
&DataRequest{RTUpdate, map[DataRequestArg]interface{}{
RPStoreName: dsname,
RPLoc: cloc,
RPVer: newVersion,
}, request.Value, true})
}
*response = cloc
return nil
}
}
}
}
if err == nil {
err = fmt.Errorf("Cluster slot not found (%v - Location: %v)",
ms.ds.MemberManager.Name(), cloc)
}
return err
}
/*
handleFreeRequest removes an object.
Distribution procedure:
Client -> Cluster Member Request Receiver
Cluster Member Request Receiver -> Cluster Member Primary Storage or Replicating Cluster Member
Storing Cluster Member does the free and writes into its transfer table
Storing Cluster Member (Transfer worker) -> Replicating / Primary Cluster Members
*/
func (ms *memberStorage) handleFreeRequest(distTable *DistributionTable, request *DataRequest, response *interface{}) error {
var err error
dsname := request.Args[RPStoreName].(string)
cloc := toUInt64(request.Args[RPLoc])
// Get the translation
transRec, ok, err := ms.at.TransClusterLoc(dsname, cloc)
if ok {
sm := ms.dataStorage(dsname, false)
if sm != nil {
// Remove the translation
_, _, err = ms.at.RemoveTransClusterLoc(dsname, cloc)
if err == nil {
// Remove from the local storage
err = sm.Free(transRec.Loc)
if !request.Transfer {
// Add transfer request for replication
// At this point the operation has succeeded. We still need to
// replicate the change to all the replicating members but
// any errors happening during this shall not fail this operation.
// The next rebalancing will then synchronize all members again.
ms.at.AddTransferRequest(distTable.OtherReplicationMembers(cloc, ms.ds.MemberManager.Name()),
&DataRequest{RTFree, map[DataRequestArg]interface{}{
RPStoreName: dsname,
RPLoc: cloc,
}, nil, true})
}
return err
}
}
}
if err == nil {
err = fmt.Errorf("Cluster slot not found (%v - Location: %v)", ms.ds.MemberManager.Name(), cloc)
}
return err
}
/*
handleFetchRequest inserts an object and return its cluster storage location.
*/
func (ms *memberStorage) handleFetchRequest(distTable *DistributionTable,
request *DataRequest, response *interface{}, fetch bool) error {
var err error
dsname := request.Args[RPStoreName].(string)
cloc := toUInt64(request.Args[RPLoc])
// Get the translation
transRec, ok, err := ms.at.TransClusterLoc(dsname, cloc)
if ok {
// Check if the data should be retrieved
if !fetch {
*response = true
return nil
}
sm := ms.dataStorage(dsname, false)
if sm != nil {
var res []byte
err = sm.Fetch(transRec.Loc, &res)
if err == nil {
*response = res
return nil
}
}
} else if !fetch {
*response = false
return err
}
if err == nil {
err = fmt.Errorf("Cluster slot not found (%v - Location: %v)", ms.ds.MemberManager.Name(), cloc)
}
return err
}
/*
handleRebalanceRequest processes rebalance requests.
*/
func (ms *memberStorage) handleRebalanceRequest(distTable *DistributionTable, request *DataRequest, response *interface{}) error {
var err error
var tr *translationRec
var found bool
var res interface{}
var lloc uint64
handleError := func(err error) {
if err != nil {
manager.LogDebug(ms.ds.MemberManager.Name(), fmt.Sprintf("(Store): Error during rebalancing request handling: %v", err))
}
}
// Get the location ranges for this member and locations which are replicated on this member.
storeRangeStart, storeRangeStop := distTable.MemberRange(ms.ds.MemberManager.Name())
repRangeStart, repRangeStop := distTable.ReplicationRange(ms.ds.MemberManager.Name())
// Get the request data
rsource := request.Args[RPSrc].(string)
smnames := request.Args[RPStoreName]
locs := request.Args[RPLoc]
vers := request.Args[RPVer]
for i, cloc := range locs.([]uint64) {
// Check if there was an error from the previous iteration
handleError(err)
smname := smnames.([]string)[i]
ver := vers.([]uint64)[i]
// Do not proceed if there is an error or if the location is out of
// range of responsibility
notInStoreRange := cloc < storeRangeStart || cloc > storeRangeStop
notInRepRange := cloc < repRangeStart || cloc > repRangeStop
// Check if the location exists in the local storage
tr, found, err = ms.at.TransClusterLoc(smname, cloc)
if err != nil || (notInStoreRange && notInRepRange) {
// Skip the location if there was an error or if this member
// is not relevant for the location in question (either as primary
// storage member or as replica)
continue
}
if found {
// Check if the version is newer and update the local record if it is
if tr.Ver < ver {
// Local record exists and needs to be updated
sm := ms.dataStorage(smname, false)
// Fetch the data from the remote machine
res, err = ms.ds.sendDataRequest(rsource, &DataRequest{RTFetch, map[DataRequestArg]interface{}{
RPStoreName: smname,
RPLoc: cloc,
}, nil, false})
if err == nil {
// Update the local storage
if err = sm.Update(tr.Loc, res); err == nil {
// Update the translation
_, _, err = ms.at.SetTransClusterLoc(smname, cloc, tr.Loc, ver)
manager.LogDebug(ms.ds.MemberManager.Name(),
fmt.Sprintf("(Store): Rebalance updated %v location: %v", smname, cloc))
}
}
}
} else {
// The data on the remote system should be inserted into the local
// datastore.
sm := ms.dataStorage(smname, true)
// Fetch the data from the remote machine
res, err = ms.ds.sendDataRequest(rsource, &DataRequest{RTFetch, map[DataRequestArg]interface{}{
RPStoreName: smname,
RPLoc: cloc,
}, nil, false})
if err == nil {
// Insert into the local storage
lloc, err = sm.Insert(res)
if err == nil {
// Add a translation
_, _, err = ms.at.SetTransClusterLoc(smname, cloc, lloc, ver)
manager.LogDebug(ms.ds.MemberManager.Name(),
fmt.Sprintf("(Store): Rebalance inserted %v location: %v", smname, cloc))
}
}
}
if err == nil {
// Should the sender have the data
sourceSRangeStart, sourceSRangeStop := distTable.MemberRange(rsource)
sourceRRangeStart, sourceRRangeStop := distTable.ReplicationRange(rsource)
notInSourceSRange := cloc < sourceSRangeStart || cloc > sourceSRangeStop
notInSourceRRange := cloc < sourceRRangeStart || cloc > sourceRRangeStop
if notInSourceSRange && notInSourceRRange {
manager.LogDebug(ms.ds.MemberManager.Name(),
fmt.Sprintf("(Store): Rebalance removes %v location: %v from member %v",
smname, tr.Loc, rsource))
_, err = ms.ds.sendDataRequest(rsource, &DataRequest{RTFree, map[DataRequestArg]interface{}{
RPStoreName: smname,
RPLoc: cloc,
}, nil, true})
}
}
}
handleError(err)
return nil
}
/*
dataStorage returns a storage.StorageManager which will only store byte slices.
*/
func (ms *memberStorage) dataStorage(dsname string, create bool) storage.Manager {
return ms.gs.StorageManager(LocalStoragePrefix+dsname, create)
}
/*
dump dumps the contents of a particular member storage manager as escaped strings.
(Works only for MemoryStorageManagers.)
*/
func (ms *memberStorage) dump(smname string) string {
var res string
printTransferTable := func(buf *bytes.Buffer) {
// Go through the transfer table and see if there is anything
it := hash.NewHTreeIterator(ms.at.transfer)
for it.HasNext() {
_, val := it.Next()
if val != nil {
tr := val.(*transferRec)
args, _ := json.Marshal(tr.Request.Args)
vals, ok := tr.Request.Value.([]byte)
if !ok {
vals, _ = json.Marshal(tr.Request.Value)
}
buf.WriteString(fmt.Sprintf("transfer: %v - %v %v %q\n",
tr.Members, tr.Request.RequestType, string(args), vals))
}
}
}
if smname == "" {
// Dump the contents of the MainDB if no name is given
buf := new(bytes.Buffer)
buf.WriteString(fmt.Sprintf("%v MemberStorageManager MainDB\n",
ms.ds.MemberManager.Name()))
var keys []string
for k := range ms.gs.MainDB() {
keys = append(keys, k)
}
sort.Strings(keys)
// Output local storage content with mapped cluster locations
for _, k := range keys {
v := ms.gs.MainDB()[k]
buf.WriteString(fmt.Sprintf("%v - %q\n", k, v))
}
printTransferTable(buf)
return buf.String()
}
sm := ms.dataStorage(smname, false)
if sm != nil {
// Make sure the storage manager is a MemoryStorageManager
if msm, ok := sm.(*storage.MemoryStorageManager); ok {
// Get all stored cluster locations
locmap := make(map[uint64]string)
it := hash.NewHTreeIterator(ms.at.translation)
for it.HasNext() {
k, v := it.Next()
key := string(k)
if strings.HasPrefix(key, fmt.Sprint(transPrefix, smname, "#")) {
key = string(key[len(fmt.Sprint(transPrefix, smname, "#")):])
locmap[v.(*translationRec).Loc] = fmt.Sprintf("%v (v:%v)",
key, v.(*translationRec).Ver)
}
}
buf := new(bytes.Buffer)
buf.WriteString(fmt.Sprintf("%v MemberStorageManager %v\n",
ms.ds.MemberManager.Name(), msm.Name()))
buf.WriteString("Roots: ")
// Go through root values
for i := 0; i < 10; i++ {
rootVal := msm.Root(i)
buf.WriteString(fmt.Sprintf("%v=%v ", i, rootVal))
}
buf.WriteString("\n")
var keys []uint64
for k := range msm.Data {
keys = append(keys, k)
}
sortutil.UInt64s(keys)
// Output local storage content with mapped cluster locations
for _, k := range keys {
v := msm.Data[k]
caddr := locmap[k]
buf.WriteString(fmt.Sprintf("cloc: %v - lloc: %v - %q\n",
caddr, k, v))
}
printTransferTable(buf)
res = buf.String()
}
}
return res
}