/
data_blob.go
609 lines (477 loc) · 13.7 KB
/
data_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
package data
import (
"bufio"
"fmt"
"github.com/gonuts/flag"
"github.com/jbenet/commander"
"io"
"os"
"path"
)
var cmd_data_blob = &commander.Command{
UsageLine: "blob <command> <hash>",
Short: "Manage blobs in the blobstore.",
Long: `data blob - Manage blobs in the blobstore.
Commands:
put <hash> <path> Upload blob named by <hash> to blobstore.
get <hash> <path> Download blob named by <hash> from blobstore.
check <hash> <path> Verify blob matches <hash>.
url <hash> Output Url for blob named by <hash>.
show <hash> Output blob contents for hash.
hash <path> Output hash for blob contents.
Arguments:
The <hash> argument is the blob's checksum, and id.
The <path> argument is the blob's target file.
If <path> is omitted, stdin/stdout are used.
What is a blob?
Datasets are made up of files, which are made up of blobs.
(For now, 1 file is 1 blob. Chunking to be implemented)
Blobs are basically blocks of data, which are checksummed
(for integrity, de-duplication, and addressing) using a crypto-
graphic hash function (sha1, for now). If git comes to mind,
that's exactly right.
Local Blobstores
data stores blobs in blobstores. Every local dataset has a
blobstore (local caching with links TBI). Like in git, the blobs
are stored safely in the blobstore (different directory) and can
be used to reconstruct any corrupted/deleted/modified dataset files.
Remote Blobstores
data uses remote blobstores to distribute datasets across users.
The datadex service includes a blobstore (currently an S3 bucket).
By default, the global datadex blobstore is where things are
uploaded to and retrieved from.
Since blobs are uniquely identified by their hash, maintaining one
global blobstore helps reduce data redundancy. However, users can
run their own datadex service. (The index and blobstore are tied
together to ensure consistency. Please do not publish datasets to
an index if blobs aren't in that index)
data can use any remote blobstore you wish. (For now, you have to
recompile, but in the future, you will be able to) Just change the
datadex configuration variable. Or pass in "-s <url>" per command.
(data-blob is part of the plumbing, lower level tools.
Use it directly if you know what you're doing.)
`,
Flag: *flag.NewFlagSet("data-blob", flag.ExitOnError),
Subcommands: []*commander.Command{
cmd_data_blob_put,
cmd_data_blob_get,
cmd_data_blob_url,
cmd_data_blob_show,
cmd_data_blob_hash,
cmd_data_blob_check,
},
}
var cmd_data_blob_put = &commander.Command{
UsageLine: "put <hash> <path>",
Short: "Upload blobs to a remote blobstore.",
Long: `data blob put - Upload blobs to a remote blobstore.
Upload the blob contents named by <hash> to a remote blobstore.
Blob contents are stored locally, to be used to reconstruct files.
In the future, the blobstore will be able to be changed. For now,
the default blobstore/datadex is used.
See data blob.
Arguments:
<hash> name (cryptographic hash, checksum) of the blob.
<path> path of the blob contents to upload.
`,
Run: blobPutCmd,
Flag: *flag.NewFlagSet("data-blob-put", flag.ExitOnError),
}
var cmd_data_blob_get = &commander.Command{
UsageLine: "get <hash> [<path>]",
Short: "Download blobs from a remote blobstore.",
Long: `data blob get - Download blobs from a remote blobstore.
Download the blob contents named by <hash> from a remote blobstore.
Blob contents are stored locally, to be used to reconstruct files.
In the future, the blobstore will be able to be changed. For now,
the default blobstore/datadex is used.
See data blob.
Arguments:
<hash> name (cryptographic hash, checksum) of the blob.
<path> path to put the blob contents in.
`,
Run: blobGetCmd,
Flag: *flag.NewFlagSet("data-blob-get", flag.ExitOnError),
}
var cmd_data_blob_url = &commander.Command{
UsageLine: "url <hash>",
Short: "Output Url for blob named by <hash>.",
Long: `data blob url - Output Url for blob named by <hash>.
Output the remote storage url for the blob contents named by <hash>.
In the future, the blobstore will be able to be changed. For now,
the default blobstore/datadex is used.
See data blob.
Arguments:
<hash> name (cryptographic hash, checksum) of the blob.
`,
Run: blobUrlCmd,
Flag: *flag.NewFlagSet("data-blob-url", flag.ExitOnError),
}
var cmd_data_blob_show = &commander.Command{
UsageLine: "show <hash>",
Short: "Output blob contents for hash.",
Long: `data blob show - Output blob contents for hash.
Output the blob contents stored in the blobstore for hash.
If the blob is available locally, that copy is used (after
hashing to verify correctness). Otherwise, it is downloaded
from the blobstore.
See data blob.
Arguments:
<hash> name (cryptographic hash, checksum) of the blob.
`,
Run: blobShowCmd,
}
var cmd_data_blob_hash = &commander.Command{
UsageLine: "hash <path>",
Short: "Output hash for blob contents.",
Long: `data blob hash - Output hash for blob contents.
Output the hash of the blob contents stored in <path>
See data blob.
Arguments:
<path> path of the blob contents
`,
Run: blobHashCmd,
}
var cmd_data_blob_check = &commander.Command{
UsageLine: "check <hash> <path>",
Short: "Verify blob matches <hash>",
Long: `data blob check - Verify blob matches <hash>.
Verify the hash of the blob contents stored in <path> matches
<hash>.
See data blob.
Arguments:
<hash> name (cryptographic hash, checksum) of the blob.
<path> path of the blob contents
`,
Run: blobCheckCmd,
}
func init() {
cmd_data_blob.Flag.Bool("all", false, "all available blobs")
cmd_data_blob_get.Flag.Bool("all", false, "get all available blobs")
cmd_data_blob_put.Flag.Bool("all", false, "put all available blobs")
cmd_data_blob_url.Flag.Bool("all", false, "urls for all available blobs")
cmd_data_blob_check.Flag.Bool("all", false, "check all available blobs")
}
type blobStore interface {
Has(key string) (bool, error)
Put(key string, value io.Reader) error
Get(key string) (io.ReadCloser, error)
Url(key string) string
}
// map { path : hash } (backward because of dup hashes)
type blobPaths map[string]string
// Handles arguments and dispatches subcommand.
func blobCmd(c *commander.Command, args []string) (blobPaths, error) {
blobs := blobPaths{}
// Use all blobs in the manifest if --all is passed in.
all := c.Flag.Lookup("all").Value.Get().(bool)
if all {
mf := NewDefaultManifest()
blobs = validBlobHashes(mf.Files)
if len(blobs) < 1 {
return nil, fmt.Errorf("%v: no blobs tracked in manifest.", c.FullName())
}
} else {
switch len(args) {
case 2:
blobs[args[1]] = args[0]
case 1:
blobs[""] = args[0]
case 0:
return nil,
fmt.Errorf("%v: requires <hash> argument (or --all)", c.FullName())
}
}
return blobs, nil
}
func blobGetCmd(c *commander.Command, args []string) error {
blobs, err := blobCmd(c, args)
if err != nil {
return err
}
return getBlobs(blobs)
}
func blobPutCmd(c *commander.Command, args []string) error {
blobs, err := blobCmd(c, args)
if err != nil {
return err
}
return putBlobs(blobs)
}
func blobUrlCmd(c *commander.Command, args []string) error {
blobs, err := blobCmd(c, args)
if err != nil {
return err
}
return urlBlobs(blobs)
}
func blobShowCmd(c *commander.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("%v: requires <hash> argument", c.FullName())
}
hash := args[0]
if !IsHash(hash) {
return fmt.Errorf("%v: invalid hash '%s'", c.FullName(), hash)
}
dataIndex, err := NewMainDataIndex()
if err != nil {
return err
}
return dataIndex.copyBlob(hash, os.Stdout)
}
func blobHashCmd(c *commander.Command, args []string) error {
if len(args) < 1 {
return fmt.Errorf("%v: requires <path> argument", c.FullName())
}
hash, err := hashFile(args[0])
if err != nil {
return err
}
pOut("%s\n", hash)
return nil
}
func blobCheckCmd(c *commander.Command, args []string) error {
blobs, err := blobCmd(c, args)
if err != nil {
return err
}
if len(args) == 1 {
return fmt.Errorf("%v: requires <path> argument", c.FullName())
}
return checkBlobs(blobs)
}
// Uploads all blobs to blobstore
func putBlobs(blobs blobPaths) error {
blobs = validBlobHashes(blobs)
dataIndex, err := NewMainDataIndex()
if err != nil {
return err
}
// flip map, to skip dupes
flipped := map[string]string{}
for path, hash := range blobs {
flipped[hash] = path
}
for hash, path := range flipped {
err = dataIndex.putBlob(hash, path)
if err != nil {
return err
}
}
return nil
}
// Downloads all blobs from blobstore
func getBlobs(blobs blobPaths) error {
blobs = validBlobHashes(blobs)
dataIndex, err := NewMainDataIndex()
if err != nil {
return err
}
// group map, to copy dupes
grouped := map[string][]string{}
for path, hash := range blobs {
g, _ := grouped[hash]
grouped[hash] = append(g, path)
}
for hash, paths := range grouped {
// download one blob
err = dataIndex.getBlob(hash, paths[0])
if err != nil {
return err
}
// copy what we got to others
for _, path := range paths[1:] {
pErr("copy blob %.7s %s\n", hash, path)
err := copyFile(paths[0], path)
if err != nil {
return err
}
}
}
return nil
}
// Shows all urls for blobs
func urlBlobs(blobs blobPaths) error {
blobs = validBlobHashes(blobs)
dataIndex, err := NewMainDataIndex()
if err != nil {
return err
}
for _, hash := range blobs {
pErr("%v\n", dataIndex.urlBlob(hash))
}
return nil
}
// Check all blob hashes
func checkBlobs(blobs blobPaths) error {
failures := 0
for fpath, hash := range blobs {
pass, err := checkBlob(hash, fpath)
if err != nil {
return err
}
if !pass {
failures++
}
}
count := len(blobs)
if failures > 0 {
return fmt.Errorf("data blob: %v/%v checksums failed!", failures, count)
}
pOut("data blob: %v checksums pass.\n", count)
return nil
}
func checkBlob(oldHash string, fpath string) (bool, error) {
mfmt := "check %.7s %s %s"
newHash, err := hashFile(fpath)
if err != nil {
switch err.(type) {
case *os.PathError:
// non existent files count as not hashing correctly.
pErr(mfmt, oldHash, fpath, "FAIL - not found\n")
return false, nil
default:
return false, err
}
}
if newHash != oldHash {
pErr(mfmt, oldHash, fpath, "FAIL\n")
return false, nil
}
dOut(mfmt, oldHash, fpath, "PASS\n")
return true, nil
}
// DataIndex extension to handle putting blob
func (i *DataIndex) putBlob(hash string, fpath string) error {
// disallow empty paths
// (stdin doesn't make sense when hashing must have already ocurred)
if len(fpath) == 0 {
return fmt.Errorf("put blob %.7s - error: no path supplied", hash)
}
fpath = path.Clean(fpath)
// first, check the blobstore doesn't already have it.
exists, err := i.hasBlob(hash)
if err != nil {
return err
}
if exists {
pErr("put blob %.7s %s - exists\n", hash, fpath)
return nil
}
// must verify hash before uploading (for integrity).
// (note that there is a TOCTTOU bug here, so not safe. just helps.)
vh, err := hashFile(fpath)
if err != nil {
return err
}
if vh != hash {
m := "put blob: %s hash error (expected %s, got %s)"
return fmt.Errorf(m, fpath, hash, vh)
}
pErr("put blob %.7s %s - uploading\n", hash, fpath)
f, err := os.Open(fpath)
if err != nil {
return err
}
defer f.Close()
bf := bufio.NewReader(f)
err = i.BlobStore.Put(BlobKey(hash), bf)
if err != nil {
return err
}
err = f.Close()
if err != nil {
return err
}
return nil
}
// DataIndex extension to handle getting blob
func (i *DataIndex) getBlob(hash string, fpath string) error {
// disallow empty paths
if len(fpath) == 0 {
return fmt.Errorf("get blob %.7s - error: no path supplied", hash)
}
fpath = path.Clean(fpath)
pErr("get blob %.7s %s\n", hash, fpath)
w, err := createFile(fpath)
if err != nil {
return err
}
defer w.Close()
return i.copyBlob(hash, w)
}
func (i *DataIndex) copyBlob(hash string, w io.WriteCloser) error {
r, err := i.findBlob(hash)
if err != nil {
return err
}
br := bufio.NewReader(r)
_, err = io.Copy(w, br)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
err = r.Close()
if err != nil {
return err
}
return nil
}
func (i *DataIndex) findBlob(hash string) (io.ReadCloser, error) {
mf := NewDefaultManifest()
paths := mf.PathsForHash(hash)
for _, p := range paths {
dOut("found local blob copy. verifying hash. %s\n", p)
h, err := hashFile(p)
if err != nil {
continue
}
if hash == h {
f, err := os.Open(p)
if err != nil {
continue
}
return f, nil
}
}
dOut("no local blob copy. fetch from remote blobstore.\n")
return i.BlobStore.Get(BlobKey(hash))
}
// DataIndex extension to check if blob exists
func (i *DataIndex) hasBlob(hash string) (bool, error) {
return i.BlobStore.Has(BlobKey(hash))
}
// DataIndex extension to handle getting blob url
func (i *DataIndex) urlBlob(hash string) string {
return i.BlobStore.Url(BlobKey(hash))
}
// Returns all paths associated with blob
func allBlobPaths(hash string) ([]string, error) {
mf := NewDefaultManifest()
paths := mf.PathsForHash(hash)
mfh, err := mf.ManifestHash()
if err != nil {
return []string{}, err
}
if mfh == hash {
paths = append(paths, mf.Path)
}
return paths, nil
}
// Returns the blobstore key for blob
func BlobKey(hash string) string {
return fmt.Sprintf("/blob/%s", hash)
}
// Prune out invalid blob paths (bad hashes, bad paths)
func validBlobHashes(blobs blobPaths) blobPaths {
pruned := blobPaths{}
for fpath, hash := range blobs {
if IsHash(hash) {
pruned[fpath] = hash
}
}
return pruned
}