forked from ipfs/kubo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add.go
517 lines (428 loc) · 10.3 KB
/
add.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
package coreunix
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
gopath "path"
ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore"
syncds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore/sync"
bstore "github.com/ipfs/go-ipfs/blocks/blockstore"
key "github.com/ipfs/go-ipfs/blocks/key"
bserv "github.com/ipfs/go-ipfs/blockservice"
"github.com/ipfs/go-ipfs/exchange/offline"
importer "github.com/ipfs/go-ipfs/importer"
"github.com/ipfs/go-ipfs/importer/chunk"
mfs "github.com/ipfs/go-ipfs/mfs"
"github.com/ipfs/go-ipfs/pin"
context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
bs "github.com/ipfs/go-ipfs/blocks/blockstore"
"github.com/ipfs/go-ipfs/commands/files"
core "github.com/ipfs/go-ipfs/core"
dag "github.com/ipfs/go-ipfs/merkledag"
unixfs "github.com/ipfs/go-ipfs/unixfs"
logging "gx/ipfs/Qmazh5oNUVsDZTs2g59rq8aYQqwpss8tcUWQzor5sCCEuH/go-log"
)
var log = logging.Logger("coreunix")
var folderData = unixfs.FolderPBData()
// how many bytes of progress to wait before sending a progress update message
const progressReaderIncrement = 1024 * 256
type Link struct {
Name, Hash string
Size uint64
}
type Object struct {
Hash string
Links []Link
}
type hiddenFileError struct {
fileName string
}
func (e *hiddenFileError) Error() string {
return fmt.Sprintf("%s is a hidden file", e.fileName)
}
type ignoreFileError struct {
fileName string
}
func (e *ignoreFileError) Error() string {
return fmt.Sprintf("%s is an ignored file", e.fileName)
}
type AddedObject struct {
Name string
Hash string `json:",omitempty"`
Bytes int64 `json:",omitempty"`
}
func NewAdder(ctx context.Context, n *core.IpfsNode, out chan interface{}) (*Adder, error) {
mr, err := mfs.NewRoot(ctx, n.DAG, newDirNode(), nil)
if err != nil {
return nil, err
}
return &Adder{
mr: mr,
ctx: ctx,
node: n,
out: out,
Progress: false,
Hidden: true,
Pin: true,
Trickle: false,
Wrap: false,
Chunker: "",
}, nil
}
// Internal structure for holding the switches passed to the `add` call
type Adder struct {
ctx context.Context
node *core.IpfsNode
out chan interface{}
Progress bool
Hidden bool
Pin bool
Trickle bool
Silent bool
Wrap bool
Chunker string
root *dag.Node
mr *mfs.Root
unlocker bs.Unlocker
tempRoot key.Key
}
// Perform the actual add & pin locally, outputting results to reader
func (adder Adder) add(reader io.Reader) (*dag.Node, error) {
chnk, err := chunk.FromString(reader, adder.Chunker)
if err != nil {
return nil, err
}
if adder.Trickle {
return importer.BuildTrickleDagFromReader(
adder.node.DAG,
chnk,
)
}
return importer.BuildDagFromReader(
adder.node.DAG,
chnk,
)
}
func (adder *Adder) RootNode() (*dag.Node, error) {
// for memoizing
if adder.root != nil {
return adder.root, nil
}
root, err := adder.mr.GetValue().GetNode()
if err != nil {
return nil, err
}
// if not wrapping, AND one root file, use that hash as root.
if !adder.Wrap && len(root.Links) == 1 {
root, err = root.Links[0].GetNode(adder.ctx, adder.node.DAG)
if err != nil {
return nil, err
}
}
adder.root = root
return root, err
}
func (adder *Adder) PinRoot() error {
root, err := adder.RootNode()
if err != nil {
return err
}
if !adder.Pin {
return nil
}
rnk, err := adder.node.DAG.Add(root)
if err != nil {
return err
}
if adder.tempRoot != "" {
err := adder.node.Pinning.Unpin(adder.ctx, adder.tempRoot, true)
if err != nil {
return err
}
adder.tempRoot = rnk
}
adder.node.Pinning.PinWithMode(rnk, pin.Recursive)
return adder.node.Pinning.Flush()
}
func (adder *Adder) Finalize() (*dag.Node, error) {
// cant just call adder.RootNode() here as we need the name for printing
root, err := adder.mr.GetValue().GetNode()
if err != nil {
return nil, err
}
var name string
if !adder.Wrap {
name = root.Links[0].Name
child, err := root.Links[0].GetNode(adder.ctx, adder.node.DAG)
if err != nil {
return nil, err
}
root = child
}
err = adder.outputDirs(name, root)
if err != nil {
return nil, err
}
err = adder.mr.Close()
if err != nil {
return nil, err
}
return root, nil
}
func (adder *Adder) outputDirs(path string, nd *dag.Node) error {
if !bytes.Equal(nd.Data, folderData) {
return nil
}
for _, l := range nd.Links {
child, err := l.GetNode(adder.ctx, adder.node.DAG)
if err != nil {
return err
}
err = adder.outputDirs(gopath.Join(path, l.Name), child)
if err != nil {
return err
}
}
return outputDagnode(adder.out, path, nd)
}
// Add builds a merkledag from the a reader, pinning all objects to the local
// datastore. Returns a key representing the root node.
func Add(n *core.IpfsNode, r io.Reader) (string, error) {
defer n.Blockstore.PinLock().Unlock()
fileAdder, err := NewAdder(n.Context(), n, nil)
if err != nil {
return "", err
}
node, err := fileAdder.add(r)
if err != nil {
return "", err
}
k, err := node.Key()
if err != nil {
return "", err
}
return k.String(), nil
}
// AddR recursively adds files in |path|.
func AddR(n *core.IpfsNode, root string) (key string, err error) {
n.Blockstore.PinLock().Unlock()
stat, err := os.Lstat(root)
if err != nil {
return "", err
}
f, err := files.NewSerialFile(root, root, false, stat)
if err != nil {
return "", err
}
defer f.Close()
fileAdder, err := NewAdder(n.Context(), n, nil)
if err != nil {
return "", err
}
err = fileAdder.addFile(f)
if err != nil {
return "", err
}
nd, err := fileAdder.Finalize()
if err != nil {
return "", err
}
k, err := nd.Key()
if err != nil {
return "", err
}
return k.String(), nil
}
// AddWrapped adds data from a reader, and wraps it with a directory object
// to preserve the filename.
// Returns the path of the added file ("<dir hash>/filename"), the DAG node of
// the directory, and and error if any.
func AddWrapped(n *core.IpfsNode, r io.Reader, filename string) (string, *dag.Node, error) {
file := files.NewReaderFile(filename, filename, ioutil.NopCloser(r), nil)
fileAdder, err := NewAdder(n.Context(), n, nil)
if err != nil {
return "", nil, err
}
fileAdder.Wrap = true
defer n.Blockstore.PinLock().Unlock()
err = fileAdder.addFile(file)
if err != nil {
return "", nil, err
}
dagnode, err := fileAdder.Finalize()
if err != nil {
return "", nil, err
}
k, err := dagnode.Key()
if err != nil {
return "", nil, err
}
return gopath.Join(k.String(), filename), dagnode, nil
}
func (adder *Adder) addNode(node *dag.Node, path string) error {
// patch it into the root
if path == "" {
key, err := node.Key()
if err != nil {
return err
}
path = key.Pretty()
}
dir := gopath.Dir(path)
if dir != "." {
if err := mfs.Mkdir(adder.mr, dir, true, false); err != nil {
return err
}
}
if err := mfs.PutNode(adder.mr, path, node); err != nil {
return err
}
if !adder.Silent {
return outputDagnode(adder.out, path, node)
}
return nil
}
// Add the given file while respecting the adder.
func (adder *Adder) AddFile(file files.File) error {
adder.unlocker = adder.node.Blockstore.PinLock()
defer func() {
adder.unlocker.Unlock()
}()
return adder.addFile(file)
}
func (adder *Adder) addFile(file files.File) error {
err := adder.maybePauseForGC()
if err != nil {
return err
}
if file.IsDirectory() {
return adder.addDir(file)
}
// case for symlink
if s, ok := file.(*files.Symlink); ok {
sdata, err := unixfs.SymlinkData(s.Target)
if err != nil {
return err
}
dagnode := &dag.Node{Data: sdata}
_, err = adder.node.DAG.Add(dagnode)
if err != nil {
return err
}
return adder.addNode(dagnode, s.FileName())
}
// case for regular file
// if the progress flag was specified, wrap the file so that we can send
// progress updates to the client (over the output channel)
var reader io.Reader = file
if adder.Progress {
reader = &progressReader{file: file, out: adder.out}
}
dagnode, err := adder.add(reader)
if err != nil {
return err
}
// patch it into the root
return adder.addNode(dagnode, file.FileName())
}
func (adder *Adder) addDir(dir files.File) error {
log.Infof("adding directory: %s", dir.FileName())
err := mfs.Mkdir(adder.mr, dir.FileName(), true, false)
if err != nil {
return err
}
for {
file, err := dir.NextFile()
if err != nil && err != io.EOF {
return err
}
if file == nil {
break
}
// Skip hidden files when adding recursively, unless Hidden is enabled.
if files.IsHidden(file) && !adder.Hidden {
log.Infof("%s is hidden, skipping", file.FileName())
continue
}
err = adder.addFile(file)
if err != nil {
return err
}
}
return nil
}
func (adder *Adder) maybePauseForGC() error {
if adder.node.Blockstore.GCRequested() {
err := adder.PinRoot()
if err != nil {
return err
}
adder.unlocker.Unlock()
adder.unlocker = adder.node.Blockstore.PinLock()
}
return nil
}
// outputDagnode sends dagnode info over the output channel
func outputDagnode(out chan interface{}, name string, dn *dag.Node) error {
if out == nil {
return nil
}
o, err := getOutput(dn)
if err != nil {
return err
}
out <- &AddedObject{
Hash: o.Hash,
Name: name,
}
return nil
}
func NewMemoryDagService() dag.DAGService {
// build mem-datastore for editor's intermediary nodes
bs := bstore.NewBlockstore(syncds.MutexWrap(ds.NewMapDatastore()))
bsrv := bserv.New(bs, offline.Exchange(bs))
return dag.NewDAGService(bsrv)
}
// TODO: generalize this to more than unix-fs nodes.
func newDirNode() *dag.Node {
return &dag.Node{Data: unixfs.FolderPBData()}
}
// from core/commands/object.go
func getOutput(dagnode *dag.Node) (*Object, error) {
key, err := dagnode.Key()
if err != nil {
return nil, err
}
output := &Object{
Hash: key.Pretty(),
Links: make([]Link, len(dagnode.Links)),
}
for i, link := range dagnode.Links {
output.Links[i] = Link{
Name: link.Name,
//Hash: link.Hash.B58String(),
Size: link.Size,
}
}
return output, nil
}
type progressReader struct {
file files.File
out chan interface{}
bytes int64
lastProgress int64
}
func (i *progressReader) Read(p []byte) (int, error) {
n, err := i.file.Read(p)
i.bytes += int64(n)
if i.bytes-i.lastProgress >= progressReaderIncrement || err == io.EOF {
i.lastProgress = i.bytes
i.out <- &AddedObject{
Name: i.file.FileName(),
Bytes: i.bytes,
}
}
return n, err
}