forked from ipfs/go-ipfs-api
-
Notifications
You must be signed in to change notification settings - Fork 1
/
shell.go
571 lines (490 loc) · 12.7 KB
/
shell.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
// package shell implements a remote API interface for a running ipfs daemon
package shell
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
gohttp "net/http"
"os"
"path"
"strings"
"time"
files "github.com/ipfs/go-ipfs-files"
homedir "github.com/mitchellh/go-homedir"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr-net"
tar "github.com/whyrusleeping/tar-utils"
p2pmetrics "github.com/libp2p/go-libp2p-metrics"
)
const (
DefaultPathName = ".ipfs"
DefaultPathRoot = "~/" + DefaultPathName
DefaultApiFile = "api"
EnvDir = "IPFS_PATH"
)
type Shell struct {
url string
httpcli *gohttp.Client
}
func NewLocalShell() *Shell {
baseDir := os.Getenv(EnvDir)
if baseDir == "" {
baseDir = DefaultPathRoot
}
baseDir, err := homedir.Expand(baseDir)
if err != nil {
return nil
}
apiFile := path.Join(baseDir, DefaultApiFile)
if _, err := os.Stat(apiFile); err != nil {
return nil
}
api, err := ioutil.ReadFile(apiFile)
if err != nil {
return nil
}
return NewShell(strings.TrimSpace(string(api)))
}
func NewShell(url string) *Shell {
c := &gohttp.Client{
Transport: &gohttp.Transport{
Proxy: gohttp.ProxyFromEnvironment,
DisableKeepAlives: true,
},
}
return NewShellWithClient(url, c)
}
// NewDirectShell creates a new shell that directly uses the provided URL,
// instead of attempting to parse it into a multiaddr.
//
// For Nexus-hosted IPFS nodes, for example, use:
//
// shell := NewDirectShell(fmt.Sprintf("nexus.temporal.cloud/network/%s", networkName))
//
func NewDirectShell(url string) *Shell {
return &Shell{
url: url,
httpcli: &gohttp.Client{
Transport: &gohttp.Transport{
Proxy: gohttp.ProxyFromEnvironment,
DisableKeepAlives: true,
},
},
}
}
func NewShellWithClient(url string, c *gohttp.Client) *Shell {
if a, err := ma.NewMultiaddr(url); err == nil {
_, host, err := manet.DialArgs(a)
if err == nil {
url = host
}
}
return &Shell{
url: url,
httpcli: c,
}
}
// WithAuthorization returns a Shell that sets the provided token to be used as
// an Authorization header in API requests. For example:
//
// resp, err := NewDirectShell(addr).
// WithAuthorization(token).
// Cat(hash)
//
func (s *Shell) WithAuthorization(token string) *Shell {
return &Shell{
url: s.url,
httpcli: &gohttp.Client{
Transport: newAuthenticatedTransport(s.httpcli.Transport, token),
},
}
}
func (s *Shell) SetTimeout(d time.Duration) {
s.httpcli.Timeout = d
}
func (s *Shell) Request(command string, args ...string) *RequestBuilder {
return &RequestBuilder{
command: command,
args: args,
shell: s,
}
}
type IdOutput struct {
ID string
PublicKey string
Addresses []string
AgentVersion string
ProtocolVersion string
}
// ID gets information about a given peer. Arguments:
//
// peer: peer.ID of the node to look up. If no peer is specified,
// return information about the local peer.
func (s *Shell) ID(peer ...string) (*IdOutput, error) {
if len(peer) > 1 {
return nil, fmt.Errorf("Too many peer arguments")
}
var out IdOutput
if err := s.Request("id", peer...).Exec(context.Background(), &out); err != nil {
return nil, err
}
return &out, nil
}
// Cat the content at the given path. Callers need to drain and close the returned reader after usage.
func (s *Shell) CatGet(path string) (io.ReadCloser, error) {
resp, err := NewRequest(context.Background(), s.url, "cat", path).SendGET(s.httpcli)
if err != nil {
return nil, err
}
if resp.Error != nil {
return nil, resp.Error
}
return resp.Output, nil
}
// Cat the content at the given path. Callers need to drain and close the returned reader after usage.
func (s *Shell) Cat(path string) (io.ReadCloser, error) {
resp, err := s.Request("cat", path).Send(context.Background())
if err != nil {
return nil, err
}
if resp.Error != nil {
return nil, resp.Error
}
return resp.Output, nil
}
const (
TRaw = iota
TDirectory
TFile
TMetadata
TSymlink
)
// List entries at the given path
func (s *Shell) List(path string) ([]*LsLink, error) {
var out struct{ Objects []LsObject }
err := s.Request("ls", path).Exec(context.Background(), &out)
if err != nil {
return nil, err
}
if len(out.Objects) != 1 {
return nil, errors.New("bad response from server")
}
return out.Objects[0].Links, nil
}
type LsLink struct {
Hash string
Name string
Size uint64
Type int
}
type LsObject struct {
Links []*LsLink
LsLink
}
// Pin the given path
func (s *Shell) Pin(path string) error {
return s.Request("pin/add", path).
Option("recursive", true).
Exec(context.Background(), nil)
}
// PinUpdate is used to update one pin path to another followed by unpinning
func (s *Shell) PinUpdate(fromPath, toPath string) (map[string][]string, error) {
var out map[string][]string
if err := s.Request("pin/update", fromPath, toPath).Exec(context.Background(), &out); err != nil {
return nil, err
}
return out, nil
}
// Unpin the given path
func (s *Shell) Unpin(path string) error {
return s.Request("pin/rm", path).
Option("recursive", true).
Exec(context.Background(), nil)
}
const (
DirectPin = "direct"
RecursivePin = "recursive"
IndirectPin = "indirect"
)
type PinInfo struct {
Type string
}
// Pins returns a map of the pin hashes to their info (currently just the
// pin type, one of DirectPin, RecursivePin, or IndirectPin. A map is returned
// instead of a slice because it is easier to do existence lookup by map key
// than unordered array searching. The map is likely to be more useful to a
// client than a flat list.
func (s *Shell) Pins() (map[string]PinInfo, error) {
var raw struct{ Keys map[string]PinInfo }
return raw.Keys, s.Request("pin/ls").Exec(context.Background(), &raw)
}
type PeerInfo struct {
Addrs []string
ID string
}
func (s *Shell) FindPeer(peer string) (*PeerInfo, error) {
var peers struct{ Responses []PeerInfo }
err := s.Request("dht/findpeer", peer).Exec(context.Background(), &peers)
if err != nil {
return nil, err
}
if len(peers.Responses) == 0 {
return nil, errors.New("peer not found")
}
return &peers.Responses[0], nil
}
func (s *Shell) Refs(hash string, recursive, unique bool) (<-chan string, error) {
resp, err := s.Request("refs", hash).
Option("recursive", recursive).
Option("unique", unique).
Send(context.Background())
if err != nil {
return nil, err
}
if resp.Error != nil {
resp.Close()
return nil, resp.Error
}
out := make(chan string)
go func() {
defer resp.Close()
var ref struct {
Ref string
}
defer close(out)
dec := json.NewDecoder(resp.Output)
for {
err := dec.Decode(&ref)
if err != nil {
return
}
if len(ref.Ref) > 0 {
out <- ref.Ref
}
}
}()
return out, nil
}
func (s *Shell) Patch(root, action string, args ...string) (string, error) {
var out object
return out.Hash, s.Request("object/patch/"+action, root).
Arguments(args...).
Exec(context.Background(), &out)
}
func (s *Shell) PatchData(root string, set bool, data interface{}) (string, error) {
var read io.Reader
switch d := data.(type) {
case io.Reader:
read = d
case []byte:
read = bytes.NewReader(d)
case string:
read = strings.NewReader(d)
default:
return "", fmt.Errorf("unrecognized type: %#v", data)
}
cmd := "append-data"
if set {
cmd = "set-data"
}
fr := files.NewReaderFile(read)
slf := files.NewSliceDirectory([]files.DirEntry{files.FileEntry("", fr)})
fileReader := files.NewMultiFileReader(slf, true)
var out object
return out.Hash, s.Request("object/patch/"+cmd, root).
Body(fileReader).
Exec(context.Background(), &out)
}
func (s *Shell) PatchLink(root, path, childhash string, create bool) (string, error) {
var out object
return out.Hash, s.Request("object/patch/add-link", root, path, childhash).
Option("create", create).
Exec(context.Background(), &out)
}
func (s *Shell) Get(hash, outdir string) error {
resp, err := s.Request("get", hash).Option("create", true).Send(context.Background())
if err != nil {
return err
}
defer resp.Close()
if resp.Error != nil {
return resp.Error
}
extractor := &tar.Extractor{Path: outdir}
return extractor.Extract(resp.Output)
}
func (s *Shell) NewObject(template string) (string, error) {
var out object
req := s.Request("object/new")
if template != "" {
req.Arguments(template)
}
return out.Hash, req.Exec(context.Background(), &out)
}
func (s *Shell) ResolvePath(path string) (string, error) {
var out struct {
Path string
}
err := s.Request("resolve", path).Exec(context.Background(), &out)
if err != nil {
return "", err
}
return strings.TrimPrefix(out.Path, "/ipfs/"), nil
}
// returns ipfs version and commit sha
func (s *Shell) Version() (string, string, error) {
ver := struct {
Version string
Commit string
}{}
if err := s.Request("version").Exec(context.Background(), &ver); err != nil {
return "", "", err
}
return ver.Version, ver.Commit, nil
}
func (s *Shell) IsUp() bool {
_, _, err := s.Version()
return err == nil
}
func (s *Shell) BlockStat(path string) (string, int, error) {
var inf struct {
Key string
Size int
}
if err := s.Request("block/stat", path).Exec(context.Background(), &inf); err != nil {
return "", 0, err
}
return inf.Key, inf.Size, nil
}
func (s *Shell) BlockGet(path string) ([]byte, error) {
resp, err := s.Request("block/get", path).Send(context.Background())
if err != nil {
return nil, err
}
defer resp.Close()
if resp.Error != nil {
return nil, resp.Error
}
return ioutil.ReadAll(resp.Output)
}
func (s *Shell) BlockPut(block []byte, format, mhtype string, mhlen int) (string, error) {
var out struct {
Key string
}
fr := files.NewBytesFile(block)
slf := files.NewSliceDirectory([]files.DirEntry{files.FileEntry("", fr)})
fileReader := files.NewMultiFileReader(slf, true)
return out.Key, s.Request("block/put").
Option("mhtype", mhtype).
Option("format", format).
Option("mhlen", mhlen).
Body(fileReader).
Exec(context.Background(), &out)
}
type IpfsObject struct {
Links []ObjectLink
Data string
}
type ObjectLink struct {
Name, Hash string
Size uint64
}
func (s *Shell) ObjectGet(path string) (*IpfsObject, error) {
var obj IpfsObject
if err := s.Request("object/get", path).Exec(context.Background(), &obj); err != nil {
return nil, err
}
return &obj, nil
}
func (s *Shell) ObjectPut(obj *IpfsObject) (string, error) {
var data bytes.Buffer
err := json.NewEncoder(&data).Encode(obj)
if err != nil {
return "", err
}
fr := files.NewReaderFile(&data)
slf := files.NewSliceDirectory([]files.DirEntry{files.FileEntry("", fr)})
fileReader := files.NewMultiFileReader(slf, true)
var out object
return out.Hash, s.Request("object/put").
Body(fileReader).
Exec(context.Background(), &out)
}
func (s *Shell) PubSubSubscribe(topic string) (*PubSubSubscription, error) {
// connect
resp, err := s.Request("pubsub/sub", topic).Send(context.Background())
if err != nil {
return nil, err
}
return newPubSubSubscription(resp), nil
}
func (s *Shell) PubSubPublish(topic, data string) (err error) {
resp, err := s.Request("pubsub/pub", topic, data).Send(context.Background())
if err != nil {
return err
}
defer resp.Close()
if resp.Error != nil {
return resp.Error
}
return nil
}
type ObjectStats struct {
Hash string
BlockSize int
CumulativeSize int
DataSize int
LinksSize int
NumLinks int
}
// ObjectStat gets stats for the DAG object named by key. It returns
// the stats of the requested Object or an error.
func (s *Shell) ObjectStat(key string) (*ObjectStats, error) {
var stat ObjectStats
err := s.Request("object/stat", key).Exec(context.Background(), &stat)
if err != nil {
return nil, err
}
return &stat, nil
}
// ObjectStat gets stats for the DAG object named by key. It returns
// the stats of the requested Object or an error.
func (s *Shell) StatsBW(ctx context.Context) (*p2pmetrics.Stats, error) {
v := &p2pmetrics.Stats{}
err := s.Request("stats/bw").Exec(ctx, &v)
return v, err
}
type SwarmStreamInfo struct {
Protocol string
}
type SwarmConnInfo struct {
Addr string
Peer string
Latency string
Muxer string
Streams []SwarmStreamInfo
}
type SwarmConnInfos struct {
Peers []SwarmConnInfo
}
// SwarmPeers gets all the swarm peers
func (s *Shell) SwarmPeers(ctx context.Context) (*SwarmConnInfos, error) {
v := &SwarmConnInfos{}
err := s.Request("swarm/peers").Exec(ctx, &v)
return v, err
}
type swarmConnection struct {
Strings []string
}
// SwarmConnect opens a swarm connection to a specific address.
func (s *Shell) SwarmConnect(ctx context.Context, addr ...string) error {
var conn *swarmConnection
err := s.Request("swarm/connect").
Arguments(addr...).
Exec(ctx, &conn)
return err
}