/
blob.go
1334 lines (1188 loc) · 46.2 KB
/
blob.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
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vsync
// This file contains blob handling code.
//
// A summary of inter-device blob management:
//
// Syncbase implements a system of "blob ownership" to reduce the
// probability that a blob will be lost due to the loss of a mobile
// device. This works as follows.
//
// When a device that has a blob Put()s the blobref in an existing syncgroup,
// or makes a row containing a blobref syncable for the first time by creating
// a syncgroup, it assigns itself an initial number of "ownership shares" to
// the blob within that syncgroup. Usually the initial number of shares per
// blob per syncgroup is 2.
//
// If a device does not have the blob, or associates the blobref with a
// syncgroup via the creation of an overlapping syncgroup, or via syncing,
// no ownership shares are assigned. Instead, the blobref is allowed to
// propagate around the syncgroup until devices request
// the blob (note that servers always request blobs; see below).
//
// Any device with a non-zero number of ownership shares for a blob
// in a syncgroup has an obligation not to discard its copy of the
// blob, and not to reduce the number of ownership shares it has
// without first passing shares to another device within the
// syncgroup. This obligation lapses if the blob ceases to be
// accessible via the syncgroup.
//
// When a device acquires a copy of a blob, it may elect to take on
// the burden of one or more ownership shares in each syncgroup in
// which the blob is accessible. To decide whether to transfer a
// share for a syncgroup, devices compare their "ownership
// priorities" within the syncgroup. The priorities are defined in
// terms of metrics suggestive of the "sync distance" of the device
// from the "servers" for the relevant syncgroup.
//
// A device that is marked as a "server" within the syncgroup is
// expected:
// - to acquire and keep copies of every blob accessible within the
// syncgroup,
// - to make these copies available to other devices on demand, and
// - to use techniques such as replication and backup to make their
// loss unlikely.
// Thus, servers have the highest ownership priority. Other
// devices have lower ownership priorities according to their
// presumed ability to transfer the blob to the servers. Each server
// periodically attempts to fetch any blob that it does not yet have that
// is referenced by the syncgroup.
//
// If a syncgroup has no servers, it is more likely that the loss of a device
// will lead to the loss of a blob, and that other devices will fail to find
// the blob should they request it. This is because servers are more likely to
// be available and to store blobs reliably, and because the location hints
// work best when well-known servers exist.
//
// Each device computes its ownership priority by keeping track of various
// numbers in the SgPriority struct in
// v.io/x/ref/services/syncbase/server/interfaces/sync_types.vdl
// - DevType indicates the type of device.
// - Distance is the mean distance (in "hops") from the servers, maintained via
// decaying average.
// - ServerTime is the time on a server at which data created there has reached
// this device. Times within timeSlop (syncgroup.go) are considered equivalent.
//
// Device types are manually assigned to devices, perhaps by default by the
// device manufacturer. The set is
// BlobDevTypeServer (accummulates blobs when possible, like a cloud server),
// BlobDevTypeNormal,
// BlobDevTypeLeaf (sheds blobs when possible, like a camera),
// defined in v.io/v23/services/syncbase/nosql/types.vdl
//
// Priorities can be compared via sgPriorityLowerThan() in syncgroup.go.
//
// Each time a device "local" receives data from a peer "remote", the remote
// device sends its Priority value, and the local device then adjusts its
// priority. See updateSyncgroupPriority() in syncgroup.go
//
// The rules for transferring an ownership share when a device receives a copy
// of a blob are:
// - A server always sets its ownership shares to non-zero for any blob
// accessible within its syncgroups. That is, a server never
// unilaterally deletes a reachable blob.
// - A non-server may transfer all its ownership shares to a server, even if
// that server already has shares. (It can choose to transfer fewer; if it
// does so, the excess shares will likely be transferred in subsequent
// communications.)
// - A non-server with at least one share may transfer one share to a
// non-server with no shares and a higher priority.
//
// When a device syncs with a device to which it would transfer some ownership
// shares, it informs that device that it should take a copy of the blob and
// accept the share. The recipient then tells the first device that it may
// decrement its share count.
//
// Example: Suppose four devices are in a syncgroup:
// - a server S (BlobDevTypeServer)
// - a laptop L (BlobDevTypeNormal)
// - a tablet T (BlobDevTypeNormal)
// - a camera C that communicates with L and T, but not directly with S.
// (BlobDevTypeLeaf)
// C's images are turned into blobs accessible via the syncgroup.
//
// When online, L and T can communicate directly with the server, so
// L.ServerTime and T.ServerTime will be recent, while L.Distance and
// T.Distance will both be close to 1. C.ServerTime will be somewhat less
// recent, and C.Distance will be close to 2. The priorities will satisfy:
// S > T > C and S > L > C. Sometimes T > L and sometimes the reverse,
// depending on when they sync with S.
//
// If L, T, and C go offline (imagine taking a vacation cruise with them),
// their ServerTime values will remain unchanged from when they were last
// online. One of L and T will have a higher priority; its Distance metric
// will remain constant, while the other two devices' distances will increase
// somewhat. The relative priority ordering of the devices will then stay the
// same until contact is re-stablished with S.
//
// Suppose C takes a picture P giving it two shares, and syncs first with L.
// L will accept one share, and refuse to accept more while its share count is
// non-zero. L's share may be taken by T or by S (if L is on-line). L could
// then take C's second share. Alternatively, C might transfer its second
// share to T, if T has not received a share from L. At this point, C is free
// to delete its copy of P, knowing that either S has the blob, or at least two
// other devices do.
//
// -----------
//
// An additional mechanism of location hints, called Signposts, exists to allow
// devices to find blobs whose blobrefs they have received.
//
// A Signpost consists of two lists:
// - a list of syncgroups whose data mention the blobref
// - a list of devices that have had the blob, or at least been instrumental
// in forwarding its blobref.
// When a device receives a blobref, it constructs a Signpost that contains the
// syncgroups and peer that the blobref arrived through, plus the peer that
// inserted the blobref into the structured data (known through the log record)
//
// When a device requests a blob that the callee does not have, the callee may
// return its Signpost for the blob. The caller then merges this into its own
// Signpost. In this way, improved hints may propagate through the system.
// The list of devices in a Signpost is restricted in length so that Signposts
// do not become too large (see mergeSignposts()). Ultimately, devices are
// expected to request blobs from the server machines within the relevant
// syncgroups.
//
// In transferring Signposts, devices filter the lists they send to avoid
// revealing private information about syncgroups (see filterSignpost()). In
// particular, they avoid sending the name of a syncgroup to a peer that does
// not have permission to join the group unless the group is "public" (a
// property chosen at group creation). Also, device location hints are given
// only to peers who have permission to join a syncgroup to which the device
// belongs, or if the device is a server in one of the syncgroups. The
// expectation is that servers have no privacy constraints; many syncgroups and
// users may be associated with any given server.
import (
"io"
"sort"
"strings"
"time"
"v.io/v23"
"v.io/v23/context"
"v.io/v23/naming"
"v.io/v23/options"
"v.io/v23/rpc"
"v.io/v23/security"
"v.io/v23/security/access"
wire "v.io/v23/services/syncbase"
"v.io/v23/vdl"
"v.io/v23/verror"
"v.io/v23/vom"
"v.io/x/lib/vlog"
"v.io/x/ref/services/syncbase/common"
blob "v.io/x/ref/services/syncbase/localblobstore"
_ "v.io/x/ref/services/syncbase/localblobstore/blobmap"
"v.io/x/ref/services/syncbase/server/interfaces"
"v.io/x/ref/services/syncbase/store"
"v.io/x/ref/services/syncbase/store/watchable"
)
const (
chunkSize = 8 * 1024
)
////////////////////////////////////////////////////////////
// RPCs for managing blobs between Syncbase and its clients.
func (sd *syncDatabase) CreateBlob(ctx *context.T, call rpc.ServerCall) (wire.BlobRef, error) {
allowCreateBlob := []access.Tag{access.Write}
vlog.VI(2).Infof("sync: CreateBlob: begin")
defer vlog.VI(2).Infof("sync: CreateBlob: end")
if err := sd.db.CheckExists(ctx, call); err != nil {
return wire.NullBlobRef, err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowCreateBlob, sd.db.St()); err != nil {
return wire.NullBlobRef, err
}
// Get this Syncbase's blob store handle.
ss := sd.sync.(*syncService)
bst := ss.bst
writer, err := bst.NewBlobWriter(ctx, "")
if err != nil {
return wire.NullBlobRef, err
}
defer writer.CloseWithoutFinalize()
name := writer.Name()
vlog.VI(4).Infof("sync: CreateBlob: blob ref %s", name)
return wire.BlobRef(name), nil
}
func (sd *syncDatabase) PutBlob(ctx *context.T, call wire.BlobManagerPutBlobServerCall, br wire.BlobRef) error {
allowPutBlob := []access.Tag{access.Write}
vlog.VI(2).Infof("sync: PutBlob: begin br %v", br)
defer vlog.VI(2).Infof("sync: PutBlob: end br %v", br)
if err := sd.db.CheckExists(ctx, call); err != nil {
return err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowPutBlob, sd.db.St()); err != nil {
return err
}
// Get this Syncbase's blob store handle.
ss := sd.sync.(*syncService)
bst := ss.bst
writer, err := bst.ResumeBlobWriter(ctx, string(br))
if err != nil {
return err
}
defer writer.CloseWithoutFinalize()
stream := call.RecvStream()
for stream.Advance() {
item := blob.BlockOrFile{Block: stream.Value()}
if err = writer.AppendBytes(item); err != nil {
return err
}
}
return stream.Err()
}
func (sd *syncDatabase) CommitBlob(ctx *context.T, call rpc.ServerCall, br wire.BlobRef) error {
allowCommitBlob := []access.Tag{access.Write}
vlog.VI(2).Infof("sync: CommitBlob: begin br %v", br)
defer vlog.VI(2).Infof("sync: CommitBlob: end br %v", br)
if err := sd.db.CheckExists(ctx, call); err != nil {
return err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowCommitBlob, sd.db.St()); err != nil {
return err
}
// Get this Syncbase's blob store handle.
ss := sd.sync.(*syncService)
bst := ss.bst
writer, err := bst.ResumeBlobWriter(ctx, string(br))
if err != nil {
return err
}
return writer.Close()
}
func (sd *syncDatabase) GetBlobSize(ctx *context.T, call rpc.ServerCall, br wire.BlobRef) (int64, error) {
allowGetBlobSize := wire.AllDatabaseTags
vlog.VI(2).Infof("sync: GetBlobSize: begin br %v", br)
defer vlog.VI(2).Infof("sync: GetBlobSize: end br %v", br)
if err := sd.db.CheckExists(ctx, call); err != nil {
return 0, err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowGetBlobSize, sd.db.St()); err != nil {
return 0, err
}
// Get this Syncbase's blob store handle.
ss := sd.sync.(*syncService)
bst := ss.bst
reader, err := bst.NewBlobReader(ctx, string(br))
if err != nil {
return 0, err
}
defer reader.Close()
return reader.Size(), nil
}
func (sd *syncDatabase) DeleteBlob(ctx *context.T, call rpc.ServerCall, br wire.BlobRef) error {
allowDeleteBlob := wire.AllDatabaseTags
if err := sd.db.CheckExists(ctx, call); err != nil {
return err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowDeleteBlob, sd.db.St()); err != nil {
return err
}
return verror.NewErrNotImplemented(ctx)
}
func (sd *syncDatabase) GetBlob(ctx *context.T, call wire.BlobManagerGetBlobServerCall, br wire.BlobRef, offset int64) error {
allowGetBlob := wire.AllDatabaseTags
vlog.VI(2).Infof("sync: GetBlob: begin br %v", br)
defer vlog.VI(2).Infof("sync: GetBlob: end br %v", br)
if err := sd.db.CheckExists(ctx, call); err != nil {
return err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowGetBlob, sd.db.St()); err != nil {
return err
}
// First get the blob locally if available.
ss := sd.sync.(*syncService)
err := getLocalBlob(ctx, call.SendStream(), ss.bst, br, offset)
if err == nil || verror.ErrorID(err) == wire.ErrBlobNotCommitted.ID {
return err
}
return ss.fetchBlobRemote(ctx, br, nil, call, offset)
}
func (sd *syncDatabase) FetchBlob(ctx *context.T, call wire.BlobManagerFetchBlobServerCall, br wire.BlobRef, priority uint64) error {
allowFetchBlob := wire.AllDatabaseTags
vlog.VI(2).Infof("sync: FetchBlob: begin br %v", br)
defer vlog.VI(2).Infof("sync: FetchBlob: end br %v", br)
if err := sd.db.CheckExists(ctx, call); err != nil {
return err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowFetchBlob, sd.db.St()); err != nil {
return err
}
clientStream := call.SendStream()
// Check if BlobRef already exists locally.
ss := sd.sync.(*syncService)
bst := ss.bst
bReader, err := bst.NewBlobReader(ctx, string(br))
if err == nil {
finalized := bReader.IsFinalized()
bReader.Close()
if !finalized {
return wire.NewErrBlobNotCommitted(ctx)
}
clientStream.Send(wire.BlobFetchStatus{State: wire.BlobFetchStateDone})
return nil
}
// Wait for this blob's turn.
// TODO(hpucha): Implement a blob queue.
clientStream.Send(wire.BlobFetchStatus{State: wire.BlobFetchStatePending})
return ss.fetchBlobRemote(ctx, br, call, nil, 0)
}
func (sd *syncDatabase) PinBlob(ctx *context.T, call rpc.ServerCall, br wire.BlobRef) error {
allowPinBlob := []access.Tag{access.Write}
if err := sd.db.CheckExists(ctx, call); err != nil {
return err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowPinBlob, sd.db.St()); err != nil {
return err
}
return verror.NewErrNotImplemented(ctx)
}
func (sd *syncDatabase) UnpinBlob(ctx *context.T, call rpc.ServerCall, br wire.BlobRef) error {
allowUnpinBlob := wire.AllDatabaseTags
if err := sd.db.CheckExists(ctx, call); err != nil {
return err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowUnpinBlob, sd.db.St()); err != nil {
return err
}
return verror.NewErrNotImplemented(ctx)
}
func (sd *syncDatabase) KeepBlob(ctx *context.T, call rpc.ServerCall, br wire.BlobRef, rank uint64) error {
allowKeepBlob := wire.AllDatabaseTags
if err := sd.db.CheckExists(ctx, call); err != nil {
return err
}
// Check permissions on Database.
if _, err := common.GetPermsWithAuth(ctx, call, sd.db, allowKeepBlob, sd.db.St()); err != nil {
return err
}
return verror.NewErrNotImplemented(ctx)
}
////////////////////////////////////////////////////////////
// RPC for blob fetch between Syncbases.
func (s *syncService) FetchBlob(ctx *context.T, call interfaces.SyncFetchBlobServerCall, br wire.BlobRef,
remoteSgPriorities interfaces.SgPriorities) (sharesToTransfer interfaces.BlobSharesBySyncgroup, err error) {
vlog.VI(2).Infof("sync: FetchBlob: sb-sb begin br %v", br)
defer vlog.VI(2).Infof("sync: FetchBlob: sb-sb end br %v", br)
err = getLocalBlob(ctx, call.SendStream(), s.bst, br, 0)
if err == nil {
// Compute how many shares in each syncgroup this syncbase should
// request that the caller take from it.
var blobMetadata blob.BlobMetadata
// Start by computing the total shares this syncbase has in all
// syncgroups. We save time later if it has none.
var totalShares int32
if s.bst.GetBlobMetadata(ctx, br, &blobMetadata) == nil {
for _, shares := range blobMetadata.OwnerShares {
totalShares += shares
}
}
if totalShares != 0 {
// For each syncgroup, compute whether to transfer shares.
// At present, we offer only one per syncgroup, unless
// the caller is a server, and could take all of them.
// No need to filter localSgPriorities explicitly; they
// will be filtered against the remoteSgPriorities in
// the loop below.
localSgPriorities := make(interfaces.SgPriorities)
if addBlobSyncgroupPriorities(ctx, s.bst, br, localSgPriorities) == nil {
// We will request that the caller take different numbers of shares
// depending on whether it is a "server" in the relevant syncgroup.
for sgId, remoteSgPriority := range remoteSgPriorities {
localShares := blobMetadata.OwnerShares[sgId]
localSgPriority, gotLocalSgPriority := localSgPriorities[sgId]
if gotLocalSgPriority && localShares > 0 && sgPriorityLowerThan(&localSgPriority, &remoteSgPriority) {
if sharesToTransfer == nil {
sharesToTransfer = make(interfaces.BlobSharesBySyncgroup)
}
if remoteSgPriority.DevType == wire.BlobDevTypeServer {
// Caller is a server in this syncgroup----give it all the shares.
sharesToTransfer[sgId] = localShares
} else { // Caller is not a server, give it one share.
sharesToTransfer[sgId] = 1
}
}
}
}
}
}
return sharesToTransfer, err
}
func (s *syncService) HaveBlob(ctx *context.T, call rpc.ServerCall,
br wire.BlobRef) (size int64, signpost interfaces.Signpost, err error) {
vlog.VI(2).Infof("sync: HaveBlob: begin br %v", br)
defer vlog.VI(2).Infof("sync: HaveBlob: end br %v", br)
// In this routine we do not set err!=nil if the blob is unavailable.
// Instead set size==-1, and set signpost.
size = -1
if bReader, err2 := s.bst.NewBlobReader(ctx, string(br)); err2 == nil {
if bReader.IsFinalized() { // found blob, and it's complete
size = bReader.Size()
}
bReader.Close()
}
if size == -1 { // can't find blob; try to return signpost
err = s.bst.GetSignpost(ctx, br, &signpost)
if err == nil {
var blessingNames []string
blessingNames, _ = security.RemoteBlessingNames(ctx, call.Security())
filterSignpost(ctx, blessingNames, s, &signpost)
}
}
return size, signpost, err
}
func (s *syncService) FetchBlobRecipe(ctx *context.T, call interfaces.SyncFetchBlobRecipeServerCall,
br wire.BlobRef, callerName string, remoteSgPriorities interfaces.SgPriorities) (interfaces.BlobSharesBySyncgroup, error) {
return nil, verror.NewErrNotImplemented(ctx)
}
func (s *syncService) FetchChunks(ctx *context.T, call interfaces.SyncFetchChunksServerCall) error {
return verror.NewErrNotImplemented(ctx)
}
// RequestTakeBlobs tells the server that client wishes the server to take some
// ownership shares for the blobs in the map blobRefToShares.
func (s *syncService) RequestTakeBlobs(ctx *context.T, call rpc.ServerCall,
callerName string, blobRefToShares map[wire.BlobRef]interfaces.BlobSharesBySyncgroup) error {
var blobRef wire.BlobRef
var sgToShares interfaces.BlobSharesBySyncgroup
var bf *blobFetcher = s.SyncServiceBlobFetcher()
if bf != nil {
for blobRef, sgToShares = range blobRefToShares {
var blobMetadata blob.BlobMetadata
err := s.bst.GetBlobMetadata(ctx, blobRef, &blobMetadata)
var shouldFetch bool
if err == nil {
var gid interfaces.GroupId
var sharesToTake int32
for gid, sharesToTake = range sgToShares {
if sharesToTake > 0 && blobMetadata.OwnerShares[gid] == 0 {
shouldFetch = true
break
}
}
} else { // if there's no metadata, should fetch the blob
shouldFetch = true
}
if shouldFetch {
bf.StartFetchingBlob(s.bst, blobRef, s, time.Now().Add(5*time.Minute),
DefaultBlobFetcherFunc)
}
}
}
return nil
}
// AcceptedBlobOwnership tells the server that the caller has accepted
// ownership shares of the blob, detailed in acceptedSharesBySyncgroup.
// TODO(m3b): need to pass mttables?
func (s *syncService) AcceptedBlobOwnership(ctx *context.T, call rpc.ServerCall, br wire.BlobRef, callerName string,
acceptedSharesBySyncgroup interfaces.BlobSharesBySyncgroup) (serverName string, keepingBlob bool, err error) {
// TODO(m3b): Perhaps verify that the caller matches the ACL on the
// syncgroups on which it's accepting ownership shares.
// TODO(m3b): Add synchronization so that two calls to
// AcceptedBlobOwnership() or calls assigning ownership in
// processBlobRefs for the same blob won't overlap. This may cause
// shares either to be lost or gained accidentally.
var blobMetadata blob.BlobMetadata
err = s.bst.GetBlobMetadata(ctx, br, &blobMetadata)
var totalShares int32
var mutatedBlobMetdata bool
if err == nil {
// Get the syncgroups associated with this blob into the sgSet, sgs.
var sgs sgSet = make(sgSet)
for groupId := range blobMetadata.OwnerShares {
sgs[groupId] = struct{}{}
}
// Get the list of syncgroups in sgs for which callerName is a server in
// sgs.
var serverSgsForCaller sgSet = s.syncgroupsWithServer(ctx, wire.Id{}, callerName, sgs)
// For each syncgroup for which the client will accept some
// shares, decrement our ownership count. Keep track of how
// many shares this syncbase has kept.
for groupId, gotShares := range blobMetadata.OwnerShares {
acceptedShares := acceptedSharesBySyncgroup[groupId]
if acceptedShares > 0 && gotShares > 0 {
if _, callerIsServer := serverSgsForCaller[groupId]; !callerIsServer {
acceptedShares = 1 // callerName not a server; give it only one share
} // else callerName is a server in this group; it can take all the shares.
if acceptedShares >= gotShares {
gotShares = 0
delete(blobMetadata.OwnerShares, groupId) // Last share taken.
} else { // Otherwise, the caller may not take our last share.
gotShares -= acceptedShares
blobMetadata.OwnerShares[groupId] = gotShares
}
mutatedBlobMetdata = true
}
totalShares += gotShares
}
if mutatedBlobMetdata {
err = s.bst.SetBlobMetadata(ctx, br, &blobMetadata)
}
if mutatedBlobMetdata && err == nil && totalShares == 0 {
// This device successfully reduced its total shares to zero,
// and may therefore discard the blob. The device that just
// accepted the shares will keep it, so add that device to the
// Signpost.
newLocData := peerLocationData(len(serverSgsForCaller) != 0, false)
sp := interfaces.Signpost{Locations: interfaces.PeerToLocationDataMap{callerName: newLocData}}
s.addToBlobSignpost(ctx, br, &sp)
}
}
// TODO(m3b): return mttables, as well as just name of syncbase?
return s.name, err == nil && totalShares > 0, err
}
// GetBlobShares returns the number of ownership shares for the specified blob
// held by the server. It is used by the DevModeGetBlobShares() call in the
// service.
func (s *syncService) GetBlobShares(ctx *context.T, call rpc.ServerCall, br wire.BlobRef) (
shares map[string]int32, err error) {
var blobMetadata blob.BlobMetadata
err = s.bst.GetBlobMetadata(ctx, br, &blobMetadata)
if err == nil {
shares = make(map[string]int32)
for sg, shareCount := range blobMetadata.OwnerShares {
shares[string(sg)] = shareCount
}
}
return shares, err
}
////////////////////////////////////////////////////////////
// Helpers.
type byteStream interface {
Send(item []byte) error
}
// getLocalBlob looks for a blob in the local store and, if found, reads the
// blob and sends it to the client. If the blob is found, it starts reading it
// from the given offset and sends its bytes into the client stream.
func getLocalBlob(ctx *context.T, stream byteStream, bst blob.BlobStore, br wire.BlobRef, offset int64) error {
vlog.VI(4).Infof("sync: getLocalBlob: begin br %v, offset %v", br, offset)
defer vlog.VI(4).Infof("sync: getLocalBlob: end br %v, offset %v", br, offset)
reader, err := bst.NewBlobReader(ctx, string(br))
if err != nil {
return err
}
defer reader.Close()
if !reader.IsFinalized() {
return wire.NewErrBlobNotCommitted(ctx)
}
buf := make([]byte, chunkSize)
for {
nbytes, err := reader.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return err
}
if nbytes <= 0 {
break
}
offset += int64(nbytes)
stream.Send(buf[:nbytes])
if err == io.EOF {
break
}
}
return nil
}
func (s *syncService) fetchBlobRemote(ctx *context.T, br wire.BlobRef, statusCall wire.BlobManagerFetchBlobServerCall, dataCall wire.BlobManagerGetBlobServerCall, offset int64) error {
vlog.VI(4).Infof("sync: fetchBlobRemote: begin br %v, offset %v", br, offset)
defer vlog.VI(4).Infof("sync: fetchBlobRemote: end br %v, offset %v", br, offset)
// TODO(m3b): If this is called concurrently on the same blobref, we'll do redundant work.
// We might also transfer too many ownership shares.
var sendStatus, sendData bool
var statusStream interface {
Send(item wire.BlobFetchStatus) error
}
var dataStream interface {
Send(item []byte) error
}
if statusCall != nil {
sendStatus = true
statusStream = statusCall.SendStream()
}
if dataCall != nil {
sendData = true
dataStream = dataCall.SendStream()
}
if sendStatus {
// Start blob source discovery.
statusStream.Send(wire.BlobFetchStatus{State: wire.BlobFetchStateLocating})
}
// Locate blob.
peer, size, err := s.locateBlob(ctx, br)
if err != nil {
return err
}
// Start blob fetching.
status := wire.BlobFetchStatus{State: wire.BlobFetchStateFetching, Total: size}
if sendStatus {
statusStream.Send(status)
}
bst := s.bst
bWriter, err := bst.NewBlobWriter(ctx, string(br))
if err != nil {
return err
}
// Get the syncgroup priorities for the blob that the peer is permitted
// to know about.
sgPriorities := make(interfaces.SgPriorities)
var signpost interfaces.Signpost
var blessingNames []string
if s.bst.GetSignpost(ctx, br, &signpost) == nil {
blessingNames, err = getPeerBlessingsForFetchBlob(ctx, peer)
if err == nil {
filterSignpost(ctx, blessingNames, s, &signpost)
addSyncgroupPriorities(ctx, s.bst, signpost.SgIds, sgPriorities)
}
}
c := interfaces.SyncClient(peer)
ctxPeer, cancel := context.WithRootCancel(ctx)
// Run FetchBlob(), but checking that the peer has at least the
// blessing names used above to generate the syncgroup priorities.
stream, err := c.FetchBlob(ctxPeer, br, sgPriorities,
options.ServerAuthorizer{namesAuthorizer{expNames: blessingNames}})
if err == nil {
peerStream := stream.RecvStream()
for peerStream.Advance() {
item := blob.BlockOrFile{Block: peerStream.Value()}
if err = bWriter.AppendBytes(item); err != nil {
break
}
curSize := int64(len(item.Block))
status.Received += curSize
if sendStatus {
statusStream.Send(status)
}
if sendData {
if curSize <= offset {
offset -= curSize
} else if offset != 0 {
dataStream.Send(item.Block[offset:])
offset = 0
} else {
dataStream.Send(item.Block)
}
}
}
if err != nil {
cancel()
stream.Finish()
} else {
err = peerStream.Err()
remoteSharesBySgId, terr := stream.Finish()
if err == nil {
err = terr
}
if err == nil {
// We successfully fetched the blob. Maybe
// take ownership in one or more syncgroups.
takingOwnership := make(interfaces.BlobSharesBySyncgroup)
for sgId, shares := range remoteSharesBySgId {
myPriority, havePriority := sgPriorities[sgId]
if shares > 0 && havePriority {
if myPriority.DevType != wire.BlobDevTypeServer && shares > 1 {
// Non server devices never accept more than one share.
shares = 1
}
takingOwnership[sgId] = shares
}
}
// If we are accepting ownership shares, tell the peer.
if len(takingOwnership) != 0 {
// Don't worry if the following call fails; its
// safe for this syncbase to treat
// itself as an owner even if the peer
// has not relinquished ownership.
// TODO(m3b): With the current code, a peer accepts blob ownership only if
// it retrieves the blob. This may mean that a laptop accepts some of
// the shares for an image from a camera, but if the laptop keeps a copy
// despite passing its shares to a server, it may never come back to
// accept the last share, forcing the camera to keep the blob forever.
// Among the possible fixes:
// a) accept all ownership shares (undesirable, to protect against
// loss of device accepting shares), or
// b) somehow (in signposts?) communicate to peers when the blob has
// reached a "server" so that they may unilaterally drop their shares, or
// c) (most likely) sometimes accept shares when we have none even for
// blobs we already have, triggered perhaps via the RequestTakeBlobs() call.
var peerName string
var peerKeepingBlob bool
peerName, peerKeepingBlob, _ = c.AcceptedBlobOwnership(ctx, br, s.name, takingOwnership)
var blobMetadata blob.BlobMetadata
s.bst.GetBlobMetadata(ctx, br, &blobMetadata)
for sgId, shares := range takingOwnership {
blobMetadata.OwnerShares[sgId] += shares
}
s.bst.SetBlobMetadata(ctx, br, &blobMetadata)
// Remove peer from local signpost if it's not keeping blob.
if !peerKeepingBlob {
var sp interfaces.Signpost
if s.bst.GetSignpost(ctx, br, &sp) == nil {
delete(sp.Locations, peerName)
s.bst.SetSignpost(ctx, br, &sp)
}
}
}
}
cancel()
}
}
bWriter.Close()
if err != nil {
// Clean up the blob with failed download, so that it can be
// downloaded again. Ignore any error from deletion.
bst.DeleteBlob(ctx, string(br))
} else {
status := wire.BlobFetchStatus{State: wire.BlobFetchStateDone}
if sendStatus {
statusStream.Send(status)
}
}
return err
}
// getPeerBlessingsForFetchBlob returns the list of blessing names for
// the given peer by invoking a null FetchBlob call on that peer.
func getPeerBlessingsForFetchBlob(ctx *context.T, peer string) (blessingNames []string, err error) {
var call rpc.ClientCall
call, err = v23.GetClient(ctx).StartCall(ctx, peer, "FetchBlob",
[]interface{}{wire.BlobRef(""), interfaces.SgPriorities{}})
if err == nil {
blessingNames, _ = call.RemoteBlessings()
call.Finish()
}
return blessingNames, err
}
// filterSignpost removes from Signpost signpost any information that cannot be
// given to an endpoint with blessings blessingNames[], or wouldn't be useful.
func filterSignpost(ctx *context.T, blessingNames []string, s *syncService, signpost *interfaces.Signpost) {
keepPeer := make(map[string]bool) // Location hints to keep.
s.forEachDatabaseStore(ctx, func(dbId wire.Id, st *watchable.Store) bool {
// For each database, fetch its syncgroup data entries by scanning their
// prefix range. Use a database snapshot for the scan.
snapshot := st.NewSnapshot()
defer snapshot.Abort()
forEachSyncgroup(snapshot, func(gid interfaces.GroupId, sg *interfaces.Syncgroup) bool {
_, sgIsPresent := signpost.SgIds[gid]
if sgIsPresent {
// Reveal a hinted syncgroup only if not private, or
// the caller has permission to join it.
isVisible := !sg.Spec.IsPrivate || isAuthorizedForTag(sg.Spec.Perms, access.Read, blessingNames)
if !isVisible { // Otherwise omit the syncgroup.
delete(signpost.SgIds, gid)
}
// Reveal a hinted location only if either:
// - the location is a public server (marked in the Signpost), or
// - the location is in a hinted syncgroup, and either is a server,
// or that syncgroup is being revealed to the caller.
for peer := range signpost.Locations {
if signpost.Locations[peer].IsServer {
keepPeer[peer] = true
} else {
sgMember, joinerInSg := sg.Joiners[peer]
if joinerInSg && (isVisible || sgMember.MemberInfo.BlobDevType == byte(wire.BlobDevTypeServer)) {
keepPeer[peer] = true
}
}
}
}
return false // from forEachSyncgroup closure
})
return false // from forEachDatabaseStore closure
})
for peer := range signpost.Locations {
if !keepPeer[peer] {
delete(signpost.Locations, peer)
}
}
}
// addBlobSyncgroupPriorities inserts into map sgPriMap the syncgroup
// priorities for the syncgroups in blob br's Signpost.
// This routine does not filter the information---this is done by the calling routine.
func addBlobSyncgroupPriorities(ctx *context.T, bst blob.BlobStore, br wire.BlobRef, sgPriMap interfaces.SgPriorities) error {
var signpost interfaces.Signpost
err := bst.GetSignpost(ctx, br, &signpost)
if err == nil {
return addSyncgroupPriorities(ctx, bst, signpost.SgIds, sgPriMap)
}
return err
}
// A peerAndLocData is a pair (peer, interfaces.LocationData),
// which represent the entries in an interfaces.PeerToLocationDataMap.
type peerAndLocData struct {
peer string
locData interfaces.LocationData
}
// A peerAndLocDataVector is a slice of peerAndLocData.
// It is used to sort the list, to allow the list to be pruned.
type peerAndLocDataVector []peerAndLocData
// The following functions implement sort.Interface for peerAndLocDataVector.
// It's used to keep the top few values for each Signpost.
func (v peerAndLocDataVector) Len() int { return len(v) }
func (v peerAndLocDataVector) Swap(i int, j int) { v[i], v[j] = v[j], v[i] }
func (v peerAndLocDataVector) Less(i int, j int) bool {
if v[i].locData.IsServer && !v[j].locData.IsServer { // Prefer to keep servers.
return true
}
if v[i].locData.IsProxy && !v[j].locData.IsProxy { // Prefer to keep proxies.
return true
}
// Prefer to keep entries with later timestamps.
return v[j].locData.WhenSeen.Before(v[i].locData.WhenSeen)
}
// mergeSignposts merges data from a source Signpost into a target Spignpost.
func mergeSignposts(targetSp *interfaces.Signpost, sourceSp *interfaces.Signpost) {
// Target's maps exist because GetSignpost() ensures they do.
if targetSp.Locations == nil || targetSp.SgIds == nil {
panic("mergeSignposts called with targetSp with nil map")
}
// Merge the source data into the target.
for sgId := range sourceSp.SgIds {
targetSp.SgIds[sgId] = struct{}{}
}
for peer, sourceLocData := range sourceSp.Locations {
if targetLocData, merging := targetSp.Locations[peer]; !merging {
targetSp.Locations[peer] = sourceLocData
} else if targetLocData.WhenSeen.Before(sourceLocData.WhenSeen) {
targetSp.Locations[peer] = sourceLocData
}
}
// If there are too many locations in the target Signpost, trim it.
if len(targetSp.Locations) > maxLocationsInSignpost {
locList := make(peerAndLocDataVector, 0, len(targetSp.Locations))
for peer, locData := range targetSp.Locations {
locList = append(locList, peerAndLocData{peer: peer, locData: locData})
}
sort.Sort(locList) // Sort by WhenSeen timestamp.
for i := maxLocationsInSignpost; i != len(locList); i++ {
delete(targetSp.Locations, locList[i].peer)
}
}
}
// TODO(hpucha): Add syncgroup driven blob discovery.
func (s *syncService) locateBlob(ctx *context.T, br wire.BlobRef) (string, int64, error) {
vlog.VI(4).Infof("sync: locateBlob: begin br %v", br)
defer vlog.VI(4).Infof("sync: locateBlob: end br %v", br)
var sp interfaces.Signpost
err := s.bst.GetSignpost(ctx, br, &sp)
if err != nil {
return "", 0, err
}
var updatedSp bool // whether "sp" has been updated since being fetched
// Search for blob amongst the Locations in the Signpost.
// Move list of peers into a slice so that we can extend iteration as
// more hints are found. Never look at more than maxLocationsInSignpost hints.
var locationList peerAndLocDataVector
locationMap := make(map[string]bool) // Set of peers in locationList.