mfs_test.go 20.1 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

	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"
21
	"github.com/ipfs/go-ipfs/path"
22 23
	ft "github.com/ipfs/go-ipfs/unixfs"
	uio "github.com/ipfs/go-ipfs/unixfs/io"
24

Steven Allen's avatar
Steven Allen committed
25 26 27
	u "gx/ipfs/QmNiJuT8Ja3hMVpBHXv3Q6dwmperaQ6JjLtpMQgMCD7xvx/go-ipfs-util"
	ds "gx/ipfs/QmPpegoMqhAEqjncrzArm7KVWAkCm78rqL2DPuNjhPrshg/go-datastore"
	dssync "gx/ipfs/QmPpegoMqhAEqjncrzArm7KVWAkCm78rqL2DPuNjhPrshg/go-datastore/sync"
28
	bstore "gx/ipfs/QmTVDM4LCSUMFNQzbDLL9zQwp8usE6QHymFdh3h8vL9v6b/go-ipfs-blockstore"
29
	chunker "gx/ipfs/QmWo8jYc19ppG7YoTsrr2kEtLRbARTJho5oNXFTR6B7Peq/go-ipfs-chunker"
Steven Allen's avatar
Steven Allen committed
30
	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
	nd, err := importer.BuildDagFromReader(ds, chunker.DefaultSplitter(r))
52 53 54 55 56 57
	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

	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)

327 328 329 330 331
	path := topd.Path()
	if path != "/foo" {
		t.Fatalf("Expected path '/foo', got '%s'", path)
	}

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 392 393 394 395 396
	// 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")
	}

397 398 399 400 401
	wfd, err := fi.Open(OpenReadWrite, true)
	if err != nil {
		t.Fatal(err)
	}

402 403
	// assert size is as expected
	size, err := fi.Size()
404 405 406
	if err != nil {
		t.Fatal(err)
	}
407 408 409 410 411 412
	if size != int64(fisize) {
		t.Fatal("size isnt correct")
	}

	// write to beginning of file
	b := []byte("THIS IS A TEST")
413
	n, err := wfd.Write(b)
414 415 416 417 418 419 420 421 422
	if err != nil {
		t.Fatal(err)
	}

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

	// sync file
423
	err = wfd.Sync()
424 425 426 427 428
	if err != nil {
		t.Fatal(err)
	}

	// make sure size hasnt changed
429
	size, err = wfd.Size()
430 431 432
	if err != nil {
		t.Fatal(err)
	}
433 434 435 436 437
	if size != int64(fisize) {
		t.Fatal("size isnt correct")
	}

	// seek back to beginning
438
	ns, err := wfd.Seek(0, io.SeekStart)
439 440 441 442 443 444 445 446 447 448
	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))
449
	n, err = wfd.Read(buf)
450 451 452 453 454 455 456 457 458 459 460 461 462
	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
463
	err = wfd.Truncate(10)
464 465 466 467
	if err != nil {
		t.Fatal(err)
	}

468
	size, err = wfd.Size()
469 470 471 472 473 474 475 476 477 478
	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")
479
	nwa, err := wfd.WriteAt(data, 5)
480 481 482 483 484 485 486 487 488
	if err != nil {
		t.Fatal(err)
	}

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

	// assert size once more
489
	size, err = wfd.Size()
490 491 492 493 494 495 496 497
	if err != nil {
		t.Fatal(err)
	}

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

498 499
	// close it out!
	err = wfd.Close()
500 501 502 503
	if err != nil {
		t.Fatal(err)
	}

504 505
	// make sure we can get node. TODO: verify it later
	_, err = fi.GetNode()
506 507 508 509
	if err != nil {
		t.Fatal(err)
	}
}
Jeromy's avatar
Jeromy committed
510 511 512

func randomWalk(d *Directory, n int) (*Directory, error) {
	for i := 0; i < n; i++ {
Jeromy's avatar
Jeromy committed
513
		dirents, err := d.List(context.Background())
Jeromy's avatar
Jeromy committed
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 553 554 555 556 557
		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()
558
	f, err := NewFile(name, dag.NodeWithData(ft.FilePBData(nil, 0)), d, d.dserv)
Jeromy's avatar
Jeromy committed
559 560 561 562
	if err != nil {
		return err
	}

563 564 565 566 567
	wfd, err := f.Open(OpenWriteOnly, true)
	if err != nil {
		return err
	}

568 569
	rread := rand.New(rand.NewSource(time.Now().UnixNano()))
	r := io.LimitReader(rread, int64(77*rand.Intn(123)))
570
	_, err = io.Copy(wfd, r)
Jeromy's avatar
Jeromy committed
571 572 573 574
	if err != nil {
		return err
	}

575
	return wfd.Close()
Jeromy's avatar
Jeromy committed
576
}
577

Jeromy's avatar
Jeromy committed
578 579 580 581 582 583 584 585
func actorMkdir(d *Directory) error {
	d, err := randomWalk(d, rand.Intn(7))
	if err != nil {
		return err
	}

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

586
	return err
Jeromy's avatar
Jeromy committed
587 588
}

589
func randomFile(d *Directory) (*File, error) {
Jeromy's avatar
Jeromy committed
590 591
	d, err := randomWalk(d, rand.Intn(6))
	if err != nil {
592
		return nil, err
Jeromy's avatar
Jeromy committed
593 594
	}

Jeromy's avatar
Jeromy committed
595
	ents, err := d.List(context.Background())
Jeromy's avatar
Jeromy committed
596
	if err != nil {
597
		return nil, err
Jeromy's avatar
Jeromy committed
598 599 600 601 602 603 604 605 606 607
	}

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

	if len(files) == 0 {
608
		return nil, nil
Jeromy's avatar
Jeromy committed
609 610 611 612 613
	}

	fname := files[rand.Intn(len(files))]
	fsn, err := d.Child(fname)
	if err != nil {
614
		return nil, err
Jeromy's avatar
Jeromy committed
615 616 617 618
	}

	fi, ok := fsn.(*File)
	if !ok {
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
		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
	}

634
	size := rand.Intn(1024) + 1
635
	buf := make([]byte, size)
636
	rand.Read(buf)
637 638 639 640 641 642

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

643 644 645 646 647
	wfd, err := fi.Open(OpenWriteOnly, true)
	if err != nil {
		return err
	}

648 649
	offset := rand.Int63n(s)

650
	n, err := wfd.WriteAt(buf, offset)
651 652 653 654 655 656 657
	if err != nil {
		return err
	}
	if n != size {
		return fmt.Errorf("didnt write enough")
	}

658
	return wfd.Close()
659 660 661 662 663 664 665 666 667
}

func actorReadFile(d *Directory) error {
	fi, err := randomFile(d)
	if err != nil {
		return err
	}
	if fi == nil {
		return nil
Jeromy's avatar
Jeromy committed
668 669 670 671 672 673 674
	}

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

675
	rfd, err := fi.Open(OpenReadOnly, false)
Jeromy's avatar
Jeromy committed
676 677 678 679
	if err != nil {
		return err
	}

680 681 682 683 684 685
	_, err = ioutil.ReadAll(rfd)
	if err != nil {
		return err
	}

	return rfd.Close()
Jeromy's avatar
Jeromy committed
686 687
}

Jeromy's avatar
Jeromy committed
688 689 690
func testActor(rt *Root, iterations int, errs chan error) {
	d := rt.GetValue().(*Directory)
	for i := 0; i < iterations; i++ {
Jeromy's avatar
Jeromy committed
691
		switch rand.Intn(5) {
Jeromy's avatar
Jeromy committed
692 693 694 695 696 697 698 699 700 701 702
		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:
703
			if err := actorWriteFile(d); err != nil {
Jeromy's avatar
Jeromy committed
704 705 706
				errs <- err
				return
			}
Jeromy's avatar
Jeromy committed
707 708 709 710 711
		case 4:
			if err := actorReadFile(d); err != nil {
				errs <- err
				return
			}
Jeromy's avatar
Jeromy committed
712 713 714 715 716 717 718 719 720 721
		}
	}
	errs <- nil
}

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

Jeromy's avatar
Jeromy committed
722
	numroutines := 10
Jeromy's avatar
Jeromy committed
723 724 725 726 727 728 729 730 731 732 733 734 735

	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
736

737 738 739 740 741
func TestMfsHugeDir(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	_, rt := setupRoot(ctx, t)

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

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

755
	err := Mkdir(rt, "/a/b/c/d/e/f", MkdirOpts{Mkparents: true, Flush: true})
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 793 794 795 796 797
	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
798 799 800 801 802 803 804 805 806 807 808
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")
809
	nd1 := dag.NodeWithData(ft.FilePBData(data, uint64(len(data))))
Jeromy's avatar
Jeromy committed
810 811 812 813 814 815 816 817 818 819

	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)
	}
820 821 822
	if err := dir.AddChild("FILE", nd1); err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
823 824 825 826 827 828 829 830 831 832 833 834 835

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

836 837 838 839
	if err := FlushPath(rt, "/FILE"); err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
840 841 842 843 844
	rnd, err := dir.GetNode()
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
845 846 847 848 849 850
	pbrnd, ok := rnd.(*dag.ProtoNode)
	if !ok {
		t.Fatal(dag.ErrNotProtobuf)
	}

	fsnode, err := ft.FSNodeFromBytes(pbrnd.Data())
851 852 853 854 855 856 857 858
	if err != nil {
		t.Fatal(err)
	}

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

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

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
	}

882
	_, err = fd.Seek(offset, io.SeekStart)
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
	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)
910
	rand.Read(buf)
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 938 939 940 941 942

	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
943

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
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
966 967
	if nw != len(data) {
		return fmt.Errorf("wrote incorrect amount: %d != 10", nw)
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 1003 1004 1005 1006 1007
	}

	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()
}
1008 1009 1010 1011 1012 1013 1014 1015

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

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

1016
	nd := dag.NodeWithData(ft.FilePBData(nil, 0))
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 1109 1110 1111 1112 1113
	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)
	}
}