dagreader.go 6.93 KB
Newer Older
1 2 3 4 5
package io

import (
	"bytes"
	"errors"
6
	"fmt"
7
	"io"
Jeromy's avatar
Jeromy committed
8
	"os"
9

10
	proto "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/gogo/protobuf/proto"
11
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
12

13 14 15
	mdag "github.com/ipfs/go-ipfs/merkledag"
	ft "github.com/ipfs/go-ipfs/unixfs"
	ftpb "github.com/ipfs/go-ipfs/unixfs/pb"
16 17 18 19
)

var ErrIsDir = errors.New("this dag node is a directory")

20 21
var ErrCantReadSymlinks = errors.New("cannot currently read symlinks")

22 23
// DagReader provides a way to easily read the data contained in a dag.
type DagReader struct {
Jeromy's avatar
Jeromy committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
	serv mdag.DAGService

	// the node being read
	node *mdag.Node

	// cached protobuf structure from node.Data
	pbdata *ftpb.Data

	// the current data buffer to be read from
	// will either be a bytes.Reader or a child DagReader
	buf ReadSeekCloser

	// NodeGetters for each of 'nodes' child links
	promises []mdag.NodeGetter

	// the index of the child link currently being read from
Jeromy's avatar
Jeromy committed
40
	linkPosition int
Jeromy's avatar
Jeromy committed
41 42 43

	// current offset for the read head within the 'file'
	offset int64
Jeromy's avatar
Jeromy committed
44 45 46 47

	// Our context
	ctx context.Context

Jeromy's avatar
Jeromy committed
48
	// context cancel for children
Jeromy's avatar
Jeromy committed
49 50 51 52 53 54 55
	cancel func()
}

type ReadSeekCloser interface {
	io.Reader
	io.Seeker
	io.Closer
56
	io.WriterTo
57 58
}

59 60
// NewDagReader creates a new reader object that reads the data represented by
// the given node, using the passed in DAGService for data retreival
61
func NewDagReader(ctx context.Context, n *mdag.Node, serv mdag.DAGService) (*DagReader, error) {
62
	pb := new(ftpb.Data)
rht's avatar
rht committed
63
	if err := proto.Unmarshal(n.Data, pb); err != nil {
64 65 66 67
		return nil, err
	}

	switch pb.GetType() {
68
	case ftpb.Data_Directory:
69 70
		// Dont allow reading directories
		return nil, ErrIsDir
71 72
	case ftpb.Data_Raw:
		fallthrough
73
	case ftpb.Data_File:
rht's avatar
rht committed
74
		return NewDataFileReader(ctx, n, pb, serv), nil
75 76 77 78
	case ftpb.Data_Metadata:
		if len(n.Links) == 0 {
			return nil, errors.New("incorrectly formatted metadata object")
		}
Jeromy's avatar
Jeromy committed
79
		child, err := n.Links[0].GetNode(ctx, serv)
80 81 82 83
		if err != nil {
			return nil, err
		}
		return NewDagReader(ctx, child, serv)
84 85
	case ftpb.Data_Symlink:
		return nil, ErrCantReadSymlinks
86 87 88 89 90
	default:
		return nil, ft.ErrUnrecognizedType
	}
}

rht's avatar
rht committed
91
func NewDataFileReader(ctx context.Context, n *mdag.Node, pb *ftpb.Data, serv mdag.DAGService) *DagReader {
92 93 94 95 96 97 98 99 100 101 102 103 104
	fctx, cancel := context.WithCancel(ctx)
	promises := serv.GetDAG(fctx, n)
	return &DagReader{
		node:     n,
		serv:     serv,
		buf:      NewRSNCFromBytes(pb.GetData()),
		promises: promises,
		ctx:      fctx,
		cancel:   cancel,
		pbdata:   pb,
	}
}

105 106
// precalcNextBuf follows the next link in line and loads it from the
// DAGService, setting the next buffer to read from
107
func (dr *DagReader) precalcNextBuf(ctx context.Context) error {
Jeromy's avatar
Jeromy committed
108 109 110
	dr.buf.Close() // Just to make sure
	if dr.linkPosition >= len(dr.promises) {
		return io.EOF
Jeromy's avatar
Jeromy committed
111
	}
112 113

	nxt, err := dr.promises[dr.linkPosition].Get(ctx)
Jeromy's avatar
Jeromy committed
114 115
	if err != nil {
		return err
116
	}
Jeromy's avatar
Jeromy committed
117
	dr.linkPosition++
Jeromy's avatar
Jeromy committed
118

119
	pb := new(ftpb.Data)
Jeromy's avatar
Jeromy committed
120
	err = proto.Unmarshal(nxt.Data, pb)
121
	if err != nil {
122
		return fmt.Errorf("incorrectly formatted protobuf: %s", err)
123 124 125
	}

	switch pb.GetType() {
126
	case ftpb.Data_Directory:
Jeromy's avatar
Jeromy committed
127
		// A directory should not exist within a file
128
		return ft.ErrInvalidDirLocation
129
	case ftpb.Data_File:
rht's avatar
rht committed
130
		dr.buf = NewDataFileReader(dr.ctx, nxt, pb, dr.serv)
Jeromy's avatar
Jeromy committed
131
		return nil
132
	case ftpb.Data_Raw:
Jeromy's avatar
Jeromy committed
133
		dr.buf = NewRSNCFromBytes(pb.GetData())
134
		return nil
135 136
	case ftpb.Data_Metadata:
		return errors.New("Shouldnt have had metadata object inside file")
137 138
	case ftpb.Data_Symlink:
		return errors.New("shouldnt have had symlink inside file")
139 140 141 142 143
	default:
		return ft.ErrUnrecognizedType
	}
}

144
// Size return the total length of the data from the DAG structured file.
rht's avatar
rht committed
145 146
func (dr *DagReader) Size() uint64 {
	return dr.pbdata.GetFilesize()
147 148
}

Jeromy's avatar
Jeromy committed
149
// Read reads data from the DAG structured file
150
func (dr *DagReader) Read(b []byte) (int, error) {
151 152 153 154 155
	return dr.CtxReadFull(dr.ctx, b)
}

// CtxReadFull reads data from the DAG structured file
func (dr *DagReader) CtxReadFull(ctx context.Context, b []byte) (int, error) {
156 157 158 159 160 161
	// If no cached buffer, load one
	total := 0
	for {
		// Attempt to fill bytes from cached buffer
		n, err := dr.buf.Read(b[total:])
		total += n
Jeromy's avatar
Jeromy committed
162
		dr.offset += int64(n)
163 164 165 166 167 168 169 170 171 172 173 174 175
		if err != nil {
			// EOF is expected
			if err != io.EOF {
				return total, err
			}
		}

		// If weve read enough bytes, return
		if total == len(b) {
			return total, nil
		}

		// Otherwise, load up the next block
176
		err = dr.precalcNextBuf(ctx)
177 178 179 180 181 182
		if err != nil {
			return total, err
		}
	}
}

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
func (dr *DagReader) WriteTo(w io.Writer) (int64, error) {
	// If no cached buffer, load one
	total := int64(0)
	for {
		// Attempt to write bytes from cached buffer
		n, err := dr.buf.WriteTo(w)
		total += n
		dr.offset += n
		if err != nil {
			if err != io.EOF {
				return total, err
			}
		}

		// Otherwise, load up the next block
198
		err = dr.precalcNextBuf(dr.ctx)
199 200 201 202 203 204 205 206 207
		if err != nil {
			if err == io.EOF {
				return total, nil
			}
			return total, err
		}
	}
}

Jeromy's avatar
Jeromy committed
208
func (dr *DagReader) Close() error {
Jeromy's avatar
Jeromy committed
209
	dr.cancel()
Jeromy's avatar
Jeromy committed
210 211 212
	return nil
}

Jeromy's avatar
Jeromy committed
213 214
// Seek implements io.Seeker, and will seek to a given offset in the file
// interface matches standard unix seek
215 216
// TODO: check if we can do relative seeks, to reduce the amount of dagreader
// recreations that need to happen.
217 218 219
func (dr *DagReader) Seek(offset int64, whence int) (int64, error) {
	switch whence {
	case os.SEEK_SET:
Jeromy's avatar
Jeromy committed
220 221 222 223
		if offset < 0 {
			return -1, errors.New("Invalid offset")
		}

Jeromy's avatar
Jeromy committed
224
		// Grab cached protobuf object (solely to make code look cleaner)
Jeromy's avatar
Jeromy committed
225
		pb := dr.pbdata
Jeromy's avatar
Jeromy committed
226 227

		// left represents the number of bytes remaining to seek to (from beginning)
Jeromy's avatar
Jeromy committed
228
		left := offset
229
		if int64(len(pb.Data)) >= offset {
Jeromy's avatar
Jeromy committed
230
			// Close current buf to close potential child dagreader
Jeromy's avatar
Jeromy committed
231
			dr.buf.Close()
Jeromy's avatar
Jeromy committed
232
			dr.buf = NewRSNCFromBytes(pb.GetData()[offset:])
Jeromy's avatar
Jeromy committed
233 234

			// start reading links from the beginning
Jeromy's avatar
Jeromy committed
235 236 237 238
			dr.linkPosition = 0
			dr.offset = offset
			return offset, nil
		} else {
Jeromy's avatar
Jeromy committed
239
			// skip past root block data
Jeromy's avatar
Jeromy committed
240 241 242
			left -= int64(len(pb.Data))
		}

Jeromy's avatar
Jeromy committed
243
		// iterate through links and find where we need to be
Jeromy's avatar
Jeromy committed
244
		for i := 0; i < len(pb.Blocksizes); i++ {
Jeromy's avatar
Jeromy committed
245
			if pb.Blocksizes[i] > uint64(left) {
Jeromy's avatar
Jeromy committed
246
				dr.linkPosition = i
247
				break
Jeromy's avatar
Jeromy committed
248 249
			} else {
				left -= int64(pb.Blocksizes[i])
250 251
			}
		}
Jeromy's avatar
Jeromy committed
252

Jeromy's avatar
Jeromy committed
253
		// start sub-block request
254
		err := dr.precalcNextBuf(dr.ctx)
255 256 257
		if err != nil {
			return 0, err
		}
Jeromy's avatar
Jeromy committed
258

Jeromy's avatar
Jeromy committed
259
		// set proper offset within child readseeker
Jeromy's avatar
Jeromy committed
260
		n, err := dr.buf.Seek(left, os.SEEK_SET)
Jeromy's avatar
Jeromy committed
261 262 263
		if err != nil {
			return -1, err
		}
Jeromy's avatar
Jeromy committed
264 265

		// sanity
Jeromy's avatar
Jeromy committed
266 267 268 269 270 271
		left -= n
		if left != 0 {
			return -1, errors.New("failed to seek properly")
		}
		dr.offset = offset
		return offset, nil
272
	case os.SEEK_CUR:
Jeromy's avatar
Jeromy committed
273
		// TODO: be smarter here
Jeromy's avatar
Jeromy committed
274 275
		noffset := dr.offset + offset
		return dr.Seek(noffset, os.SEEK_SET)
276
	case os.SEEK_END:
Jeromy's avatar
Jeromy committed
277
		noffset := int64(dr.pbdata.GetFilesize()) - offset
Jeromy's avatar
Jeromy committed
278
		return dr.Seek(noffset, os.SEEK_SET)
279 280 281 282 283
	default:
		return 0, errors.New("invalid whence")
	}
	return 0, nil
}
Jeromy's avatar
Jeromy committed
284

Jeromy's avatar
Jeromy committed
285
// readSeekNopCloser wraps a bytes.Reader to implement ReadSeekCloser
Jeromy's avatar
Jeromy committed
286 287 288 289 290 291 292 293 294
type readSeekNopCloser struct {
	*bytes.Reader
}

func NewRSNCFromBytes(b []byte) ReadSeekCloser {
	return &readSeekNopCloser{bytes.NewReader(b)}
}

func (r *readSeekNopCloser) Close() error { return nil }