get.go 8.12 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 22 23 24 25 26 27 28 29 30 31 32 33

	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"
)

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'.
34 35 36

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
37 38 39 40 41 42 43 44 45
`,
	},

	Arguments: []cmds.Argument{
		cmds.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to be outputted").EnableStdin(),
	},
	Options: []cmds.Option{
		cmds.StringOption("output", "o", "The path where output should be stored"),
		cmds.BoolOption("archive", "a", "Output a TAR archive"),
46 47
		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
48 49 50 51 52 53 54 55
	},
	Run: func(req cmds.Request, res cmds.Response) {
		node, err := req.Context().GetNode()
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}

56 57 58 59 60 61 62 63 64 65 66
		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
67 68 69 70 71 72
		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
		res.SetOutput(reader)
	},
73 74 75 76
	PostRun: func(req cmds.Request, res cmds.Response) {
		reader := res.Output().(io.Reader)
		res.SetOutput(nil)

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

82 83 84 85 86
		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 {
87 88 89
			if !strings.HasSuffix(outPath, ".tar") {
				outPath += ".tar"
			}
90 91 92
			if compress {
				outPath += ".gz"
			}
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
			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()

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

			return
		}

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

		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
		}

124 125 126 127 128 129 130 131 132 133 134 135
		var tarReader *tar.Reader
		if compress {
			gzipReader, err := gzip.NewReader(reader)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}
			defer gzipReader.Close()
			tarReader = tar.NewReader(gzipReader)
		} else {
			tarReader = tar.NewReader(reader)
		}
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

		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
202 203
}

204
func get(node *core.IpfsNode, path string, compression int) (io.Reader, error) {
205
	buf := NewBufReadWriter()
Matt Bell's avatar
Matt Bell committed
206 207

	go func() {
208
		err := copyFilesAsTar(node, buf, path, compression)
Matt Bell's avatar
Matt Bell committed
209 210 211 212 213 214
		if err != nil {
			log.Error(err)
			return
		}
	}()

215
	return buf, nil
Matt Bell's avatar
Matt Bell committed
216 217
}

218 219 220 221 222 223 224 225 226 227 228 229 230
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)
	}
231

232
	err = _copyFilesAsTar(node, writer, buf, path, nil)
233 234 235 236
	if err != nil {
		return err
	}

237
	buf.mutex.Lock()
238
	err = writer.Close()
239 240 241
	if err != nil {
		return err
	}
242 243 244 245 246 247
	if gzipWriter != nil {
		err = gzipWriter.Close()
		if err != nil {
			return err
		}
	}
248
	buf.Close()
249
	buf.mutex.Unlock()
250 251 252 253 254
	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
255 256 257 258
	var err error
	if dagnode == nil {
		dagnode, err = node.Resolver.ResolvePath(path)
		if err != nil {
259
			return err
Matt Bell's avatar
Matt Bell committed
260 261 262 263 264 265
		}
	}

	pb := new(upb.Data)
	err = proto.Unmarshal(dagnode.Data, pb)
	if err != nil {
266
		return err
Matt Bell's avatar
Matt Bell committed
267 268 269
	}

	if pb.GetType() == upb.Data_Directory {
270
		buf.mutex.Lock()
Matt Bell's avatar
Matt Bell committed
271 272 273 274 275 276
		err = writer.WriteHeader(&tar.Header{
			Name:     path,
			Typeflag: tar.TypeDir,
			Mode:     0777,
			// TODO: set mode, dates, etc. when added to unixFS
		})
277
		buf.mutex.Unlock()
Matt Bell's avatar
Matt Bell committed
278
		if err != nil {
279
			return err
Matt Bell's avatar
Matt Bell committed
280 281 282
		}

		for _, link := range dagnode.Links {
283
			err := _copyFilesAsTar(node, writer, buf, p.Join(path, link.Name), link.Node)
Matt Bell's avatar
Matt Bell committed
284
			if err != nil {
285
				return err
Matt Bell's avatar
Matt Bell committed
286 287 288
			}
		}

289 290
		return nil
	}
Matt Bell's avatar
Matt Bell committed
291

292 293 294 295 296 297 298 299 300 301 302 303
	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
304

305 306 307 308 309 310 311 312
	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
313
	}
314 315

	return nil
Matt Bell's avatar
Matt Bell committed
316 317
}

318
type bufReadWriter struct {
Matt Bell's avatar
Matt Bell committed
319 320 321
	buf        bytes.Buffer
	closed     bool
	signalChan chan struct{}
322 323 324 325 326 327 328 329
	mutex      *sync.Mutex
}

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

332
func (i *bufReadWriter) Read(p []byte) (int, error) {
Matt Bell's avatar
Matt Bell committed
333
	<-i.signalChan
334 335 336 337 338 339 340 341 342 343
	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
344
	n, err := i.buf.Read(p)
345
	if err == io.EOF && !i.closed || i.buf.Len() > 0 {
Matt Bell's avatar
Matt Bell committed
346 347 348 349 350
		return n, nil
	}
	return n, err
}

351 352 353 354 355
func (i *bufReadWriter) Write(p []byte) (int, error) {
	return i.buf.Write(p)
}

func (i *bufReadWriter) Signal() {
Matt Bell's avatar
Matt Bell committed
356 357 358
	i.signalChan <- struct{}{}
}

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