net_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package chord_test
  2. import (
  3. "fmt"
  4. "testing"
  5. "time"
  6. "trial/chord"
  7. )
  8. func prepRing(port int) (*chord.Config, *chord.TCPTransport, error) {
  9. listen := fmt.Sprintf("localhost:%d", port)
  10. conf := chord.DefaultConfig(listen)
  11. conf.StabilizeMin = time.Duration(15 * time.Millisecond)
  12. conf.StabilizeMax = time.Duration(45 * time.Millisecond)
  13. timeout := time.Duration(20 * time.Millisecond)
  14. trans, err := chord.InitTCPTransport(listen, timeout)
  15. if err != nil {
  16. return nil, nil, err
  17. }
  18. return conf, trans, nil
  19. }
  20. func TestTCPJoin(t *testing.T) {
  21. // Prepare to create 2 nodes
  22. c1, t1, err := prepRing(10025)
  23. if err != nil {
  24. t.Fatalf("unexpected err. %s", err)
  25. }
  26. c2, t2, err := prepRing(10026)
  27. if err != nil {
  28. t.Fatalf("unexpected err. %s", err)
  29. }
  30. // Create initial ring
  31. r1, err := chord.Create(c1, t1)
  32. if err != nil {
  33. t.Fatalf("unexpected err. %s", err)
  34. }
  35. // Join ring
  36. r2, err := chord.Join(c2, t2, c1.Hostname)
  37. if err != nil {
  38. t.Fatalf("failed to join local node! Got %s", err)
  39. }
  40. // Shutdown
  41. r1.Shutdown()
  42. r2.Shutdown()
  43. t1.Shutdown()
  44. t2.Shutdown()
  45. }
  46. func TestTCPLeave(t *testing.T) {
  47. // Prepare to create 2 nodes
  48. c1, t1, err := prepRing(10027)
  49. if err != nil {
  50. t.Fatalf("unexpected err. %s", err)
  51. }
  52. c2, t2, err := prepRing(10028)
  53. if err != nil {
  54. t.Fatalf("unexpected err. %s", err)
  55. }
  56. // Create initial ring
  57. r1, err := chord.Create(c1, t1)
  58. if err != nil {
  59. t.Fatalf("unexpected err. %s", err)
  60. }
  61. // Join ring
  62. r2, err := chord.Join(c2, t2, c1.Hostname)
  63. if err != nil {
  64. t.Fatalf("failed to join local node! Got %s", err)
  65. }
  66. // Wait for some stabilization
  67. <-time.After(100 * time.Millisecond)
  68. // Node 1 should leave
  69. r1.Leave()
  70. t1.Shutdown()
  71. // Wait for stabilization
  72. <-time.After(100 * time.Millisecond)
  73. // Verify r2 ring is still in tact
  74. for _, vn := range r2.Vnodes {
  75. if vn.Successors[0].Host != r2.Config.Hostname {
  76. t.Fatalf("bad successor! Got:%s:%s", vn.Successors[0].Host,
  77. vn.Successors[0])
  78. }
  79. }
  80. }