flatfs_test.go 24.5 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
	"github.com/ipfs/go-datastore"
19
	"github.com/ipfs/go-datastore/mount"
Jeromy's avatar
Jeromy committed
20 21
	"github.com/ipfs/go-datastore/query"
	dstest "github.com/ipfs/go-datastore/test"
22

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

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
}

40 41 42 43
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) })
44 45
}

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

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

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

58
	err = fs.Put(datastore.NewKey("QUUX"), []byte("foobar"))
Tommi Virtanen's avatar
Tommi Virtanen committed
59 60 61
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}
62 63 64 65 66

	err = fs.Put(datastore.NewKey("foo"), []byte("nonono"))
	if err == nil {
		t.Fatalf("did not expect to put a lowercase key")
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
67 68
}

69
func TestPut(t *testing.T) { tryAllShardFuncs(t, testPut) }
70

71
func testGet(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
72 73 74
	temp, cleanup := tempdir(t)
	defer cleanup()

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

	const input = "foobar"
82
	err = fs.Put(datastore.NewKey("QUUX"), []byte(input))
Tommi Virtanen's avatar
Tommi Virtanen committed
83 84 85 86
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

87
	buf, err := fs.Get(datastore.NewKey("QUUX"))
Tommi Virtanen's avatar
Tommi Virtanen committed
88 89 90 91 92 93
	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)
	}
94 95 96 97 98

	_, err = fs.Get(datastore.NewKey("/FOO/BAR"))
	if err != datastore.ErrNotFound {
		t.Fatalf("expected ErrNotFound, got %s", err)
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
99 100
}

101
func TestGet(t *testing.T) { tryAllShardFuncs(t, testGet) }
102

103
func testPutOverwrite(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
104 105 106
	temp, cleanup := tempdir(t)
	defer cleanup()

107
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
108 109 110
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
111
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
112 113 114 115 116

	const (
		loser  = "foobar"
		winner = "xyzzy"
	)
117
	err = fs.Put(datastore.NewKey("QUUX"), []byte(loser))
Tommi Virtanen's avatar
Tommi Virtanen committed
118 119 120 121
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

122
	err = fs.Put(datastore.NewKey("QUUX"), []byte(winner))
Tommi Virtanen's avatar
Tommi Virtanen committed
123 124 125 126
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

127
	data, err := fs.Get(datastore.NewKey("QUUX"))
Tommi Virtanen's avatar
Tommi Virtanen committed
128 129 130
	if err != nil {
		t.Fatalf("Get failed: %v", err)
	}
131
	if g, e := string(data), winner; g != e {
Tommi Virtanen's avatar
Tommi Virtanen committed
132 133 134 135
		t.Fatalf("Get gave wrong content: %q != %q", g, e)
	}
}

136
func TestPutOverwrite(t *testing.T) { tryAllShardFuncs(t, testPutOverwrite) }
137

138
func testGetNotFoundError(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
139 140 141
	temp, cleanup := tempdir(t)
	defer cleanup()

142
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
143 144 145
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
146
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
147

148
	_, err = fs.Get(datastore.NewKey("QUUX"))
Tommi Virtanen's avatar
Tommi Virtanen committed
149 150 151 152 153
	if g, e := err, datastore.ErrNotFound; g != e {
		t.Fatalf("expected ErrNotFound, got: %v\n", g)
	}
}

154
func TestGetNotFoundError(t *testing.T) { tryAllShardFuncs(t, testGetNotFoundError) }
155 156

type params struct {
157
	shard *flatfs.ShardIdV1
Kevin Atkinson's avatar
Kevin Atkinson committed
158 159
	dir   string
	key   string
160 161 162
}

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

166
	target := p.dir + string(os.PathSeparator) + p.key + ".data"
167
	fs, err := flatfs.CreateOrOpen(temp, p.shard, false)
Tommi Virtanen's avatar
Tommi Virtanen committed
168 169 170
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
171
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
172

173
	err = fs.Put(datastore.NewKey(p.key), []byte("foobar"))
Tommi Virtanen's avatar
Tommi Virtanen committed
174 175 176 177
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

178
	fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
179
	seen := false
180
	haveREADME := false
Tommi Virtanen's avatar
Tommi Virtanen committed
181 182 183 184 185 186 187 188 189
	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 {
190
		case ".", "..", "SHARDING", flatfs.DiskUsageFile:
Tommi Virtanen's avatar
Tommi Virtanen committed
191
			// ignore
Kevin Atkinson's avatar
Kevin Atkinson committed
192
		case "_README":
193 194 195 196 197
			_, err := ioutil.ReadFile(absPath)
			if err != nil {
				t.Error("could not read _README file")
			}
			haveREADME = true
198
		case p.dir:
Tommi Virtanen's avatar
Tommi Virtanen committed
199
			if !fi.IsDir() {
Kevin Atkinson's avatar
Kevin Atkinson committed
200
				t.Errorf("directory is not a file? %v", fi.Mode())
Tommi Virtanen's avatar
Tommi Virtanen committed
201 202 203 204 205 206 207 208
			}
			// 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())
			}
209 210 211 212
			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
213 214 215 216 217 218 219
			}
		default:
			t.Errorf("saw unexpected directory entry: %q %v", path, fi.Mode())
		}
		return nil
	}
	if err := filepath.Walk(temp, walk); err != nil {
220
		t.Fatalf("walk: %v", err)
Tommi Virtanen's avatar
Tommi Virtanen committed
221 222 223 224
	}
	if !seen {
		t.Error("did not see the data file")
	}
225
	if fs.ShardStr() == flatfs.IPFS_DEF_SHARD_STR && !haveREADME {
226
		t.Error("expected _README file")
227
	} else if fs.ShardStr() != flatfs.IPFS_DEF_SHARD_STR && haveREADME {
228 229
		t.Error("did not expect _README file")
	}
Tommi Virtanen's avatar
Tommi Virtanen committed
230
}
Tommi Virtanen's avatar
Tommi Virtanen committed
231

232 233 234
func TestStorage(t *testing.T) {
	t.Run("prefix", func(t *testing.T) {
		testStorage(&params{
235
			shard: flatfs.Prefix(2),
236 237
			dir:   "QU",
			key:   "QUUX",
238 239 240 241
		}, t)
	})
	t.Run("suffix", func(t *testing.T) {
		testStorage(&params{
242
			shard: flatfs.Suffix(2),
243 244
			dir:   "UX",
			key:   "QUUX",
245 246
		}, t)
	})
247 248
	t.Run("next-to-last", func(t *testing.T) {
		testStorage(&params{
249
			shard: flatfs.NextToLast(2),
250 251
			dir:   "UU",
			key:   "QUUX",
252 253
		}, t)
	})
254 255
}

256
func testHasNotFound(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
257 258 259
	temp, cleanup := tempdir(t)
	defer cleanup()

260
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
261 262 263
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
264
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
265

266
	found, err := fs.Has(datastore.NewKey("QUUX"))
Tommi Virtanen's avatar
Tommi Virtanen committed
267 268 269
	if err != nil {
		t.Fatalf("Has fail: %v\n", err)
	}
Steven Allen's avatar
Steven Allen committed
270 271
	if found {
		t.Fatal("Has should have returned false")
Tommi Virtanen's avatar
Tommi Virtanen committed
272 273 274
	}
}

275
func TestHasNotFound(t *testing.T) { tryAllShardFuncs(t, testHasNotFound) }
276

277
func testHasFound(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
278 279 280
	temp, cleanup := tempdir(t)
	defer cleanup()

281
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
282 283 284
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
285 286
	defer fs.Close()

287
	err = fs.Put(datastore.NewKey("QUUX"), []byte("foobar"))
Tommi Virtanen's avatar
Tommi Virtanen committed
288 289 290 291
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

292
	found, err := fs.Has(datastore.NewKey("QUUX"))
Tommi Virtanen's avatar
Tommi Virtanen committed
293 294 295
	if err != nil {
		t.Fatalf("Has fail: %v\n", err)
	}
Steven Allen's avatar
Steven Allen committed
296 297
	if !found {
		t.Fatal("Has should have returned true")
Tommi Virtanen's avatar
Tommi Virtanen committed
298 299
	}
}
Tommi Virtanen's avatar
Tommi Virtanen committed
300

301
func TestHasFound(t *testing.T) { tryAllShardFuncs(t, testHasFound) }
302

Steven Allen's avatar
Steven Allen committed
303 304 305 306 307 308 309 310 311 312
func testGetSizeFound(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)
	}
	defer fs.Close()

313
	_, err = fs.GetSize(datastore.NewKey("QUUX"))
Steven Allen's avatar
Steven Allen committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
	if err != datastore.ErrNotFound {
		t.Fatalf("GetSize should have returned ErrNotFound, got: %v\n", err)
	}
}

func TestGetSizeFound(t *testing.T) { tryAllShardFuncs(t, testGetSizeFound) }

func testGetSizeNotFound(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)
	}
	defer fs.Close()

331
	err = fs.Put(datastore.NewKey("QUUX"), []byte("foobar"))
Steven Allen's avatar
Steven Allen committed
332 333 334 335
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

336
	size, err := fs.GetSize(datastore.NewKey("QUUX"))
Steven Allen's avatar
Steven Allen committed
337 338 339 340 341 342 343 344 345 346
	if err != nil {
		t.Fatalf("GetSize failed with: %v\n", err)
	}
	if size != len("foobar") {
		t.Fatalf("GetSize returned wrong size: got %d, expected %d", size, len("foobar"))
	}
}

func TestGetSizeNotFound(t *testing.T) { tryAllShardFuncs(t, testGetSizeNotFound) }

347
func testDeleteNotFound(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
348 349 350
	temp, cleanup := tempdir(t)
	defer cleanup()

351
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
352 353 354
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
355
	defer fs.Close()
Tommi Virtanen's avatar
Tommi Virtanen committed
356

357
	err = fs.Delete(datastore.NewKey("QUUX"))
Steven Allen's avatar
Steven Allen committed
358 359
	if err != nil {
		t.Fatalf("expected nil, got: %v\n", err)
Tommi Virtanen's avatar
Tommi Virtanen committed
360 361 362
	}
}

363
func TestDeleteNotFound(t *testing.T) { tryAllShardFuncs(t, testDeleteNotFound) }
364

365
func testDeleteFound(dirFunc mkShardFunc, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
366 367 368
	temp, cleanup := tempdir(t)
	defer cleanup()

369
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Tommi Virtanen's avatar
Tommi Virtanen committed
370 371 372
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
373 374
	defer fs.Close()

375
	err = fs.Put(datastore.NewKey("QUUX"), []byte("foobar"))
Tommi Virtanen's avatar
Tommi Virtanen committed
376 377 378 379
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

380
	err = fs.Delete(datastore.NewKey("QUUX"))
Tommi Virtanen's avatar
Tommi Virtanen committed
381 382 383 384 385
	if err != nil {
		t.Fatalf("Delete fail: %v\n", err)
	}

	// check that it's gone
386
	_, err = fs.Get(datastore.NewKey("QUUX"))
Tommi Virtanen's avatar
Tommi Virtanen committed
387 388 389 390
	if g, e := err, datastore.ErrNotFound; g != e {
		t.Fatalf("expected Get after Delete to give ErrNotFound, got: %v\n", g)
	}
}
391

392
func TestDeleteFound(t *testing.T) { tryAllShardFuncs(t, testDeleteFound) }
393

394
func testQuerySimple(dirFunc mkShardFunc, t *testing.T) {
395 396 397
	temp, cleanup := tempdir(t)
	defer cleanup()

398
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
399 400 401
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
402 403
	defer fs.Close()

404
	const myKey = "QUUX"
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
	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
431

432
func TestQuerySimple(t *testing.T) { tryAllShardFuncs(t, testQuerySimple) }
433

434 435 436 437 438 439 440 441
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)
	}
442
	defer fs.Close()
443 444 445 446 447 448 449 450 451 452

	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++ {
453
		k := datastore.NewKey(fmt.Sprintf("TEST-%d", i))
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
		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++ {
469
		k := datastore.NewKey(fmt.Sprintf("TEST-%d", i))
470 471 472 473 474 475 476 477 478 479 480 481 482
		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)

483 484 485 486
	du, err := fs.DiskUsage()
	t.Log("duFinal:", du)
	if err != nil {
		t.Fatal(err)
487
	}
488
	fs.Close()
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511

	// 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"])
	}
512 513

	// Make sure size is correctly calculated on re-open
514
	os.Remove(filepath.Join(temp, flatfs.DiskUsageFile))
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
	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)
	}
563
	defer fs.Close()
564 565 566

	var count int
	var wg sync.WaitGroup
567
	testKey := datastore.NewKey("TEST")
568 569 570 571 572 573 574

	put := func() {
		defer wg.Done()
		for i := 0; i < count; i++ {
			v := []byte("10bytes---")
			err := fs.Put(testKey, v)
			if err != nil {
Steven Allen's avatar
Steven Allen committed
575
				t.Errorf("Put fail: %v\n", err)
576 577 578 579 580 581 582 583 584
			}
		}
	}

	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") {
Steven Allen's avatar
Steven Allen committed
585
				t.Errorf("Delete fail: %v\n", err)
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
			}
		}
	}

	// 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)
	}
636
	defer fs.Close()
637

Steven Allen's avatar
Steven Allen committed
638 639 640 641
	fsBatch, err := fs.Batch()
	if err != nil {
		t.Fatal(err)
	}
642 643 644 645 646

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

	put := func() {
		for i := 0; i < count; i++ {
Steven Allen's avatar
Steven Allen committed
653 654 655 656
			err := fsBatch.Put(testKeys[i], []byte("10bytes---"))
			if err != nil {
				t.Error(err)
			}
657 658 659 660 661 662
		}
	}
	commit := func() {
		defer wg.Done()
		err := fsBatch.Commit()
		if err != nil {
Steven Allen's avatar
Steven Allen committed
663
			t.Errorf("Batch Put fail: %v\n", err)
664 665 666 667 668 669 670 671
		}
	}

	del := func() {
		defer wg.Done()
		for _, k := range testKeys {
			err := fs.Delete(k)
			if err != nil && !strings.Contains(err.Error(), "key not found") {
Steven Allen's avatar
Steven Allen committed
672
				t.Errorf("Delete fail: %v\n", err)
673 674 675 676 677 678 679 680 681
			}
		}
	}

	// Put many elements and then delete them and check disk usage
	// makes sense
	wg.Add(2)
	put()
	commit()
Steven Allen's avatar
Steven Allen committed
682 683 684 685
	du, err := fs.DiskUsage()
	if err != nil {
		t.Fatal(err)
	}
686
	del()
Steven Allen's avatar
Steven Allen committed
687 688 689 690
	du2, err := fs.DiskUsage()
	if err != nil {
		t.Fatal(err)
	}
691 692 693 694 695 696 697 698 699 700 701
	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()

Steven Allen's avatar
Steven Allen committed
702 703 704 705
	du3, err := fs.DiskUsage()
	if err != nil {
		t.Fatal(err)
	}
706 707 708 709
	// Now query how many keys we have
	results, err := fs.Query(query.Query{
		KeysOnly: true,
	})
Steven Allen's avatar
Steven Allen committed
710 711 712
	if err != nil {
		t.Fatal(err)
	}
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
	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)
	}
736
	defer fs.Close()
737 738 739

	count := 50000
	for i := 0; i < count; i++ {
740
		k := datastore.NewKey(fmt.Sprintf("%d-TEST-%d", i, i))
741 742 743 744 745 746 747 748 749 750 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
		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 {
788
		t.Fatalf("expected a better estimation within 5%%")
789
	}
790 791 792 793 794

	// Make sure the accuracy value is correct
	if fs.Accuracy() != "initial-approximate" {
		t.Errorf("Unexpected value for fs.Accuracy(): %s", fs.Accuracy())
	}
795 796 797 798 799 800 801 802 803 804 805 806 807

	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())
	}
808 809 810 811
}

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

812
func testBatchPut(dirFunc mkShardFunc, t *testing.T) {
Jeromy's avatar
Jeromy committed
813 814 815
	temp, cleanup := tempdir(t)
	defer cleanup()

816
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Jeromy's avatar
Jeromy committed
817 818 819
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
820
	defer fs.Close()
Jeromy's avatar
Jeromy committed
821

Jeromy's avatar
Jeromy committed
822 823
	dstest.RunBatchTest(t, fs)
}
Jeromy's avatar
Jeromy committed
824

825
func TestBatchPut(t *testing.T) { tryAllShardFuncs(t, testBatchPut) }
826

827
func testBatchDelete(dirFunc mkShardFunc, t *testing.T) {
Jeromy's avatar
Jeromy committed
828 829
	temp, cleanup := tempdir(t)
	defer cleanup()
Jeromy's avatar
Jeromy committed
830

831
	fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
Jeromy's avatar
Jeromy committed
832
	if err != nil {
Jeromy's avatar
Jeromy committed
833
		t.Fatalf("New fail: %v\n", err)
Jeromy's avatar
Jeromy committed
834
	}
835
	defer fs.Close()
Jeromy's avatar
Jeromy committed
836

Jeromy's avatar
Jeromy committed
837
	dstest.RunBatchDeleteTest(t, fs)
Jeromy's avatar
Jeromy committed
838 839
}

840
func TestBatchDelete(t *testing.T) { tryAllShardFuncs(t, testBatchDelete) }
841

Steven Allen's avatar
Steven Allen committed
842 843 844 845 846 847 848 849 850
func testClose(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)
	}

851
	err = fs.Put(datastore.NewKey("QUUX"), []byte("foobar"))
Steven Allen's avatar
Steven Allen committed
852 853 854 855 856 857
	if err != nil {
		t.Fatalf("Put fail: %v\n", err)
	}

	fs.Close()

858
	err = fs.Put(datastore.NewKey("QAAX"), []byte("foobar"))
Steven Allen's avatar
Steven Allen committed
859 860 861 862 863 864 865
	if err == nil {
		t.Fatal("expected put on closed datastore to fail")
	}
}

func TestClose(t *testing.T) { tryAllShardFuncs(t, testClose) }

866 867 868 869
func TestSHARDINGFile(t *testing.T) {
	tempdir, cleanup := tempdir(t)
	defer cleanup()

870
	fun := flatfs.IPFS_DEF_SHARD
871

872
	err := flatfs.Create(tempdir, fun)
873
	if err != nil {
874
		t.Fatalf("Create: %v\n", err)
875 876
	}

877
	fs, err := flatfs.Open(tempdir, false)
878
	if err != nil {
879
		t.Fatalf("Open fail: %v\n", err)
880
	}
881 882
	if fs.ShardStr() != flatfs.IPFS_DEF_SHARD_STR {
		t.Fatalf("Expected '%s' for shard function got '%s'", flatfs.IPFS_DEF_SHARD_STR, fs.ShardStr())
883 884 885
	}
	fs.Close()

886
	fs, err = flatfs.CreateOrOpen(tempdir, fun, false)
887 888 889 890 891
	if err != nil {
		t.Fatalf("Could not reopen repo: %v\n", err)
	}
	fs.Close()

892
	fs, err = flatfs.CreateOrOpen(tempdir, flatfs.Prefix(5), false)
893
	if err == nil {
Steven Allen's avatar
Steven Allen committed
894
		fs.Close()
895 896 897 898
		t.Fatalf("Was able to open repo with incompatible sharding function")
	}
}

899
func TestInvalidPrefix(t *testing.T) {
900
	_, err := flatfs.ParseShardFunc("/bad/prefix/v1/next-to-last/2")
901
	if err == nil {
902
		t.Fatalf("Expected an error while parsing a shard identifier with a bad prefix")
903 904 905
	}
}

906 907 908 909
func TestNonDatastoreDir(t *testing.T) {
	tempdir, cleanup := tempdir(t)
	defer cleanup()

Steven Allen's avatar
Steven Allen committed
910 911 912 913
	err := ioutil.WriteFile(filepath.Join(tempdir, "afile"), []byte("Some Content"), 0644)
	if err != nil {
		t.Fatal(err)
	}
914

Steven Allen's avatar
Steven Allen committed
915
	err = flatfs.Create(tempdir, flatfs.NextToLast(2))
916 917 918 919 920
	if err == nil {
		t.Fatalf("Expected an error when creating a datastore in a non-empty directory")
	}
}

921 922 923 924
func TestNoCluster(t *testing.T) {
	tempdir, cleanup := tempdir(t)
	defer cleanup()

925
	fs, err := flatfs.CreateOrOpen(tempdir, flatfs.NextToLast(1), false)
926 927 928
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
929
	defer fs.Close()
930

931
	r := rand.New(rand.NewSource(0))
932
	N := 3200 // should be divisible by 32 so the math works out
933 934 935 936 937 938 939 940 941 942 943
	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
944
	fs.Close()
945 946 947 948 949
	dirs, err := ioutil.ReadDir(tempdir)
	if err != nil {
		t.Fatalf("ReadDir fail: %v\n", err)
	}
	idealFilesPerDir := float64(N) / 32.0
950
	tolerance := math.Floor(idealFilesPerDir * 0.25)
951
	count := 0
952
	for _, dir := range dirs {
953 954 955
		if dir.Name() == flatfs.SHARDING_FN ||
			dir.Name() == flatfs.README_FN ||
			dir.Name() == flatfs.DiskUsageFile {
956 957 958
			continue
		}
		count += 1
959 960 961 962 963 964 965 966 967 968
		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)
		}
	}
969 970 971
	if count != 32 {
		t.Fatalf("Expected 32 directories and one file in %s", tempdir)
	}
972 973
}

Jeromy's avatar
Jeromy committed
974
func BenchmarkConsecutivePut(b *testing.B) {
975
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
Jeromy's avatar
Jeromy committed
976 977 978 979 980 981 982 983 984 985 986 987 988
	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()

989
	fs, err := flatfs.CreateOrOpen(temp, flatfs.Prefix(2), false)
Jeromy's avatar
Jeromy committed
990 991 992
	if err != nil {
		b.Fatalf("New fail: %v\n", err)
	}
993
	defer fs.Close()
Jeromy's avatar
Jeromy committed
994 995 996 997 998 999 1000 1001 1002

	b.ResetTimer()

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

func BenchmarkBatchedPut(b *testing.B) {
1007
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
Jeromy's avatar
Jeromy committed
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
	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()

1021
	fs, err := flatfs.CreateOrOpen(temp, flatfs.Prefix(2), false)
Jeromy's avatar
Jeromy committed
1022 1023 1024
	if err != nil {
		b.Fatalf("New fail: %v\n", err)
	}
1025
	defer fs.Close()
Jeromy's avatar
Jeromy committed
1026 1027 1028 1029

	b.ResetTimer()

	for i := 0; i < b.N; {
Jeromy's avatar
Jeromy committed
1030 1031 1032 1033
		batch, err := fs.Batch()
		if err != nil {
			b.Fatal(err)
		}
Jeromy's avatar
Jeromy committed
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

		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)
		}
	}
1046
	b.StopTimer() // avoid counting cleanup
Jeromy's avatar
Jeromy committed
1047
}
Steven Allen's avatar
Steven Allen committed
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

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

	fs, err := flatfs.CreateOrOpen(temp, flatfs.Prefix(2), false)
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
	defer fs.Close()

	for i := 0; i < 1000; i++ {
		err = fs.Put(datastore.NewKey(fmt.Sprint(i)), []byte("foobar"))
		if err != nil {
			t.Fatalf("Put fail: %v\n", err)
		}
	}

	before := runtime.NumGoroutine()
	for i := 0; i < 200; i++ {
		res, err := fs.Query(query.Query{KeysOnly: true})
		if err != nil {
			t.Errorf("Query fail: %v\n", err)
		}
		res.Close()
	}
	after := runtime.NumGoroutine()
	if after-before > 100 {
		t.Errorf("leaked %d goroutines", after-before)
	}
}
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

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

	fs, err := flatfs.CreateOrOpen(temp, flatfs.Prefix(2), false)
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}

	ds := mount.New([]mount.Mount{{
		Prefix:    datastore.RawKey("/"),
		Datastore: datastore.NewMapDatastore(),
	}, {
		Prefix:    datastore.RawKey("/capital"),
		Datastore: fs,
	}})
	defer func() {
		err := ds.Close()
		if err != nil {
			t.Error(err)
		}
	}()

	dstest.SubtestAll(t, ds)
}