get.go 9.14 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
	"errors"
8
	"fmt"
Matt Bell's avatar
Matt Bell committed
9
	"io"
10
	"os"
Matt Bell's avatar
Matt Bell committed
11
	p "path"
12 13
	fp "path/filepath"
	"strings"
14
	"sync"
Matt Bell's avatar
Matt Bell committed
15 16 17 18 19 20 21 22

	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"
23
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/cheggaaa/pb"
Matt Bell's avatar
Matt Bell committed
24 25
)

26 27
var ErrInvalidCompressionLevel = errors.New("Compression level must be between 1 and 9")

Matt Bell's avatar
Matt Bell committed
28 29 30 31 32 33 34 35 36 37
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'.
38 39 40

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
41 42 43 44
`,
	},

	Arguments: []cmds.Argument{
45
		cmds.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted").EnableStdin(),
Matt Bell's avatar
Matt Bell committed
46 47 48 49
	},
	Options: []cmds.Option{
		cmds.StringOption("output", "o", "The path where output should be stored"),
		cmds.BoolOption("archive", "a", "Output a TAR archive"),
50 51
		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
52
	},
53
	PreRun: getCheckOptions,
Matt Bell's avatar
Matt Bell committed
54
	Run: func(req cmds.Request, res cmds.Response) {
55 56 57 58 59 60
		err := getCheckOptions(req)
		if err != nil {
			res.SetError(err, cmds.ErrClient)
			return
		}

Matt Bell's avatar
Matt Bell committed
61 62 63 64 65 66
		node, err := req.Context().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

67 68 69 70 71 72 73 74
		compress, _, _ := req.Option("compress").Bool()
		compressionLevel, found, _ := req.Option("compression-level").Int()
		if !found {
			if compress {
				compressionLevel = gzip.DefaultCompression
			} else {
				compressionLevel = gzip.NoCompression
			}
75 76 77 78 79
		} else {
			if compressionLevel < 1 || compressionLevel > 9 {
				res.SetError(ErrInvalidCompressionLevel, cmds.ErrClient)
				return
			}
80 81 82
		}

		reader, err := get(node, req.Arguments()[0], compressionLevel)
Matt Bell's avatar
Matt Bell committed
83 84 85 86 87 88
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		res.SetOutput(reader)
	},
89 90 91 92
	PostRun: func(req cmds.Request, res cmds.Response) {
		reader := res.Output().(io.Reader)
		res.SetOutput(nil)

93
		outPath, _, _ := req.Option("output").String()
94
		if len(outPath) == 0 {
95
			outPath = req.Arguments()[0]
96 97
		}

98 99 100 101 102
		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 {
103 104 105
			if !strings.HasSuffix(outPath, ".tar") {
				outPath += ".tar"
			}
106 107 108
			if compress {
				outPath += ".gz"
			}
109 110 111 112 113 114 115 116 117
			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()

118 119 120 121 122 123 124
			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)
125 126 127 128 129 130 131 132 133 134
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

			return
		}

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

135 136 137 138
		// TODO: get total length of files
		bar := pb.New(0).SetUnits(pb.U_BYTES)
		bar.Output = os.Stderr

139 140 141 142 143 144 145 146 147 148 149
		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
		}

150 151 152 153 154 155 156 157
		var tarReader *tar.Reader
		if compress {
			gzipReader, err := gzip.NewReader(reader)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
			defer gzipReader.Close()
158 159
			pbReader := bar.NewProxyReader(gzipReader)
			tarReader = tar.NewReader(pbReader)
160
		} else {
161 162
			pbReader := bar.NewProxyReader(reader)
			tarReader = tar.NewReader(pbReader)
163
		}
164

165 166 167
		bar.Start()
		defer bar.Finish()

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
		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
233 234
}

235 236 237 238 239 240 241 242
func getCheckOptions(req cmds.Request) error {
	compressionLevel, found, _ := req.Option("compression-level").Int()
	if found && (compressionLevel < 1 || compressionLevel > 9) {
		return ErrInvalidCompressionLevel
	}
	return nil
}

243
func get(node *core.IpfsNode, path string, compression int) (io.Reader, error) {
244
	buf := NewBufReadWriter()
Matt Bell's avatar
Matt Bell committed
245 246

	go func() {
247
		err := copyFilesAsTar(node, buf, path, compression)
Matt Bell's avatar
Matt Bell committed
248 249 250 251 252 253
		if err != nil {
			log.Error(err)
			return
		}
	}()

254
	return buf, nil
Matt Bell's avatar
Matt Bell committed
255 256
}

257 258 259 260 261 262 263 264 265 266 267 268 269
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)
	}
270

271
	err = _copyFilesAsTar(node, writer, buf, path, nil)
272 273 274 275
	if err != nil {
		return err
	}

276
	buf.mutex.Lock()
277
	err = writer.Close()
278 279 280
	if err != nil {
		return err
	}
281 282 283 284 285 286
	if gzipWriter != nil {
		err = gzipWriter.Close()
		if err != nil {
			return err
		}
	}
287
	buf.Close()
288
	buf.mutex.Unlock()
289 290 291 292 293
	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
294 295 296 297
	var err error
	if dagnode == nil {
		dagnode, err = node.Resolver.ResolvePath(path)
		if err != nil {
298
			return err
Matt Bell's avatar
Matt Bell committed
299 300 301 302 303 304
		}
	}

	pb := new(upb.Data)
	err = proto.Unmarshal(dagnode.Data, pb)
	if err != nil {
305
		return err
Matt Bell's avatar
Matt Bell committed
306 307 308
	}

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

		for _, link := range dagnode.Links {
322
			err := _copyFilesAsTar(node, writer, buf, p.Join(path, link.Name), link.Node)
Matt Bell's avatar
Matt Bell committed
323
			if err != nil {
324
				return err
Matt Bell's avatar
Matt Bell committed
325 326 327
			}
		}

328 329
		return nil
	}
Matt Bell's avatar
Matt Bell committed
330

331 332 333 334 335 336 337 338 339 340 341 342
	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
343

344 345 346 347 348 349 350 351
	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
352
	}
353 354

	return nil
Matt Bell's avatar
Matt Bell committed
355 356
}

357
type bufReadWriter struct {
Matt Bell's avatar
Matt Bell committed
358 359 360
	buf        bytes.Buffer
	closed     bool
	signalChan chan struct{}
361 362 363 364 365 366 367 368
	mutex      *sync.Mutex
}

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

371
func (i *bufReadWriter) Read(p []byte) (int, error) {
Matt Bell's avatar
Matt Bell committed
372
	<-i.signalChan
373 374 375 376 377 378 379 380 381 382
	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
383
	n, err := i.buf.Read(p)
384
	if err == io.EOF && !i.closed || i.buf.Len() > 0 {
Matt Bell's avatar
Matt Bell committed
385 386 387 388 389
		return n, nil
	}
	return n, err
}

390 391 392 393 394
func (i *bufReadWriter) Write(p []byte) (int, error) {
	return i.buf.Write(p)
}

func (i *bufReadWriter) Signal() {
Matt Bell's avatar
Matt Bell committed
395 396 397
	i.signalChan <- struct{}{}
}

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