-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathpin.go
689 lines (597 loc) · 16.8 KB
/
pin.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
package commands
import (
"bytes"
"context"
"fmt"
"io"
"time"
cmds "github.com/ipfs/go-ipfs/commands"
core "github.com/ipfs/go-ipfs/core"
e "github.com/ipfs/go-ipfs/core/commands/e"
corerepo "github.com/ipfs/go-ipfs/core/corerepo"
pin "github.com/ipfs/go-ipfs/pin"
uio "gx/ipfs/QmPL8bYtbACcSFFiSr4s2du7Na382NxRADR8hC7D9FkEA2/go-unixfs/io"
cid "gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid"
"gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit"
"gx/ipfs/QmVkMRSkXrpjqrroEXWuYBvDBnXCdMMY6gsKicBGVGUqKT/go-verifcid"
path "gx/ipfs/QmX7uSbkNz76yNwBhuwYwRbhihLnJqM73VTCjS3UMJud9A/go-path"
resolver "gx/ipfs/QmX7uSbkNz76yNwBhuwYwRbhihLnJqM73VTCjS3UMJud9A/go-path/resolver"
dag "gx/ipfs/QmXv5mwmQ74r4aiHcNeQ4GAmfB3aWJuqaE4WyDfDfvkgLM/go-merkledag"
bserv "gx/ipfs/Qma2KhbQarYTkmSJAeaMGRAg8HAXAhEWK8ge4SReG7ZSD3/go-blockservice"
offline "gx/ipfs/QmcRC35JF2pJQneAxa5LdQBQRumWggccWErogSrCkS1h8T/go-ipfs-exchange-offline"
)
var PinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Pin (and unpin) objects to local storage.",
},
Subcommands: map[string]*cmds.Command{
"add": addPinCmd,
"rm": rmPinCmd,
"ls": listPinCmd,
"verify": verifyPinCmd,
"update": updatePinCmd,
},
}
type PinOutput struct {
Pins []string
}
type AddPinOutput struct {
Pins []string
Progress int `json:",omitempty"`
}
var addPinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Pin objects to local storage.",
ShortDescription: "Stores an IPFS object(s) from a given path locally to disk.",
},
Arguments: []cmdkit.Argument{
cmdkit.StringArg("ipfs-path", true, true, "Path to object(s) to be pinned.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("recursive", "r", "Recursively pin the object linked to by the specified object(s).").WithDefault(true),
cmdkit.BoolOption("progress", "Show progress"),
},
Type: AddPinOutput{},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
defer n.Blockstore.PinLock().Unlock()
// set recursive flag
recursive, _, err := req.Option("recursive").Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
showProgress, _, _ := req.Option("progress").Bool()
if !showProgress {
added, err := corerepo.Pin(n, req.Context(), req.Arguments(), recursive)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
res.SetOutput(&AddPinOutput{Pins: cidsToStrings(added)})
return
}
out := make(chan interface{})
res.SetOutput((<-chan interface{})(out))
v := new(dag.ProgressTracker)
ctx := v.DeriveContext(req.Context())
type pinResult struct {
pins []cid.Cid
err error
}
ch := make(chan pinResult, 1)
go func() {
added, err := corerepo.Pin(n, ctx, req.Arguments(), recursive)
ch <- pinResult{pins: added, err: err}
}()
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
defer close(out)
for {
select {
case val := <-ch:
if val.err != nil {
res.SetError(val.err, cmdkit.ErrNormal)
return
}
if pv := v.Value(); pv != 0 {
out <- &AddPinOutput{Progress: v.Value()}
}
out <- &AddPinOutput{Pins: cidsToStrings(val.pins)}
return
case <-ticker.C:
out <- &AddPinOutput{Progress: v.Value()}
case <-ctx.Done():
log.Error(ctx.Err())
res.SetError(ctx.Err(), cmdkit.ErrNormal)
return
}
}
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
}
var added []string
switch out := v.(type) {
case *AddPinOutput:
if out.Pins != nil {
added = out.Pins
} else {
// this can only happen if the progress option is set
fmt.Fprintf(res.Stderr(), "Fetched/Processed %d nodes\r", out.Progress)
}
if res.Error() != nil {
return nil, res.Error()
}
default:
return nil, e.TypeErr(out, v)
}
var pintype string
rec, found, _ := res.Request().Option("recursive").Bool()
if rec || !found {
pintype = "recursively"
} else {
pintype = "directly"
}
buf := new(bytes.Buffer)
for _, k := range added {
fmt.Fprintf(buf, "pinned %s %s\n", k, pintype)
}
return buf, nil
},
},
}
var rmPinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Remove pinned objects from local storage.",
ShortDescription: `
Removes the pin from the given object allowing it to be garbage
collected if needed. (By default, recursively. Use -r=false for direct pins.)
`,
},
Arguments: []cmdkit.Argument{
cmdkit.StringArg("ipfs-path", true, true, "Path to object(s) to be unpinned.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("recursive", "r", "Recursively unpin the object linked to by the specified object(s).").WithDefault(true),
},
Type: PinOutput{},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
// set recursive flag
recursive, _, err := req.Option("recursive").Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
removed, err := corerepo.Unpin(n, req.Context(), req.Arguments(), recursive)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
res.SetOutput(&PinOutput{cidsToStrings(removed)})
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
}
added, ok := v.(*PinOutput)
if !ok {
return nil, e.TypeErr(added, v)
}
buf := new(bytes.Buffer)
for _, k := range added.Pins {
fmt.Fprintf(buf, "unpinned %s\n", k)
}
return buf, nil
},
},
}
var listPinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "List objects pinned to local storage.",
ShortDescription: `
Returns a list of objects that are pinned locally.
By default, all pinned objects are returned, but the '--type' flag or
arguments can restrict that to a specific pin type or to some specific objects
respectively.
`,
LongDescription: `
Returns a list of objects that are pinned locally.
By default, all pinned objects are returned, but the '--type' flag or
arguments can restrict that to a specific pin type or to some specific objects
respectively.
Use --type=<type> to specify the type of pinned keys to list.
Valid values are:
* "direct": pin that specific object.
* "recursive": pin that specific object, and indirectly pin all its
descendants
* "indirect": pinned indirectly by an ancestor (like a refcount)
* "all"
With arguments, the command fails if any of the arguments is not a pinned
object. And if --type=<type> is additionally used, the command will also fail
if any of the arguments is not of the specified type.
Example:
$ echo "hello" | ipfs add -q
QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN
$ ipfs pin ls
QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN recursive
# now remove the pin, and repin it directly
$ ipfs pin rm QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN
unpinned QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN
$ ipfs pin add -r=false QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN
pinned QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN directly
$ ipfs pin ls --type=direct
QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN direct
$ ipfs pin ls QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN
QmZULkCELmmk5XNfCgTnCyFgAVxBRBXyDHGGMVoLFLiXEN direct
`,
},
Arguments: []cmdkit.Argument{
cmdkit.StringArg("ipfs-path", false, true, "Path to object(s) to be listed."),
},
Options: []cmdkit.Option{
cmdkit.StringOption("type", "t", "The type of pinned keys to list. Can be \"direct\", \"indirect\", \"recursive\", or \"all\".").WithDefault("all"),
cmdkit.BoolOption("quiet", "q", "Write just hashes of objects."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
typeStr, _, err := req.Option("type").String()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
switch typeStr {
case "all", "direct", "indirect", "recursive":
default:
err = fmt.Errorf("invalid type '%s', must be one of {direct, indirect, recursive, all}", typeStr)
res.SetError(err, cmdkit.ErrClient)
return
}
var keys map[string]RefKeyObject
if len(req.Arguments()) > 0 {
keys, err = pinLsKeys(req.Context(), req.Arguments(), typeStr, n)
} else {
keys, err = pinLsAll(req.Context(), typeStr, n)
}
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
} else {
res.SetOutput(&RefKeyList{Keys: keys})
}
},
Type: RefKeyList{},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
}
quiet, _, err := res.Request().Option("quiet").Bool()
if err != nil {
return nil, err
}
keys, ok := v.(*RefKeyList)
if !ok {
return nil, e.TypeErr(keys, v)
}
out := new(bytes.Buffer)
for k, v := range keys.Keys {
if quiet {
fmt.Fprintf(out, "%s\n", k)
} else {
fmt.Fprintf(out, "%s %s\n", k, v.Type)
}
}
return out, nil
},
},
}
var updatePinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Update a recursive pin",
ShortDescription: `
Updates one pin to another, making sure that all objects in the new pin are
local. Then removes the old pin. This is an optimized version of adding the
new pin and removing the old one.
`,
},
Arguments: []cmdkit.Argument{
cmdkit.StringArg("from-path", true, false, "Path to old object."),
cmdkit.StringArg("to-path", true, false, "Path to new object to be pinned."),
},
Options: []cmdkit.Option{
cmdkit.BoolOption("unpin", "Remove the old pin.").WithDefault(true),
},
Type: PinOutput{},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
unpin, _, err := req.Option("unpin").Bool()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
from, err := path.ParsePath(req.Arguments()[0])
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
to, err := path.ParsePath(req.Arguments()[1])
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
r := &resolver.Resolver{
DAG: n.DAG,
ResolveOnce: uio.ResolveUnixfsOnce,
}
fromc, err := core.ResolveToCid(req.Context(), n.Namesys, r, from)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
toc, err := core.ResolveToCid(req.Context(), n.Namesys, r, to)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
err = n.Pinning.Update(req.Context(), fromc, toc, unpin)
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
err = n.Pinning.Flush()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
res.SetOutput(&PinOutput{Pins: []string{from.String(), to.String()}})
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
v, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
}
added, ok := v.(*PinOutput)
if !ok {
return nil, e.TypeErr(added, v)
}
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "updated %s to %s\n", added.Pins[0], added.Pins[1])
return buf, nil
},
},
}
var verifyPinCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Verify that recursive pins are complete.",
},
Options: []cmdkit.Option{
cmdkit.BoolOption("verbose", "Also write the hashes of non-broken pins."),
cmdkit.BoolOption("quiet", "q", "Write just hashes of broken pins."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmdkit.ErrNormal)
return
}
verbose, _, _ := res.Request().Option("verbose").Bool()
quiet, _, _ := res.Request().Option("quiet").Bool()
if verbose && quiet {
res.SetError(fmt.Errorf("the --verbose and --quiet options can not be used at the same time"), cmdkit.ErrNormal)
}
opts := pinVerifyOpts{
explain: !quiet,
includeOk: verbose,
}
out := pinVerify(req.Context(), n, opts)
res.SetOutput(out)
},
Type: PinVerifyRes{},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
quiet, _, _ := res.Request().Option("quiet").Bool()
out, err := unwrapOutput(res.Output())
if err != nil {
return nil, err
}
r, ok := out.(*PinVerifyRes)
if !ok {
return nil, e.TypeErr(r, out)
}
buf := &bytes.Buffer{}
if quiet && !r.Ok {
fmt.Fprintf(buf, "%s\n", r.Cid)
} else if !quiet {
r.Format(buf)
}
return buf, nil
},
},
}
type RefKeyObject struct {
Type string
}
type RefKeyList struct {
Keys map[string]RefKeyObject
}
func pinLsKeys(ctx context.Context, args []string, typeStr string, n *core.IpfsNode) (map[string]RefKeyObject, error) {
mode, ok := pin.StringToMode(typeStr)
if !ok {
return nil, fmt.Errorf("invalid pin mode '%s'", typeStr)
}
keys := make(map[string]RefKeyObject)
r := &resolver.Resolver{
DAG: n.DAG,
ResolveOnce: uio.ResolveUnixfsOnce,
}
for _, p := range args {
pth, err := path.ParsePath(p)
if err != nil {
return nil, err
}
c, err := core.ResolveToCid(ctx, n.Namesys, r, pth)
if err != nil {
return nil, err
}
pinType, pinned, err := n.Pinning.IsPinnedWithType(c, mode)
if err != nil {
return nil, err
}
if !pinned {
return nil, fmt.Errorf("path '%s' is not pinned", p)
}
switch pinType {
case "direct", "indirect", "recursive", "internal":
default:
pinType = "indirect through " + pinType
}
keys[c.String()] = RefKeyObject{
Type: pinType,
}
}
return keys, nil
}
func pinLsAll(ctx context.Context, typeStr string, n *core.IpfsNode) (map[string]RefKeyObject, error) {
keys := make(map[string]RefKeyObject)
AddToResultKeys := func(keyList []cid.Cid, typeStr string) {
for _, c := range keyList {
keys[c.String()] = RefKeyObject{
Type: typeStr,
}
}
}
if typeStr == "direct" || typeStr == "all" {
AddToResultKeys(n.Pinning.DirectKeys(), "direct")
}
if typeStr == "indirect" || typeStr == "all" {
set := cid.NewSet()
for _, k := range n.Pinning.RecursiveKeys() {
err := dag.EnumerateChildren(ctx, dag.GetLinksWithDAG(n.DAG), k, set.Visit)
if err != nil {
return nil, err
}
}
AddToResultKeys(set.Keys(), "indirect")
}
if typeStr == "recursive" || typeStr == "all" {
AddToResultKeys(n.Pinning.RecursiveKeys(), "recursive")
}
return keys, nil
}
// PinVerifyRes is the result returned for each pin checked in "pin verify"
type PinVerifyRes struct {
Cid string
PinStatus
}
// PinStatus is part of PinVerifyRes, do not use directly
type PinStatus struct {
Ok bool
BadNodes []BadNode `json:",omitempty"`
}
// BadNode is used in PinVerifyRes
type BadNode struct {
Cid string
Err string
}
type pinVerifyOpts struct {
explain bool
includeOk bool
}
func pinVerify(ctx context.Context, n *core.IpfsNode, opts pinVerifyOpts) <-chan interface{} {
visited := make(map[string]PinStatus)
bs := n.Blocks.Blockstore()
DAG := dag.NewDAGService(bserv.New(bs, offline.Exchange(bs)))
getLinks := dag.GetLinksWithDAG(DAG)
recPins := n.Pinning.RecursiveKeys()
var checkPin func(root cid.Cid) PinStatus
checkPin = func(root cid.Cid) PinStatus {
key := root.String()
if status, ok := visited[key]; ok {
return status
}
if err := verifcid.ValidateCid(root); err != nil {
status := PinStatus{Ok: false}
if opts.explain {
status.BadNodes = []BadNode{BadNode{Cid: key, Err: err.Error()}}
}
visited[key] = status
return status
}
links, err := getLinks(ctx, root)
if err != nil {
status := PinStatus{Ok: false}
if opts.explain {
status.BadNodes = []BadNode{BadNode{Cid: key, Err: err.Error()}}
}
visited[key] = status
return status
}
status := PinStatus{Ok: true}
for _, lnk := range links {
res := checkPin(lnk.Cid)
if !res.Ok {
status.Ok = false
status.BadNodes = append(status.BadNodes, res.BadNodes...)
}
}
visited[key] = status
return status
}
out := make(chan interface{})
go func() {
defer close(out)
for _, cid := range recPins {
pinStatus := checkPin(cid)
if !pinStatus.Ok || opts.includeOk {
select {
case out <- &PinVerifyRes{cid.String(), pinStatus}:
case <-ctx.Done():
return
}
}
}
}()
return out
}
// Format formats PinVerifyRes
func (r PinVerifyRes) Format(out io.Writer) {
if r.Ok {
fmt.Fprintf(out, "%s ok\n", r.Cid)
} else {
fmt.Fprintf(out, "%s broken\n", r.Cid)
for _, e := range r.BadNodes {
fmt.Fprintf(out, " %s: %s\n", e.Cid, e.Err)
}
}
}
func cidsToStrings(cs []cid.Cid) []string {
out := make([]string, 0, len(cs))
for _, c := range cs {
out = append(out, c.String())
}
return out
}