flatfs_test.go 21.2 KB
Newer Older
Tommi Virtanen's avatar
Tommi Virtanen committed
1 2 3
package flatfs_test

import (
Jeromy's avatar
Jeromy committed
4
	"encoding/base32"
5
	"encoding/json"
6
	"fmt"
Tommi Virtanen's avatar
Tommi Virtanen committed
7
	"io/ioutil"
8
	"math"
9
	"math/rand"
Tommi Virtanen's avatar
Tommi Virtanen committed
10 11
	"os"
	"path/filepath"
12
	"runtime"
13 14
	"strings"
	"sync"
Tommi Virtanen's avatar
Tommi Virtanen committed
15
	"testing"
16
	"time"
Tommi Virtanen's avatar
Tommi Virtanen committed
17

Jeromy's avatar
Jeromy committed
18 19 20
	"github.com/ipfs/go-datastore"
	"github.com/ipfs/go-datastore/query"
	dstest "github.com/ipfs/go-datastore/test"
21

Jakub Sztandera's avatar
Jakub Sztandera committed
22
	"github.com/ipfs/go-ds-flatfs"
Tommi Virtanen's avatar
Tommi Virtanen committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
)

func tempdir(t testing.TB) (path string, cleanup func()) {
	path, err := ioutil.TempDir("", "test-datastore-flatfs-")
	if err != nil {
		t.Fatalf("cannot create temp directory: %v", err)
	}

	cleanup = func() {
		if err := os.RemoveAll(path); err != nil {
			t.Errorf("tempdir cleanup failed: %v", err)
		}
	}
	return path, cleanup
}

39 40 41 42
func tryAllShardFuncs(t *testing.T, testFunc func(mkShardFunc, *testing.T)) {
	t.Run("prefix", func(t *testing.T) { testFunc(flatfs.Prefix, t) })
	t.Run("suffix", func(t *testing.T) { testFunc(flatfs.Suffix, t) })
	t.Run("next-to-last", func(t *testing.T) { testFunc(flatfs.NextToLast, t) })
43 44
}

45 46 47
type mkShardFunc func(int) *flatfs.ShardIdV1

func testPut(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
48 49 50
	temp, cleanup := tempdir(t)
	defer cleanup()

51
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
52 53 54
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
55
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
56 57 58 59 60 61 62

	err = fs.Put(datastore.NewKey("quux"), []byte("foobar"))
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}
}

63
func TestPut(t *testing.T) { tryAllShardFuncs(t, testPut) }
64

65
func testGet(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
66 67 68
	temp, cleanup := tempdir(t)
	defer cleanup()

69
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
70 71 72
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
73
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
74 75 76 77 78 79 80

	const input = "foobar"
	err = fs.Put(datastore.NewKey("quux"), []byte(input))
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

81
	buf, err := fs.Get(datastore.NewKey("quux"))
Tommi Virtanen's avatar
Tommi Virtanen committed
82 83 84 85 86 87 88 89
	if err != nil {
		t.Fatalf("Get failed: %v", err)
	}
	if g, e := string(buf), input; g != e {
		t.Fatalf("Get gave wrong content: %q != %q", g, e)
	}
}

90
func TestGet(t *testing.T) { tryAllShardFuncs(t, testGet) }
91

92
func testPutOverwrite(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
93 94 95
	temp, cleanup := tempdir(t)
	defer cleanup()

96
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
97 98 99
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
100
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

	const (
		loser  = "foobar"
		winner = "xyzzy"
	)
	err = fs.Put(datastore.NewKey("quux"), []byte(loser))
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

	err = fs.Put(datastore.NewKey("quux"), []byte(winner))
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

	data, err := fs.Get(datastore.NewKey("quux"))
	if err != nil {
		t.Fatalf("Get failed: %v", err)
	}
120
	if g, e := string(data), winner; g != e {
Tommi Virtanen's avatar
Tommi Virtanen committed
121 122 123 124
		t.Fatalf("Get gave wrong content: %q != %q", g, e)
	}
}

125
func TestPutOverwrite(t *testing.T) { tryAllShardFuncs(t, testPutOverwrite) }
126

127
func testGetNotFoundError(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
128 129 130
	temp, cleanup := tempdir(t)
	defer cleanup()

131
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
132 133 134
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
135
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
136 137 138 139 140 141 142

	_, err = fs.Get(datastore.NewKey("quux"))
	if g, e := err, datastore.ErrNotFound; g != e {
		t.Fatalf("expected ErrNotFound, got: %v\n", g)
	}
}

143
func TestGetNotFoundError(t *testing.T) { tryAllShardFuncs(t, testGetNotFoundError) }
144 145

type params struct {
146
	shard *flatfs.ShardIdV1
Kevin Atkinson's avatar
Kevin Atkinson committed
147 148
	dir   string
	key   string
149 150 151
}

func testStorage(p *params, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
152 153 154
	temp, cleanup := tempdir(t)
	defer cleanup()

155
	target := p.dir + string(os.PathSeparator) + p.key + ".data"
156
	fs, err := flatfs.CreateOrOpen(temp, p.shard, false)
Tommi Virtanen's avatar
Tommi Virtanen committed
157 158 159
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
160
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
161

162
	err = fs.Put(datastore.NewKey(p.key), []byte("foobar"))
Tommi Virtanen's avatar
Tommi Virtanen committed
163 164 165 166
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

167
	fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
168
	seen := false
169
	haveREADME := false
Tommi Virtanen's avatar
Tommi Virtanen committed
170 171 172 173 174 175 176 177 178
	walk := func(absPath string, fi os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		path, err := filepath.Rel(temp, absPath)
		if err != nil {
			return err
		}
		switch path {
179
		case ".", "..", "SHARDING", flatfs.DiskUsageFile:
Tommi Virtanen's avatar
Tommi Virtanen committed
180
			// ignore
Kevin Atkinson's avatar
Kevin Atkinson committed
181
		case "_README":
182 183 184 185 186
			_, err := ioutil.ReadFile(absPath)
			if err != nil {
				t.Error("could not read _README file")
			}
			haveREADME = true
187
		case p.dir:
Tommi Virtanen's avatar
Tommi Virtanen committed
188
			if !fi.IsDir() {
Kevin Atkinson's avatar
Kevin Atkinson committed
189
				t.Errorf("directory is not a file? %v", fi.Mode())
Tommi Virtanen's avatar
Tommi Virtanen committed
190 191 192 193 194 195 196 197
			}
			// we know it's there if we see the file, nothing more to
			// do here
		case target:
			seen = true
			if !fi.Mode().IsRegular() {
				t.Errorf("expected a regular file, mode: %04o", fi.Mode())
			}
198 199 200 201
			if runtime.GOOS != "windows" {
				if g, e := fi.Mode()&os.ModePerm&0007, os.FileMode(0000); g != e {
					t.Errorf("file should not be world accessible: %04o", fi.Mode())
				}
Tommi Virtanen's avatar
Tommi Virtanen committed
202 203 204 205 206 207 208
			}
		default:
			t.Errorf("saw unexpected directory entry: %q %v", path, fi.Mode())
		}
		return nil
	}
	if err := filepath.Walk(temp, walk); err != nil {
209
		t.Fatalf("walk: %v", err)
Tommi Virtanen's avatar
Tommi Virtanen committed
210 211 212 213
	}
	if !seen {
		t.Error("did not see the data file")
	}
214
	if fs.ShardStr() == flatfs.IPFS_DEF_SHARD_STR && !haveREADME {
215
		t.Error("expected _README file")
216
	} else if fs.ShardStr() != flatfs.IPFS_DEF_SHARD_STR && haveREADME {
217 218
		t.Error("did not expect _README file")
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
219
}
Tommi Virtanen's avatar
Tommi Virtanen committed
220

221 222 223
func TestStorage(t *testing.T) {
	t.Run("prefix", func(t *testing.T) {
		testStorage(&params{
224
			shard: flatfs.Prefix(2),
Kevin Atkinson's avatar
Kevin Atkinson committed
225 226
			dir:   "qu",
			key:   "quux",
227 228 229 230
		}, t)
	})
	t.Run("suffix", func(t *testing.T) {
		testStorage(&params{
231
			shard: flatfs.Suffix(2),
Kevin Atkinson's avatar
Kevin Atkinson committed
232 233
			dir:   "ux",
			key:   "quux",
234 235
		}, t)
	})
236 237
	t.Run("next-to-last", func(t *testing.T) {
		testStorage(&params{
238
			shard: flatfs.NextToLast(2),
Kevin Atkinson's avatar
Kevin Atkinson committed
239 240
			dir:   "uu",
			key:   "quux",
241 242
		}, t)
	})
243 244
}

245
func testHasNotFound(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
246 247 248
	temp, cleanup := tempdir(t)
	defer cleanup()

249
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
250 251 252
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
253
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
254 255 256 257 258 259 260 261 262 263

	found, err := fs.Has(datastore.NewKey("quux"))
	if err != nil {
		t.Fatalf("Has fail: %v\n", err)
	}
	if g, e := found, false; g != e {
		t.Fatalf("wrong Has: %v != %v", g, e)
	}
}

264
func TestHasNotFound(t *testing.T) { tryAllShardFuncs(t, testHasNotFound) }
265

266
func testHasFound(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
267 268 269
	temp, cleanup := tempdir(t)
	defer cleanup()

270
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
271 272 273
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
274 275
	defer fs.Close()

Tommi Virtanen's avatar
Tommi Virtanen committed
276 277 278 279 280 281 282 283 284 285 286 287 288
	err = fs.Put(datastore.NewKey("quux"), []byte("foobar"))
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

	found, err := fs.Has(datastore.NewKey("quux"))
	if err != nil {
		t.Fatalf("Has fail: %v\n", err)
	}
	if g, e := found, true; g != e {
		t.Fatalf("wrong Has: %v != %v", g, e)
	}
}
Tommi Virtanen's avatar
Tommi Virtanen committed
289

290
func TestHasFound(t *testing.T) { tryAllShardFuncs(t, testHasFound) }
291

292
func testDeleteNotFound(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
293 294 295
	temp, cleanup := tempdir(t)
	defer cleanup()

296
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
297 298 299
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
300
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
301 302 303 304 305 306 307

	err = fs.Delete(datastore.NewKey("quux"))
	if g, e := err, datastore.ErrNotFound; g != e {
		t.Fatalf("expected ErrNotFound, got: %v\n", g)
	}
}

308
func TestDeleteNotFound(t *testing.T) { tryAllShardFuncs(t, testDeleteNotFound) }
309

310
func testDeleteFound(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
311 312 313
	temp, cleanup := tempdir(t)
	defer cleanup()

314
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
315 316 317
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
318 319
	defer fs.Close()

Tommi Virtanen's avatar
Tommi Virtanen committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
	err = fs.Put(datastore.NewKey("quux"), []byte("foobar"))
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

	err = fs.Delete(datastore.NewKey("quux"))
	if err != nil {
		t.Fatalf("Delete fail: %v\n", err)
	}

	// check that it's gone
	_, err = fs.Get(datastore.NewKey("quux"))
	if g, e := err, datastore.ErrNotFound; g != e {
		t.Fatalf("expected Get after Delete to give ErrNotFound, got: %v\n", g)
	}
}
336

337
func TestDeleteFound(t *testing.T) { tryAllShardFuncs(t, testDeleteFound) }
338

339
func testQuerySimple(dirFunc mkShardFunc, t *testing.T) {
340 341 342
	temp, cleanup := tempdir(t)
	defer cleanup()

343
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
344 345 346
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
347 348
	defer fs.Close()

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
	const myKey = "quux"
	err = fs.Put(datastore.NewKey(myKey), []byte("foobar"))
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

	res, err := fs.Query(query.Query{KeysOnly: true})
	if err != nil {
		t.Fatalf("Query fail: %v\n", err)
	}
	entries, err := res.Rest()
	if err != nil {
		t.Fatalf("Query Results.Rest fail: %v\n", err)
	}
	seen := false
	for _, e := range entries {
		switch e.Key {
		case datastore.NewKey(myKey).String():
			seen = true
		default:
			t.Errorf("saw unexpected key: %q", e.Key)
		}
	}
	if !seen {
		t.Errorf("did not see wanted key %q in %+v", myKey, entries)
	}
}
Jeromy's avatar
Jeromy committed
376

377
func TestQuerySimple(t *testing.T) { tryAllShardFuncs(t, testQuerySimple) }
378

379 380 381 382 383 384 385 386
func testDiskUsage(dirFunc mkShardFunc, t *testing.T) {
	temp, cleanup := tempdir(t)
	defer cleanup()

	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
387
	defer fs.Close()
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

	time.Sleep(100 * time.Millisecond)
	duNew, err := fs.DiskUsage()
	if err != nil {
		t.Fatal(err)
	}
	t.Log("duNew:", duNew)

	count := 200
	for i := 0; i < count; i++ {
		k := datastore.NewKey(fmt.Sprintf("test-%d", i))
		v := []byte("10bytes---")
		err = fs.Put(k, v)
		if err != nil {
			t.Fatalf("Put fail: %v\n", err)
		}
	}

	time.Sleep(100 * time.Millisecond)
	duElems, err := fs.DiskUsage()
	if err != nil {
		t.Fatal(err)
	}
	t.Log("duPostPut:", duElems)

	for i := 0; i < count; i++ {
		k := datastore.NewKey(fmt.Sprintf("test-%d", i))
		err = fs.Delete(k)
		if err != nil {
			t.Fatalf("Delete fail: %v\n", err)
		}
	}

	time.Sleep(100 * time.Millisecond)
	duDelete, err := fs.DiskUsage()
	if err != nil {
		t.Fatal(err)
	}
	t.Log("duPostDelete:", duDelete)

428 429 430 431
	du, err := fs.DiskUsage()
	t.Log("duFinal:", du)
	if err != nil {
		t.Fatal(err)
432
	}
433
	fs.Close()
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

	// Check that disk usage file is correct
	duB, err := ioutil.ReadFile(filepath.Join(temp, flatfs.DiskUsageFile))
	if err != nil {
		t.Fatal(err)
	}
	contents := make(map[string]interface{})
	err = json.Unmarshal(duB, &contents)
	if err != nil {
		t.Fatal(err)
	}

	// Make sure diskUsage value is correct
	if val, ok := contents["diskUsage"].(float64); !ok || uint64(val) != du {
		t.Fatalf("Unexpected value for diskUsage in %s: %v (expected %d)",
			flatfs.DiskUsageFile, contents["diskUsage"], du)
	}

	// Make sure the accuracy value is correct
	if val, ok := contents["accuracy"].(string); !ok || val != "initial-exact" {
		t.Fatalf("Unexpected value for accuracyin %s: %v",
			flatfs.DiskUsageFile, contents["accuracy"])
	}
457 458

	// Make sure size is correctly calculated on re-open
459
	os.Remove(filepath.Join(temp, flatfs.DiskUsageFile))
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
	fs, err = flatfs.Open(temp, false)
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}

	duReopen, err := fs.DiskUsage()
	if err != nil {
		t.Fatal(err)
	}
	t.Log("duReopen:", duReopen)

	// Checks
	if duNew == 0 {
		t.Error("new datastores should have some size")
	}

	if duElems <= duNew {
		t.Error("size should grow as new elements are added")
	}

	if duElems-duDelete != uint64(count*10) {
		t.Error("size should be reduced exactly as size of objects deleted")
	}

	if duReopen < duNew {
		t.Error("Reopened datastore should not be smaller")
	}
}

func TestDiskUsage(t *testing.T) {
	tryAllShardFuncs(t, testDiskUsage)
}

func TestDiskUsageDoubleCount(t *testing.T) {
	tryAllShardFuncs(t, testDiskUsageDoubleCount)
}

// test that concurrently writing and deleting the same key/value
// does not throw any errors and disk usage does not do
// any double-counting.
func testDiskUsageDoubleCount(dirFunc mkShardFunc, t *testing.T) {
	temp, cleanup := tempdir(t)
	defer cleanup()

	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
508
	defer fs.Close()
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 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580

	var count int
	var wg sync.WaitGroup
	testKey := datastore.NewKey("test")

	put := func() {
		defer wg.Done()
		for i := 0; i < count; i++ {
			v := []byte("10bytes---")
			err := fs.Put(testKey, v)
			if err != nil {
				t.Fatalf("Put fail: %v\n", err)
			}
		}
	}

	del := func() {
		defer wg.Done()
		for i := 0; i < count; i++ {
			err := fs.Delete(testKey)
			if err != nil && !strings.Contains(err.Error(), "key not found") {
				t.Fatalf("Delete fail: %v\n", err)
			}
		}
	}

	// Add one element and then remove it and check disk usage
	// makes sense
	count = 1
	wg.Add(2)
	put()
	du, _ := fs.DiskUsage()
	del()
	du2, _ := fs.DiskUsage()
	if du-10 != du2 {
		t.Error("should have deleted exactly 10 bytes:", du, du2)
	}

	// Add and remove many times at the same time
	count = 200
	wg.Add(4)
	go put()
	go del()
	go put()
	go del()
	wg.Wait()

	du3, _ := fs.DiskUsage()
	has, err := fs.Has(testKey)
	if err != nil {
		t.Fatal(err)
	}

	if has { // put came last
		if du3 != du {
			t.Error("du should be the same as after first put:", du, du3)
		}
	} else { //delete came last
		if du3 != du2 {
			t.Error("du should be the same as after first delete:", du2, du3)
		}
	}
}

func testDiskUsageBatch(dirFunc mkShardFunc, t *testing.T) {
	temp, cleanup := tempdir(t)
	defer cleanup()

	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
581
	defer fs.Close()
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662

	fsBatch, _ := fs.Batch()

	count := 200
	var wg sync.WaitGroup
	testKeys := []datastore.Key{}
	for i := 0; i < count; i++ {
		k := datastore.NewKey(fmt.Sprintf("test%d", i))
		testKeys = append(testKeys, k)
	}

	put := func() {
		for i := 0; i < count; i++ {
			fsBatch.Put(testKeys[i], []byte("10bytes---"))
		}
	}
	commit := func() {
		defer wg.Done()
		err := fsBatch.Commit()
		if err != nil {
			t.Fatalf("Batch Put fail: %v\n", err)
		}
	}

	del := func() {
		defer wg.Done()
		for _, k := range testKeys {
			err := fs.Delete(k)
			if err != nil && !strings.Contains(err.Error(), "key not found") {
				t.Fatalf("Delete fail: %v\n", err)
			}
		}
	}

	// Put many elements and then delete them and check disk usage
	// makes sense
	wg.Add(2)
	put()
	commit()
	du, _ := fs.DiskUsage()
	del()
	du2, _ := fs.DiskUsage()
	if du-uint64(10*count) != du2 {
		t.Errorf("should have deleted exactly %d bytes: %d %d", 10*count, du, du2)
	}

	// Do deletes while doing putManys concurrently
	wg.Add(2)
	put()
	go commit()
	go del()
	wg.Wait()

	du3, _ := fs.DiskUsage()
	// Now query how many keys we have
	results, err := fs.Query(query.Query{
		KeysOnly: true,
	})
	rest, err := results.Rest()
	if err != nil {
		t.Fatal(err)
	}

	expectedSize := uint64(len(rest) * 10)

	if exp := du2 + expectedSize; exp != du3 {
		t.Error("diskUsage has skewed off from real size:",
			exp, du3)
	}
}

func TestDiskUsageBatch(t *testing.T) { tryAllShardFuncs(t, testDiskUsageBatch) }

func testDiskUsageEstimation(dirFunc mkShardFunc, t *testing.T) {
	temp, cleanup := tempdir(t)
	defer cleanup()

	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
663
	defer fs.Close()
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714

	count := 50000
	for i := 0; i < count; i++ {
		k := datastore.NewKey(fmt.Sprintf("%d-test-%d", i, i))
		v := make([]byte, 1000)
		err = fs.Put(k, v)
		if err != nil {
			t.Fatalf("Put fail: %v\n", err)
		}
	}

	// Delete checkpoint
	fs.Close()
	os.Remove(filepath.Join(temp, flatfs.DiskUsageFile))

	// This will do a full du
	flatfs.DiskUsageFilesAverage = -1
	fs, err = flatfs.Open(temp, false)
	if err != nil {
		t.Fatalf("Open fail: %v\n", err)
	}

	duReopen, err := fs.DiskUsage()
	if err != nil {
		t.Fatal(err)
	}

	fs.Close()
	os.Remove(filepath.Join(temp, flatfs.DiskUsageFile))

	// This will estimate the size. Since all files are the same
	// length we can use a low file average number.
	flatfs.DiskUsageFilesAverage = 100
	// Make sure size is correctly calculated on re-open
	fs, err = flatfs.Open(temp, false)
	if err != nil {
		t.Fatalf("Open fail: %v\n", err)
	}

	duEst, err := fs.DiskUsage()
	if err != nil {
		t.Fatal(err)
	}

	t.Log("RealDu:", duReopen)
	t.Log("Est:", duEst)

	diff := int(math.Abs(float64(int(duReopen) - int(duEst))))
	maxDiff := int(0.05 * float64(duReopen)) // %5 of actual

	if diff > maxDiff {
715
		t.Fatalf("expected a better estimation within 5%%")
716
	}
717 718 719 720 721

	// Make sure the accuracy value is correct
	if fs.Accuracy() != "initial-approximate" {
		t.Errorf("Unexpected value for fs.Accuracy(): %s", fs.Accuracy())
	}
722 723 724 725 726 727 728 729 730 731 732 733 734

	fs.Close()

	// Reopen into a new variable
	fs2, err := flatfs.Open(temp, false)
	if err != nil {
		t.Fatalf("Open fail: %v\n", err)
	}

	// Make sure the accuracy value is preserved
	if fs2.Accuracy() != "initial-approximate" {
		t.Errorf("Unexpected value for fs.Accuracy(): %s", fs2.Accuracy())
	}
735 736 737 738
}

func TestDiskUsageEstimation(t *testing.T) { tryAllShardFuncs(t, testDiskUsageEstimation) }

739
func testBatchPut(dirFunc mkShardFunc, t *testing.T) {
Jeromy's avatar
Jeromy committed
740 741 742
	temp, cleanup := tempdir(t)
	defer cleanup()

743
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Jeromy's avatar
Jeromy committed
744 745 746
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
747
	defer fs.Close()
Jeromy's avatar
Jeromy committed
748

Jeromy's avatar
Jeromy committed
749 750
	dstest.RunBatchTest(t, fs)
}
Jeromy's avatar
Jeromy committed
751

752
func TestBatchPut(t *testing.T) { tryAllShardFuncs(t, testBatchPut) }
753

754
func testBatchDelete(dirFunc mkShardFunc, t *testing.T) {
Jeromy's avatar
Jeromy committed
755 756
	temp, cleanup := tempdir(t)
	defer cleanup()
Jeromy's avatar
Jeromy committed
757

758
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Jeromy's avatar
Jeromy committed
759
	if err != nil {
Jeromy's avatar
Jeromy committed
760
		t.Fatalf("New fail: %v\n", err)
Jeromy's avatar
Jeromy committed
761
	}
762
	defer fs.Close()
Jeromy's avatar
Jeromy committed
763

Jeromy's avatar
Jeromy committed
764
	dstest.RunBatchDeleteTest(t, fs)
Jeromy's avatar
Jeromy committed
765 766
}

767
func TestBatchDelete(t *testing.T) { tryAllShardFuncs(t, testBatchDelete) }
768

769 770 771 772
func TestSHARDINGFile(t *testing.T) {
	tempdir, cleanup := tempdir(t)
	defer cleanup()

773
	fun := flatfs.IPFS_DEF_SHARD
774

775
	err := flatfs.Create(tempdir, fun)
776
	if err != nil {
777
		t.Fatalf("Create: %v\n", err)
778 779
	}

780
	fs, err := flatfs.Open(tempdir, false)
781
	if err != nil {
782
		t.Fatalf("Open fail: %v\n", err)
783
	}
784 785
	if fs.ShardStr() != flatfs.IPFS_DEF_SHARD_STR {
		t.Fatalf("Expected '%s' for shard function got '%s'", flatfs.IPFS_DEF_SHARD_STR, fs.ShardStr())
786 787 788
	}
	fs.Close()

789
	fs, err = flatfs.CreateOrOpen(tempdir, fun, false)
790 791 792 793 794
	if err != nil {
		t.Fatalf("Could not reopen repo: %v\n", err)
	}
	fs.Close()

795
	fs, err = flatfs.CreateOrOpen(tempdir, flatfs.Prefix(5), false)
796 797 798 799 800
	if err == nil {
		t.Fatalf("Was able to open repo with incompatible sharding function")
	}
}

801
func TestInvalidPrefix(t *testing.T) {
802
	_, err := flatfs.ParseShardFunc("/bad/prefix/v1/next-to-last/2")
803
	if err == nil {
804
		t.Fatalf("Expected an error while parsing a shard identifier with a bad prefix")
805 806 807
	}
}

808 809 810 811 812 813
func TestNonDatastoreDir(t *testing.T) {
	tempdir, cleanup := tempdir(t)
	defer cleanup()

	ioutil.WriteFile(filepath.Join(tempdir, "afile"), []byte("Some Content"), 0644)

814
	err := flatfs.Create(tempdir, flatfs.NextToLast(2))
815 816 817 818 819
	if err == nil {
		t.Fatalf("Expected an error when creating a datastore in a non-empty directory")
	}
}

820 821 822 823
func TestNoCluster(t *testing.T) {
	tempdir, cleanup := tempdir(t)
	defer cleanup()

824
	fs, err := flatfs.CreateOrOpen(tempdir, flatfs.NextToLast(1), false)
825 826 827
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
828
	defer fs.Close()
829

830
	r := rand.New(rand.NewSource(0))
831
	N := 3200 // should be divisible by 32 so the math works out
832 833 834 835 836 837 838 839 840 841 842
	for i := 0; i < N; i++ {
		blk := make([]byte, 1000)
		r.Read(blk)

		key := "CIQ" + base32.StdEncoding.EncodeToString(blk[:10])
		err := fs.Put(datastore.NewKey(key), blk)
		if err != nil {
			t.Fatalf("Put fail: %v\n", err)
		}
	}

Kevin Atkinson's avatar
Kevin Atkinson committed
843
	fs.Close()
844 845 846 847 848
	dirs, err := ioutil.ReadDir(tempdir)
	if err != nil {
		t.Fatalf("ReadDir fail: %v\n", err)
	}
	idealFilesPerDir := float64(N) / 32.0
849
	tolerance := math.Floor(idealFilesPerDir * 0.25)
850
	count := 0
851
	for _, dir := range dirs {
852 853 854
		if dir.Name() == flatfs.SHARDING_FN ||
			dir.Name() == flatfs.README_FN ||
			dir.Name() == flatfs.DiskUsageFile {
855 856 857
			continue
		}
		count += 1
858 859 860 861 862 863 864 865 866 867
		files, err := ioutil.ReadDir(filepath.Join(tempdir, dir.Name()))
		if err != nil {
			t.Fatalf("ReadDir fail: %v\n", err)
		}
		num := float64(len(files))
		if math.Abs(num-idealFilesPerDir) > tolerance {
			t.Fatalf("Dir %s has %.0f files, expected between %.f and %.f files",
				filepath.Join(tempdir, dir.Name()), num, idealFilesPerDir-tolerance, idealFilesPerDir+tolerance)
		}
	}
868 869 870
	if count != 32 {
		t.Fatalf("Expected 32 directories and one file in %s", tempdir)
	}
871 872
}

Jeromy's avatar
Jeromy committed
873
func BenchmarkConsecutivePut(b *testing.B) {
874
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
Jeromy's avatar
Jeromy committed
875 876 877 878 879 880 881 882 883 884 885 886 887
	var blocks [][]byte
	var keys []datastore.Key
	for i := 0; i < b.N; i++ {
		blk := make([]byte, 256*1024)
		r.Read(blk)
		blocks = append(blocks, blk)

		key := base32.StdEncoding.EncodeToString(blk[:8])
		keys = append(keys, datastore.NewKey(key))
	}
	temp, cleanup := tempdir(b)
	defer cleanup()

888
	fs, err := flatfs.CreateOrOpen(temp, flatfs.Prefix(2), false)
Jeromy's avatar
Jeromy committed
889 890 891
	if err != nil {
		b.Fatalf("New fail: %v\n", err)
	}
892
	defer fs.Close()
Jeromy's avatar
Jeromy committed
893 894 895 896 897 898 899 900 901

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		err := fs.Put(keys[i], blocks[i])
		if err != nil {
			b.Fatal(err)
		}
	}
902
	b.StopTimer() // avoid counting cleanup
Jeromy's avatar
Jeromy committed
903 904 905
}

func BenchmarkBatchedPut(b *testing.B) {
906
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
Jeromy's avatar
Jeromy committed
907 908 909 910 911 912 913 914 915 916 917 918 919
	var blocks [][]byte
	var keys []datastore.Key
	for i := 0; i < b.N; i++ {
		blk := make([]byte, 256*1024)
		r.Read(blk)
		blocks = append(blocks, blk)

		key := base32.StdEncoding.EncodeToString(blk[:8])
		keys = append(keys, datastore.NewKey(key))
	}
	temp, cleanup := tempdir(b)
	defer cleanup()

920
	fs, err := flatfs.CreateOrOpen(temp, flatfs.Prefix(2), false)
Jeromy's avatar
Jeromy committed
921 922 923
	if err != nil {
		b.Fatalf("New fail: %v\n", err)
	}
924
	defer fs.Close()
Jeromy's avatar
Jeromy committed
925 926 927 928

	b.ResetTimer()

	for i := 0; i < b.N; {
Jeromy's avatar
Jeromy committed
929 930 931 932
		batch, err := fs.Batch()
		if err != nil {
			b.Fatal(err)
		}
Jeromy's avatar
Jeromy committed
933 934 935 936 937 938 939 940 941 942 943 944

		for n := i; i-n < 512 && i < b.N; i++ {
			err := batch.Put(keys[i], blocks[i])
			if err != nil {
				b.Fatal(err)
			}
		}
		err = batch.Commit()
		if err != nil {
			b.Fatal(err)
		}
	}
945
	b.StopTimer() // avoid counting cleanup
Jeromy's avatar
Jeromy committed
946
}