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

import (
4
	"bufio"
5
	"compress/gzip"
6
	"errors"
7
	"fmt"
Matt Bell's avatar
Matt Bell committed
8
	"io"
9
	"os"
10
	"path"
Dominic Della Valle's avatar
Dominic Della Valle committed
11
	"path/filepath"
12
	"strings"
Matt Bell's avatar
Matt Bell committed
13

Łukasz Magiera's avatar
Łukasz Magiera committed
14 15
	"github.com/ipfs/go-ipfs/core/commands/cmdenv"
	"github.com/ipfs/go-ipfs/core/commands/e"
Jan Winkelmann's avatar
Jan Winkelmann committed
16

Jakub Sztandera's avatar
Jakub Sztandera committed
17 18 19 20 21 22
	"github.com/cheggaaa/pb"
	"github.com/ipfs/go-ipfs-cmdkit"
	"github.com/ipfs/go-ipfs-cmds"
	"github.com/ipfs/go-ipfs-files"
	"github.com/ipfs/interface-go-ipfs-core"
	"github.com/whyrusleeping/tar-utils"
Matt Bell's avatar
Matt Bell committed
23 24
)

Łukasz Magiera's avatar
Łukasz Magiera committed
25
var ErrInvalidCompressionLevel = errors.New("compression level must be between 1 and 9")
26

Kejie Zhang's avatar
Kejie Zhang committed
27 28 29 30 31 32 33
const (
	outputOptionName           = "output"
	archiveOptionName          = "archive"
	compressOptionName         = "compress"
	compressionLevelOptionName = "compression-level"
)

Matt Bell's avatar
Matt Bell committed
34
var GetCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
35
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
36
		Tagline: "Download IPFS objects.",
Matt Bell's avatar
Matt Bell committed
37
		ShortDescription: `
Richard Littauer's avatar
Richard Littauer committed
38
Stores to disk the data contained an IPFS or IPNS object(s) at the given path.
Matt Bell's avatar
Matt Bell committed
39

40 41
By default, the output will be stored at './<ipfs-path>', but an alternate
path can be specified with '--output=<path>' or '-o=<path>'.
Matt Bell's avatar
Matt Bell committed
42 43

To output a TAR archive instead of unpacked files, use '--archive' or '-a'.
44 45 46

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
47 48 49
`,
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
50 51
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted.").EnableStdin(),
Matt Bell's avatar
Matt Bell committed
52
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
53
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
54 55 56 57
		cmdkit.StringOption(outputOptionName, "o", "The path where the output should be stored."),
		cmdkit.BoolOption(archiveOptionName, "a", "Output a TAR archive."),
		cmdkit.BoolOption(compressOptionName, "C", "Compress the output with GZIP compression."),
		cmdkit.IntOption(compressionLevelOptionName, "l", "The level of compression (1-9)."),
Matt Bell's avatar
Matt Bell committed
58
	},
Jeromy's avatar
Jeromy committed
59
	PreRun: func(req *cmds.Request, env cmds.Environment) error {
60 61 62
		_, err := getCompressOptions(req)
		return err
	},
keks's avatar
keks committed
63
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
64
		cmplvl, err := getCompressOptions(req)
65
		if err != nil {
keks's avatar
keks committed
66
			return err
67 68
		}

Łukasz Magiera's avatar
Łukasz Magiera committed
69
		api, err := cmdenv.GetApi(env, req)
Matt Bell's avatar
Matt Bell committed
70
		if err != nil {
keks's avatar
keks committed
71
			return err
Matt Bell's avatar
Matt Bell committed
72
		}
Łukasz Magiera's avatar
Łukasz Magiera committed
73 74

		p, err := iface.ParsePath(req.Arguments[0])
rht's avatar
rht committed
75
		if err != nil {
keks's avatar
keks committed
76
			return err
rht's avatar
rht committed
77
		}
rht's avatar
rht committed
78

Łukasz Magiera's avatar
Łukasz Magiera committed
79 80 81 82
		file, err := api.Unixfs().Get(req.Context, p)
		if err != nil {
			return err
		}
83

Łukasz Magiera's avatar
Łukasz Magiera committed
84 85
		size, err := file.Size()
		if err != nil {
keks's avatar
keks committed
86
			return err
87 88
		}

Łukasz Magiera's avatar
Łukasz Magiera committed
89 90
		res.SetLength(uint64(size))

Kejie Zhang's avatar
Kejie Zhang committed
91
		archive, _ := req.Options[archiveOptionName].(bool)
92
		reader, err := fileArchive(file, p.String(), archive, cmplvl)
Matt Bell's avatar
Matt Bell committed
93
		if err != nil {
keks's avatar
keks committed
94
			return err
95
		}
96

keks's avatar
keks committed
97
		return res.Emit(reader)
Jan Winkelmann's avatar
Jan Winkelmann committed
98
	},
99
	PostRun: cmds.PostRunMap{
keks's avatar
keks committed
100 101 102 103 104 105 106 107 108 109
		cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error {
			req := res.Request()

			v, err := res.Next()
			if err != nil {
				return err
			}

			outReader, ok := v.(io.Reader)
			if !ok {
keks's avatar
keks committed
110
				return e.New(e.TypeErr(outReader, v))
keks's avatar
keks committed
111 112 113 114 115 116 117 118 119
			}

			outPath := getOutPath(req)

			cmplvl, err := getCompressOptions(req)
			if err != nil {
				return err
			}

Kejie Zhang's avatar
Kejie Zhang committed
120
			archive, _ := req.Options[archiveOptionName].(bool)
keks's avatar
keks committed
121 122 123 124 125 126 127 128 129 130

			gw := getWriter{
				Out:         os.Stdout,
				Err:         os.Stderr,
				Archive:     archive,
				Compression: cmplvl,
				Size:        int64(res.Length()),
			}

			return gw.Write(outReader, outPath)
Jan Winkelmann's avatar
Jan Winkelmann committed
131
		},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132 133
	},
}
134

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
type clearlineReader struct {
	io.Reader
	out io.Writer
}

func (r *clearlineReader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	if err == io.EOF {
		// callback
		fmt.Fprintf(r.out, "\033[2K\r") // clear progress bar line on EOF
	}
	return
}

func progressBarForReader(out io.Writer, r io.Reader, l int64) (*pb.ProgressBar, io.Reader) {
Jeromy's avatar
Jeromy committed
150 151 152 153 154 155
	bar := makeProgressBar(out, l)
	barR := bar.NewProxyReader(r)
	return bar, &clearlineReader{barR, out}
}

func makeProgressBar(out io.Writer, l int64) *pb.ProgressBar {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156 157
	// setup bar reader
	// TODO: get total length of files
158
	bar := pb.New64(l).SetUnits(pb.U_BYTES)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159
	bar.Output = out
160 161 162 163 164 165 166 167

	// the progress bar lib doesn't give us a way to get the width of the output,
	// so as a hack we just use a callback to measure the output, then git rid of it
	bar.Callback = func(line string) {
		terminalWidth := len(line)
		bar.Callback = nil
		log.Infof("terminal width: %v\n", terminalWidth)
	}
Jeromy's avatar
Jeromy committed
168
	return bar
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
}
170

171
func getOutPath(req *cmds.Request) string {
Kejie Zhang's avatar
Kejie Zhang committed
172
	outPath, _ := req.Options[outputOptionName].(string)
173
	if outPath == "" {
174
		trimmed := strings.TrimRight(req.Arguments[0], "/")
Dominic Della Valle's avatar
Dominic Della Valle committed
175 176
		_, outPath = filepath.Split(trimmed)
		outPath = filepath.Clean(outPath)
177 178 179 180
	}
	return outPath
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
181 182 183
type getWriter struct {
	Out io.Writer // for output to user
	Err io.Writer // for progress bar output
184

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185 186
	Archive     bool
	Compression int
Jeromy's avatar
Jeromy committed
187
	Size        int64
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
}
189

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190 191 192 193 194 195 196 197 198 199 200 201
func (gw *getWriter) Write(r io.Reader, fpath string) error {
	if gw.Archive || gw.Compression != gzip.NoCompression {
		return gw.writeArchive(r, fpath)
	}
	return gw.writeExtracted(r, fpath)
}

func (gw *getWriter) writeArchive(r io.Reader, fpath string) error {
	// adjust file name if tar
	if gw.Archive {
		if !strings.HasSuffix(fpath, ".tar") && !strings.HasSuffix(fpath, ".tar.gz") {
			fpath += ".tar"
202
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	}

	// adjust file name if gz
	if gw.Compression != gzip.NoCompression {
		if !strings.HasSuffix(fpath, ".gz") {
			fpath += ".gz"
		}
	}

	// create file
	file, err := os.Create(fpath)
	if err != nil {
		return err
	}
	defer file.Close()

	fmt.Fprintf(gw.Out, "Saving archive to %s\n", fpath)
Jeromy's avatar
Jeromy committed
220
	bar, barR := progressBarForReader(gw.Err, r, gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221 222 223 224 225 226 227 228 229
	bar.Start()
	defer bar.Finish()

	_, err = io.Copy(file, barR)
	return err
}

func (gw *getWriter) writeExtracted(r io.Reader, fpath string) error {
	fmt.Fprintf(gw.Out, "Saving file(s) to %s\n", fpath)
Jeromy's avatar
Jeromy committed
230
	bar := makeProgressBar(gw.Err, gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231 232
	bar.Start()
	defer bar.Finish()
Jeromy's avatar
Jeromy committed
233
	defer bar.Set64(gw.Size)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234

Steven Allen's avatar
Steven Allen committed
235
	extractor := &tar.Extractor{Path: fpath, Progress: bar.Add64}
Jeromy's avatar
Jeromy committed
236
	return extractor.Extract(r)
Matt Bell's avatar
Matt Bell committed
237 238
}

239
func getCompressOptions(req *cmds.Request) (int, error) {
Kejie Zhang's avatar
Kejie Zhang committed
240 241
	cmprs, _ := req.Options[compressOptionName].(bool)
	cmplvl, cmplvlFound := req.Options[compressionLevelOptionName].(int)
242 243 244
	switch {
	case !cmprs:
		return gzip.NoCompression, nil
Steven Allen's avatar
Steven Allen committed
245
	case cmprs && !cmplvlFound:
246
		return gzip.DefaultCompression, nil
keks's avatar
keks committed
247
	case cmprs && (cmplvl < 1 || cmplvl > 9):
248
		return gzip.NoCompression, ErrInvalidCompressionLevel
249
	}
250
	return cmplvl, nil
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

// DefaultBufSize is the buffer size for gets. for now, 1MB, which is ~4 blocks.
// TODO: does this need to be configurable?
var DefaultBufSize = 1048576

type identityWriteCloser struct {
	w io.Writer
}

func (i *identityWriteCloser) Write(p []byte) (int, error) {
	return i.w.Write(p)
}

func (i *identityWriteCloser) Close() error {
	return nil
}

func fileArchive(f files.Node, name string, archive bool, compression int) (io.Reader, error) {
	cleaned := path.Clean(name)
	_, filename := path.Split(cleaned)

	// need to connect a writer to a reader
	piper, pipew := io.Pipe()
	checkErrAndClosePipe := func(err error) bool {
		if err != nil {
			pipew.CloseWithError(err)
			return true
		}
		return false
	}

	// use a buffered writer to parallelize task
	bufw := bufio.NewWriterSize(pipew, DefaultBufSize)

	// compression determines whether to use gzip compression.
	maybeGzw, err := newMaybeGzWriter(bufw, compression)
	if checkErrAndClosePipe(err) {
		return nil, err
	}

	closeGzwAndPipe := func() {
		if err := maybeGzw.Close(); checkErrAndClosePipe(err) {
			return
		}
		if err := bufw.Flush(); checkErrAndClosePipe(err) {
			return
		}
		pipew.Close() // everything seems to be ok.
	}

	if !archive && compression != gzip.NoCompression {
		// the case when the node is a file
		r := files.ToFile(f)
		if r == nil {
			return nil, errors.New("file is not regular")
		}

		go func() {
			if _, err := io.Copy(maybeGzw, r); checkErrAndClosePipe(err) {
				return
			}
			closeGzwAndPipe() // everything seems to be ok
		}()
	} else {
		// the case for 1. archive, and 2. not archived and not compressed, in which tar is used anyway as a transport format

		// construct the tar writer
		w, err := files.NewTarWriter(maybeGzw)
		if checkErrAndClosePipe(err) {
			return nil, err
		}

		go func() {
			// write all the nodes recursively
			if err := w.WriteFile(f, filename); checkErrAndClosePipe(err) {
				return
			}
			w.Close()         // close tar writer
			closeGzwAndPipe() // everything seems to be ok
		}()
	}

	return piper, nil
}

func newMaybeGzWriter(w io.Writer, compression int) (io.WriteCloser, error) {
	if compression != gzip.NoCompression {
		return gzip.NewWriterLevel(w, compression)
	}
	return &identityWriteCloser{w}, nil
}