server_utils.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package tests
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "time"
  6. "github.com/coreos/etcd/server"
  7. "github.com/coreos/etcd/store"
  8. )
  9. const (
  10. testName = "ETCDTEST"
  11. testClientURL = "localhost:4401"
  12. testRaftURL = "localhost:7701"
  13. testSnapshotCount = 10000
  14. testHeartbeatTimeout = time.Duration(50) * time.Millisecond
  15. testElectionTimeout = time.Duration(200) * time.Millisecond
  16. )
  17. // Starts a server in a temporary directory.
  18. func RunServer(f func(*server.Server)) {
  19. path, _ := ioutil.TempDir("", "etcd-")
  20. defer os.RemoveAll(path)
  21. store := store.New()
  22. registry := server.NewRegistry(store)
  23. corsInfo, _ := server.NewCORSInfo([]string{})
  24. psConfig := server.PeerServerConfig{
  25. Name: testName,
  26. Path: path,
  27. URL: "http://"+testRaftURL,
  28. BindAddr: testRaftURL,
  29. SnapshotCount: testSnapshotCount,
  30. HeartbeatTimeout: testHeartbeatTimeout,
  31. ElectionTimeout: testElectionTimeout,
  32. MaxClusterSize: 9,
  33. CORS: corsInfo,
  34. }
  35. ps := server.NewPeerServer(psConfig, &server.TLSConfig{Scheme: "http"}, &server.TLSInfo{}, registry, store, nil)
  36. sConfig := server.ServerConfig{
  37. Name: testName,
  38. URL: "http://"+testClientURL,
  39. CORS: corsInfo,
  40. }
  41. s := server.New(sConfig, ps, registry, store, nil)
  42. sListener, err := server.NewListener(testClientURL)
  43. if err != nil {
  44. panic(err)
  45. }
  46. ps.SetServer(s)
  47. // Start up peer server.
  48. c := make(chan bool)
  49. go func() {
  50. c <- true
  51. ps.ListenAndServe(false, []string{})
  52. }()
  53. <-c
  54. // Start up etcd server.
  55. go func() {
  56. c <- true
  57. s.Serve(sListener)
  58. }()
  59. <-c
  60. // Wait to make sure servers have started.
  61. time.Sleep(50 * time.Millisecond)
  62. // Execute the function passed in.
  63. f(s)
  64. // Clean up servers.
  65. ps.Close()
  66. s.Close()
  67. }