[ARVADOS] created: 1.1.0-143-g0e95e76

Git user git at public.curoverse.com
Mon Nov 13 16:52:58 EST 2017


        at  0e95e76365592a407faab7b9bf468889a191d393 (commit)


commit 0e95e76365592a407faab7b9bf468889a191d393
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Mon Nov 13 16:50:22 2017 -0500

    12453: Persist written data to keep.
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index f0f8b0c..6580a1d 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -5,7 +5,6 @@
 package arvados
 
 import (
-	"crypto/md5"
 	"errors"
 	"fmt"
 	"io"
@@ -44,6 +43,7 @@ type File interface {
 
 type keepClient interface {
 	ReadAt(locator string, p []byte, off int) (int, error)
+	Write(p []byte) (string, error)
 }
 
 type fileinfo struct {
@@ -429,7 +429,6 @@ func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePt
 // FileSystem returns a CollectionFileSystem for the collection.
 func (c *Collection) FileSystem(client *Client, kc keepClient) CollectionFileSystem {
 	fs := &fileSystem{dirnode: dirnode{
-		cache:    &keepBlockCache{kc: kc},
 		client:   client,
 		kc:       kc,
 		fileinfo: fileinfo{name: ".", mode: os.ModeDir | 0755},
@@ -527,7 +526,6 @@ type dirnode struct {
 	parent *dirnode
 	client *Client
 	kc     keepClient
-	cache  blockCache
 	inodes map[string]inode
 	sync.RWMutex
 }
@@ -545,24 +543,21 @@ func (dn *dirnode) sync() error {
 		if len(sbs) == 0 {
 			return nil
 		}
-		hash := md5.New()
-		size := 0
+		block := make([]byte, 0, maxBlockSize)
 		for _, sb := range sbs {
-			data := sb.fn.extents[sb.idx].(*memExtent).buf
-			if _, err := hash.Write(data); err != nil {
-				return err
-			}
-			size += len(data)
+			block = append(block, sb.fn.extents[sb.idx].(*memExtent).buf...)
+		}
+		locator, err := dn.kc.Write(block)
+		if err != nil {
+			return err
 		}
-		// FIXME: write to keep
-		locator := fmt.Sprintf("%x+%d", hash.Sum(nil), size)
 		off := 0
 		for _, sb := range sbs {
 			data := sb.fn.extents[sb.idx].(*memExtent).buf
 			sb.fn.extents[sb.idx] = storedExtent{
-				cache:   dn.cache,
+				kc:      dn.kc,
 				locator: locator,
-				size:    size,
+				size:    len(block),
 				offset:  off,
 				length:  len(data),
 			}
@@ -674,14 +669,14 @@ func (dn *dirnode) MarshalManifest(prefix string) (string, error) {
 	}
 	var filetokens []string
 	for _, s := range segments {
-		filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, s.name))
+		filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, manifestEscape(s.name)))
 	}
 	if len(filetokens) == 0 {
 		return subdirs, nil
 	} else if len(blocks) == 0 {
 		blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
 	}
-	return prefix + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n" + subdirs, nil
+	return manifestEscape(prefix) + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n" + subdirs, nil
 }
 
 func (dn *dirnode) loadManifest(txt string) {
@@ -732,13 +727,13 @@ func (dn *dirnode) loadManifest(txt string) {
 			dn.makeParentDirs(name)
 			f, err := dn.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0700)
 			if err != nil {
-				// FIXME: broken
-				continue
+				// FIXME: don't panic
+				panic(fmt.Errorf("cannot append to %q: %s", name, err))
 			}
 			if f.inode.Stat().IsDir() {
 				f.Close()
-				// FIXME: broken manifest
-				continue
+				// FIXME: don't panic
+				panic(fmt.Errorf("cannot append to %q: is a directory", name))
 			}
 			// Map the stream offset/range coordinates to
 			// block/offset/range coordinates and add
@@ -762,7 +757,7 @@ func (dn *dirnode) loadManifest(txt string) {
 					blkLen = int(offset + length - pos - int64(blkOff))
 				}
 				f.inode.(*filenode).appendExtent(storedExtent{
-					cache:   dn.cache,
+					kc:      dn.kc,
 					locator: e.locator,
 					size:    e.size,
 					offset:  blkOff,
@@ -1015,7 +1010,7 @@ func (me *memExtent) ReadAt(p []byte, off int64) (n int, err error) {
 }
 
 type storedExtent struct {
-	cache   blockCache
+	kc      keepClient
 	locator string
 	size    int
 	offset  int
@@ -1042,27 +1037,13 @@ func (se storedExtent) ReadAt(p []byte, off int64) (n int, err error) {
 	maxlen := se.length - int(off)
 	if len(p) > maxlen {
 		p = p[:maxlen]
-		n, err = se.cache.ReadAt(se.locator, p, int(off)+se.offset)
+		n, err = se.kc.ReadAt(se.locator, p, int(off)+se.offset)
 		if err == nil {
 			err = io.EOF
 		}
 		return
 	}
-	return se.cache.ReadAt(se.locator, p, int(off)+se.offset)
-}
-
-type blockCache interface {
-	ReadAt(locator string, p []byte, off int) (n int, err error)
-}
-
-type keepBlockCache struct {
-	kc keepClient
-}
-
-var scratch = make([]byte, 2<<26)
-
-func (kbc *keepBlockCache) ReadAt(locator string, p []byte, off int) (int, error) {
-	return kbc.kc.ReadAt(locator, p, off)
+	return se.kc.ReadAt(se.locator, p, int(off)+se.offset)
 }
 
 func canonicalName(name string) string {
@@ -1077,7 +1058,7 @@ func canonicalName(name string) string {
 
 var manifestEscapeSeq = regexp.MustCompile(`\\([0-9]{3}|\\)`)
 
-func manifestUnescapeSeq(seq string) string {
+func manifestUnescapeFunc(seq string) string {
 	if seq == `\\` {
 		return `\`
 	}
@@ -1090,5 +1071,15 @@ func manifestUnescapeSeq(seq string) string {
 }
 
 func manifestUnescape(s string) string {
-	return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeSeq)
+	return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeFunc)
+}
+
+var manifestEscapedChar = regexp.MustCompile(`[^\.\w/]`)
+
+func manifestEscapeFunc(seq string) string {
+	return fmt.Sprintf("\\%03o", byte(seq[0]))
+}
+
+func manifestEscape(s string) string {
+	return manifestEscapedChar.ReplaceAllStringFunc(s, manifestEscapeFunc)
 }
diff --git a/sdk/go/arvados/collection_fs_test.go b/sdk/go/arvados/collection_fs_test.go
index ce3f85d..da1fb2f 100644
--- a/sdk/go/arvados/collection_fs_test.go
+++ b/sdk/go/arvados/collection_fs_test.go
@@ -5,6 +5,8 @@
 package arvados
 
 import (
+	"crypto/md5"
+	"errors"
 	"fmt"
 	"io"
 	"io/ioutil"
@@ -23,16 +25,31 @@ var _ = check.Suite(&CollectionFSSuite{})
 
 type keepClientStub struct {
 	blocks map[string][]byte
+	sync.RWMutex
 }
 
+var errStub404 = errors.New("404 block not found")
+
 func (kcs *keepClientStub) ReadAt(locator string, p []byte, off int) (int, error) {
+	kcs.RLock()
+	defer kcs.RUnlock()
 	buf := kcs.blocks[locator[:32]]
 	if buf == nil {
-		return 0, os.ErrNotExist
+		return 0, errStub404
 	}
 	return copy(p, buf[off:]), nil
 }
 
+func (kcs *keepClientStub) Write(p []byte) (string, error) {
+	locator := fmt.Sprintf("%x+%d+A12345 at abcde", md5.Sum(p), len(p))
+	buf := make([]byte, len(p))
+	copy(buf, p)
+	kcs.Lock()
+	defer kcs.Unlock()
+	kcs.blocks[locator[:32]] = buf
+	return locator, nil
+}
+
 type CollectionFSSuite struct {
 	client *Client
 	coll   Collection
@@ -371,7 +388,7 @@ func (s *CollectionFSSuite) TestMkdir(c *check.C) {
 	// creating foo/bar as a directory should fail
 	f, err = s.fs.OpenFile("foo/bar", os.O_CREATE|os.O_EXCL, os.ModeDir)
 	c.Check(err, check.NotNil)
-	err = s.fs.Mkdir("foo/bar")
+	err = s.fs.Mkdir("foo/bar", 0755)
 	c.Check(err, check.NotNil)
 
 	m, err := s.fs.MarshalManifest(".")
@@ -422,6 +439,8 @@ func (s *CollectionFSSuite) TestRandomWrites(c *check.C) {
 	maxBlockSize = 8
 	defer func() { maxBlockSize = 2 << 26 }()
 
+	s.fs = (&Collection{}).FileSystem(s.client, s.kc)
+
 	var wg sync.WaitGroup
 	for n := 0; n < 128; n++ {
 		wg.Add(1)
@@ -467,11 +486,75 @@ func (s *CollectionFSSuite) TestRandomWrites(c *check.C) {
 	defer root.Close()
 	fi, err := root.Readdir(-1)
 	c.Check(err, check.IsNil)
-	c.Logf("Readdir(): %#v", fi)
+	c.Check(len(fi), check.Equals, 128)
+
+	_, err = s.fs.MarshalManifest(".")
+	c.Check(err, check.IsNil)
+	// TODO: check manifest content
+}
+
+func (s *CollectionFSSuite) TestPersist(c *check.C) {
+	maxBlockSize = 1024
+	defer func() { maxBlockSize = 2 << 26 }()
+
+	s.fs = (&Collection{}).FileSystem(s.client, s.kc)
+	err := s.fs.Mkdir("d:r", 0755)
+	c.Assert(err, check.IsNil)
+
+	expect := map[string][]byte{}
+
+	var wg sync.WaitGroup
+	for _, name := range []string{"random 1", "random:2", "random\\3", "d:r/random4"} {
+		buf := make([]byte, 500)
+		rand.Read(buf)
+		expect[name] = buf
+
+		f, err := s.fs.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0)
+		c.Assert(err, check.IsNil)
+		// Note: we don't close the file until after the test
+		// is done. Writes to unclosed files should persist.
+		defer f.Close()
+
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			for i := 0; i < len(buf); i += 5 {
+				_, err := f.Write(buf[i : i+5])
+				c.Assert(err, check.IsNil)
+			}
+		}()
+	}
+	wg.Wait()
 
 	m, err := s.fs.MarshalManifest(".")
 	c.Check(err, check.IsNil)
-	c.Logf("%s", m)
+	c.Logf("%q", m)
+
+	root, err := s.fs.Open("/")
+	c.Assert(err, check.IsNil)
+	defer root.Close()
+	fi, err := root.Readdir(-1)
+	c.Check(err, check.IsNil)
+	c.Check(len(fi), check.Equals, 4)
+
+	persisted := (&Collection{ManifestText: m}).FileSystem(s.client, s.kc)
+
+	root, err = persisted.Open("/")
+	c.Assert(err, check.IsNil)
+	defer root.Close()
+	fi, err = root.Readdir(-1)
+	c.Check(err, check.IsNil)
+	c.Check(len(fi), check.Equals, 4)
+
+	for name, content := range expect {
+		c.Logf("read %q", name)
+		f, err := persisted.Open(name)
+		c.Assert(err, check.IsNil)
+		defer f.Close()
+		buf, err := ioutil.ReadAll(f)
+		c.Check(err, check.IsNil)
+		c.Check(buf, check.DeepEquals, content)
+	}
 }
 
 // Gocheck boilerplate

commit cd45aed0312fc44046dcafe1681f5a4dc3ec1512
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Mon Nov 13 16:50:07 2017 -0500

    12483: Remove unnecessary OpenFile() from inode interface.
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index eb029fc..f0f8b0c 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -126,7 +126,6 @@ func (fs *fileSystem) Stat(name string) (os.FileInfo, error) {
 
 type inode interface {
 	os.FileInfo
-	OpenFile(string, int, os.FileMode) (*file, error)
 	Parent() inode
 	Read([]byte, filenodePtr) (int, filenodePtr, error)
 	Write([]byte, filenodePtr) (int, filenodePtr, error)
@@ -226,10 +225,6 @@ func (fn *filenode) appendExtent(e extent) {
 	fn.fileinfo.size += int64(e.Len())
 }
 
-func (fn *filenode) OpenFile(string, int, os.FileMode) (*file, error) {
-	return nil, os.ErrNotExist
-}
-
 func (fn *filenode) Parent() inode {
 	return fn.parent
 }
@@ -527,10 +522,6 @@ func (f *file) Close() error {
 	return nil
 }
 
-func (f *file) OpenFile(name string, flag int, perm os.FileMode) (*file, error) {
-	return f.inode.OpenFile(name, flag, perm)
-}
-
 type dirnode struct {
 	fileinfo
 	parent *dirnode

commit 4f21d0e5c0d2dca218bc9a204d364c15ad7450b1
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Mon Nov 13 10:36:50 2017 -0500

    12483: Add Mkdir(), Remove().
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index 2f1ec2f..eb029fc 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -21,11 +21,12 @@ import (
 )
 
 var (
-	ErrReadOnlyFile     = errors.New("read-only file")
-	ErrNegativeOffset   = errors.New("cannot seek to negative offset")
-	ErrFileExists       = errors.New("file exists")
-	ErrInvalidOperation = errors.New("invalid operation")
-	ErrPermission       = os.ErrPermission
+	ErrReadOnlyFile      = errors.New("read-only file")
+	ErrNegativeOffset    = errors.New("cannot seek to negative offset")
+	ErrFileExists        = errors.New("file exists")
+	ErrInvalidOperation  = errors.New("invalid operation")
+	ErrDirectoryNotEmpty = errors.New("directory not empty")
+	ErrPermission        = os.ErrPermission
 
 	maxBlockSize = 1 << 26
 )
@@ -93,6 +94,8 @@ type CollectionFileSystem interface {
 	Stat(name string) (os.FileInfo, error)
 	Create(name string) (File, error)
 	OpenFile(name string, flag int, perm os.FileMode) (File, error)
+	Mkdir(name string, perm os.FileMode) error
+	Remove(name string) error
 	MarshalManifest(string) (string, error)
 }
 
@@ -781,37 +784,63 @@ func (dn *dirnode) loadManifest(txt string) {
 	}
 }
 
-func (dn *dirnode) makeParentDirs(name string) {
+func (dn *dirnode) makeParentDirs(name string) (err error) {
 	names := strings.Split(name, "/")
 	for _, name := range names[:len(names)-1] {
-		dn.Lock()
-		defer dn.Unlock()
-		if n, ok := dn.inodes[name]; !ok {
-			n := &dirnode{
-				parent: dn,
-				client: dn.client,
-				kc:     dn.kc,
-				fileinfo: fileinfo{
-					name: name,
-					mode: os.ModeDir | 0755,
-				},
-			}
-			if dn.inodes == nil {
-				dn.inodes = make(map[string]inode)
-			}
-			dn.inodes[name] = n
-			dn.fileinfo.size++
-			dn = n
-		} else if n, ok := n.(*dirnode); ok {
-			dn = n
-		} else {
-			// fail
-			return
+		f, err := dn.mkdir(name)
+		if err != nil {
+			return err
+		}
+		defer f.Close()
+		var ok bool
+		dn, ok = f.inode.(*dirnode)
+		if !ok {
+			return ErrFileExists
+		}
+	}
+	return nil
+}
+
+func (dn *dirnode) mkdir(name string) (*file, error) {
+	return dn.OpenFile(name, os.O_CREATE|os.O_EXCL, os.ModeDir|0755)
+}
+
+func (dn *dirnode) Mkdir(name string, perm os.FileMode) error {
+	f, err := dn.mkdir(name)
+	if err != nil {
+		f.Close()
+	}
+	return err
+}
+
+func (dn *dirnode) Remove(name string) error {
+	dirname, name := path.Split(name)
+	if name == "" || name == "." || name == ".." {
+		return ErrInvalidOperation
+	}
+	dn, ok := dn.lookupPath(dirname).(*dirnode)
+	if !ok {
+		return os.ErrNotExist
+	}
+	dn.Lock()
+	defer dn.Unlock()
+	switch node := dn.inodes[name].(type) {
+	case nil:
+		return os.ErrNotExist
+	case *dirnode:
+		node.RLock()
+		defer node.RUnlock()
+		if len(node.inodes) > 0 {
+			return ErrDirectoryNotEmpty
 		}
 	}
+	delete(dn.inodes, name)
+	return nil
 }
 
 func (dn *dirnode) Parent() inode {
+	dn.RLock()
+	defer dn.RUnlock()
 	return dn.parent
 }
 
@@ -837,42 +866,78 @@ func (dn *dirnode) Truncate(int64) error {
 	return ErrInvalidOperation
 }
 
+// lookupPath returns the inode for the file/directory with the given
+// name (which may contain "/" separators), along with its parent
+// node. If no such file/directory exists, the returned node is nil.
+func (dn *dirnode) lookupPath(path string) (node inode) {
+	node = dn
+	for _, name := range strings.Split(path, "/") {
+		dn, ok := node.(*dirnode)
+		if !ok {
+			return nil
+		}
+		if name == "." || name == "" {
+			continue
+		}
+		if name == ".." {
+			node = node.Parent()
+			continue
+		}
+		dn.RLock()
+		node = dn.inodes[name]
+		dn.RUnlock()
+	}
+	return
+}
+
 func (dn *dirnode) OpenFile(name string, flag int, perm os.FileMode) (*file, error) {
-	name = strings.TrimSuffix(name, "/")
-	if name == "." || name == "" {
-		return &file{inode: dn}, nil
+	dirname, name := path.Split(name)
+	dn, ok := dn.lookupPath(dirname).(*dirnode)
+	if !ok {
+		return nil, os.ErrNotExist
 	}
-	if dirname, name := path.Split(name); dirname != "" {
-		// OpenFile("foo/bar/baz") =>
-		// OpenFile("foo/bar").OpenFile("baz") (or
-		// ErrNotExist, if foo/bar is a file)
-		f, err := dn.OpenFile(dirname, os.O_RDONLY, 0)
-		if err != nil {
-			return nil, err
-		}
-		defer f.Close()
-		if dn, ok := f.inode.(*dirnode); ok {
-			return dn.OpenFile(name, flag, perm)
-		} else {
-			return nil, os.ErrNotExist
+	writeMode := flag&(os.O_RDWR|os.O_WRONLY|os.O_CREATE) != 0
+	if !writeMode {
+		// A directory can be opened via "foo/", "foo/.", or
+		// "foo/..".
+		switch name {
+		case ".", "":
+			return &file{inode: dn}, nil
+		case "..":
+			return &file{inode: dn.Parent()}, nil
 		}
 	}
-	dn.Lock()
-	defer dn.Unlock()
-	if name == ".." {
-		return &file{inode: dn.parent}, nil
+	createMode := flag&os.O_CREATE != 0
+	if createMode {
+		dn.Lock()
+		defer dn.Unlock()
+	} else {
+		dn.RLock()
+		defer dn.RUnlock()
 	}
 	n, ok := dn.inodes[name]
 	if !ok {
-		if flag&os.O_CREATE == 0 {
+		if !createMode {
 			return nil, os.ErrNotExist
 		}
-		n = &filenode{
-			parent: dn,
-			fileinfo: fileinfo{
-				name: name,
-				mode: 0755,
-			},
+		if perm.IsDir() {
+			n = &dirnode{
+				parent: dn,
+				client: dn.client,
+				kc:     dn.kc,
+				fileinfo: fileinfo{
+					name: name,
+					mode: os.ModeDir | 0755,
+				},
+			}
+		} else {
+			n = &filenode{
+				parent: dn,
+				fileinfo: fileinfo{
+					name: name,
+					mode: 0755,
+				},
+			}
 		}
 		if dn.inodes == nil {
 			dn.inodes = make(map[string]inode)
diff --git a/sdk/go/arvados/collection_fs_test.go b/sdk/go/arvados/collection_fs_test.go
index 70d46e2..ce3f85d 100644
--- a/sdk/go/arvados/collection_fs_test.go
+++ b/sdk/go/arvados/collection_fs_test.go
@@ -325,6 +325,61 @@ func (s *CollectionFSSuite) TestMarshalSmallBlocks(c *check.C) {
 	c.Check(m, check.Equals, ". c3c23db5285662ef7172373df0003206+6 acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:bar 3:3:baz 6:3:foo\n")
 }
 
+func (s *CollectionFSSuite) TestMkdir(c *check.C) {
+	err := s.fs.Mkdir("foo/bar", 0755)
+	c.Check(err, check.Equals, os.ErrNotExist)
+
+	f, err := s.fs.OpenFile("foo/bar", os.O_CREATE, 0)
+	c.Check(err, check.Equals, os.ErrNotExist)
+
+	err = s.fs.Mkdir("foo", 0755)
+	c.Check(err, check.IsNil)
+
+	f, err = s.fs.OpenFile("foo/bar", os.O_CREATE|os.O_WRONLY, 0)
+	c.Check(err, check.IsNil)
+	if err == nil {
+		defer f.Close()
+		f.Write([]byte("foo"))
+	}
+
+	// mkdir fails if a file already exists with that name
+	err = s.fs.Mkdir("foo/bar", 0755)
+	c.Check(err, check.NotNil)
+
+	err = s.fs.Remove("foo/bar")
+	c.Check(err, check.IsNil)
+
+	// mkdir succeds after the file is deleted
+	err = s.fs.Mkdir("foo/bar", 0755)
+	c.Check(err, check.IsNil)
+
+	// creating a file in a nonexistent subdir should still fail
+	f, err = s.fs.OpenFile("foo/bar/baz/foo.txt", os.O_CREATE|os.O_WRONLY, 0)
+	c.Check(err, check.Equals, os.ErrNotExist)
+
+	f, err = s.fs.OpenFile("foo/bar/foo.txt", os.O_CREATE|os.O_WRONLY, 0)
+	c.Check(err, check.IsNil)
+	if err == nil {
+		defer f.Close()
+		f.Write([]byte("foo"))
+	}
+
+	// creating foo/bar as a regular file should fail
+	f, err = s.fs.OpenFile("foo/bar", os.O_CREATE|os.O_EXCL, 0)
+	c.Check(err, check.NotNil)
+
+	// creating foo/bar as a directory should fail
+	f, err = s.fs.OpenFile("foo/bar", os.O_CREATE|os.O_EXCL, os.ModeDir)
+	c.Check(err, check.NotNil)
+	err = s.fs.Mkdir("foo/bar")
+	c.Check(err, check.NotNil)
+
+	m, err := s.fs.MarshalManifest(".")
+	c.Check(err, check.IsNil)
+	m = regexp.MustCompile(`\+A[^\+ ]+`).ReplaceAllLiteralString(m, "")
+	c.Check(m, check.Equals, "./dir1 3858f62230ac3c915f300c664312c63f+6 3:3:bar 0:3:foo\n./foo/bar acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:foo.txt\n")
+}
+
 func (s *CollectionFSSuite) TestConcurrentWriters(c *check.C) {
 	maxBlockSize = 8
 	defer func() { maxBlockSize = 2 << 26 }()

commit 236ede1415d7a09f97a05c5ab63e2cedd4d19d48
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Sun Nov 12 03:31:16 2017 -0500

    12483: Add MarshalManifest().
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index 17740db..2f1ec2f 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -5,12 +5,15 @@
 package arvados
 
 import (
+	"crypto/md5"
 	"errors"
+	"fmt"
 	"io"
 	"net/http"
 	"os"
 	"path"
 	"regexp"
+	"sort"
 	"strconv"
 	"strings"
 	"sync"
@@ -90,6 +93,7 @@ type CollectionFileSystem interface {
 	Stat(name string) (os.FileInfo, error)
 	Create(name string) (File, error)
 	OpenFile(name string, flag int, perm os.FileMode) (File, error)
+	MarshalManifest(string) (string, error)
 }
 
 type fileSystem struct {
@@ -534,6 +538,158 @@ type dirnode struct {
 	sync.RWMutex
 }
 
+// caller must hold dn.Lock().
+func (dn *dirnode) sync() error {
+	type shortBlock struct {
+		fn  *filenode
+		idx int
+	}
+	var pending []shortBlock
+	var pendingLen int
+
+	flush := func(sbs []shortBlock) error {
+		if len(sbs) == 0 {
+			return nil
+		}
+		hash := md5.New()
+		size := 0
+		for _, sb := range sbs {
+			data := sb.fn.extents[sb.idx].(*memExtent).buf
+			if _, err := hash.Write(data); err != nil {
+				return err
+			}
+			size += len(data)
+		}
+		// FIXME: write to keep
+		locator := fmt.Sprintf("%x+%d", hash.Sum(nil), size)
+		off := 0
+		for _, sb := range sbs {
+			data := sb.fn.extents[sb.idx].(*memExtent).buf
+			sb.fn.extents[sb.idx] = storedExtent{
+				cache:   dn.cache,
+				locator: locator,
+				size:    size,
+				offset:  off,
+				length:  len(data),
+			}
+			off += len(data)
+		}
+		return nil
+	}
+
+	names := make([]string, 0, len(dn.inodes))
+	for name := range dn.inodes {
+		names = append(names, name)
+	}
+	sort.Strings(names)
+
+	for _, name := range names {
+		fn, ok := dn.inodes[name].(*filenode)
+		if !ok {
+			continue
+		}
+		fn.Lock()
+		defer fn.Unlock()
+		for idx, ext := range fn.extents {
+			ext, ok := ext.(*memExtent)
+			if !ok {
+				continue
+			}
+			if ext.Len() > maxBlockSize/2 {
+				if err := flush([]shortBlock{{fn, idx}}); err != nil {
+					return err
+				}
+				continue
+			}
+			if pendingLen+ext.Len() > maxBlockSize {
+				if err := flush(pending); err != nil {
+					return err
+				}
+				pending = nil
+				pendingLen = 0
+			}
+			pending = append(pending, shortBlock{fn, idx})
+			pendingLen += ext.Len()
+		}
+	}
+	return flush(pending)
+}
+
+func (dn *dirnode) MarshalManifest(prefix string) (string, error) {
+	dn.Lock()
+	defer dn.Unlock()
+	if err := dn.sync(); err != nil {
+		return "", err
+	}
+
+	var streamLen int64
+	type m1segment struct {
+		name   string
+		offset int64
+		length int64
+	}
+	var segments []m1segment
+	var subdirs string
+	var blocks []string
+
+	names := make([]string, 0, len(dn.inodes))
+	for name := range dn.inodes {
+		names = append(names, name)
+	}
+	sort.Strings(names)
+
+	for _, name := range names {
+		node := dn.inodes[name]
+		switch node := node.(type) {
+		case *dirnode:
+			subdir, err := node.MarshalManifest(prefix + "/" + node.Name())
+			if err != nil {
+				return "", err
+			}
+			subdirs = subdirs + subdir
+		case *filenode:
+			for _, e := range node.extents {
+				switch e := e.(type) {
+				case *memExtent:
+					blocks = append(blocks, fmt.Sprintf("FIXME+%d", e.Len()))
+					segments = append(segments, m1segment{
+						name:   node.Name(),
+						offset: streamLen,
+						length: int64(e.Len()),
+					})
+					streamLen += int64(e.Len())
+				case storedExtent:
+					if len(blocks) > 0 && blocks[len(blocks)-1] == e.locator {
+						streamLen -= int64(e.size)
+					} else {
+						blocks = append(blocks, e.locator)
+					}
+					segments = append(segments, m1segment{
+						name:   node.Name(),
+						offset: streamLen + int64(e.offset),
+						length: int64(e.length),
+					})
+					streamLen += int64(e.size)
+				default:
+					panic(fmt.Sprintf("can't marshal extent type %T", e))
+				}
+			}
+		default:
+			panic(fmt.Sprintf("can't marshal inode type %T", node))
+		}
+	}
+	var filetokens []string
+	for _, s := range segments {
+		filetokens = append(filetokens, fmt.Sprintf("%d:%d:%s", s.offset, s.length, s.name))
+	}
+	if len(filetokens) == 0 {
+		return subdirs, nil
+	} else if len(blocks) == 0 {
+		blocks = []string{"d41d8cd98f00b204e9800998ecf8427e+0"}
+	}
+	return prefix + " " + strings.Join(blocks, " ") + " " + strings.Join(filetokens, " ") + "\n" + subdirs, nil
+}
+
 func (dn *dirnode) loadManifest(txt string) {
 	// FIXME: faster
 	var dirname string
@@ -557,6 +713,7 @@ func (dn *dirnode) loadManifest(txt string) {
 				}
 				extents = append(extents, storedExtent{
 					locator: token,
+					size:    int(length),
 					offset:  0,
 					length:  int(length),
 				})
@@ -613,6 +770,7 @@ func (dn *dirnode) loadManifest(txt string) {
 				f.inode.(*filenode).appendExtent(storedExtent{
 					cache:   dn.cache,
 					locator: e.locator,
+					size:    e.size,
 					offset:  blkOff,
 					length:  blkLen,
 				})
@@ -803,6 +961,7 @@ func (me *memExtent) ReadAt(p []byte, off int64) (n int, err error) {
 type storedExtent struct {
 	cache   blockCache
 	locator string
+	size    int
 	offset  int
 	length  int
 }
diff --git a/sdk/go/arvados/collection_fs_test.go b/sdk/go/arvados/collection_fs_test.go
index 4208079..70d46e2 100644
--- a/sdk/go/arvados/collection_fs_test.go
+++ b/sdk/go/arvados/collection_fs_test.go
@@ -11,6 +11,7 @@ import (
 	"math/rand"
 	"net/http"
 	"os"
+	"regexp"
 	"sync"
 	"testing"
 
@@ -299,6 +300,29 @@ func (s *CollectionFSSuite) TestReadWriteFile(c *check.C) {
 	c.Check(err, check.IsNil)
 	c.Check(string(buf2), check.Equals, "123")
 	c.Check(len(f.(*file).inode.(*filenode).extents), check.Equals, 1)
+
+	m, err := s.fs.MarshalManifest(".")
+	c.Check(err, check.IsNil)
+	m = regexp.MustCompile(`\+A[^\+ ]+`).ReplaceAllLiteralString(m, "")
+	c.Check(m, check.Equals, "./dir1 3858f62230ac3c915f300c664312c63f+6 202cb962ac59075b964b07152d234b70+3 3:3:bar 6:3:foo\n")
+}
+
+func (s *CollectionFSSuite) TestMarshalSmallBlocks(c *check.C) {
+	maxBlockSize = 8
+	defer func() { maxBlockSize = 2 << 26 }()
+
+	s.fs = (&Collection{}).FileSystem(s.client, s.kc)
+	for _, name := range []string{"foo", "bar", "baz"} {
+		f, err := s.fs.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0)
+		c.Assert(err, check.IsNil)
+		f.Write([]byte(name))
+		f.Close()
+	}
+
+	m, err := s.fs.MarshalManifest(".")
+	c.Check(err, check.IsNil)
+	m = regexp.MustCompile(`\+A[^\+ ]+`).ReplaceAllLiteralString(m, "")
+	c.Check(m, check.Equals, ". c3c23db5285662ef7172373df0003206+6 acbd18db4cc2f85cedef654fccc4a4d8+3 0:3:bar 3:3:baz 6:3:foo\n")
 }
 
 func (s *CollectionFSSuite) TestConcurrentWriters(c *check.C) {
@@ -389,6 +413,10 @@ func (s *CollectionFSSuite) TestRandomWrites(c *check.C) {
 	fi, err := root.Readdir(-1)
 	c.Check(err, check.IsNil)
 	c.Logf("Readdir(): %#v", fi)
+
+	m, err := s.fs.MarshalManifest(".")
+	c.Check(err, check.IsNil)
+	c.Logf("%s", m)
 }
 
 // Gocheck boilerplate

commit 8bd416797eb97ed25e52611f1644fda4e7fb7eba
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Sun Nov 12 03:30:18 2017 -0500

    12483: Remove unnecessary repack.
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index 5a3afbd..17740db 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -217,7 +217,6 @@ func (fn *filenode) appendExtent(e extent) {
 	defer fn.Unlock()
 	fn.extents = append(fn.extents, e)
 	fn.fileinfo.size += int64(e.Len())
-	fn.repacked++
 }
 
 func (fn *filenode) OpenFile(string, int, os.FileMode) (*file, error) {

commit 015e3798f9cbba4f27e1cd23b48eb396533cc0d8
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Sat Nov 11 16:48:54 2017 -0500

    12483: Add tests for concurrent writers and random write sequences.
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index fc2a2b9..5a3afbd 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -263,7 +263,7 @@ func (fn *filenode) Truncate(size int64) error {
 	fn.Lock()
 	defer fn.Unlock()
 	if size < fn.fileinfo.size {
-		ptr := fn.seek(filenodePtr{off: size})
+		ptr := fn.seek(filenodePtr{off: size, repacked: fn.repacked - 1})
 		if ptr.extentOff == 0 {
 			fn.extents = fn.extents[:ptr.extentIdx]
 		} else {
diff --git a/sdk/go/arvados/collection_fs_test.go b/sdk/go/arvados/collection_fs_test.go
index e635bb7..4208079 100644
--- a/sdk/go/arvados/collection_fs_test.go
+++ b/sdk/go/arvados/collection_fs_test.go
@@ -5,10 +5,13 @@
 package arvados
 
 import (
+	"fmt"
 	"io"
 	"io/ioutil"
+	"math/rand"
 	"net/http"
 	"os"
+	"sync"
 	"testing"
 
 	"git.curoverse.com/arvados.git/sdk/go/arvadostest"
@@ -298,6 +301,96 @@ func (s *CollectionFSSuite) TestReadWriteFile(c *check.C) {
 	c.Check(len(f.(*file).inode.(*filenode).extents), check.Equals, 1)
 }
 
+func (s *CollectionFSSuite) TestConcurrentWriters(c *check.C) {
+	maxBlockSize = 8
+	defer func() { maxBlockSize = 2 << 26 }()
+
+	var wg sync.WaitGroup
+	for n := 0; n < 128; n++ {
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			f, err := s.fs.OpenFile("/dir1/foo", os.O_RDWR, 0)
+			c.Assert(err, check.IsNil)
+			defer f.Close()
+			for i := 0; i < 6502; i++ {
+				switch rand.Int() & 3 {
+				case 0:
+					f.Truncate(int64(rand.Intn(64)))
+				case 1:
+					f.Seek(int64(rand.Intn(64)), os.SEEK_SET)
+				case 2:
+					_, err := f.Write([]byte("beep boop"))
+					c.Check(err, check.IsNil)
+				case 3:
+					_, err := ioutil.ReadAll(f)
+					c.Check(err, check.IsNil)
+				}
+			}
+		}()
+	}
+	wg.Wait()
+
+	f, err := s.fs.OpenFile("/dir1/foo", os.O_RDWR, 0)
+	c.Assert(err, check.IsNil)
+	defer f.Close()
+	buf, err := ioutil.ReadAll(f)
+	c.Check(err, check.IsNil)
+	c.Logf("after lots of random r/w/seek/trunc, buf is %q", buf)
+}
+
+func (s *CollectionFSSuite) TestRandomWrites(c *check.C) {
+	maxBlockSize = 8
+	defer func() { maxBlockSize = 2 << 26 }()
+
+	var wg sync.WaitGroup
+	for n := 0; n < 128; n++ {
+		wg.Add(1)
+		go func(n int) {
+			defer wg.Done()
+			expect := make([]byte, 0, 64)
+			wbytes := []byte("there's no simple explanation for anything important that any of us do")
+			f, err := s.fs.OpenFile(fmt.Sprintf("random-%d", n), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0)
+			c.Assert(err, check.IsNil)
+			defer f.Close()
+			for i := 0; i < 6502; i++ {
+				trunc := rand.Intn(65)
+				woff := rand.Intn(trunc + 1)
+				wbytes = wbytes[:rand.Intn(64-woff+1)]
+				for buf, i := expect[:cap(expect)], len(expect); i < trunc; i++ {
+					buf[i] = 0
+				}
+				expect = expect[:trunc]
+				if trunc < woff+len(wbytes) {
+					expect = expect[:woff+len(wbytes)]
+				}
+				copy(expect[woff:], wbytes)
+				f.Truncate(int64(trunc))
+				pos, err := f.Seek(int64(woff), os.SEEK_SET)
+				c.Check(pos, check.Equals, int64(woff))
+				c.Check(err, check.IsNil)
+				n, err := f.Write(wbytes)
+				c.Check(n, check.Equals, len(wbytes))
+				c.Check(err, check.IsNil)
+				pos, err = f.Seek(0, os.SEEK_SET)
+				c.Check(pos, check.Equals, int64(0))
+				c.Check(err, check.IsNil)
+				buf, err := ioutil.ReadAll(f)
+				c.Check(string(buf), check.Equals, string(expect))
+				c.Check(err, check.IsNil)
+			}
+		}(n)
+	}
+	wg.Wait()
+
+	root, err := s.fs.Open("/")
+	c.Assert(err, check.IsNil)
+	defer root.Close()
+	fi, err := root.Readdir(-1)
+	c.Check(err, check.IsNil)
+	c.Logf("Readdir(): %#v", fi)
+}
+
 // Gocheck boilerplate
 func Test(t *testing.T) {
 	check.TestingT(t)

commit 9009baaf0e3aa800de8af11c741d0adc46563200
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Sat Nov 11 15:32:47 2017 -0500

    12483: Add (File)Truncate().
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index 1669f88..fc2a2b9 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -35,6 +35,7 @@ type File interface {
 	Size() int64
 	Readdir(int) ([]os.FileInfo, error)
 	Stat() (os.FileInfo, error)
+	Truncate(int64) error
 }
 
 type keepClient interface {
@@ -122,6 +123,7 @@ type inode interface {
 	Parent() inode
 	Read([]byte, filenodePtr) (int, filenodePtr, error)
 	Write([]byte, filenodePtr) (int, filenodePtr, error)
+	Truncate(int64) error
 	Readdir() []os.FileInfo
 	Stat() os.FileInfo
 	sync.Locker
@@ -257,6 +259,48 @@ func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr
 	return
 }
 
+func (fn *filenode) Truncate(size int64) error {
+	fn.Lock()
+	defer fn.Unlock()
+	if size < fn.fileinfo.size {
+		ptr := fn.seek(filenodePtr{off: size})
+		if ptr.extentOff == 0 {
+			fn.extents = fn.extents[:ptr.extentIdx]
+		} else {
+			fn.extents = fn.extents[:ptr.extentIdx+1]
+			e := fn.extents[ptr.extentIdx]
+			if e, ok := e.(writableExtent); ok {
+				e.Truncate(ptr.extentOff)
+			} else {
+				fn.extents[ptr.extentIdx] = e.Slice(0, ptr.extentOff)
+			}
+		}
+		fn.fileinfo.size = size
+		fn.repacked++
+		return nil
+	}
+	for size > fn.fileinfo.size {
+		grow := size - fn.fileinfo.size
+		var e writableExtent
+		var ok bool
+		if len(fn.extents) == 0 {
+			e = &memExtent{}
+			fn.extents = append(fn.extents, e)
+		} else if e, ok = fn.extents[len(fn.extents)-1].(writableExtent); !ok || e.Len() >= maxBlockSize {
+			e = &memExtent{}
+			fn.extents = append(fn.extents, e)
+		} else {
+			fn.repacked++
+		}
+		if maxgrow := int64(maxBlockSize - e.Len()); maxgrow < grow {
+			grow = maxgrow
+		}
+		e.Truncate(e.Len() + int(grow))
+		fn.fileinfo.size += grow
+	}
+	return nil
+}
+
 func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
 	fn.Lock()
 	defer fn.Unlock()
@@ -435,6 +479,10 @@ func (f *file) Seek(off int64, whence int) (pos int64, err error) {
 	return f.ptr.off, nil
 }
 
+func (f *file) Truncate(size int64) error {
+	return f.inode.Truncate(size)
+}
+
 func (f *file) Write(p []byte) (n int, err error) {
 	if !f.writable {
 		return 0, ErrReadOnlyFile
@@ -628,6 +676,10 @@ func (dn *dirnode) Write(p []byte, ptr filenodePtr) (int, filenodePtr, error) {
 	return 0, ptr, ErrInvalidOperation
 }
 
+func (dn *dirnode) Truncate(int64) error {
+	return ErrInvalidOperation
+}
+
 func (dn *dirnode) OpenFile(name string, flag int, perm os.FileMode) (*file, error) {
 	name = strings.TrimSuffix(name, "/")
 	if name == "." || name == "" {
@@ -720,6 +772,12 @@ func (me *memExtent) Truncate(n int) {
 		newbuf := make([]byte, n, newsize)
 		copy(newbuf, me.buf)
 		me.buf = newbuf
+	} else {
+		// Zero unused part when shrinking, in case we grow
+		// and start using it again later.
+		for i := n; i < len(me.buf); i++ {
+			me.buf[i] = 0
+		}
 	}
 	me.buf = me.buf[:n]
 }
diff --git a/sdk/go/arvados/collection_fs_test.go b/sdk/go/arvados/collection_fs_test.go
index e4eeeff..e635bb7 100644
--- a/sdk/go/arvados/collection_fs_test.go
+++ b/sdk/go/arvados/collection_fs_test.go
@@ -236,6 +236,66 @@ func (s *CollectionFSSuite) TestReadWriteFile(c *check.C) {
 	buf2, err := ioutil.ReadAll(f2)
 	c.Check(err, check.IsNil)
 	c.Check(string(buf2), check.Equals, "f0123456789abcdefg")
+
+	// truncate to current size
+	err = f.Truncate(18)
+	f2.Seek(0, os.SEEK_SET)
+	buf2, err = ioutil.ReadAll(f2)
+	c.Check(err, check.IsNil)
+	c.Check(string(buf2), check.Equals, "f0123456789abcdefg")
+
+	// shrink to zero some data
+	f.Truncate(15)
+	f2.Seek(0, os.SEEK_SET)
+	buf2, err = ioutil.ReadAll(f2)
+	c.Check(err, check.IsNil)
+	c.Check(string(buf2), check.Equals, "f0123456789abcd")
+
+	// grow to partial block/extent
+	f.Truncate(20)
+	f2.Seek(0, os.SEEK_SET)
+	buf2, err = ioutil.ReadAll(f2)
+	c.Check(err, check.IsNil)
+	c.Check(string(buf2), check.Equals, "f0123456789abcd\x00\x00\x00\x00\x00")
+
+	f.Truncate(0)
+	f2.Write([]byte("12345678abcdefghijkl"))
+
+	// grow to block/extent boundary
+	f.Truncate(64)
+	f2.Seek(0, os.SEEK_SET)
+	buf2, err = ioutil.ReadAll(f2)
+	c.Check(err, check.IsNil)
+	c.Check(len(buf2), check.Equals, 64)
+	c.Check(len(f.(*file).inode.(*filenode).extents), check.Equals, 8)
+
+	// shrink to block/extent boundary
+	err = f.Truncate(32)
+	f2.Seek(0, os.SEEK_SET)
+	buf2, err = ioutil.ReadAll(f2)
+	c.Check(err, check.IsNil)
+	c.Check(len(buf2), check.Equals, 32)
+	c.Check(len(f.(*file).inode.(*filenode).extents), check.Equals, 4)
+
+	// shrink to partial block/extent
+	err = f.Truncate(15)
+	f2.Seek(0, os.SEEK_SET)
+	buf2, err = ioutil.ReadAll(f2)
+	c.Check(err, check.IsNil)
+	c.Check(string(buf2), check.Equals, "12345678abcdefg")
+	c.Check(len(f.(*file).inode.(*filenode).extents), check.Equals, 2)
+
+	// Truncate to size=3 while f2's ptr is at 15
+	err = f.Truncate(3)
+	c.Check(err, check.IsNil)
+	buf2, err = ioutil.ReadAll(f2)
+	c.Check(err, check.IsNil)
+	c.Check(string(buf2), check.Equals, "")
+	f2.Seek(0, os.SEEK_SET)
+	buf2, err = ioutil.ReadAll(f2)
+	c.Check(err, check.IsNil)
+	c.Check(string(buf2), check.Equals, "123")
+	c.Check(len(f.(*file).inode.(*filenode).extents), check.Equals, 1)
 }
 
 // Gocheck boilerplate

commit 6ce00fb7121813f187b555435a3f01c2aa380f93
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Sat Nov 11 13:26:37 2017 -0500

    12483: Simplify extent packing, reduce type casting.
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index 44b3c72..1669f88 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -23,9 +23,9 @@ var (
 	ErrFileExists       = errors.New("file exists")
 	ErrInvalidOperation = errors.New("invalid operation")
 	ErrPermission       = os.ErrPermission
-)
 
-const maxBlockSize = 1 << 26
+	maxBlockSize = 1 << 26
+)
 
 type File interface {
 	io.Reader
@@ -38,7 +38,7 @@ type File interface {
 }
 
 type keepClient interface {
-	ReadAt(locator string, p []byte, off int64) (int, error)
+	ReadAt(locator string, p []byte, off int) (int, error)
 }
 
 type fileinfo struct {
@@ -177,7 +177,7 @@ func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
 	} else if ptr.repacked == fn.repacked {
 		// extentIdx and extentOff accurately reflect ptr.off,
 		// but might have fallen off the end of an extent
-		if int64(ptr.extentOff) >= fn.extents[ptr.extentIdx].Len() {
+		if ptr.extentOff >= fn.extents[ptr.extentIdx].Len() {
 			ptr.extentIdx++
 			ptr.extentOff = 0
 		}
@@ -200,7 +200,7 @@ func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
 		// sum(fn.extents[i].Len()) -- but that can't happen
 		// because we have ensured fn.fileinfo.size is always
 		// accurate.
-		extLen := fn.extents[ptr.extentIdx].Len()
+		extLen := int64(fn.extents[ptr.extentIdx].Len())
 		if off+extLen > ptr.off {
 			ptr.extentOff = int(ptr.off - off)
 			break
@@ -214,7 +214,7 @@ func (fn *filenode) appendExtent(e extent) {
 	fn.Lock()
 	defer fn.Unlock()
 	fn.extents = append(fn.extents, e)
-	fn.fileinfo.size += e.Len()
+	fn.fileinfo.size += int64(e.Len())
 	fn.repacked++
 }
 
@@ -246,7 +246,7 @@ func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr
 	if n > 0 {
 		ptr.off += int64(n)
 		ptr.extentOff += n
-		if int64(ptr.extentOff) == fn.extents[ptr.extentIdx].Len() {
+		if ptr.extentOff == fn.extents[ptr.extentIdx].Len() {
 			ptr.extentIdx++
 			ptr.extentOff = 0
 			if ptr.extentIdx < len(fn.extents) && err == io.EOF {
@@ -280,76 +280,90 @@ func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePt
 			_, curWritable = fn.extents[cur].(writableExtent)
 		}
 		var prevAppendable bool
-		if prev >= 0 && fn.extents[prev].Len() < int64(maxBlockSize) {
+		if prev >= 0 && fn.extents[prev].Len() < maxBlockSize {
 			_, prevAppendable = fn.extents[prev].(writableExtent)
 		}
-		if ptr.extentOff > 0 {
-			if !curWritable {
-				// Split a non-writable block.
-				if max := int(fn.extents[cur].Len()) - ptr.extentOff; max <= len(cando) {
-					cando = cando[:max]
-					fn.extents = append(fn.extents, nil)
-					copy(fn.extents[cur+1:], fn.extents[cur:])
-				} else {
-					fn.extents = append(fn.extents, nil, nil)
-					copy(fn.extents[cur+2:], fn.extents[cur:])
-					fn.extents[cur+2] = fn.extents[cur+2].Slice(ptr.extentOff+len(cando), -1)
-				}
-				cur++
-				prev++
-				e := &memExtent{}
-				e.Truncate(len(cando))
-				fn.extents[cur] = e
-				fn.extents[prev] = fn.extents[prev].Slice(0, ptr.extentOff)
-				ptr.extentIdx++
-				ptr.extentOff = 0
-				fn.repacked++
-				ptr.repacked++
+		if ptr.extentOff > 0 && !curWritable {
+			// Split a non-writable block.
+			if max := fn.extents[cur].Len() - ptr.extentOff; max <= len(cando) {
+				// Truncate cur, and insert a new
+				// extent after it.
+				cando = cando[:max]
+				fn.extents = append(fn.extents, nil)
+				copy(fn.extents[cur+1:], fn.extents[cur:])
+			} else {
+				// Split cur into two copies, truncate
+				// the one on the left, shift the one
+				// on the right, and insert a new
+				// extent between them.
+				fn.extents = append(fn.extents, nil, nil)
+				copy(fn.extents[cur+2:], fn.extents[cur:])
+				fn.extents[cur+2] = fn.extents[cur+2].Slice(ptr.extentOff+len(cando), -1)
 			}
-		} else if len(fn.extents) == 0 {
-			// File has no extents yet.
+			cur++
+			prev++
 			e := &memExtent{}
 			e.Truncate(len(cando))
-			fn.fileinfo.size += e.Len()
-			fn.extents = append(fn.extents, e)
+			fn.extents[cur] = e
+			fn.extents[prev] = fn.extents[prev].Slice(0, ptr.extentOff)
+			ptr.extentIdx++
+			ptr.extentOff = 0
+			fn.repacked++
+			ptr.repacked++
 		} else if curWritable {
 			if fit := int(fn.extents[cur].Len()) - ptr.extentOff; fit < len(cando) {
 				cando = cando[:fit]
 			}
 		} else {
 			if prevAppendable {
-				// Grow prev.
-				if cangrow := int(maxBlockSize - fn.extents[prev].Len()); cangrow < len(cando) {
+				// Shrink cando if needed to fit in prev extent.
+				if cangrow := maxBlockSize - fn.extents[prev].Len(); cangrow < len(cando) {
 					cando = cando[:cangrow]
 				}
-				ptr.extentIdx--
-				ptr.extentOff = int(fn.extents[prev].Len())
-				fn.extents[prev].(*memExtent).Truncate(ptr.extentOff + len(cando))
-			} else {
-				// Insert an extent between prev and cur. It will be the new prev.
-				fn.extents = append(fn.extents, nil)
-				copy(fn.extents[cur+1:], fn.extents[cur:])
-				e := &memExtent{}
-				e.Truncate(len(cando))
-				fn.extents[cur] = e
-				cur++
-				prev++
 			}
 
 			if cur == len(fn.extents) {
-				// There is no cur.
-			} else if el := int(fn.extents[cur].Len()); el <= len(cando) {
-				// Drop cur.
+				// ptr is at EOF, filesize is changing.
+				fn.fileinfo.size += int64(len(cando))
+			} else if el := fn.extents[cur].Len(); el <= len(cando) {
+				// cando is long enough that we won't
+				// need cur any more. shrink cando to
+				// be exactly as long as cur
+				// (otherwise we'd accidentally shift
+				// the effective position of all
+				// extents after cur).
 				cando = cando[:el]
 				copy(fn.extents[cur:], fn.extents[cur+1:])
 				fn.extents = fn.extents[:len(fn.extents)-1]
 			} else {
-				// Shrink cur.
+				// shrink cur by the same #bytes we're growing prev
 				fn.extents[cur] = fn.extents[cur].Slice(len(cando), -1)
 			}
 
-			ptr.repacked++
-			fn.repacked++
+			if prevAppendable {
+				// Grow prev.
+				ptr.extentIdx--
+				ptr.extentOff = fn.extents[prev].Len()
+				fn.extents[prev].(writableExtent).Truncate(ptr.extentOff + len(cando))
+				ptr.repacked++
+				fn.repacked++
+			} else {
+				// Insert an extent between prev and cur, and advance prev/cur.
+				fn.extents = append(fn.extents, nil)
+				if cur < len(fn.extents) {
+					copy(fn.extents[cur+1:], fn.extents[cur:])
+					ptr.repacked++
+					fn.repacked++
+				} else {
+					// appending a new extent does
+					// not invalidate any ptrs
+				}
+				e := &memExtent{}
+				e.Truncate(len(cando))
+				fn.extents[cur] = e
+				cur++
+				prev++
+			}
 		}
 
 		// Finally we can copy bytes from cando to the current extent.
@@ -359,7 +373,7 @@ func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePt
 
 		ptr.off += int64(len(cando))
 		ptr.extentOff += len(cando)
-		if fn.extents[ptr.extentIdx].Len() == int64(ptr.extentOff) {
+		if fn.extents[ptr.extentIdx].Len() == ptr.extentOff {
 			ptr.extentOff = 0
 			ptr.extentIdx++
 		}
@@ -528,10 +542,14 @@ func (dn *dirnode) loadManifest(txt string) {
 				// FIXME: broken manifest
 				continue
 			}
+			// Map the stream offset/range coordinates to
+			// block/offset/range coordinates and add
+			// corresponding storedExtents to the filenode
 			var pos int64
 			for _, e := range extents {
-				if pos+e.Len() < offset {
-					pos += e.Len()
+				next := pos + int64(e.Len())
+				if next < offset {
+					pos = next
 					continue
 				}
 				if pos > offset+length {
@@ -541,7 +559,7 @@ func (dn *dirnode) loadManifest(txt string) {
 				if pos < offset {
 					blkOff = int(offset - pos)
 				}
-				blkLen := int(e.Len()) - blkOff
+				blkLen := e.Len() - blkOff
 				if pos+int64(blkOff+blkLen) > offset+length {
 					blkLen = int(offset + length - pos - int64(blkOff))
 				}
@@ -551,7 +569,7 @@ func (dn *dirnode) loadManifest(txt string) {
 					offset:  blkOff,
 					length:  blkLen,
 				})
-				pos += e.Len()
+				pos = next
 			}
 			f.Close()
 		}
@@ -664,8 +682,10 @@ func (dn *dirnode) OpenFile(name string, flag int, perm os.FileMode) (*file, err
 
 type extent interface {
 	io.ReaderAt
-	Len() int64
-	Slice(int, int) extent
+	Len() int
+	// Return a new extent with a subsection of the data from this
+	// one. length<0 means length=Len()-off.
+	Slice(off int, length int) extent
 }
 
 type writableExtent interface {
@@ -678,15 +698,17 @@ type memExtent struct {
 	buf []byte
 }
 
-func (me *memExtent) Len() int64 {
-	return int64(len(me.buf))
+func (me *memExtent) Len() int {
+	return len(me.buf)
 }
 
-func (me *memExtent) Slice(n, size int) extent {
-	if size < 0 {
-		size = len(me.buf) - n
+func (me *memExtent) Slice(off, length int) extent {
+	if length < 0 {
+		length = len(me.buf) - off
 	}
-	return &memExtent{buf: me.buf[n : n+size]}
+	buf := make([]byte, length)
+	copy(buf, me.buf[off:])
+	return &memExtent{buf: buf}
 }
 
 func (me *memExtent) Truncate(n int) {
@@ -710,7 +732,7 @@ func (me *memExtent) WriteAt(p []byte, off int) {
 }
 
 func (me *memExtent) ReadAt(p []byte, off int64) (n int, err error) {
-	if off > me.Len() {
+	if off > int64(me.Len()) {
 		err = io.EOF
 		return
 	}
@@ -728,8 +750,8 @@ type storedExtent struct {
 	length  int
 }
 
-func (se storedExtent) Len() int64 {
-	return int64(se.length)
+func (se storedExtent) Len() int {
+	return se.length
 }
 
 func (se storedExtent) Slice(n, size int) extent {
@@ -742,20 +764,23 @@ func (se storedExtent) Slice(n, size int) extent {
 }
 
 func (se storedExtent) ReadAt(p []byte, off int64) (n int, err error) {
-	maxlen := int(int64(se.length) - off)
+	if off > int64(se.length) {
+		return 0, io.EOF
+	}
+	maxlen := se.length - int(off)
 	if len(p) > maxlen {
 		p = p[:maxlen]
-		n, err = se.cache.ReadAt(se.locator, p, off+int64(se.offset))
+		n, err = se.cache.ReadAt(se.locator, p, int(off)+se.offset)
 		if err == nil {
 			err = io.EOF
 		}
 		return
 	}
-	return se.cache.ReadAt(se.locator, p, off+int64(se.offset))
+	return se.cache.ReadAt(se.locator, p, int(off)+se.offset)
 }
 
 type blockCache interface {
-	ReadAt(locator string, p []byte, off int64) (n int, err error)
+	ReadAt(locator string, p []byte, off int) (n int, err error)
 }
 
 type keepBlockCache struct {
@@ -764,7 +789,7 @@ type keepBlockCache struct {
 
 var scratch = make([]byte, 2<<26)
 
-func (kbc *keepBlockCache) ReadAt(locator string, p []byte, off int64) (int, error) {
+func (kbc *keepBlockCache) ReadAt(locator string, p []byte, off int) (int, error) {
 	return kbc.kc.ReadAt(locator, p, off)
 }
 
diff --git a/sdk/go/arvados/collection_fs_test.go b/sdk/go/arvados/collection_fs_test.go
index ae57078..e4eeeff 100644
--- a/sdk/go/arvados/collection_fs_test.go
+++ b/sdk/go/arvados/collection_fs_test.go
@@ -21,12 +21,12 @@ type keepClientStub struct {
 	blocks map[string][]byte
 }
 
-func (kcs *keepClientStub) ReadAt(locator string, p []byte, off int64) (int, error) {
+func (kcs *keepClientStub) ReadAt(locator string, p []byte, off int) (int, error) {
 	buf := kcs.blocks[locator[:32]]
 	if buf == nil {
 		return 0, os.ErrNotExist
 	}
-	return copy(p, buf[int(off):]), nil
+	return copy(p, buf[off:]), nil
 }
 
 type CollectionFSSuite struct {
@@ -177,13 +177,21 @@ func (s *CollectionFSSuite) TestCreateFile(c *check.C) {
 }
 
 func (s *CollectionFSSuite) TestReadWriteFile(c *check.C) {
+	maxBlockSize = 8
+	defer func() { maxBlockSize = 2 << 26 }()
+
 	f, err := s.fs.OpenFile("/dir1/foo", os.O_RDWR, 0)
 	c.Assert(err, check.IsNil)
+	defer f.Close()
 	st, err := f.Stat()
 	c.Assert(err, check.IsNil)
 	c.Check(st.Size(), check.Equals, int64(3))
 
-	buf := make([]byte, 4)
+	f2, err := s.fs.OpenFile("/dir1/foo", os.O_RDWR, 0)
+	c.Assert(err, check.IsNil)
+	defer f2.Close()
+
+	buf := make([]byte, 64)
 	n, err := f.Read(buf)
 	c.Check(n, check.Equals, 3)
 	c.Check(err, check.Equals, io.EOF)
@@ -193,6 +201,7 @@ func (s *CollectionFSSuite) TestReadWriteFile(c *check.C) {
 	c.Check(pos, check.Equals, int64(1))
 	c.Check(err, check.IsNil)
 
+	// Split a storedExtent in two, and insert a memExtent
 	n, err = f.Write([]byte("*"))
 	c.Check(n, check.Equals, 1)
 	c.Check(err, check.IsNil)
@@ -205,11 +214,28 @@ func (s *CollectionFSSuite) TestReadWriteFile(c *check.C) {
 	c.Check(pos, check.Equals, int64(0))
 	c.Check(err, check.IsNil)
 
-	buf = make([]byte, 4)
-	buf, err = ioutil.ReadAll(f)
-	c.Check(len(buf), check.Equals, 3)
+	rbuf, err := ioutil.ReadAll(f)
+	c.Check(len(rbuf), check.Equals, 3)
+	c.Check(err, check.IsNil)
+	c.Check(string(rbuf), check.Equals, "f*o")
+
+	// Write multiple blocks in one call
+	f.Seek(1, os.SEEK_SET)
+	n, err = f.Write([]byte("0123456789abcdefg"))
+	c.Check(n, check.Equals, 17)
+	c.Check(err, check.IsNil)
+	pos, err = f.Seek(0, os.SEEK_CUR)
+	c.Check(pos, check.Equals, int64(18))
+	pos, err = f.Seek(-18, os.SEEK_CUR)
+	c.Check(err, check.IsNil)
+	n, err = io.ReadFull(f, buf)
+	c.Check(n, check.Equals, 18)
+	c.Check(err, check.Equals, io.ErrUnexpectedEOF)
+	c.Check(string(buf[:n]), check.Equals, "f0123456789abcdefg")
+
+	buf2, err := ioutil.ReadAll(f2)
 	c.Check(err, check.IsNil)
-	c.Check(string(buf), check.Equals, "f*o")
+	c.Check(string(buf2), check.Equals, "f0123456789abcdefg")
 }
 
 // Gocheck boilerplate
diff --git a/sdk/go/keepclient/block_cache.go b/sdk/go/keepclient/block_cache.go
index c1138fa..539975e 100644
--- a/sdk/go/keepclient/block_cache.go
+++ b/sdk/go/keepclient/block_cache.go
@@ -51,15 +51,15 @@ func (c *BlockCache) Sweep() {
 
 // ReadAt returns data from the cache, first retrieving it from Keep if
 // necessary.
-func (c *BlockCache) ReadAt(kc *KeepClient, locator string, p []byte, off int64) (int, error) {
+func (c *BlockCache) ReadAt(kc *KeepClient, locator string, p []byte, off int) (int, error) {
 	buf, err := c.Get(kc, locator)
 	if err != nil {
 		return 0, err
 	}
-	if off > int64(len(buf)) {
+	if off > len(buf) {
 		return 0, io.ErrUnexpectedEOF
 	}
-	return copy(p, buf[int(off):]), nil
+	return copy(p, buf[off:]), nil
 }
 
 // Get returns data from the cache, first retrieving it from Keep if
diff --git a/sdk/go/keepclient/keepclient.go b/sdk/go/keepclient/keepclient.go
index c3d63ed..4bc0fc5 100644
--- a/sdk/go/keepclient/keepclient.go
+++ b/sdk/go/keepclient/keepclient.go
@@ -294,7 +294,7 @@ func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error)
 
 // ReadAt() retrieves a portion of block from the cache if it's
 // present, otherwise from the network.
-func (kc *KeepClient) ReadAt(locator string, p []byte, off int64) (int, error) {
+func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
 	return kc.cache().ReadAt(kc, locator, p, off)
 }
 

commit cad7d333436703d48c2811de8a26caef9fc130ad
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Sat Nov 11 03:30:24 2017 -0500

    12483: Implement some writable cases.
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index 1dee6f1..44b3c72 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -25,6 +25,8 @@ var (
 	ErrPermission       = os.ErrPermission
 )
 
+const maxBlockSize = 1 << 26
+
 type File interface {
 	io.Reader
 	io.Writer
@@ -263,7 +265,105 @@ func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePt
 		err = ErrNegativeOffset
 		return
 	}
-	err = ErrReadOnlyFile
+	for len(p) > 0 && err == nil {
+		cando := p
+		if len(cando) > maxBlockSize {
+			cando = cando[:maxBlockSize]
+		}
+		// Rearrange/grow fn.extents (and shrink cando if
+		// needed) such that cando can be copied to
+		// fn.extents[ptr.extentIdx] at offset ptr.extentOff.
+		cur := ptr.extentIdx
+		prev := ptr.extentIdx - 1
+		var curWritable bool
+		if cur < len(fn.extents) {
+			_, curWritable = fn.extents[cur].(writableExtent)
+		}
+		var prevAppendable bool
+		if prev >= 0 && fn.extents[prev].Len() < int64(maxBlockSize) {
+			_, prevAppendable = fn.extents[prev].(writableExtent)
+		}
+		if ptr.extentOff > 0 {
+			if !curWritable {
+				// Split a non-writable block.
+				if max := int(fn.extents[cur].Len()) - ptr.extentOff; max <= len(cando) {
+					cando = cando[:max]
+					fn.extents = append(fn.extents, nil)
+					copy(fn.extents[cur+1:], fn.extents[cur:])
+				} else {
+					fn.extents = append(fn.extents, nil, nil)
+					copy(fn.extents[cur+2:], fn.extents[cur:])
+					fn.extents[cur+2] = fn.extents[cur+2].Slice(ptr.extentOff+len(cando), -1)
+				}
+				cur++
+				prev++
+				e := &memExtent{}
+				e.Truncate(len(cando))
+				fn.extents[cur] = e
+				fn.extents[prev] = fn.extents[prev].Slice(0, ptr.extentOff)
+				ptr.extentIdx++
+				ptr.extentOff = 0
+				fn.repacked++
+				ptr.repacked++
+			}
+		} else if len(fn.extents) == 0 {
+			// File has no extents yet.
+			e := &memExtent{}
+			e.Truncate(len(cando))
+			fn.fileinfo.size += e.Len()
+			fn.extents = append(fn.extents, e)
+		} else if curWritable {
+			if fit := int(fn.extents[cur].Len()) - ptr.extentOff; fit < len(cando) {
+				cando = cando[:fit]
+			}
+		} else {
+			if prevAppendable {
+				// Grow prev.
+				if cangrow := int(maxBlockSize - fn.extents[prev].Len()); cangrow < len(cando) {
+					cando = cando[:cangrow]
+				}
+				ptr.extentIdx--
+				ptr.extentOff = int(fn.extents[prev].Len())
+				fn.extents[prev].(*memExtent).Truncate(ptr.extentOff + len(cando))
+			} else {
+				// Insert an extent between prev and cur. It will be the new prev.
+				fn.extents = append(fn.extents, nil)
+				copy(fn.extents[cur+1:], fn.extents[cur:])
+				e := &memExtent{}
+				e.Truncate(len(cando))
+				fn.extents[cur] = e
+				cur++
+				prev++
+			}
+
+			if cur == len(fn.extents) {
+				// There is no cur.
+			} else if el := int(fn.extents[cur].Len()); el <= len(cando) {
+				// Drop cur.
+				cando = cando[:el]
+				copy(fn.extents[cur:], fn.extents[cur+1:])
+				fn.extents = fn.extents[:len(fn.extents)-1]
+			} else {
+				// Shrink cur.
+				fn.extents[cur] = fn.extents[cur].Slice(len(cando), -1)
+			}
+
+			ptr.repacked++
+			fn.repacked++
+		}
+
+		// Finally we can copy bytes from cando to the current extent.
+		fn.extents[ptr.extentIdx].(writableExtent).WriteAt(cando, ptr.extentOff)
+		n += len(cando)
+		p = p[len(cando):]
+
+		ptr.off += int64(len(cando))
+		ptr.extentOff += len(cando)
+		if fn.extents[ptr.extentIdx].Len() == int64(ptr.extentOff) {
+			ptr.extentOff = 0
+			ptr.extentIdx++
+		}
+	}
 	return
 }
 
@@ -322,6 +422,9 @@ func (f *file) Seek(off int64, whence int) (pos int64, err error) {
 }
 
 func (f *file) Write(p []byte) (n int, err error) {
+	if !f.writable {
+		return 0, ErrReadOnlyFile
+	}
 	n, f.ptr, err = f.inode.Write(p, f.ptr)
 	return
 }
@@ -562,6 +665,7 @@ func (dn *dirnode) OpenFile(name string, flag int, perm os.FileMode) (*file, err
 type extent interface {
 	io.ReaderAt
 	Len() int64
+	Slice(int, int) extent
 }
 
 type writableExtent interface {
@@ -578,6 +682,13 @@ func (me *memExtent) Len() int64 {
 	return int64(len(me.buf))
 }
 
+func (me *memExtent) Slice(n, size int) extent {
+	if size < 0 {
+		size = len(me.buf) - n
+	}
+	return &memExtent{buf: me.buf[n : n+size]}
+}
+
 func (me *memExtent) Truncate(n int) {
 	if n > cap(me.buf) {
 		newsize := 1024
@@ -621,8 +732,17 @@ func (se storedExtent) Len() int64 {
 	return int64(se.length)
 }
 
+func (se storedExtent) Slice(n, size int) extent {
+	se.offset += n
+	se.length -= n
+	if size >= 0 && se.length > size {
+		se.length = size
+	}
+	return se
+}
+
 func (se storedExtent) ReadAt(p []byte, off int64) (n int, err error) {
-	maxlen := int(int64(se.length) - int64(se.offset) - off)
+	maxlen := int(int64(se.length) - off)
 	if len(p) > maxlen {
 		p = p[:maxlen]
 		n, err = se.cache.ReadAt(se.locator, p, off+int64(se.offset))
diff --git a/sdk/go/arvados/collection_fs_test.go b/sdk/go/arvados/collection_fs_test.go
index 605c41c..ae57078 100644
--- a/sdk/go/arvados/collection_fs_test.go
+++ b/sdk/go/arvados/collection_fs_test.go
@@ -6,6 +6,7 @@ package arvados
 
 import (
 	"io"
+	"io/ioutil"
 	"net/http"
 	"os"
 	"testing"
@@ -205,10 +206,10 @@ func (s *CollectionFSSuite) TestReadWriteFile(c *check.C) {
 	c.Check(err, check.IsNil)
 
 	buf = make([]byte, 4)
-	n, err = f.Read(buf)
-	c.Check(n, check.Equals, 3)
-	c.Check(err, check.Equals, io.EOF)
-	c.Check(string(buf[:3]), check.Equals, "f*o")
+	buf, err = ioutil.ReadAll(f)
+	c.Check(len(buf), check.Equals, 3)
+	c.Check(err, check.IsNil)
+	c.Check(string(buf), check.Equals, "f*o")
 }
 
 // Gocheck boilerplate

commit da3f22835804cc1bafe7daf373867ef46cbb20e8
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Fri Nov 10 16:34:28 2017 -0500

    12483: Add basic file writing tests.
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs_test.go b/sdk/go/arvados/collection_fs_test.go
index 7bd3570..605c41c 100644
--- a/sdk/go/arvados/collection_fs_test.go
+++ b/sdk/go/arvados/collection_fs_test.go
@@ -135,14 +135,80 @@ func (s *CollectionFSSuite) TestNotExist(c *check.C) {
 	}
 }
 
-func (s *CollectionFSSuite) TestOpenFile(c *check.C) {
-	c.Skip("cannot test files with nil keepclient")
+func (s *CollectionFSSuite) TestReadOnlyFile(c *check.C) {
+	f, err := s.fs.OpenFile("/dir1/foo", os.O_RDONLY, 0)
+	c.Assert(err, check.IsNil)
+	st, err := f.Stat()
+	c.Assert(err, check.IsNil)
+	c.Check(st.Size(), check.Equals, int64(3))
+	n, err := f.Write([]byte("bar"))
+	c.Check(n, check.Equals, 0)
+	c.Check(err, check.Equals, ErrReadOnlyFile)
+}
+
+func (s *CollectionFSSuite) TestCreateFile(c *check.C) {
+	f, err := s.fs.OpenFile("/newfile", os.O_RDWR|os.O_CREATE, 0)
+	c.Assert(err, check.IsNil)
+	st, err := f.Stat()
+	c.Assert(err, check.IsNil)
+	c.Check(st.Size(), check.Equals, int64(0))
+
+	n, err := f.Write([]byte("bar"))
+	c.Check(n, check.Equals, 3)
+	c.Check(err, check.IsNil)
+
+	c.Check(f.Close(), check.IsNil)
+
+	f, err = s.fs.OpenFile("/newfile", os.O_RDWR|os.O_CREATE|os.O_EXCL, 0)
+	c.Check(f, check.IsNil)
+	c.Assert(err, check.NotNil)
+
+	f, err = s.fs.OpenFile("/newfile", os.O_RDWR, 0)
+	c.Assert(err, check.IsNil)
+	st, err = f.Stat()
+	c.Assert(err, check.IsNil)
+	c.Check(st.Size(), check.Equals, int64(3))
+
+	c.Check(f.Close(), check.IsNil)
+
+	// TODO: serialize to Collection, confirm manifest contents,
+	// make new FileSystem, confirm file contents.
+}
 
-	f, err := s.fs.Open("/foo.txt")
+func (s *CollectionFSSuite) TestReadWriteFile(c *check.C) {
+	f, err := s.fs.OpenFile("/dir1/foo", os.O_RDWR, 0)
 	c.Assert(err, check.IsNil)
 	st, err := f.Stat()
 	c.Assert(err, check.IsNil)
 	c.Check(st.Size(), check.Equals, int64(3))
+
+	buf := make([]byte, 4)
+	n, err := f.Read(buf)
+	c.Check(n, check.Equals, 3)
+	c.Check(err, check.Equals, io.EOF)
+	c.Check(string(buf[:3]), check.DeepEquals, "foo")
+
+	pos, err := f.Seek(-2, os.SEEK_CUR)
+	c.Check(pos, check.Equals, int64(1))
+	c.Check(err, check.IsNil)
+
+	n, err = f.Write([]byte("*"))
+	c.Check(n, check.Equals, 1)
+	c.Check(err, check.IsNil)
+
+	pos, err = f.Seek(0, os.SEEK_CUR)
+	c.Check(pos, check.Equals, int64(2))
+	c.Check(err, check.IsNil)
+
+	pos, err = f.Seek(0, os.SEEK_SET)
+	c.Check(pos, check.Equals, int64(0))
+	c.Check(err, check.IsNil)
+
+	buf = make([]byte, 4)
+	n, err = f.Read(buf)
+	c.Check(n, check.Equals, 3)
+	c.Check(err, check.Equals, io.EOF)
+	c.Check(string(buf[:3]), check.Equals, "f*o")
 }
 
 // Gocheck boilerplate

commit 3e3abb01d17b0968e22e6738da12c86ad0a2a06c
Author: Tom Clegg <tclegg at veritasgenetics.com>
Date:   Thu Nov 9 13:24:34 2017 -0500

    12483: Rewrite collection filesystem.
    
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tclegg at veritasgenetics.com>

diff --git a/sdk/go/arvados/collection_fs.go b/sdk/go/arvados/collection_fs.go
index 1acf274..1dee6f1 100644
--- a/sdk/go/arvados/collection_fs.go
+++ b/sdk/go/arvados/collection_fs.go
@@ -5,268 +5,647 @@
 package arvados
 
 import (
+	"errors"
 	"io"
 	"net/http"
 	"os"
 	"path"
+	"regexp"
+	"strconv"
 	"strings"
 	"sync"
 	"time"
+)
 
-	"git.curoverse.com/arvados.git/sdk/go/manifest"
+var (
+	ErrReadOnlyFile     = errors.New("read-only file")
+	ErrNegativeOffset   = errors.New("cannot seek to negative offset")
+	ErrFileExists       = errors.New("file exists")
+	ErrInvalidOperation = errors.New("invalid operation")
+	ErrPermission       = os.ErrPermission
 )
 
 type File interface {
 	io.Reader
+	io.Writer
 	io.Closer
 	io.Seeker
 	Size() int64
+	Readdir(int) ([]os.FileInfo, error)
+	Stat() (os.FileInfo, error)
 }
 
 type keepClient interface {
-	ManifestFileReader(manifest.Manifest, string) (File, error)
+	ReadAt(locator string, p []byte, off int64) (int, error)
 }
 
-type collectionFile struct {
-	File
-	collection *Collection
-	name       string
-	size       int64
+type fileinfo struct {
+	name    string
+	mode    os.FileMode
+	size    int64
+	modTime time.Time
 }
 
-func (cf *collectionFile) Size() int64 {
-	return cf.size
+// Name implements os.FileInfo.
+func (fi fileinfo) Name() string {
+	return fi.name
 }
 
-func (cf *collectionFile) Readdir(count int) ([]os.FileInfo, error) {
-	return nil, io.EOF
+// ModTime implements os.FileInfo.
+func (fi fileinfo) ModTime() time.Time {
+	return fi.modTime
 }
 
-func (cf *collectionFile) Stat() (os.FileInfo, error) {
-	return collectionDirent{
-		collection: cf.collection,
-		name:       cf.name,
-		size:       cf.size,
-		isDir:      false,
-	}, nil
+// Mode implements os.FileInfo.
+func (fi fileinfo) Mode() os.FileMode {
+	return fi.mode
 }
 
-type collectionDir struct {
-	collection *Collection
-	stream     string
-	dirents    []os.FileInfo
+// IsDir implements os.FileInfo.
+func (fi fileinfo) IsDir() bool {
+	return fi.mode&os.ModeDir != 0
 }
 
-// Readdir implements os.File.
-func (cd *collectionDir) Readdir(count int) ([]os.FileInfo, error) {
-	ret := cd.dirents
-	if count <= 0 {
-		cd.dirents = nil
-		return ret, nil
-	} else if len(ret) == 0 {
-		return nil, io.EOF
-	}
-	var err error
-	if count >= len(ret) {
-		count = len(ret)
-		err = io.EOF
-	}
-	cd.dirents = cd.dirents[count:]
-	return ret[:count], err
+// Size implements os.FileInfo.
+func (fi fileinfo) Size() int64 {
+	return fi.size
 }
 
-// Stat implements os.File.
-func (cd *collectionDir) Stat() (os.FileInfo, error) {
-	return collectionDirent{
-		collection: cd.collection,
-		name:       path.Base(cd.stream),
-		isDir:      true,
-		size:       int64(len(cd.dirents)),
-	}, nil
+// Sys implements os.FileInfo.
+func (fi fileinfo) Sys() interface{} {
+	return nil
 }
 
-// Close implements os.File.
-func (cd *collectionDir) Close() error {
-	return nil
+func (fi fileinfo) Stat() os.FileInfo {
+	return fi
 }
 
-// Read implements os.File.
-func (cd *collectionDir) Read([]byte) (int, error) {
-	return 0, nil
+// A CollectionFileSystem is an http.Filesystem plus Stat() and
+// support for opening writable files.
+type CollectionFileSystem interface {
+	http.FileSystem
+	Stat(name string) (os.FileInfo, error)
+	Create(name string) (File, error)
+	OpenFile(name string, flag int, perm os.FileMode) (File, error)
 }
 
-// Seek implements os.File.
-func (cd *collectionDir) Seek(int64, int) (int64, error) {
-	return 0, nil
+type fileSystem struct {
+	dirnode
 }
 
-// collectionDirent implements os.FileInfo.
-type collectionDirent struct {
-	collection *Collection
-	name       string
-	isDir      bool
-	mode       os.FileMode
-	size       int64
+func (fs *fileSystem) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
+	return fs.dirnode.OpenFile(path.Clean(name), flag, perm)
 }
 
-// Name implements os.FileInfo.
-func (e collectionDirent) Name() string {
-	return e.name
+func (fs *fileSystem) Open(name string) (http.File, error) {
+	return fs.dirnode.OpenFile(path.Clean(name), os.O_RDONLY, 0)
 }
 
-// ModTime implements os.FileInfo.
-func (e collectionDirent) ModTime() time.Time {
-	if e.collection.ModifiedAt == nil {
-		return time.Now()
+func (fs *fileSystem) Create(name string) (File, error) {
+	return fs.dirnode.OpenFile(path.Clean(name), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0)
+}
+
+func (fs *fileSystem) Stat(name string) (os.FileInfo, error) {
+	f, err := fs.OpenFile(name, os.O_RDONLY, 0)
+	if err != nil {
+		return nil, err
 	}
-	return *e.collection.ModifiedAt
+	defer f.Close()
+	return f.Stat()
 }
 
-// Mode implements os.FileInfo.
-func (e collectionDirent) Mode() os.FileMode {
-	if e.isDir {
-		return 0555
-	} else {
-		return 0444
+type inode interface {
+	os.FileInfo
+	OpenFile(string, int, os.FileMode) (*file, error)
+	Parent() inode
+	Read([]byte, filenodePtr) (int, filenodePtr, error)
+	Write([]byte, filenodePtr) (int, filenodePtr, error)
+	Readdir() []os.FileInfo
+	Stat() os.FileInfo
+	sync.Locker
+	RLock()
+	RUnlock()
+}
+
+// filenode implements inode.
+type filenode struct {
+	fileinfo
+	parent   *dirnode
+	extents  []extent
+	repacked int64 // number of times anything in []extents has changed len
+	sync.RWMutex
+}
+
+// filenodePtr is an offset into a file that is (usually) efficient to
+// seek to. Specifically, if filenode.repacked==filenodePtr.repacked
+// then filenode.extents[filenodePtr.extentIdx][filenodePtr.extentOff]
+// corresponds to file offset filenodePtr.off. Otherwise, it is
+// necessary to reexamine len(filenode.extents[0]) etc. to find the
+// correct extent and offset.
+type filenodePtr struct {
+	off       int64
+	extentIdx int
+	extentOff int
+	repacked  int64
+}
+
+// seek returns a ptr that is consistent with both startPtr.off and
+// the current state of fn. The caller must already hold fn.RLock() or
+// fn.Lock().
+//
+// If startPtr points beyond the end of the file, ptr will point to
+// exactly the end of the file.
+//
+// After seeking:
+//
+//     ptr.extentIdx == len(filenode.extents) // i.e., at EOF
+//     ||
+//     filenode.extents[ptr.extentIdx].Len() >= ptr.extentOff
+func (fn *filenode) seek(startPtr filenodePtr) (ptr filenodePtr) {
+	ptr = startPtr
+	if ptr.off < 0 {
+		// meaningless anyway
+		return
+	} else if ptr.off >= fn.fileinfo.size {
+		ptr.off = fn.fileinfo.size
+		ptr.extentIdx = len(fn.extents)
+		ptr.extentOff = 0
+		ptr.repacked = fn.repacked
+		return
+	} else if ptr.repacked == fn.repacked {
+		// extentIdx and extentOff accurately reflect ptr.off,
+		// but might have fallen off the end of an extent
+		if int64(ptr.extentOff) >= fn.extents[ptr.extentIdx].Len() {
+			ptr.extentIdx++
+			ptr.extentOff = 0
+		}
+		return
+	}
+	defer func() {
+		ptr.repacked = fn.repacked
+	}()
+	if ptr.off >= fn.fileinfo.size {
+		ptr.extentIdx, ptr.extentOff = len(fn.extents), 0
+		return
 	}
+	// Recompute extentIdx and extentOff.  We have already
+	// established fn.fileinfo.size > ptr.off >= 0, so we don't
+	// have to deal with edge cases here.
+	var off int64
+	for ptr.extentIdx, ptr.extentOff = 0, 0; off < ptr.off; ptr.extentIdx++ {
+		// This would panic (index out of range) if
+		// fn.fileinfo.size were larger than
+		// sum(fn.extents[i].Len()) -- but that can't happen
+		// because we have ensured fn.fileinfo.size is always
+		// accurate.
+		extLen := fn.extents[ptr.extentIdx].Len()
+		if off+extLen > ptr.off {
+			ptr.extentOff = int(ptr.off - off)
+			break
+		}
+		off += extLen
+	}
+	return
 }
 
-// IsDir implements os.FileInfo.
-func (e collectionDirent) IsDir() bool {
-	return e.isDir
+func (fn *filenode) appendExtent(e extent) {
+	fn.Lock()
+	defer fn.Unlock()
+	fn.extents = append(fn.extents, e)
+	fn.fileinfo.size += e.Len()
+	fn.repacked++
 }
 
-// Size implements os.FileInfo.
-func (e collectionDirent) Size() int64 {
-	return e.size
+func (fn *filenode) OpenFile(string, int, os.FileMode) (*file, error) {
+	return nil, os.ErrNotExist
 }
 
-// Sys implements os.FileInfo.
-func (e collectionDirent) Sys() interface{} {
+func (fn *filenode) Parent() inode {
+	return fn.parent
+}
+
+func (fn *filenode) Readdir() []os.FileInfo {
 	return nil
 }
 
-// A CollectionFileSystem is an http.Filesystem with an added Stat() method.
-type CollectionFileSystem interface {
-	http.FileSystem
-	Stat(name string) (os.FileInfo, error)
+func (fn *filenode) Read(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
+	fn.RLock()
+	defer fn.RUnlock()
+	ptr = fn.seek(startPtr)
+	if ptr.off < 0 {
+		err = ErrNegativeOffset
+		return
+	}
+	if ptr.extentIdx >= len(fn.extents) {
+		err = io.EOF
+		return
+	}
+	n, err = fn.extents[ptr.extentIdx].ReadAt(p, int64(ptr.extentOff))
+	if n > 0 {
+		ptr.off += int64(n)
+		ptr.extentOff += n
+		if int64(ptr.extentOff) == fn.extents[ptr.extentIdx].Len() {
+			ptr.extentIdx++
+			ptr.extentOff = 0
+			if ptr.extentIdx < len(fn.extents) && err == io.EOF {
+				err = nil
+			}
+		}
+	}
+	return
 }
 
-// collectionFS implements CollectionFileSystem.
-type collectionFS struct {
-	collection *Collection
-	client     *Client
-	kc         keepClient
-	sizes      map[string]int64
-	sizesOnce  sync.Once
+func (fn *filenode) Write(p []byte, startPtr filenodePtr) (n int, ptr filenodePtr, err error) {
+	fn.Lock()
+	defer fn.Unlock()
+	ptr = fn.seek(startPtr)
+	if ptr.off < 0 {
+		err = ErrNegativeOffset
+		return
+	}
+	err = ErrReadOnlyFile
+	return
 }
 
 // FileSystem returns a CollectionFileSystem for the collection.
 func (c *Collection) FileSystem(client *Client, kc keepClient) CollectionFileSystem {
-	return &collectionFS{
-		collection: c,
-		client:     client,
-		kc:         kc,
-	}
-}
-
-func (c *collectionFS) Stat(name string) (os.FileInfo, error) {
-	name = canonicalName(name)
-	if name == "." {
-		return collectionDirent{
-			collection: c.collection,
-			name:       "/",
-			isDir:      true,
-		}, nil
-	}
-	if size, ok := c.fileSizes()[name]; ok {
-		return collectionDirent{
-			collection: c.collection,
-			name:       path.Base(name),
-			size:       size,
-			isDir:      false,
-		}, nil
-	}
-	for fnm := range c.fileSizes() {
-		if !strings.HasPrefix(fnm, name+"/") {
-			continue
+	fs := &fileSystem{dirnode: dirnode{
+		cache:    &keepBlockCache{kc: kc},
+		client:   client,
+		kc:       kc,
+		fileinfo: fileinfo{name: ".", mode: os.ModeDir | 0755},
+		parent:   nil,
+		inodes:   make(map[string]inode),
+	}}
+	fs.dirnode.parent = &fs.dirnode
+	fs.dirnode.loadManifest(c.ManifestText)
+	return fs
+}
+
+type file struct {
+	inode
+	ptr        filenodePtr
+	append     bool
+	writable   bool
+	unreaddirs []os.FileInfo
+}
+
+func (f *file) Read(p []byte) (n int, err error) {
+	n, f.ptr, err = f.inode.Read(p, f.ptr)
+	return
+}
+
+func (f *file) Seek(off int64, whence int) (pos int64, err error) {
+	size := f.inode.Size()
+	ptr := f.ptr
+	switch whence {
+	case os.SEEK_SET:
+		ptr.off = off
+	case os.SEEK_CUR:
+		ptr.off += off
+	case os.SEEK_END:
+		ptr.off = size + off
+	}
+	if ptr.off < 0 {
+		return f.ptr.off, ErrNegativeOffset
+	}
+	if ptr.off > size {
+		ptr.off = size
+	}
+	if ptr.off != f.ptr.off {
+		f.ptr = ptr
+		// force filenode to recompute f.ptr fields on next
+		// use
+		f.ptr.repacked = -1
+	}
+	return f.ptr.off, nil
+}
+
+func (f *file) Write(p []byte) (n int, err error) {
+	n, f.ptr, err = f.inode.Write(p, f.ptr)
+	return
+}
+
+func (f *file) Readdir(count int) ([]os.FileInfo, error) {
+	if !f.inode.IsDir() {
+		return nil, ErrInvalidOperation
+	}
+	if count <= 0 {
+		return f.inode.Readdir(), nil
+	}
+	if f.unreaddirs == nil {
+		f.unreaddirs = f.inode.Readdir()
+	}
+	if len(f.unreaddirs) == 0 {
+		return nil, io.EOF
+	}
+	if count > len(f.unreaddirs) {
+		count = len(f.unreaddirs)
+	}
+	ret := f.unreaddirs[:count]
+	f.unreaddirs = f.unreaddirs[count:]
+	return ret, nil
+}
+
+func (f *file) Stat() (os.FileInfo, error) {
+	return f.inode, nil
+}
+
+func (f *file) Close() error {
+	// FIXME: flush
+	return nil
+}
+
+func (f *file) OpenFile(name string, flag int, perm os.FileMode) (*file, error) {
+	return f.inode.OpenFile(name, flag, perm)
+}
+
+type dirnode struct {
+	fileinfo
+	parent *dirnode
+	client *Client
+	kc     keepClient
+	cache  blockCache
+	inodes map[string]inode
+	sync.RWMutex
+}
+
+func (dn *dirnode) loadManifest(txt string) {
+	// FIXME: faster
+	var dirname string
+	for _, stream := range strings.Split(txt, "\n") {
+		var extents []storedExtent
+		for i, token := range strings.Split(stream, " ") {
+			if i == 0 {
+				dirname = manifestUnescape(token)
+				continue
+			}
+			if !strings.Contains(token, ":") {
+				toks := strings.SplitN(token, "+", 3)
+				if len(toks) < 2 {
+					// FIXME: broken
+					continue
+				}
+				length, err := strconv.ParseInt(toks[1], 10, 32)
+				if err != nil || length < 0 {
+					// FIXME: broken
+					continue
+				}
+				extents = append(extents, storedExtent{
+					locator: token,
+					offset:  0,
+					length:  int(length),
+				})
+				continue
+			}
+			toks := strings.Split(token, ":")
+			if len(toks) != 3 {
+				// FIXME: broken manifest
+				continue
+			}
+			offset, err := strconv.ParseInt(toks[0], 10, 64)
+			if err != nil || offset < 0 {
+				// FIXME: broken manifest
+				continue
+			}
+			length, err := strconv.ParseInt(toks[1], 10, 64)
+			if err != nil || length < 0 {
+				// FIXME: broken manifest
+				continue
+			}
+			name := path.Clean(dirname + "/" + manifestUnescape(toks[2]))
+			dn.makeParentDirs(name)
+			f, err := dn.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0700)
+			if err != nil {
+				// FIXME: broken
+				continue
+			}
+			if f.inode.Stat().IsDir() {
+				f.Close()
+				// FIXME: broken manifest
+				continue
+			}
+			var pos int64
+			for _, e := range extents {
+				if pos+e.Len() < offset {
+					pos += e.Len()
+					continue
+				}
+				if pos > offset+length {
+					break
+				}
+				var blkOff int
+				if pos < offset {
+					blkOff = int(offset - pos)
+				}
+				blkLen := int(e.Len()) - blkOff
+				if pos+int64(blkOff+blkLen) > offset+length {
+					blkLen = int(offset + length - pos - int64(blkOff))
+				}
+				f.inode.(*filenode).appendExtent(storedExtent{
+					cache:   dn.cache,
+					locator: e.locator,
+					offset:  blkOff,
+					length:  blkLen,
+				})
+				pos += e.Len()
+			}
+			f.Close()
 		}
-		return collectionDirent{
-			collection: c.collection,
-			name:       path.Base(name),
-			isDir:      true,
-		}, nil
 	}
-	return nil, os.ErrNotExist
 }
 
-func (c *collectionFS) Open(name string) (http.File, error) {
-	// Ensure name looks the way it does in a manifest.
-	name = canonicalName(name)
+func (dn *dirnode) makeParentDirs(name string) {
+	names := strings.Split(name, "/")
+	for _, name := range names[:len(names)-1] {
+		dn.Lock()
+		defer dn.Unlock()
+		if n, ok := dn.inodes[name]; !ok {
+			n := &dirnode{
+				parent: dn,
+				client: dn.client,
+				kc:     dn.kc,
+				fileinfo: fileinfo{
+					name: name,
+					mode: os.ModeDir | 0755,
+				},
+			}
+			if dn.inodes == nil {
+				dn.inodes = make(map[string]inode)
+			}
+			dn.inodes[name] = n
+			dn.fileinfo.size++
+			dn = n
+		} else if n, ok := n.(*dirnode); ok {
+			dn = n
+		} else {
+			// fail
+			return
+		}
+	}
+}
+
+func (dn *dirnode) Parent() inode {
+	return dn.parent
+}
+
+func (dn *dirnode) Readdir() (fi []os.FileInfo) {
+	dn.RLock()
+	defer dn.RUnlock()
+	fi = make([]os.FileInfo, 0, len(dn.inodes))
+	for _, inode := range dn.inodes {
+		fi = append(fi, inode.Stat())
+	}
+	return
+}
 
-	m := manifest.Manifest{Text: c.collection.ManifestText}
+func (dn *dirnode) Read(p []byte, ptr filenodePtr) (int, filenodePtr, error) {
+	return 0, ptr, ErrInvalidOperation
+}
+
+func (dn *dirnode) Write(p []byte, ptr filenodePtr) (int, filenodePtr, error) {
+	return 0, ptr, ErrInvalidOperation
+}
 
-	// Return a file if it exists.
-	if size, ok := c.fileSizes()[name]; ok {
-		reader, err := c.kc.ManifestFileReader(m, name)
+func (dn *dirnode) OpenFile(name string, flag int, perm os.FileMode) (*file, error) {
+	name = strings.TrimSuffix(name, "/")
+	if name == "." || name == "" {
+		return &file{inode: dn}, nil
+	}
+	if dirname, name := path.Split(name); dirname != "" {
+		// OpenFile("foo/bar/baz") =>
+		// OpenFile("foo/bar").OpenFile("baz") (or
+		// ErrNotExist, if foo/bar is a file)
+		f, err := dn.OpenFile(dirname, os.O_RDONLY, 0)
 		if err != nil {
 			return nil, err
 		}
-		return &collectionFile{
-			File:       reader,
-			collection: c.collection,
-			name:       path.Base(name),
-			size:       size,
-		}, nil
-	}
-
-	// Return a directory if it's the root dir or there are file
-	// entries below it.
-	children := map[string]collectionDirent{}
-	for fnm, size := range c.fileSizes() {
-		if !strings.HasPrefix(fnm, name+"/") {
-			continue
+		defer f.Close()
+		if dn, ok := f.inode.(*dirnode); ok {
+			return dn.OpenFile(name, flag, perm)
+		} else {
+			return nil, os.ErrNotExist
+		}
+	}
+	dn.Lock()
+	defer dn.Unlock()
+	if name == ".." {
+		return &file{inode: dn.parent}, nil
+	}
+	n, ok := dn.inodes[name]
+	if !ok {
+		if flag&os.O_CREATE == 0 {
+			return nil, os.ErrNotExist
+		}
+		n = &filenode{
+			parent: dn,
+			fileinfo: fileinfo{
+				name: name,
+				mode: 0755,
+			},
 		}
-		isDir := false
-		ent := fnm[len(name)+1:]
-		if i := strings.Index(ent, "/"); i >= 0 {
-			ent = ent[:i]
-			isDir = true
+		if dn.inodes == nil {
+			dn.inodes = make(map[string]inode)
 		}
-		e := children[ent]
-		e.collection = c.collection
-		e.isDir = isDir
-		e.name = ent
-		e.size = size
-		children[ent] = e
-	}
-	if len(children) == 0 && name != "." {
-		return nil, os.ErrNotExist
-	}
-	dirents := make([]os.FileInfo, 0, len(children))
-	for _, ent := range children {
-		dirents = append(dirents, ent)
-	}
-	return &collectionDir{
-		collection: c.collection,
-		stream:     name,
-		dirents:    dirents,
+		dn.inodes[name] = n
+		dn.fileinfo.size++
+	} else if flag&os.O_EXCL != 0 {
+		return nil, ErrFileExists
+	}
+	return &file{
+		inode:    n,
+		append:   flag&os.O_APPEND != 0,
+		writable: flag&(os.O_WRONLY|os.O_RDWR) != 0,
 	}, nil
 }
 
-// fileSizes returns a map of files that can be opened. Each key
-// starts with "./".
-func (c *collectionFS) fileSizes() map[string]int64 {
-	c.sizesOnce.Do(func() {
-		c.sizes = map[string]int64{}
-		m := manifest.Manifest{Text: c.collection.ManifestText}
-		for ms := range m.StreamIter() {
-			for _, fss := range ms.FileStreamSegments {
-				c.sizes[ms.StreamName+"/"+fss.Name] += int64(fss.SegLen)
-			}
+type extent interface {
+	io.ReaderAt
+	Len() int64
+}
+
+type writableExtent interface {
+	extent
+	WriteAt(p []byte, off int)
+	Truncate(n int)
+}
+
+type memExtent struct {
+	buf []byte
+}
+
+func (me *memExtent) Len() int64 {
+	return int64(len(me.buf))
+}
+
+func (me *memExtent) Truncate(n int) {
+	if n > cap(me.buf) {
+		newsize := 1024
+		for newsize < n {
+			newsize = newsize << 2
+		}
+		newbuf := make([]byte, n, newsize)
+		copy(newbuf, me.buf)
+		me.buf = newbuf
+	}
+	me.buf = me.buf[:n]
+}
+
+func (me *memExtent) WriteAt(p []byte, off int) {
+	if off+len(p) > len(me.buf) {
+		panic("overflowed extent")
+	}
+	copy(me.buf[off:], p)
+}
+
+func (me *memExtent) ReadAt(p []byte, off int64) (n int, err error) {
+	if off > me.Len() {
+		err = io.EOF
+		return
+	}
+	n = copy(p, me.buf[int(off):])
+	if n < len(p) {
+		err = io.EOF
+	}
+	return
+}
+
+type storedExtent struct {
+	cache   blockCache
+	locator string
+	offset  int
+	length  int
+}
+
+func (se storedExtent) Len() int64 {
+	return int64(se.length)
+}
+
+func (se storedExtent) ReadAt(p []byte, off int64) (n int, err error) {
+	maxlen := int(int64(se.length) - int64(se.offset) - off)
+	if len(p) > maxlen {
+		p = p[:maxlen]
+		n, err = se.cache.ReadAt(se.locator, p, off+int64(se.offset))
+		if err == nil {
+			err = io.EOF
 		}
-	})
-	return c.sizes
+		return
+	}
+	return se.cache.ReadAt(se.locator, p, off+int64(se.offset))
+}
+
+type blockCache interface {
+	ReadAt(locator string, p []byte, off int64) (n int, err error)
+}
+
+type keepBlockCache struct {
+	kc keepClient
+}
+
+var scratch = make([]byte, 2<<26)
+
+func (kbc *keepBlockCache) ReadAt(locator string, p []byte, off int64) (int, error) {
+	return kbc.kc.ReadAt(locator, p, off)
 }
 
 func canonicalName(name string) string {
@@ -278,3 +657,21 @@ func canonicalName(name string) string {
 	}
 	return name
 }
+
+var manifestEscapeSeq = regexp.MustCompile(`\\([0-9]{3}|\\)`)
+
+func manifestUnescapeSeq(seq string) string {
+	if seq == `\\` {
+		return `\`
+	}
+	i, err := strconv.ParseUint(seq[1:], 8, 8)
+	if err != nil {
+		// Invalid escape sequence: can't unescape.
+		return seq
+	}
+	return string([]byte{byte(i)})
+}
+
+func manifestUnescape(s string) string {
+	return manifestEscapeSeq.ReplaceAllStringFunc(s, manifestUnescapeSeq)
+}
diff --git a/sdk/go/arvados/collection_fs_test.go b/sdk/go/arvados/collection_fs_test.go
index f51d1eb..7bd3570 100644
--- a/sdk/go/arvados/collection_fs_test.go
+++ b/sdk/go/arvados/collection_fs_test.go
@@ -16,17 +16,39 @@ import (
 
 var _ = check.Suite(&CollectionFSSuite{})
 
+type keepClientStub struct {
+	blocks map[string][]byte
+}
+
+func (kcs *keepClientStub) ReadAt(locator string, p []byte, off int64) (int, error) {
+	buf := kcs.blocks[locator[:32]]
+	if buf == nil {
+		return 0, os.ErrNotExist
+	}
+	return copy(p, buf[int(off):]), nil
+}
+
 type CollectionFSSuite struct {
 	client *Client
 	coll   Collection
-	fs     http.FileSystem
+	fs     CollectionFileSystem
+	kc     keepClient
 }
 
 func (s *CollectionFSSuite) SetUpTest(c *check.C) {
 	s.client = NewClientFromEnv()
 	err := s.client.RequestAndDecode(&s.coll, "GET", "arvados/v1/collections/"+arvadostest.FooAndBarFilesInDirUUID, nil, nil)
 	c.Assert(err, check.IsNil)
-	s.fs = s.coll.FileSystem(s.client, nil)
+	s.kc = &keepClientStub{
+		blocks: map[string][]byte{
+			"3858f62230ac3c915f300c664312c63f": []byte("foobar"),
+		}}
+	s.fs = s.coll.FileSystem(s.client, s.kc)
+}
+
+func (s *CollectionFSSuite) TestHttpFileSystemInterface(c *check.C) {
+	_, ok := s.fs.(http.FileSystem)
+	c.Check(ok, check.Equals, true)
 }
 
 func (s *CollectionFSSuite) TestReaddirFull(c *check.C) {
@@ -58,7 +80,7 @@ func (s *CollectionFSSuite) TestReaddirLimited(c *check.C) {
 	}
 
 	fis, err = f.Readdir(1)
-	c.Check(err, check.Equals, io.EOF)
+	c.Check(err, check.IsNil)
 	c.Check(len(fis), check.Equals, 1)
 	if len(fis) > 0 {
 		c.Check(fis[0].Size(), check.Equals, int64(3))
@@ -76,7 +98,7 @@ func (s *CollectionFSSuite) TestReaddirLimited(c *check.C) {
 	c.Assert(err, check.IsNil)
 	fis, err = f.Readdir(2)
 	c.Check(len(fis), check.Equals, 1)
-	c.Assert(err, check.Equals, io.EOF)
+	c.Assert(err, check.IsNil)
 	fis, err = f.Readdir(2)
 	c.Check(len(fis), check.Equals, 0)
 	c.Assert(err, check.Equals, io.EOF)
diff --git a/sdk/go/keepclient/block_cache.go b/sdk/go/keepclient/block_cache.go
index e841a00..c1138fa 100644
--- a/sdk/go/keepclient/block_cache.go
+++ b/sdk/go/keepclient/block_cache.go
@@ -49,6 +49,19 @@ func (c *BlockCache) Sweep() {
 	}
 }
 
+// ReadAt returns data from the cache, first retrieving it from Keep if
+// necessary.
+func (c *BlockCache) ReadAt(kc *KeepClient, locator string, p []byte, off int64) (int, error) {
+	buf, err := c.Get(kc, locator)
+	if err != nil {
+		return 0, err
+	}
+	if off > int64(len(buf)) {
+		return 0, io.ErrUnexpectedEOF
+	}
+	return copy(p, buf[int(off):]), nil
+}
+
 // Get returns data from the cache, first retrieving it from Keep if
 // necessary.
 func (c *BlockCache) Get(kc *KeepClient, locator string) ([]byte, error) {
diff --git a/sdk/go/keepclient/collectionreader.go b/sdk/go/keepclient/collectionreader.go
index 57829aa..3f39aff 100644
--- a/sdk/go/keepclient/collectionreader.go
+++ b/sdk/go/keepclient/collectionreader.go
@@ -43,14 +43,7 @@ func (kc *KeepClient) CollectionFileReader(collection map[string]interface{}, fi
 }
 
 func (kc *KeepClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
-	f := &file{
-		kc: kc,
-	}
-	err := f.load(m, filename)
-	if err != nil {
-		return nil, err
-	}
-	return f, nil
+	return (&arvados.Collection{ManifestText: m.Text}).FileSystem(nil, kc).OpenFile(filename, os.O_RDONLY, 0)
 }
 
 type file struct {
diff --git a/sdk/go/keepclient/keepclient.go b/sdk/go/keepclient/keepclient.go
index cbfad81..c3d63ed 100644
--- a/sdk/go/keepclient/keepclient.go
+++ b/sdk/go/keepclient/keepclient.go
@@ -292,6 +292,12 @@ func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error)
 	return kc.getOrHead("GET", locator)
 }
 
+// ReadAt() retrieves a portion of block from the cache if it's
+// present, otherwise from the network.
+func (kc *KeepClient) ReadAt(locator string, p []byte, off int64) (int, error) {
+	return kc.cache().ReadAt(kc, locator, p, off)
+}
+
 // Ask() verifies that a block with the given hash is available and
 // readable, according to at least one Keep service. Unlike Get, it
 // does not retrieve the data or verify that the data content matches

-----------------------------------------------------------------------


hooks/post-receive
-- 




More information about the arvados-commits mailing list