mfs_test.go 20 KB
Newer Older
1 2 3 4
package mfs

import (
	"bytes"
Jeromy's avatar
Jeromy committed
5
	"context"
6 7 8 9
	"errors"
	"fmt"
	"io"
	"io/ioutil"
Jeromy's avatar
Jeromy committed
10
	"math/rand"
11 12
	"os"
	"sort"
13
	"sync"
14
	"testing"
15
	"time"
16 17 18 19 20 21

	bstore "github.com/ipfs/go-ipfs/blocks/blockstore"
	bserv "github.com/ipfs/go-ipfs/blockservice"
	offline "github.com/ipfs/go-ipfs/exchange/offline"
	importer "github.com/ipfs/go-ipfs/importer"
	dag "github.com/ipfs/go-ipfs/merkledag"
22
	"github.com/ipfs/go-ipfs/path"
23 24
	ft "github.com/ipfs/go-ipfs/unixfs"
	uio "github.com/ipfs/go-ipfs/unixfs/io"
25
	chunk "gx/ipfs/QmQXcAyrC4VBu9ZBqxoCthPot9PNhb4Uiw6iBDfQXudZJd/go-ipfs-chunker"
26

Steven Allen's avatar
Steven Allen committed
27 28 29 30
	u "gx/ipfs/QmNiJuT8Ja3hMVpBHXv3Q6dwmperaQ6JjLtpMQgMCD7xvx/go-ipfs-util"
	ds "gx/ipfs/QmPpegoMqhAEqjncrzArm7KVWAkCm78rqL2DPuNjhPrshg/go-datastore"
	dssync "gx/ipfs/QmPpegoMqhAEqjncrzArm7KVWAkCm78rqL2DPuNjhPrshg/go-datastore/sync"
	cid "gx/ipfs/QmcZfnkapfECQGcLZaf9B79NRg7cRa9EnZh4LSbkCzwNvY/go-cid"
31
	ipld "gx/ipfs/Qme5bWv7wtjUNGsK2BNGVUFPKiuxWrsqrtvYwCLRw8YFES/go-ipld-format"
32 33
)

34
func emptyDirNode() *dag.ProtoNode {
35 36 37
	return dag.NodeWithData(ft.FolderPBData())
}

38
func getDagserv(t *testing.T) ipld.DAGService {
39 40 41 42 43 44
	db := dssync.MutexWrap(ds.NewMapDatastore())
	bs := bstore.NewBlockstore(db)
	blockserv := bserv.New(bs, offline.Exchange(bs))
	return dag.NewDAGService(blockserv)
}

45
func getRandFile(t *testing.T, ds ipld.DAGService, size int64) ipld.Node {
46
	r := io.LimitReader(u.NewTimeSeededRand(), size)
47 48 49
	return fileNodeFromReader(t, ds, r)
}

50
func fileNodeFromReader(t *testing.T, ds ipld.DAGService, r io.Reader) ipld.Node {
51 52 53 54 55 56 57
	nd, err := importer.BuildDagFromReader(ds, chunk.DefaultSplitter(r))
	if err != nil {
		t.Fatal(err)
	}
	return nd
}

rht's avatar
rht committed
58 59
func mkdirP(t *testing.T, root *Directory, pth string) *Directory {
	dirs := path.SplitList(pth)
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
	cur := root
	for _, d := range dirs {
		n, err := cur.Mkdir(d)
		if err != nil && err != os.ErrExist {
			t.Fatal(err)
		}
		if err == os.ErrExist {
			fsn, err := cur.Child(d)
			if err != nil {
				t.Fatal(err)
			}
			switch fsn := fsn.(type) {
			case *Directory:
				n = fsn
			case *File:
				t.Fatal("tried to make a directory where a file already exists")
			}
		}

		cur = n
	}
	return cur
}

rht's avatar
rht committed
84
func assertDirAtPath(root *Directory, pth string, children []string) error {
Jeromy's avatar
Jeromy committed
85 86 87
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

rht's avatar
rht committed
88
	fsn, err := DirLookup(root, pth)
89 90 91 92 93 94
	if err != nil {
		return err
	}

	dir, ok := fsn.(*Directory)
	if !ok {
rht's avatar
rht committed
95
		return fmt.Errorf("%s was not a directory", pth)
96 97
	}

Jeromy's avatar
Jeromy committed
98
	listing, err := dir.List(ctx)
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
	if err != nil {
		return err
	}

	var names []string
	for _, d := range listing {
		names = append(names, d.Name)
	}

	sort.Strings(children)
	sort.Strings(names)
	if !compStrArrs(children, names) {
		return errors.New("directories children did not match!")
	}

	return nil
}

func compStrArrs(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}

	for i := 0; i < len(a); i++ {
		if a[i] != b[i] {
			return false
		}
	}

	return true
}

131
func assertFileAtPath(ds ipld.DAGService, root *Directory, expn ipld.Node, pth string) error {
132 133 134 135 136
	exp, ok := expn.(*dag.ProtoNode)
	if !ok {
		return dag.ErrNotProtobuf
	}

rht's avatar
rht committed
137
	parts := path.SplitList(pth)
138 139 140 141
	cur := root
	for i, d := range parts[:len(parts)-1] {
		next, err := cur.Child(d)
		if err != nil {
rht's avatar
rht committed
142
			return fmt.Errorf("looking for %s failed: %s", pth, err)
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
		}

		nextDir, ok := next.(*Directory)
		if !ok {
			return fmt.Errorf("%s points to a non-directory", parts[:i+1])
		}

		cur = nextDir
	}

	last := parts[len(parts)-1]
	finaln, err := cur.Child(last)
	if err != nil {
		return err
	}

	file, ok := finaln.(*File)
	if !ok {
rht's avatar
rht committed
161
		return fmt.Errorf("%s was not a file!", pth)
162 163
	}

164 165 166 167 168 169
	rfd, err := file.Open(OpenReadOnly, false)
	if err != nil {
		return err
	}

	out, err := ioutil.ReadAll(rfd)
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
	if err != nil {
		return err
	}

	expbytes, err := catNode(ds, exp)
	if err != nil {
		return err
	}

	if !bytes.Equal(out, expbytes) {
		return fmt.Errorf("Incorrect data at path!")
	}
	return nil
}

185
func catNode(ds ipld.DAGService, nd *dag.ProtoNode) ([]byte, error) {
186 187 188 189 190 191 192 193 194
	r, err := uio.NewDagReader(context.TODO(), nd, ds)
	if err != nil {
		return nil, err
	}
	defer r.Close()

	return ioutil.ReadAll(r)
}

195
func setupRoot(ctx context.Context, t *testing.T) (ipld.DAGService, *Root) {
196 197
	ds := getDagserv(t)

198
	root := emptyDirNode()
Jeromy's avatar
Jeromy committed
199 200
	rt, err := NewRoot(ctx, ds, root, func(ctx context.Context, c *cid.Cid) error {
		fmt.Println("PUBLISHED: ", c)
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
		return nil
	})

	if err != nil {
		t.Fatal(err)
	}

	return ds, rt
}

func TestBasic(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ds, rt := setupRoot(ctx, t)

	rootdir := rt.GetValue().(*Directory)

	// test making a basic dir
	_, err := rootdir.Mkdir("a")
	if err != nil {
		t.Fatal(err)
	}

	path := "a/b/c/d/e/f/g"
	d := mkdirP(t, rootdir, path)

	fi := getRandFile(t, ds, 1000)

	// test inserting that file
	err = d.AddChild("afile", fi)
	if err != nil {
		t.Fatal(err)
	}

	err = assertFileAtPath(ds, rootdir, fi, "a/b/c/d/e/f/g/afile")
	if err != nil {
		t.Fatal(err)
	}
}

func TestMkdir(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	_, rt := setupRoot(ctx, t)

	rootdir := rt.GetValue().(*Directory)

	dirsToMake := []string{"a", "B", "foo", "bar", "cats", "fish"}
	sort.Strings(dirsToMake) // sort for easy comparing later

	for _, d := range dirsToMake {
		_, err := rootdir.Mkdir(d)
		if err != nil {
			t.Fatal(err)
		}
	}

	err := assertDirAtPath(rootdir, "/", dirsToMake)
	if err != nil {
		t.Fatal(err)
	}

	for _, d := range dirsToMake {
		mkdirP(t, rootdir, "a/"+d)
	}

	err = assertDirAtPath(rootdir, "/a", dirsToMake)
	if err != nil {
		t.Fatal(err)
	}

	// mkdir over existing dir should fail
	_, err = rootdir.Mkdir("a")
	if err == nil {
		t.Fatal("should have failed!")
	}
}

func TestDirectoryLoadFromDag(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ds, rt := setupRoot(ctx, t)

	rootdir := rt.GetValue().(*Directory)

	nd := getRandFile(t, ds, 1000)
287
	err := ds.Add(ctx, nd)
288 289 290 291
	if err != nil {
		t.Fatal(err)
	}

292
	fihash := nd.Cid()
293

294
	dir := emptyDirNode()
295
	err = ds.Add(ctx, dir)
296 297 298 299
	if err != nil {
		t.Fatal(err)
	}

300
	dirhash := dir.Cid()
301

302
	top := emptyDirNode()
303
	top.SetLinks([]*ipld.Link{
Jeromy's avatar
Jeromy committed
304
		{
305
			Name: "a",
306
			Cid:  fihash,
307
		},
Jeromy's avatar
Jeromy committed
308
		{
309
			Name: "b",
310
			Cid:  dirhash,
311
		},
312
	})
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

	err = rootdir.AddChild("foo", top)
	if err != nil {
		t.Fatal(err)
	}

	// get this dir
	topi, err := rootdir.Child("foo")
	if err != nil {
		t.Fatal(err)
	}

	topd := topi.(*Directory)

	// mkdir over existing but unloaded child file should fail
	_, err = topd.Mkdir("a")
	if err == nil {
		t.Fatal("expected to fail!")
	}

	// mkdir over existing but unloaded child dir should fail
	_, err = topd.Mkdir("b")
	if err == nil {
		t.Fatal("expected to fail!")
	}

	// adding a child over an existing path fails
	err = topd.AddChild("b", nd)
	if err == nil {
		t.Fatal("expected to fail!")
	}

	err = assertFileAtPath(ds, rootdir, nd, "foo/a")
	if err != nil {
		t.Fatal(err)
	}

	err = assertDirAtPath(rootdir, "foo/b", nil)
	if err != nil {
		t.Fatal(err)
	}

	err = rootdir.Unlink("foo")
	if err != nil {
		t.Fatal(err)
	}

	err = assertDirAtPath(rootdir, "", nil)
	if err != nil {
		t.Fatal(err)
	}
}

func TestMfsFile(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ds, rt := setupRoot(ctx, t)

	rootdir := rt.GetValue().(*Directory)

	fisize := 1000
	nd := getRandFile(t, ds, 1000)

	err := rootdir.AddChild("file", nd)
	if err != nil {
		t.Fatal(err)
	}

	fsn, err := rootdir.Child("file")
	if err != nil {
		t.Fatal(err)
	}

	fi := fsn.(*File)

	if fi.Type() != TFile {
		t.Fatal("some is seriously wrong here")
	}

392 393 394 395 396
	wfd, err := fi.Open(OpenReadWrite, true)
	if err != nil {
		t.Fatal(err)
	}

397 398
	// assert size is as expected
	size, err := fi.Size()
399 400 401
	if err != nil {
		t.Fatal(err)
	}
402 403 404 405 406 407
	if size != int64(fisize) {
		t.Fatal("size isnt correct")
	}

	// write to beginning of file
	b := []byte("THIS IS A TEST")
408
	n, err := wfd.Write(b)
409 410 411 412 413 414 415 416 417
	if err != nil {
		t.Fatal(err)
	}

	if n != len(b) {
		t.Fatal("didnt write correct number of bytes")
	}

	// sync file
418
	err = wfd.Sync()
419 420 421 422 423
	if err != nil {
		t.Fatal(err)
	}

	// make sure size hasnt changed
424
	size, err = wfd.Size()
425 426 427
	if err != nil {
		t.Fatal(err)
	}
428 429 430 431 432
	if size != int64(fisize) {
		t.Fatal("size isnt correct")
	}

	// seek back to beginning
433
	ns, err := wfd.Seek(0, io.SeekStart)
434 435 436 437 438 439 440 441 442 443
	if err != nil {
		t.Fatal(err)
	}

	if ns != 0 {
		t.Fatal("didnt seek to beginning")
	}

	// read back bytes we wrote
	buf := make([]byte, len(b))
444
	n, err = wfd.Read(buf)
445 446 447 448 449 450 451 452 453 454 455 456 457
	if err != nil {
		t.Fatal(err)
	}

	if n != len(buf) {
		t.Fatal("didnt read enough")
	}

	if !bytes.Equal(buf, b) {
		t.Fatal("data read was different than data written")
	}

	// truncate file to ten bytes
458
	err = wfd.Truncate(10)
459 460 461 462
	if err != nil {
		t.Fatal(err)
	}

463
	size, err = wfd.Size()
464 465 466 467 468 469 470 471 472 473
	if err != nil {
		t.Fatal(err)
	}

	if size != 10 {
		t.Fatal("size was incorrect: ", size)
	}

	// 'writeAt' to extend it
	data := []byte("this is a test foo foo foo")
474
	nwa, err := wfd.WriteAt(data, 5)
475 476 477 478 479 480 481 482 483
	if err != nil {
		t.Fatal(err)
	}

	if nwa != len(data) {
		t.Fatal(err)
	}

	// assert size once more
484
	size, err = wfd.Size()
485 486 487 488 489 490 491 492
	if err != nil {
		t.Fatal(err)
	}

	if size != int64(5+len(data)) {
		t.Fatal("size was incorrect")
	}

493 494
	// close it out!
	err = wfd.Close()
495 496 497 498
	if err != nil {
		t.Fatal(err)
	}

499 500
	// make sure we can get node. TODO: verify it later
	_, err = fi.GetNode()
501 502 503 504
	if err != nil {
		t.Fatal(err)
	}
}
Jeromy's avatar
Jeromy committed
505 506 507

func randomWalk(d *Directory, n int) (*Directory, error) {
	for i := 0; i < n; i++ {
Jeromy's avatar
Jeromy committed
508
		dirents, err := d.List(context.Background())
Jeromy's avatar
Jeromy committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
		if err != nil {
			return nil, err
		}

		var childdirs []NodeListing
		for _, child := range dirents {
			if child.Type == int(TDir) {
				childdirs = append(childdirs, child)
			}
		}
		if len(childdirs) == 0 {
			return d, nil
		}

		next := childdirs[rand.Intn(len(childdirs))].Name

		nextD, err := d.Child(next)
		if err != nil {
			return nil, err
		}

		d = nextD.(*Directory)
	}
	return d, nil
}

func randomName() string {
	set := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"
	length := rand.Intn(10) + 2
	var out string
	for i := 0; i < length; i++ {
		j := rand.Intn(len(set))
		out += set[j : j+1]
	}
	return out
}

func actorMakeFile(d *Directory) error {
	d, err := randomWalk(d, rand.Intn(7))
	if err != nil {
		return err
	}

	name := randomName()
553
	f, err := NewFile(name, dag.NodeWithData(ft.FilePBData(nil, 0)), d, d.dserv)
Jeromy's avatar
Jeromy committed
554 555 556 557
	if err != nil {
		return err
	}

558 559 560 561 562
	wfd, err := f.Open(OpenWriteOnly, true)
	if err != nil {
		return err
	}

563 564
	rread := rand.New(rand.NewSource(time.Now().UnixNano()))
	r := io.LimitReader(rread, int64(77*rand.Intn(123)))
565
	_, err = io.Copy(wfd, r)
Jeromy's avatar
Jeromy committed
566 567 568 569
	if err != nil {
		return err
	}

570
	return wfd.Close()
Jeromy's avatar
Jeromy committed
571
}
572

Jeromy's avatar
Jeromy committed
573 574 575 576 577 578 579 580
func actorMkdir(d *Directory) error {
	d, err := randomWalk(d, rand.Intn(7))
	if err != nil {
		return err
	}

	_, err = d.Mkdir(randomName())

581
	return err
Jeromy's avatar
Jeromy committed
582 583
}

584
func randomFile(d *Directory) (*File, error) {
Jeromy's avatar
Jeromy committed
585 586
	d, err := randomWalk(d, rand.Intn(6))
	if err != nil {
587
		return nil, err
Jeromy's avatar
Jeromy committed
588 589
	}

Jeromy's avatar
Jeromy committed
590
	ents, err := d.List(context.Background())
Jeromy's avatar
Jeromy committed
591
	if err != nil {
592
		return nil, err
Jeromy's avatar
Jeromy committed
593 594 595 596 597 598 599 600 601 602
	}

	var files []string
	for _, e := range ents {
		if e.Type == int(TFile) {
			files = append(files, e.Name)
		}
	}

	if len(files) == 0 {
603
		return nil, nil
Jeromy's avatar
Jeromy committed
604 605 606 607 608
	}

	fname := files[rand.Intn(len(files))]
	fsn, err := d.Child(fname)
	if err != nil {
609
		return nil, err
Jeromy's avatar
Jeromy committed
610 611 612 613
	}

	fi, ok := fsn.(*File)
	if !ok {
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
		return nil, errors.New("file wasnt a file, race?")
	}

	return fi, nil
}

func actorWriteFile(d *Directory) error {
	fi, err := randomFile(d)
	if err != nil {
		return err
	}
	if fi == nil {
		return nil
	}

629
	size := rand.Intn(1024) + 1
630
	buf := make([]byte, size)
631
	rand.Read(buf)
632 633 634 635 636 637

	s, err := fi.Size()
	if err != nil {
		return err
	}

638 639 640 641 642
	wfd, err := fi.Open(OpenWriteOnly, true)
	if err != nil {
		return err
	}

643 644
	offset := rand.Int63n(s)

645
	n, err := wfd.WriteAt(buf, offset)
646 647 648 649 650 651 652
	if err != nil {
		return err
	}
	if n != size {
		return fmt.Errorf("didnt write enough")
	}

653
	return wfd.Close()
654 655 656 657 658 659 660 661 662
}

func actorReadFile(d *Directory) error {
	fi, err := randomFile(d)
	if err != nil {
		return err
	}
	if fi == nil {
		return nil
Jeromy's avatar
Jeromy committed
663 664 665 666 667 668 669
	}

	_, err = fi.Size()
	if err != nil {
		return err
	}

670
	rfd, err := fi.Open(OpenReadOnly, false)
Jeromy's avatar
Jeromy committed
671 672 673 674
	if err != nil {
		return err
	}

675 676 677 678 679 680
	_, err = ioutil.ReadAll(rfd)
	if err != nil {
		return err
	}

	return rfd.Close()
Jeromy's avatar
Jeromy committed
681 682
}

Jeromy's avatar
Jeromy committed
683 684 685
func testActor(rt *Root, iterations int, errs chan error) {
	d := rt.GetValue().(*Directory)
	for i := 0; i < iterations; i++ {
Jeromy's avatar
Jeromy committed
686
		switch rand.Intn(5) {
Jeromy's avatar
Jeromy committed
687 688 689 690 691 692 693 694 695 696 697
		case 0:
			if err := actorMkdir(d); err != nil {
				errs <- err
				return
			}
		case 1, 2:
			if err := actorMakeFile(d); err != nil {
				errs <- err
				return
			}
		case 3:
698
			if err := actorWriteFile(d); err != nil {
Jeromy's avatar
Jeromy committed
699 700 701
				errs <- err
				return
			}
Jeromy's avatar
Jeromy committed
702 703 704 705 706
		case 4:
			if err := actorReadFile(d); err != nil {
				errs <- err
				return
			}
Jeromy's avatar
Jeromy committed
707 708 709 710 711 712 713 714 715 716
		}
	}
	errs <- nil
}

func TestMfsStress(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	_, rt := setupRoot(ctx, t)

Jeromy's avatar
Jeromy committed
717
	numroutines := 10
Jeromy's avatar
Jeromy committed
718 719 720 721 722 723 724 725 726 727 728 729 730

	errs := make(chan error)
	for i := 0; i < numroutines; i++ {
		go testActor(rt, 50, errs)
	}

	for i := 0; i < numroutines; i++ {
		err := <-errs
		if err != nil {
			t.Fatal(err)
		}
	}
}
Jeromy's avatar
Jeromy committed
731

732 733 734 735 736
func TestMfsHugeDir(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	_, rt := setupRoot(ctx, t)

Jeromy's avatar
Jeromy committed
737
	for i := 0; i < 10000; i++ {
738
		err := Mkdir(rt, fmt.Sprintf("/dir%d", i), MkdirOpts{Mkparents: false, Flush: false})
739 740 741 742 743 744 745 746 747 748 749
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestMkdirP(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	_, rt := setupRoot(ctx, t)

750
	err := Mkdir(rt, "/a/b/c/d/e/f", MkdirOpts{Mkparents: true, Flush: true})
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
	if err != nil {
		t.Fatal(err)
	}
}

func TestConcurrentWriteAndFlush(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ds, rt := setupRoot(ctx, t)

	d := mkdirP(t, rt.GetValue().(*Directory), "foo/bar/baz")
	fn := fileNodeFromReader(t, ds, bytes.NewBuffer(nil))
	err := d.AddChild("file", fn)
	if err != nil {
		t.Fatal(err)
	}

	nloops := 5000

	wg := new(sync.WaitGroup)
	wg.Add(1)
	go func() {
		defer wg.Done()
		for i := 0; i < nloops; i++ {
			err := writeFile(rt, "/foo/bar/baz/file", []byte("STUFF"))
			if err != nil {
				t.Error("file write failed: ", err)
				return
			}
		}
	}()

	for i := 0; i < nloops; i++ {
		_, err := rt.GetValue().GetNode()
		if err != nil {
			t.Fatal(err)
		}
	}

	wg.Wait()
}

Jeromy's avatar
Jeromy committed
793 794 795 796 797 798 799 800 801 802 803
func TestFlushing(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	_, rt := setupRoot(ctx, t)

	dir := rt.GetValue().(*Directory)
	c := mkdirP(t, dir, "a/b/c")
	d := mkdirP(t, dir, "a/b/d")
	e := mkdirP(t, dir, "a/b/e")

	data := []byte("this is a test\n")
804
	nd1 := dag.NodeWithData(ft.FilePBData(data, uint64(len(data))))
Jeromy's avatar
Jeromy committed
805 806 807 808 809 810 811 812 813 814

	if err := c.AddChild("TEST", nd1); err != nil {
		t.Fatal(err)
	}
	if err := d.AddChild("TEST", nd1); err != nil {
		t.Fatal(err)
	}
	if err := e.AddChild("TEST", nd1); err != nil {
		t.Fatal(err)
	}
815 816 817
	if err := dir.AddChild("FILE", nd1); err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
818 819 820 821 822 823 824 825 826 827 828 829 830

	if err := FlushPath(rt, "/a/b/c/TEST"); err != nil {
		t.Fatal(err)
	}

	if err := FlushPath(rt, "/a/b/d/TEST"); err != nil {
		t.Fatal(err)
	}

	if err := FlushPath(rt, "/a/b/e/TEST"); err != nil {
		t.Fatal(err)
	}

831 832 833 834
	if err := FlushPath(rt, "/FILE"); err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
835 836 837 838 839
	rnd, err := dir.GetNode()
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
840 841 842 843 844 845
	pbrnd, ok := rnd.(*dag.ProtoNode)
	if !ok {
		t.Fatal(dag.ErrNotProtobuf)
	}

	fsnode, err := ft.FSNodeFromBytes(pbrnd.Data())
846 847 848 849 850 851 852 853
	if err != nil {
		t.Fatal(err)
	}

	if fsnode.Type != ft.TDirectory {
		t.Fatal("root wasnt a directory")
	}

Jeromy's avatar
Jeromy committed
854
	rnk := rnd.Cid()
855
	exp := "QmWMVyhTuyxUrXX3ynz171jq76yY3PktfY9Bxiph7b9ikr"
Jeromy's avatar
Jeromy committed
856 857
	if rnk.String() != exp {
		t.Fatalf("dag looks wrong, expected %s, but got %s", exp, rnk.String())
Jeromy's avatar
Jeromy committed
858 859
	}
}
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876

func readFile(rt *Root, path string, offset int64, buf []byte) error {
	n, err := Lookup(rt, path)
	if err != nil {
		return err
	}

	fi, ok := n.(*File)
	if !ok {
		return fmt.Errorf("%s was not a file", path)
	}

	fd, err := fi.Open(OpenReadOnly, false)
	if err != nil {
		return err
	}

877
	_, err = fd.Seek(offset, io.SeekStart)
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
	if err != nil {
		return err
	}

	nread, err := fd.Read(buf)
	if err != nil {
		return err
	}
	if nread != len(buf) {
		return fmt.Errorf("didnt read enough!")
	}

	return fd.Close()
}

func TestConcurrentReads(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	ds, rt := setupRoot(ctx, t)

	rootdir := rt.GetValue().(*Directory)

	path := "a/b/c"
	d := mkdirP(t, rootdir, path)

	buf := make([]byte, 2048)
905
	rand.Read(buf)
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937

	fi := fileNodeFromReader(t, ds, bytes.NewReader(buf))
	err := d.AddChild("afile", fi)
	if err != nil {
		t.Fatal(err)
	}

	var wg sync.WaitGroup
	nloops := 100
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(me int) {
			defer wg.Done()
			mybuf := make([]byte, len(buf))
			for j := 0; j < nloops; j++ {
				offset := rand.Intn(len(buf))
				length := rand.Intn(len(buf) - offset)

				err := readFile(rt, "/a/b/c/afile", int64(offset), mybuf[:length])
				if err != nil {
					t.Error("readfile failed: ", err)
					return
				}

				if !bytes.Equal(mybuf[:length], buf[offset:offset+length]) {
					t.Error("incorrect read!")
				}
			}
		}(i)
	}
	wg.Wait()
}
Jeromy's avatar
Jeromy committed
938

939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
func writeFile(rt *Root, path string, data []byte) error {
	n, err := Lookup(rt, path)
	if err != nil {
		return err
	}

	fi, ok := n.(*File)
	if !ok {
		return fmt.Errorf("expected to receive a file, but didnt get one")
	}

	fd, err := fi.Open(OpenWriteOnly, true)
	if err != nil {
		return err
	}
	defer fd.Close()

	nw, err := fd.Write(data)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
961 962
	if nw != len(data) {
		return fmt.Errorf("wrote incorrect amount: %d != 10", nw)
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
	}

	return nil
}

func TestConcurrentWrites(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	ds, rt := setupRoot(ctx, t)

	rootdir := rt.GetValue().(*Directory)

	path := "a/b/c"
	d := mkdirP(t, rootdir, path)

	fi := fileNodeFromReader(t, ds, bytes.NewReader(make([]byte, 0)))
	err := d.AddChild("afile", fi)
	if err != nil {
		t.Fatal(err)
	}

	var wg sync.WaitGroup
	nloops := 100
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(me int) {
			defer wg.Done()
			mybuf := bytes.Repeat([]byte{byte(me)}, 10)
			for j := 0; j < nloops; j++ {
				err := writeFile(rt, "a/b/c/afile", mybuf)
				if err != nil {
					t.Error("writefile failed: ", err)
					return
				}
			}
		}(i)
	}
	wg.Wait()
}
1003 1004 1005 1006 1007 1008 1009 1010

func TestFileDescriptors(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	ds, rt := setupRoot(ctx, t)
	dir := rt.GetValue().(*Directory)

1011
	nd := dag.NodeWithData(ft.FilePBData(nil, 0))
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
	fi, err := NewFile("test", nd, dir, ds)
	if err != nil {
		t.Fatal(err)
	}

	// test read only
	rfd1, err := fi.Open(OpenReadOnly, false)
	if err != nil {
		t.Fatal(err)
	}

	err = rfd1.Truncate(0)
	if err == nil {
		t.Fatal("shouldnt be able to truncate readonly fd")
	}

	_, err = rfd1.Write([]byte{})
	if err == nil {
		t.Fatal("shouldnt be able to write to readonly fd")
	}

	_, err = rfd1.Read([]byte{})
	if err != nil {
		t.Fatalf("expected to be able to read from file: %s", err)
	}

	done := make(chan struct{})
	go func() {
		defer close(done)
		// can open second readonly file descriptor
		rfd2, err := fi.Open(OpenReadOnly, false)
		if err != nil {
			t.Error(err)
			return
		}

		rfd2.Close()
	}()

	select {
	case <-time.After(time.Second):
		t.Fatal("open second file descriptor failed")
	case <-done:
	}

	if t.Failed() {
		return
	}

	// test not being able to open for write until reader are closed
	done = make(chan struct{})
	go func() {
		defer close(done)
		wfd1, err := fi.Open(OpenWriteOnly, true)
		if err != nil {
			t.Error(err)
		}

		wfd1.Close()
	}()

	select {
	case <-time.After(time.Millisecond * 200):
	case <-done:
		if t.Failed() {
			return
		}

		t.Fatal("shouldnt have been able to open file for writing")
	}

	err = rfd1.Close()
	if err != nil {
		t.Fatal(err)
	}

	select {
	case <-time.After(time.Second):
		t.Fatal("should have been able to open write fd after closing read fd")
	case <-done:
	}

	wfd, err := fi.Open(OpenWriteOnly, true)
	if err != nil {
		t.Fatal(err)
	}

	_, err = wfd.Read([]byte{})
	if err == nil {
		t.Fatal("shouldnt have been able to read from write only filedescriptor")
	}

	_, err = wfd.Write([]byte{})
	if err != nil {
		t.Fatal(err)
	}
}