get.go 8.56 KB
Newer Older
Matt Bell's avatar
Matt Bell committed
1 2 3 4 5
package commands

import (
	"archive/tar"
	"bytes"
6
	"compress/gzip"
7
	"fmt"
Matt Bell's avatar
Matt Bell committed
8
	"io"
9
	"os"
Matt Bell's avatar
Matt Bell committed
10
	p "path"
11 12
	fp "path/filepath"
	"strings"
13
	"sync"
Matt Bell's avatar
Matt Bell committed
14 15 16 17 18 19 20 21

	cmds "github.com/jbenet/go-ipfs/commands"
	core "github.com/jbenet/go-ipfs/core"
	dag "github.com/jbenet/go-ipfs/merkledag"
	uio "github.com/jbenet/go-ipfs/unixfs/io"
	upb "github.com/jbenet/go-ipfs/unixfs/pb"

	proto "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
22
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/cheggaaa/pb"
Matt Bell's avatar
Matt Bell committed
23 24 25 26 27 28 29 30 31 32 33 34
)

var GetCmd = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "Download IPFS objects",
		ShortDescription: `
Retrieves the object named by <ipfs-path> and stores the data to disk.

By default, the output will be stored at ./<ipfs-path>, but an alternate path
can be specified with '--output=<path>' or '-o=<path>'.

To output a TAR archive instead of unpacked files, use '--archive' or '-a'.
35 36 37

To compress the output with GZIP compression, use '--compress' or '-C'. You
may also specify the level of compression by specifying '-l=<1-9>'.
Matt Bell's avatar
Matt Bell committed
38 39 40 41
`,
	},

	Arguments: []cmds.Argument{
42
		cmds.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted").EnableStdin(),
Matt Bell's avatar
Matt Bell committed
43 44 45 46
	},
	Options: []cmds.Option{
		cmds.StringOption("output", "o", "The path where output should be stored"),
		cmds.BoolOption("archive", "a", "Output a TAR archive"),
47 48
		cmds.BoolOption("compress", "C", "Compress the output with GZIP compression"),
		cmds.IntOption("compression-level", "l", "The level of compression (an int between 1 and 9)"),
Matt Bell's avatar
Matt Bell committed
49 50 51 52 53 54 55 56
	},
	Run: func(req cmds.Request, res cmds.Response) {
		node, err := req.Context().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

57 58 59 60 61 62 63 64 65 66 67
		compress, _, _ := req.Option("compress").Bool()
		compressionLevel, found, _ := req.Option("compression-level").Int()
		if !found {
			if compress {
				compressionLevel = gzip.DefaultCompression
			} else {
				compressionLevel = gzip.NoCompression
			}
		}

		reader, err := get(node, req.Arguments()[0], compressionLevel)
Matt Bell's avatar
Matt Bell committed
68 69 70 71 72 73
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		res.SetOutput(reader)
	},
74 75 76 77
	PostRun: func(req cmds.Request, res cmds.Response) {
		reader := res.Output().(io.Reader)
		res.SetOutput(nil)

78
		outPath, _, _ := req.Option("output").String()
79
		if len(outPath) == 0 {
80
			outPath = req.Arguments()[0]
81 82
		}

83 84 85 86 87
		compress, _, _ := req.Option("compress").Bool()
		compressionLevel, found, _ := req.Option("compression-level").Int()
		compress = (compress && (compressionLevel > 0 || !found)) || compressionLevel > 0

		if archive, _, _ := req.Option("archive").Bool(); archive {
88 89 90
			if !strings.HasSuffix(outPath, ".tar") {
				outPath += ".tar"
			}
91 92 93
			if compress {
				outPath += ".gz"
			}
94 95 96 97 98 99 100 101 102
			fmt.Printf("Saving archive to %s\n", outPath)

			file, err := os.Create(outPath)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
			defer file.Close()

103 104 105 106 107 108 109
			bar := pb.New(0).SetUnits(pb.U_BYTES)
			bar.Output = os.Stderr
			pbReader := bar.NewProxyReader(reader)
			bar.Start()
			defer bar.Finish()

			_, err = io.Copy(file, pbReader)
110 111 112 113 114 115 116 117 118 119
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			return
		}

		fmt.Printf("Saving file(s) to %s\n", outPath)

120 121 122 123
		// TODO: get total length of files
		bar := pb.New(0).SetUnits(pb.U_BYTES)
		bar.Output = os.Stderr

124 125 126 127 128 129 130 131 132 133 134
		preexisting := true
		pathIsDir := false
		if stat, err := os.Stat(outPath); err != nil && os.IsNotExist(err) {
			preexisting = false
		} else if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		} else if stat.IsDir() {
			pathIsDir = true
		}

135 136 137 138 139 140 141 142
		var tarReader *tar.Reader
		if compress {
			gzipReader, err := gzip.NewReader(reader)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
			defer gzipReader.Close()
143 144
			pbReader := bar.NewProxyReader(gzipReader)
			tarReader = tar.NewReader(pbReader)
145
		} else {
146 147
			pbReader := bar.NewProxyReader(reader)
			tarReader = tar.NewReader(pbReader)
148
		}
149

150 151 152
		bar.Start()
		defer bar.Finish()

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
		for i := 0; ; i++ {
			header, err := tarReader.Next()
			if err != nil && err != io.EOF {
				res.SetError(err, cmds.ErrNormal)
				return
			}
			if header == nil || err == io.EOF {
				break
			}

			if header.Typeflag == tar.TypeDir {
				pathElements := strings.Split(header.Name, "/")
				if !preexisting {
					pathElements = pathElements[1:]
				}
				path := fp.Join(pathElements...)
				path = fp.Join(outPath, path)
				if i == 0 {
					outPath = path
				}

				err = os.MkdirAll(path, 0755)
				if err != nil {
					res.SetError(err, cmds.ErrNormal)
					return
				}
				continue
			}

			var path string
			if i == 0 {
				if preexisting {
					if !pathIsDir {
						res.SetError(os.ErrExist, cmds.ErrNormal)
						return
					}
					path = fp.Join(outPath, header.Name)
				} else {
					path = outPath
				}
			} else {
				pathElements := strings.Split(header.Name, "/")[1:]
				path = fp.Join(pathElements...)
				path = fp.Join(outPath, path)
			}

			file, err := os.Create(path)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			_, err = io.Copy(file, tarReader)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			err = file.Close()
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
		}
	},
Matt Bell's avatar
Matt Bell committed
218 219
}

220
func get(node *core.IpfsNode, path string, compression int) (io.Reader, error) {
221
	buf := NewBufReadWriter()
Matt Bell's avatar
Matt Bell committed
222 223

	go func() {
224
		err := copyFilesAsTar(node, buf, path, compression)
Matt Bell's avatar
Matt Bell committed
225 226 227 228 229 230
		if err != nil {
			log.Error(err)
			return
		}
	}()

231
	return buf, nil
Matt Bell's avatar
Matt Bell committed
232 233
}

234 235 236 237 238 239 240 241 242 243 244 245 246
func copyFilesAsTar(node *core.IpfsNode, buf *bufReadWriter, path string, compression int) error {
	var gzipWriter *gzip.Writer
	var writer *tar.Writer
	var err error
	if compression != gzip.NoCompression {
		gzipWriter, err = gzip.NewWriterLevel(buf, compression)
		if err != nil {
			return err
		}
		writer = tar.NewWriter(gzipWriter)
	} else {
		writer = tar.NewWriter(buf)
	}
247

248
	err = _copyFilesAsTar(node, writer, buf, path, nil)
249 250 251 252
	if err != nil {
		return err
	}

253
	buf.mutex.Lock()
254
	err = writer.Close()
255 256 257
	if err != nil {
		return err
	}
258 259 260 261 262 263
	if gzipWriter != nil {
		err = gzipWriter.Close()
		if err != nil {
			return err
		}
	}
264
	buf.Close()
265
	buf.mutex.Unlock()
266 267 268 269 270
	buf.Signal()
	return nil
}

func _copyFilesAsTar(node *core.IpfsNode, writer *tar.Writer, buf *bufReadWriter, path string, dagnode *dag.Node) error {
Matt Bell's avatar
Matt Bell committed
271 272 273 274
	var err error
	if dagnode == nil {
		dagnode, err = node.Resolver.ResolvePath(path)
		if err != nil {
275
			return err
Matt Bell's avatar
Matt Bell committed
276 277 278 279 280 281
		}
	}

	pb := new(upb.Data)
	err = proto.Unmarshal(dagnode.Data, pb)
	if err != nil {
282
		return err
Matt Bell's avatar
Matt Bell committed
283 284 285
	}

	if pb.GetType() == upb.Data_Directory {
286
		buf.mutex.Lock()
Matt Bell's avatar
Matt Bell committed
287 288 289 290 291 292
		err = writer.WriteHeader(&tar.Header{
			Name:     path,
			Typeflag: tar.TypeDir,
			Mode:     0777,
			// TODO: set mode, dates, etc. when added to unixFS
		})
293
		buf.mutex.Unlock()
Matt Bell's avatar
Matt Bell committed
294
		if err != nil {
295
			return err
Matt Bell's avatar
Matt Bell committed
296 297 298
		}

		for _, link := range dagnode.Links {
299
			err := _copyFilesAsTar(node, writer, buf, p.Join(path, link.Name), link.Node)
Matt Bell's avatar
Matt Bell committed
300
			if err != nil {
301
				return err
Matt Bell's avatar
Matt Bell committed
302 303 304
			}
		}

305 306
		return nil
	}
Matt Bell's avatar
Matt Bell committed
307

308 309 310 311 312 313 314 315 316 317 318 319
	buf.mutex.Lock()
	err = writer.WriteHeader(&tar.Header{
		Name:     path,
		Size:     int64(pb.GetFilesize()),
		Typeflag: tar.TypeReg,
		Mode:     0644,
		// TODO: set mode, dates, etc. when added to unixFS
	})
	buf.mutex.Unlock()
	if err != nil {
		return err
	}
Matt Bell's avatar
Matt Bell committed
320

321 322 323 324 325 326 327 328
	reader, err := uio.NewDagReader(dagnode, node.DAG)
	if err != nil {
		return err
	}

	_, err = syncCopy(writer, reader, buf)
	if err != nil {
		return err
Matt Bell's avatar
Matt Bell committed
329
	}
330 331

	return nil
Matt Bell's avatar
Matt Bell committed
332 333
}

334
type bufReadWriter struct {
Matt Bell's avatar
Matt Bell committed
335 336 337
	buf        bytes.Buffer
	closed     bool
	signalChan chan struct{}
338 339 340 341 342 343 344 345
	mutex      *sync.Mutex
}

func NewBufReadWriter() *bufReadWriter {
	return &bufReadWriter{
		signalChan: make(chan struct{}),
		mutex:      &sync.Mutex{},
	}
Matt Bell's avatar
Matt Bell committed
346 347
}

348
func (i *bufReadWriter) Read(p []byte) (int, error) {
Matt Bell's avatar
Matt Bell committed
349
	<-i.signalChan
350 351 352 353 354 355 356 357 358 359
	i.mutex.Lock()
	defer i.mutex.Unlock()

	if i.buf.Len() == 0 {
		if i.closed {
			return 0, io.EOF
		}
		return 0, nil
	}

Matt Bell's avatar
Matt Bell committed
360
	n, err := i.buf.Read(p)
361
	if err == io.EOF && !i.closed || i.buf.Len() > 0 {
Matt Bell's avatar
Matt Bell committed
362 363 364 365 366
		return n, nil
	}
	return n, err
}

367 368 369 370 371
func (i *bufReadWriter) Write(p []byte) (int, error) {
	return i.buf.Write(p)
}

func (i *bufReadWriter) Signal() {
Matt Bell's avatar
Matt Bell committed
372 373 374
	i.signalChan <- struct{}{}
}

375
func (i *bufReadWriter) Close() error {
Matt Bell's avatar
Matt Bell committed
376
	i.closed = true
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
	return nil
}

func syncCopy(writer io.Writer, reader io.Reader, buf *bufReadWriter) (int64, error) {
	written := int64(0)
	copyBuf := make([]byte, 32*1024)
	for {
		nr, err := reader.Read(copyBuf)
		if nr > 0 {
			buf.mutex.Lock()
			nw, err := writer.Write(copyBuf[:nr])
			buf.mutex.Unlock()
			if err != nil {
				return written, err
			}
			written += int64(nw)
			buf.Signal()
		}
		if err == io.EOF {
			break
		}
		if err != nil {
			return written, err
		}
	}
	return written, nil
Matt Bell's avatar
Matt Bell committed
403
}