block.go 7.45 KB
Newer Older
1 2 3 4
package commands

import (
	"bytes"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
	"fmt"
6
	"io"
7
	"io/ioutil"
Jan Winkelmann's avatar
Jan Winkelmann committed
8
	"os"
9

10
	util "github.com/ipfs/go-ipfs/blocks/blockstore/util"
Jan Winkelmann's avatar
Jan Winkelmann committed
11
	e "github.com/ipfs/go-ipfs/core/commands/e"
Steven Allen's avatar
Steven Allen committed
12 13
	"gx/ipfs/QmP9vZfc5WSjfGTXmwX2EcicMFzmZ6fXn7HTdKYat6ccmH/go-ipfs-cmds"
	"gx/ipfs/QmQp2a2Hhb7F6eK2A5hN8f9aJy4mtkEikL9Zj4cgB7d1dD/go-ipfs-cmdkit"
14

Steven Allen's avatar
Steven Allen committed
15 16 17
	mh "gx/ipfs/QmYeKnKpubCMRiq3PGZcTREErthbb5Q9cXsCoSkD9bjEBd/go-multihash"
	blocks "gx/ipfs/QmYsEQydGrsxNZfAiskvQ76N2xE9hDQtSAkRSynwMiUK3c/go-block-format"
	cid "gx/ipfs/QmeSrf6pzut73u6zLQkRFQ3ygt3k6XFT2kjdYP8Tnkwwyg/go-cid"
18 19
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20 21 22 23 24 25 26
type BlockStat struct {
	Key  string
	Size int
}

func (bs BlockStat) String() string {
	return fmt.Sprintf("Key: %s\nSize: %d\n", bs.Key, bs.Size)
27 28
}

29
var BlockCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
30
	Helptext: cmdkit.HelpText{
31
		Tagline: "Interact with raw IPFS blocks.",
32
		ShortDescription: `
33
'ipfs block' is a plumbing command used to manipulate raw IPFS blocks.
34
Reads from stdin or writes to stdout, and <key> is a base58 encoded
35 36 37 38
multihash.
`,
	},

39
	Subcommands: map[string]*cmds.Command{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40 41 42
		"stat": blockStatCmd,
		"get":  blockGetCmd,
		"put":  blockPutCmd,
Kevin Atkinson's avatar
Kevin Atkinson committed
43
		"rm":   blockRmCmd,
44 45 46
	},
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47
var blockStatCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
48
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
49
		Tagline: "Print information of a raw IPFS block.",
50
		ShortDescription: `
rht's avatar
rht committed
51
'ipfs block stat' is a plumbing command for retrieving information
52
on raw IPFS blocks. It outputs the following to stdout:
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53 54 55 56

	Key  - the base58 encoded multihash
	Size - the size of the block in bytes

57 58
`,
	},
59

Jan Winkelmann's avatar
Jan Winkelmann committed
60 61
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("key", true, false, "The base58 multihash of an existing block to stat.").EnableStdin(),
62
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
63
	Run: func(req cmds.Request, res cmds.ResponseEmitter) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64
		b, err := getBlockForKey(req, req.Arguments()[0])
65
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
66
			res.SetError(err, cmdkit.ErrNormal)
67
			return
68
		}
69

keks's avatar
keks committed
70
		err = cmds.EmitOnce(res, &BlockStat{
71
			Key:  b.Cid().String(),
Jeromy's avatar
Jeromy committed
72
			Size: len(b.RawData()),
73
		})
Jan Winkelmann's avatar
Jan Winkelmann committed
74 75 76
		if err != nil {
			log.Error(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77 78
	},
	Type: BlockStat{},
Jan Winkelmann's avatar
Jan Winkelmann committed
79 80 81 82 83 84 85 86 87
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeEncoder(func(req cmds.Request, w io.Writer, v interface{}) error {
			bs, ok := v.(*BlockStat)
			if !ok {
				return e.TypeErr(bs, v)
			}
			_, err := fmt.Fprintf(w, "%s", bs)
			return err
		}),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88 89
	},
}
90

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91
var blockGetCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
92
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
93
		Tagline: "Get a raw IPFS block.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94
		ShortDescription: `
95
'ipfs block get' is a plumbing command for retrieving raw IPFS blocks.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96 97 98
It outputs to stdout, and <key> is a base58 encoded multihash.
`,
	},
99

Jan Winkelmann's avatar
Jan Winkelmann committed
100 101
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("key", true, false, "The base58 multihash of an existing block to get.").EnableStdin(),
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
102
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
103
	Run: func(req cmds.Request, res cmds.ResponseEmitter) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
		b, err := getBlockForKey(req, req.Arguments()[0])
105
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
106
			res.SetError(err, cmdkit.ErrNormal)
107
			return
108 109
		}

Jan Winkelmann's avatar
Jan Winkelmann committed
110 111 112 113
		err = res.Emit(bytes.NewReader(b.RawData()))
		if err != nil {
			log.Error(err)
		}
114 115 116 117
	},
}

var blockPutCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
118
	Helptext: cmdkit.HelpText{
119
		Tagline: "Store input as an IPFS block.",
120
		ShortDescription: `
121
'ipfs block put' is a plumbing command for storing raw IPFS blocks.
122 123 124
It reads from stdin, and <key> is a base58 encoded multihash.
`,
	},
125

Jan Winkelmann's avatar
Jan Winkelmann committed
126 127
	Arguments: []cmdkit.Argument{
		cmdkit.FileArg("data", true, false, "The data to be stored as an IPFS block.").EnableStdin(),
128
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
129
	Options: []cmdkit.Option{
130 131 132
		cmdkit.StringOption("format", "f", "cid format for blocks to be created with.").WithDefault("v0"),
		cmdkit.StringOption("mhtype", "multihash hash function").WithDefault("sha2-256"),
		cmdkit.IntOption("mhlen", "multihash hash length").WithDefault(-1),
133
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
134
	Run: func(req cmds.Request, res cmds.ResponseEmitter) {
Jeromy's avatar
Jeromy committed
135
		n, err := req.InvocContext().GetNode()
136
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
137
			res.SetError(err, cmdkit.ErrNormal)
138
			return
139
		}
140

141 142
		file, err := req.Files().NextFile()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
143
			res.SetError(err, cmdkit.ErrNormal)
144
			return
145 146 147 148
		}

		data, err := ioutil.ReadAll(file)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
149
			res.SetError(err, cmdkit.ErrNormal)
150
			return
151 152
		}

153
		err = file.Close()
154
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
155
			res.SetError(err, cmdkit.ErrNormal)
156
			return
157 158
		}

159 160
		var pref cid.Prefix
		pref.Version = 1
161 162

		format, _, _ := req.Option("format").String()
163 164
		formatval, ok := cid.Codecs[format]
		if !ok {
Jan Winkelmann's avatar
Jan Winkelmann committed
165
			res.SetError(fmt.Errorf("unrecognized format: %s", format), cmdkit.ErrNormal)
166 167
			return
		}
168 169 170 171
		if format == "v0" {
			pref.Version = 0
		}
		pref.Codec = formatval
172

173 174 175
		mhtype, _, _ := req.Option("mhtype").String()
		mhtval, ok := mh.Names[mhtype]
		if !ok {
Jan Winkelmann's avatar
Jan Winkelmann committed
176 177
			err := fmt.Errorf("unrecognized multihash function: %s", mhtype)
			res.SetError(err, cmdkit.ErrNormal)
178 179 180 181 182 183
			return
		}
		pref.MhType = mhtval

		mhlen, _, err := req.Option("mhlen").Int()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
184
			res.SetError(err, cmdkit.ErrNormal)
185 186 187 188
			return
		}
		pref.MhLength = mhlen

189 190
		bcid, err := pref.Sum(data)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
191
			res.SetError(err, cmdkit.ErrNormal)
192 193 194 195 196
			return
		}

		b, err := blocks.NewBlockWithCid(data, bcid)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
197
			res.SetError(err, cmdkit.ErrNormal)
198 199
			return
		}
200

201
		k, err := n.Blocks.AddBlock(b)
202
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
203
			res.SetError(err, cmdkit.ErrNormal)
204
			return
205 206
		}

keks's avatar
keks committed
207
		err = cmds.EmitOnce(res, &BlockStat{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208 209
			Key:  k.String(),
			Size: len(data),
210
		})
Jan Winkelmann's avatar
Jan Winkelmann committed
211 212 213
		if err != nil {
			log.Error(err)
		}
214
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
215 216 217 218 219 220 221 222 223
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeEncoder(func(req cmds.Request, w io.Writer, v interface{}) error {
			bs, ok := v.(*BlockStat)
			if !ok {
				return e.TypeErr(bs, v)
			}
			_, err := fmt.Fprintf(w, "%s\n", bs.Key)
			return err
		}),
224
	},
Matt Bell's avatar
Matt Bell committed
225
	Type: BlockStat{},
226
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227

228
func getBlockForKey(req cmds.Request, skey string) (blocks.Block, error) {
229 230 231 232
	if len(skey) == 0 {
		return nil, fmt.Errorf("zero length cid invalid")
	}

Jeromy's avatar
Jeromy committed
233
	n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234 235 236 237
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
238
	c, err := cid.Decode(skey)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239 240 241 242
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
243
	b, err := n.Blocks.GetBlock(req.Context(), c)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244 245 246
	if err != nil {
		return nil, err
	}
247

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
248 249
	return b, nil
}
Kevin Atkinson's avatar
Kevin Atkinson committed
250 251

var blockRmCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
252
	Helptext: cmdkit.HelpText{
Kevin Atkinson's avatar
Kevin Atkinson committed
253 254 255 256 257 258
		Tagline: "Remove IPFS block(s).",
		ShortDescription: `
'ipfs block rm' is a plumbing command for removing raw ipfs blocks.
It takes a list of base58 encoded multihashs to remove.
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
259 260
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("hash", true, true, "Bash58 encoded multihash of block(s) to remove."),
Kevin Atkinson's avatar
Kevin Atkinson committed
261
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
262
	Options: []cmdkit.Option{
263 264
		cmdkit.BoolOption("force", "f", "Ignore nonexistent blocks."),
		cmdkit.BoolOption("quiet", "q", "Write minimal output."),
265
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
266
	Run: func(req cmds.Request, res cmds.ResponseEmitter) {
Kevin Atkinson's avatar
Kevin Atkinson committed
267 268
		n, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
269
			res.SetError(err, cmdkit.ErrNormal)
Kevin Atkinson's avatar
Kevin Atkinson committed
270 271 272
			return
		}
		hashes := req.Arguments()
273 274
		force, _, _ := req.Option("force").Bool()
		quiet, _, _ := req.Option("quiet").Bool()
Jeromy's avatar
Jeromy committed
275
		cids := make([]*cid.Cid, 0, len(hashes))
Kevin Atkinson's avatar
Kevin Atkinson committed
276
		for _, hash := range hashes {
Jeromy's avatar
Jeromy committed
277 278
			c, err := cid.Decode(hash)
			if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
279 280
				err = fmt.Errorf("invalid content id: %s (%s)", hash, err)
				res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
281 282 283 284
				return
			}

			cids = append(cids, c)
Kevin Atkinson's avatar
Kevin Atkinson committed
285
		}
286
		ch, err := util.RmBlocks(n.Blockstore, n.Pinning, cids, util.RmBlocksOpts{
287 288 289
			Quiet: quiet,
			Force: force,
		})
Jan Winkelmann's avatar
Jan Winkelmann committed
290

291
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
292
			res.SetError(err, cmdkit.ErrNormal)
293 294
			return
		}
Jan Winkelmann's avatar
Jan Winkelmann committed
295 296 297 298 299

		err = res.Emit(ch)
		if err != nil {
			log.Error(err)
		}
Kevin Atkinson's avatar
Kevin Atkinson committed
300
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
301 302 303 304 305 306 307 308 309 310
	PostRun: map[cmds.EncodingType]func(cmds.Request, cmds.ResponseEmitter) cmds.ResponseEmitter{
		cmds.CLI: func(req cmds.Request, re cmds.ResponseEmitter) cmds.ResponseEmitter {
			reNext, res := cmds.NewChanResponsePair(req)

			go func() {
				defer re.Close()

				err := util.ProcRmOutput(res.Next, os.Stdout, os.Stderr)
				cmds.HandleError(err, res, re)
			}()
311

Jan Winkelmann's avatar
Jan Winkelmann committed
312
			return reNext
313
		},
Kevin Atkinson's avatar
Kevin Atkinson committed
314
	},
315
	Type: util.RemovedBlock{},
Kevin Atkinson's avatar
Kevin Atkinson committed
316
}