flatfs_test.go 13.1 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"
Tommi Virtanen's avatar
Tommi Virtanen committed
5
	"io/ioutil"
6
	"math"
7
	"math/rand"
Tommi Virtanen's avatar
Tommi Virtanen committed
8 9
	"os"
	"path/filepath"
10
	"runtime"
Tommi Virtanen's avatar
Tommi Virtanen committed
11 12
	"testing"

Jeromy's avatar
Jeromy committed
13 14 15
	"github.com/ipfs/go-datastore"
	"github.com/ipfs/go-datastore/query"
	dstest "github.com/ipfs/go-datastore/test"
Jakub Sztandera's avatar
Jakub Sztandera committed
16
	"github.com/ipfs/go-ds-flatfs"
Jeromy's avatar
Jeromy committed
17

18
	randbo "github.com/dustin/randbo"
Tommi Virtanen's avatar
Tommi Virtanen committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
)

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
}

35
func tryAllShardFuncs(t *testing.T, testFunc func(string, *testing.T)) {
36 37 38
	t.Run("prefix", func(t *testing.T) { testFunc("v1/prefix", t) })
	t.Run("suffix", func(t *testing.T) { testFunc("v1/suffix", t) })
	t.Run("next-to-last", func(t *testing.T) { testFunc("v1/next-to-last", t) })
39 40
}

Tommi Virtanen's avatar
Tommi Virtanen committed
41 42 43 44
func TestPutBadValueType(t *testing.T) {
	temp, cleanup := tempdir(t)
	defer cleanup()

45
	fs, err := flatfs.CreateOrOpen(temp, "v1/prefix/2", false)
Tommi Virtanen's avatar
Tommi Virtanen committed
46 47 48 49 50 51 52 53 54 55
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}

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

56
func testPut(dirFunc string, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
57 58 59
	temp, cleanup := tempdir(t)
	defer cleanup()

60
	fs, err := flatfs.CreateOrOpen(temp, dirFunc+"/2", false)
Tommi Virtanen's avatar
Tommi Virtanen committed
61 62 63 64 65 66 67 68 69 70
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}

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

71
func TestPut(t *testing.T) { tryAllShardFuncs(t, testPut) }
72

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

77
	fs, err := flatfs.CreateOrOpen(temp, dirFunc+"/2", false)
Tommi Virtanen's avatar
Tommi Virtanen committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}

	const input = "foobar"
	err = fs.Put(datastore.NewKey("quux"), []byte(input))
	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)
	}
	buf, ok := data.([]byte)
	if !ok {
		t.Fatalf("expected []byte from Get, got %T: %v", data, data)
	}
	if g, e := string(buf), input; g != e {
		t.Fatalf("Get gave wrong content: %q != %q", g, e)
	}
}

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

103
func testPutOverwrite(dirFunc string, 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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}

	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)
	}
	if g, e := string(data.([]byte)), winner; g != e {
		t.Fatalf("Get gave wrong content: %q != %q", g, e)
	}
}

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

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

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

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

152
func TestGetNotFoundError(t *testing.T) { tryAllShardFuncs(t, testGetNotFoundError) }
153 154

type params struct {
Kevin Atkinson's avatar
Kevin Atkinson committed
155 156 157
	shard string
	dir   string
	key   string
158 159 160
}

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

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

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

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

228 229 230
func TestStorage(t *testing.T) {
	t.Run("prefix", func(t *testing.T) {
		testStorage(&params{
Kevin Atkinson's avatar
Kevin Atkinson committed
231 232 233
			shard: "v1/prefix/2",
			dir:   "qu",
			key:   "quux",
234 235 236 237
		}, t)
	})
	t.Run("suffix", func(t *testing.T) {
		testStorage(&params{
Kevin Atkinson's avatar
Kevin Atkinson committed
238 239 240
			shard: "v1/suffix/2",
			dir:   "ux",
			key:   "quux",
241 242
		}, t)
	})
243 244
	t.Run("next-to-last", func(t *testing.T) {
		testStorage(&params{
Kevin Atkinson's avatar
Kevin Atkinson committed
245 246 247
			shard: flatfs.IPFS_DEF_SHARD,
			dir:   "uu",
			key:   "quux",
248 249
		}, t)
	})
250 251
}

252
func testHasNotFound(dirFunc string, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
253 254 255
	temp, cleanup := tempdir(t)
	defer cleanup()

256
	fs, err := flatfs.CreateOrOpen(temp, dirFunc+"/2", false)
Tommi Virtanen's avatar
Tommi Virtanen committed
257 258 259 260 261 262 263 264 265 266 267 268 269
	if err != nil {
		t.Fatalf("New 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, false; g != e {
		t.Fatalf("wrong Has: %v != %v", g, e)
	}
}

270
func TestHasNotFound(t *testing.T) { tryAllShardFuncs(t, testHasNotFound) }
271

272
func testHasFound(dirFunc string, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
273 274 275
	temp, cleanup := tempdir(t)
	defer cleanup()

276
	fs, err := flatfs.CreateOrOpen(temp, dirFunc+"/2", false)
Tommi Virtanen's avatar
Tommi Virtanen committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
	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
293

294
func TestHasFound(t *testing.T) { tryAllShardFuncs(t, testHasFound) }
295

296
func testDeleteNotFound(dirFunc string, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
297 298 299
	temp, cleanup := tempdir(t)
	defer cleanup()

300
	fs, err := flatfs.CreateOrOpen(temp, dirFunc+"/2", false)
Tommi Virtanen's avatar
Tommi Virtanen committed
301 302 303 304 305 306 307 308 309 310
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}

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

311
func TestDeleteNotFound(t *testing.T) { tryAllShardFuncs(t, testDeleteNotFound) }
312

313
func testDeleteFound(dirFunc string, t *testing.T) {
Tommi Virtanen's avatar
Tommi Virtanen committed
314 315 316
	temp, cleanup := tempdir(t)
	defer cleanup()

317
	fs, err := flatfs.CreateOrOpen(temp, dirFunc+"/2", false)
Tommi Virtanen's avatar
Tommi Virtanen committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
	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)
	}
}
337

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

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

344 345 346 347 348
	err := ioutil.WriteFile(filepath.Join(temp, "README"), []byte("something"), 0666)
	if err != nil {
		t.Fatalf("WriteFile fail: %v\n", err)
	}

349
	fs, err := flatfs.CreateOrOpen(temp, dirFunc+"/2", false)
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
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}
	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
380

381
func TestQuerySimple(t *testing.T) { tryAllShardFuncs(t, testQuerySimple) }
382

383
func testBatchPut(dirFunc string, t *testing.T) {
Jeromy's avatar
Jeromy committed
384 385 386
	temp, cleanup := tempdir(t)
	defer cleanup()

387
	fs, err := flatfs.CreateOrOpen(temp, dirFunc+"/2", false)
Jeromy's avatar
Jeromy committed
388 389 390 391
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}

Jeromy's avatar
Jeromy committed
392 393
	dstest.RunBatchTest(t, fs)
}
Jeromy's avatar
Jeromy committed
394

395
func TestBatchPut(t *testing.T) { tryAllShardFuncs(t, testBatchPut) }
396

397
func testBatchDelete(dirFunc string, t *testing.T) {
Jeromy's avatar
Jeromy committed
398 399
	temp, cleanup := tempdir(t)
	defer cleanup()
Jeromy's avatar
Jeromy committed
400

401
	fs, err := flatfs.CreateOrOpen(temp, dirFunc+"/2", false)
Jeromy's avatar
Jeromy committed
402
	if err != nil {
Jeromy's avatar
Jeromy committed
403
		t.Fatalf("New fail: %v\n", err)
Jeromy's avatar
Jeromy committed
404 405
	}

Jeromy's avatar
Jeromy committed
406
	dstest.RunBatchDeleteTest(t, fs)
Jeromy's avatar
Jeromy committed
407 408
}

409
func TestBatchDelete(t *testing.T) { tryAllShardFuncs(t, testBatchDelete) }
410

411 412 413 414
func TestSHARDINGFile(t *testing.T) {
	tempdir, cleanup := tempdir(t)
	defer cleanup()

415
	fun := flatfs.IPFS_DEF_SHARD
416

417
	err := flatfs.Create(tempdir, fun)
418
	if err != nil {
419
		t.Fatalf("Create: %v\n", err)
420 421
	}

422
	fs, err := flatfs.Open(tempdir, false)
423
	if err != nil {
424
		t.Fatalf("Open fail: %v\n", err)
425
	}
426 427
	if fs.ShardFunc() != flatfs.IPFS_DEF_SHARD {
		t.Fatalf("Expected '%s' for shard function got '%s'", flatfs.IPFS_DEF_SHARD, fs.ShardFunc())
428 429 430
	}
	fs.Close()

431
	fs, err = flatfs.CreateOrOpen(tempdir, fun, false)
432 433 434 435 436
	if err != nil {
		t.Fatalf("Could not reopen repo: %v\n", err)
	}
	fs.Close()

437
	fs, err = flatfs.CreateOrOpen(tempdir, "prefix/5", false)
438 439 440 441 442
	if err == nil {
		t.Fatalf("Was able to open repo with incompatible sharding function")
	}
}

443 444 445 446 447 448 449 450 451 452
func TestInvalidPrefix(t *testing.T) {
	tempdir, cleanup := tempdir(t)
	defer cleanup()

	err := flatfs.Create(tempdir, "/bad/prefix/v1/next-to-last/2")
	if err == nil {
		t.Fatalf("Expected an error when creating a datastore with a bad prefix for the sharding function")
	}
}

453 454 455 456
func TestNoCluster(t *testing.T) {
	tempdir, cleanup := tempdir(t)
	defer cleanup()

457
	fs, err := flatfs.CreateOrOpen(tempdir, "v1/next-to-last/1", false)
458 459 460 461
	if err != nil {
		t.Fatalf("New fail: %v\n", err)
	}

462 463
	r := randbo.NewFrom(rand.NewSource(0))
	N := 3200 // should be divisible by 32 so the math works out
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
	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)
		}
	}

	dirs, err := ioutil.ReadDir(tempdir)
	if err != nil {
		t.Fatalf("ReadDir fail: %v\n", err)
	}
	idealFilesPerDir := float64(N) / 32.0
480
	tolerance := math.Floor(idealFilesPerDir * 0.20)
481
	count := 0
482
	for _, dir := range dirs {
483 484 485 486
		if dir.Name() == "SHARDING" {
			continue
		}
		count += 1
487 488 489 490 491 492 493 494 495 496
		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)
		}
	}
497 498 499
	if count != 32 {
		t.Fatalf("Expected 32 directories and one file in %s", tempdir)
	}
500 501
}

Jeromy's avatar
Jeromy committed
502
func BenchmarkConsecutivePut(b *testing.B) {
503
	r := randbo.New()
Jeromy's avatar
Jeromy committed
504 505 506 507 508 509 510 511 512 513 514 515 516
	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()

517
	fs, err := flatfs.CreateOrOpen(temp, "prefix/2", false)
Jeromy's avatar
Jeromy committed
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
	if err != nil {
		b.Fatalf("New fail: %v\n", err)
	}

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		err := fs.Put(keys[i], blocks[i])
		if err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkBatchedPut(b *testing.B) {
533
	r := randbo.New()
Jeromy's avatar
Jeromy committed
534 535 536 537 538 539 540 541 542 543 544 545 546
	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()

547
	fs, err := flatfs.CreateOrOpen(temp, "prefix/2", false)
Jeromy's avatar
Jeromy committed
548 549 550 551 552 553 554
	if err != nil {
		b.Fatalf("New fail: %v\n", err)
	}

	b.ResetTimer()

	for i := 0; i < b.N; {
Jeromy's avatar
Jeromy committed
555 556 557 558
		batch, err := fs.Batch()
		if err != nil {
			b.Fatal(err)
		}
Jeromy's avatar
Jeromy committed
559 560 561 562 563 564 565 566 567 568 569 570 571

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