ipns_test.go 11.5 KB
Newer Older
1 2
// +build !nofuse

3 4 5
package ipns

import (
6
	"bytes"
Jeromy's avatar
Jeromy committed
7
	"fmt"
8
	"io/ioutil"
Jeromy's avatar
Jeromy committed
9
	mrand "math/rand"
10
	"os"
Jeromy's avatar
Jeromy committed
11
	"sync"
12 13
	"testing"

14 15
	fstest "github.com/ipfs/go-ipfs/Godeps/_workspace/src/bazil.org/fuse/fs/fstestutil"
	racedet "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-detect-race"
16

17 18 19
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	core "github.com/ipfs/go-ipfs/core"
	nsfs "github.com/ipfs/go-ipfs/ipnsfs"
Jeromy's avatar
Jeromy committed
20 21
	namesys "github.com/ipfs/go-ipfs/namesys"
	offroute "github.com/ipfs/go-ipfs/routing/offline"
22
	u "github.com/ipfs/go-ipfs/util"
23
	ci "github.com/ipfs/go-ipfs/util/testutil/ci"
24 25
)

26 27 28
func maybeSkipFuseTests(t *testing.T) {
	if ci.NoFuse() {
		t.Skip("Skipping FUSE tests")
29 30 31
	}
}

32 33
func randBytes(size int) []byte {
	b := make([]byte, size)
34
	u.NewTimeSeededRand().Read(b)
35 36 37
	return b
}

Jeromy's avatar
Jeromy committed
38 39 40 41 42 43 44
func mkdir(t *testing.T, path string) {
	err := os.Mkdir(path, os.ModeDir)
	if err != nil {
		t.Fatal(err)
	}
}

Jeromy's avatar
Jeromy committed
45
func writeFile(t *testing.T, size int, path string) []byte {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47 48 49
	return writeFileData(t, randBytes(size), path)
}

func writeFileData(t *testing.T, data []byte, path string) []byte {
Jeromy's avatar
Jeromy committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
	fi, err := os.Create(path)
	if err != nil {
		t.Fatal(err)
	}

	n, err := fi.Write(data)
	if err != nil {
		t.Fatal(err)
	}

	if n != len(data) {
		t.Fatal("Didnt write proper amount!")
	}

	err = fi.Close()
65 66 67 68
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
69
	return data
Jeromy's avatar
Jeromy committed
70 71
}

72 73
func verifyFile(t *testing.T, path string, wantData []byte) {
	isData, err := ioutil.ReadFile(path)
Jeromy's avatar
Jeromy committed
74 75 76
	if err != nil {
		t.Fatal(err)
	}
77 78 79 80 81
	if len(isData) != len(wantData) {
		t.Fatal("Data not equal - length check failed")
	}
	if !bytes.Equal(isData, wantData) {
		t.Fatal("Data not equal")
Jeromy's avatar
Jeromy committed
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
	}
}

func checkExists(t *testing.T, path string) {
	_, err := os.Stat(path)
	if err != nil {
		t.Fatal(err)
	}
}

func closeMount(mnt *fstest.Mount) {
	if err := recover(); err != nil {
		log.Error("Recovered panic")
		log.Error(err)
	}
	mnt.Close()
}

Jeromy's avatar
Jeromy committed
100
func setupIpnsTest(t *testing.T, node *core.IpfsNode) (*core.IpfsNode, *fstest.Mount) {
101 102
	maybeSkipFuseTests(t)

Jeromy's avatar
Jeromy committed
103 104
	var err error
	if node == nil {
Jeromy's avatar
Jeromy committed
105
		node, err = core.NewNode(context.Background(), nil)
Jeromy's avatar
Jeromy committed
106 107 108
		if err != nil {
			t.Fatal(err)
		}
Jeromy's avatar
Jeromy committed
109

Jeromy's avatar
Jeromy committed
110 111 112 113 114 115
		err = node.LoadPrivateKey()
		if err != nil {
			t.Fatal(err)
		}

		node.Routing = offroute.NewOfflineRouter(node.Repo.Datastore(), node.PrivateKey)
116
		node.Namesys = namesys.NewNameSystem(node.Routing, node.Repo.Datastore())
Jeromy's avatar
Jeromy committed
117

118
		ipnsfs, err := nsfs.NewFilesystem(context.Background(), node.DAG, node.Namesys, node.Pinning, node.PrivateKey)
Jeromy's avatar
Jeromy committed
119 120 121 122 123
		if err != nil {
			t.Fatal(err)
		}

		node.IpnsFs = ipnsfs
Jeromy's avatar
Jeromy committed
124 125
	}

126
	fs, err := NewFileSystem(node, node.PrivateKey, "", "")
127 128 129 130 131 132 133
	if err != nil {
		t.Fatal(err)
	}
	mnt, err := fstest.MountedT(t, fs)
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
134 135 136 137

	return node, mnt
}

Jeromy's avatar
Jeromy committed
138
func TestIpnsLocalLink(t *testing.T) {
139
	nd, mnt := setupIpnsTest(t, nil)
Jeromy's avatar
Jeromy committed
140 141 142
	defer mnt.Close()
	name := mnt.Dir + "/local"

143 144 145 146 147 148
	_, err := os.Stat(name)
	if err != nil {
		t.Fatal(err)
	}

	linksto, err := os.Readlink(name)
Jeromy's avatar
Jeromy committed
149 150 151 152
	if err != nil {
		t.Fatal(err)
	}

153 154 155
	if linksto != nd.Identity.Pretty() {
		t.Fatal("Link invalid")
	}
Jeromy's avatar
Jeromy committed
156 157
}

158
// Test writing a file and reading it back
Jeromy's avatar
Jeromy committed
159
func TestIpnsBasicIO(t *testing.T) {
160 161 162
	if testing.Short() {
		t.SkipNow()
	}
Jeromy's avatar
Jeromy committed
163
	_, mnt := setupIpnsTest(t, nil)
Jeromy's avatar
Jeromy committed
164
	defer closeMount(mnt)
165

Jeromy's avatar
Jeromy committed
166
	fname := mnt.Dir + "/local/testfile"
Jeromy's avatar
Jeromy committed
167
	data := writeFile(t, 10, fname)
168

Jeromy's avatar
Jeromy committed
169
	rbuf, err := ioutil.ReadFile(fname)
170 171 172 173
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
174 175
	if !bytes.Equal(rbuf, data) {
		t.Fatal("Incorrect Read!")
176
	}
Jeromy's avatar
Jeromy committed
177
}
178

179
// Test to make sure file changes persist over mounts of ipns
Jeromy's avatar
Jeromy committed
180
func TestFilePersistence(t *testing.T) {
181 182 183
	if testing.Short() {
		t.SkipNow()
	}
Jeromy's avatar
Jeromy committed
184
	node, mnt := setupIpnsTest(t, nil)
185

Jeromy's avatar
Jeromy committed
186
	fname := "/local/atestfile"
Jeromy's avatar
Jeromy committed
187
	data := writeFile(t, 127, mnt.Dir+fname)
188

Jeromy's avatar
Jeromy committed
189 190
	mnt.Close()

Jeromy's avatar
Jeromy committed
191
	t.Log("Closed, opening new fs")
Jeromy's avatar
Jeromy committed
192 193 194 195
	node, mnt = setupIpnsTest(t, node)
	defer mnt.Close()

	rbuf, err := ioutil.ReadFile(mnt.Dir + fname)
196 197 198 199
	if err != nil {
		t.Fatal(err)
	}

200
	if !bytes.Equal(rbuf, data) {
Jeromy's avatar
Jeromy committed
201
		t.Fatalf("File data changed between mounts! sizes differ: %d != %d", len(data), len(rbuf))
202 203
	}
}
Jeromy's avatar
Jeromy committed
204

205
func TestMultipleDirs(t *testing.T) {
Jeromy's avatar
Jeromy committed
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
	node, mnt := setupIpnsTest(t, nil)

	t.Log("make a top level dir")
	dir1 := "/local/test1"
	mkdir(t, mnt.Dir+dir1)

	checkExists(t, mnt.Dir+dir1)

	t.Log("write a file in it")
	data1 := writeFile(t, 4000, mnt.Dir+dir1+"/file1")

	verifyFile(t, mnt.Dir+dir1+"/file1", data1)

	t.Log("sub directory")
	mkdir(t, mnt.Dir+dir1+"/dir2")

	checkExists(t, mnt.Dir+dir1+"/dir2")

	t.Log("file in that subdirectory")
	data2 := writeFile(t, 5000, mnt.Dir+dir1+"/dir2/file2")

	verifyFile(t, mnt.Dir+dir1+"/dir2/file2", data2)

	mnt.Close()
	t.Log("closing mount, then restarting")

	_, mnt = setupIpnsTest(t, node)

	checkExists(t, mnt.Dir+dir1)

	verifyFile(t, mnt.Dir+dir1+"/file1", data1)

	verifyFile(t, mnt.Dir+dir1+"/dir2/file2", data2)
	mnt.Close()
}

242
// Test to make sure the filesystem reports file sizes correctly
Jeromy's avatar
Jeromy committed
243
func TestFileSizeReporting(t *testing.T) {
244 245 246
	if testing.Short() {
		t.SkipNow()
	}
Jeromy's avatar
Jeromy committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
	_, mnt := setupIpnsTest(t, nil)
	defer mnt.Close()

	fname := mnt.Dir + "/local/sizecheck"
	data := writeFile(t, 5555, fname)

	finfo, err := os.Stat(fname)
	if err != nil {
		t.Fatal(err)
	}

	if finfo.Size() != int64(len(data)) {
		t.Fatal("Read incorrect size from stat!")
	}
}
262 263 264

// Test to make sure you cant create multiple entries with the same name
func TestDoubleEntryFailure(t *testing.T) {
265 266 267
	if testing.Short() {
		t.SkipNow()
	}
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
	_, mnt := setupIpnsTest(t, nil)
	defer mnt.Close()

	dname := mnt.Dir + "/local/thisisadir"
	err := os.Mkdir(dname, 0777)
	if err != nil {
		t.Fatal(err)
	}

	err = os.Mkdir(dname, 0777)
	if err == nil {
		t.Fatal("Should have gotten error one creating new directory.")
	}
}

func TestAppendFile(t *testing.T) {
284 285 286
	if testing.Short() {
		t.SkipNow()
	}
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
	_, mnt := setupIpnsTest(t, nil)
	defer mnt.Close()

	fname := mnt.Dir + "/local/file"
	data := writeFile(t, 1300, fname)

	fi, err := os.OpenFile(fname, os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		t.Fatal(err)
	}

	nudata := randBytes(500)

	n, err := fi.Write(nudata)
	if err != nil {
		t.Fatal(err)
	}
	err = fi.Close()
	if err != nil {
		t.Fatal(err)
	}

	if n != len(nudata) {
		t.Fatal("Failed to write enough bytes.")
	}

	data = append(data, nudata...)

	rbuf, err := ioutil.ReadFile(fname)
	if err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(rbuf, data) {
		t.Fatal("Data inconsistent!")
	}
}

Jeromy's avatar
Jeromy committed
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
func TestConcurrentWrites(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	_, mnt := setupIpnsTest(t, nil)
	defer mnt.Close()

	nactors := 4
	filesPerActor := 400
	fileSize := 2000

	data := make([][][]byte, nactors)

	if racedet.WithRace() {
		nactors = 2
		filesPerActor = 50
	}

	wg := sync.WaitGroup{}
	for i := 0; i < nactors; i++ {
		data[i] = make([][]byte, filesPerActor)
		wg.Add(1)
		go func(n int) {
			defer wg.Done()
			for j := 0; j < filesPerActor; j++ {
				out := writeFile(t, fileSize, mnt.Dir+fmt.Sprintf("/local/%dFILE%d", n, j))
				data[n][j] = out
			}
		}(i)
	}
	wg.Wait()

	for i := 0; i < nactors; i++ {
		for j := 0; j < filesPerActor; j++ {
			verifyFile(t, mnt.Dir+fmt.Sprintf("/local/%dFILE%d", i, j), data[i][j])
		}
	}
}

func TestFSThrash(t *testing.T) {
	files := make(map[string][]byte)

	if testing.Short() {
		t.SkipNow()
	}
	_, mnt := setupIpnsTest(t, nil)
	defer mnt.Close()

	base := mnt.Dir + "/local"
	dirs := []string{base}
	dirlock := sync.RWMutex{}
	filelock := sync.Mutex{}

	ndirWorkers := 2
	nfileWorkers := 2

	ndirs := 100
	nfiles := 200

	wg := sync.WaitGroup{}

	// Spawn off workers to make directories
	for i := 0; i < ndirWorkers; i++ {
		wg.Add(1)
		go func(worker int) {
			defer wg.Done()
			for j := 0; j < ndirs; j++ {
				dirlock.RLock()
				n := mrand.Intn(len(dirs))
				dir := dirs[n]
				dirlock.RUnlock()

				newDir := fmt.Sprintf("%s/dir%d-%d", dir, worker, j)
				err := os.Mkdir(newDir, os.ModeDir)
				if err != nil {
					t.Fatal(err)
				}
				dirlock.Lock()
				dirs = append(dirs, newDir)
				dirlock.Unlock()
			}
		}(i)
	}

	// Spawn off workers to make files
	for i := 0; i < nfileWorkers; i++ {
		wg.Add(1)
		go func(worker int) {
			defer wg.Done()
			for j := 0; j < nfiles; j++ {
				dirlock.RLock()
				n := mrand.Intn(len(dirs))
				dir := dirs[n]
				dirlock.RUnlock()

				newFileName := fmt.Sprintf("%s/file%d-%d", dir, worker, j)

				data := writeFile(t, 2000+mrand.Intn(5000), newFileName)
				filelock.Lock()
				files[newFileName] = data
				filelock.Unlock()
			}
		}(i)
	}

	wg.Wait()
	for name, data := range files {
		out, err := ioutil.ReadFile(name)
		if err != nil {
			t.Fatal(err)
		}

		if !bytes.Equal(data, out) {
			t.Fatal("Data didnt match")
		}
	}
}

/*
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
443
func TestFastRepublish(t *testing.T) {
444 445 446
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
447 448 449 450 451 452 453 454 455 456

	// make timeout noticeable.
	osrt := shortRepublishTimeout
	shortRepublishTimeout = time.Millisecond * 100

	olrt := longRepublishTimeout
	longRepublishTimeout = time.Second

	node, mnt := setupIpnsTest(t, nil)

457
	h, err := node.PrivateKey.GetPublic().Hash()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
458 459 460
	if err != nil {
		t.Fatal(err)
	}
461
	pubkeyPath := "/ipns/" + u.Key(h).String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478

	// set them back
	defer func() {
		shortRepublishTimeout = osrt
		longRepublishTimeout = olrt
		mnt.Close()
	}()

	closed := make(chan struct{})
	dataA := []byte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	dataB := []byte("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")

	fname := mnt.Dir + "/local/file"

	// get first resolved hash
	log.Debug("publishing first hash")
	writeFileData(t, dataA, fname) // random
479
	<-time.After(shortRepublishTimeout * 2)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
480
	log.Debug("resolving first hash")
481
	resolvedHash, err := node.Namesys.Resolve(context.Background(), pubkeyPath)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
482
	if err != nil {
483
		t.Fatal("resolve err:", pubkeyPath, err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
484 485 486
	}

	// constantly keep writing to the file
Brian Tiger Chow's avatar
Brian Tiger Chow committed
487
	go func(timeout time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
488 489 490 491 492
		for {
			select {
			case <-closed:
				return

Brian Tiger Chow's avatar
Brian Tiger Chow committed
493
			case <-time.After(timeout * 8 / 10):
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
494 495 496
				writeFileData(t, dataB, fname)
			}
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
497
	}(shortRepublishTimeout)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
498 499

	hasPublished := func() bool {
500
		res, err := node.Namesys.Resolve(context.Background(), pubkeyPath)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
501
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
502
			t.Fatalf("resolve err: %v", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
503 504 505 506 507 508 509 510 511
		}
		return res != resolvedHash
	}

	// test things

	// at this point, should not have written dataA and not have written dataB
	rbuf, err := ioutil.ReadFile(fname)
	if err != nil || !bytes.Equal(rbuf, dataA) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
512
		t.Fatalf("Data inconsistent! %v %v", err, string(rbuf))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
513 514 515 516 517 518 519 520 521 522 523
	}

	if hasPublished() {
		t.Fatal("published (wrote)")
	}

	<-time.After(shortRepublishTimeout * 11 / 10)

	// at this point, should have written written dataB, but not published it
	rbuf, err = ioutil.ReadFile(fname)
	if err != nil || !bytes.Equal(rbuf, dataB) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
524
		t.Fatalf("Data inconsistent! %v %v", err, string(rbuf))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
525 526 527 528 529 530 531 532 533 534 535
	}

	if hasPublished() {
		t.Fatal("published (wrote)")
	}

	<-time.After(longRepublishTimeout * 11 / 10)

	// at this point, should have written written dataB, and published it
	rbuf, err = ioutil.ReadFile(fname)
	if err != nil || !bytes.Equal(rbuf, dataB) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
536
		t.Fatalf("Data inconsistent! %v %v", err, string(rbuf))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
537 538 539 540 541 542 543 544
	}

	if !hasPublished() {
		t.Fatal("not published")
	}

	close(closed)
}
Jeromy's avatar
Jeromy committed
545
*/
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
546

547 548
// Test writing a medium sized file one byte at a time
func TestMultiWrite(t *testing.T) {
Jeromy's avatar
Jeromy committed
549

550 551 552
	if testing.Short() {
		t.SkipNow()
	}
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 581 582 583
	_, mnt := setupIpnsTest(t, nil)
	defer mnt.Close()

	fpath := mnt.Dir + "/local/file"
	fi, err := os.Create(fpath)
	if err != nil {
		t.Fatal(err)
	}

	data := randBytes(1001)
	for i := 0; i < len(data); i++ {
		n, err := fi.Write(data[i : i+1])
		if err != nil {
			t.Fatal(err)
		}
		if n != 1 {
			t.Fatal("Somehow wrote the wrong number of bytes! (n != 1)")
		}
	}
	fi.Close()

	rbuf, err := ioutil.ReadFile(fpath)
	if err != nil {
		t.Fatal(err)
	}

	if !bytes.Equal(rbuf, data) {
		t.Fatal("File on disk did not match bytes written")
	}
}