net_test.go 2.0 KB

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