server_utils.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. psConfig := server.PeerServerConfig{
  24. Name: testName,
  25. Path: path,
  26. URL: "http://"+testRaftURL,
  27. BindAddr: testRaftURL,
  28. SnapshotCount: testSnapshotCount,
  29. HeartbeatTimeout: testHeartbeatTimeout,
  30. ElectionTimeout: testElectionTimeout,
  31. MaxClusterSize: 9,
  32. }
  33. ps := server.NewPeerServer(psConfig, &server.TLSConfig{Scheme: "http"}, &server.TLSInfo{}, registry, store, nil)
  34. sConfig := server.ServerConfig{
  35. Name: testName,
  36. URL: "http://"+testClientURL,
  37. BindAddr: testClientURL,
  38. }
  39. s := server.New(sConfig, &server.TLSConfig{Scheme: "http"}, &server.TLSInfo{}, ps, registry, store, nil)
  40. ps.SetServer(s)
  41. // Start up peer server.
  42. c := make(chan bool)
  43. go func() {
  44. c <- true
  45. ps.ListenAndServe(false, []string{})
  46. }()
  47. <-c
  48. // Start up etcd server.
  49. go func() {
  50. c <- true
  51. s.ListenAndServe()
  52. }()
  53. <-c
  54. // Wait to make sure servers have started.
  55. time.Sleep(50 * time.Millisecond)
  56. // Execute the function passed in.
  57. f(s)
  58. // Clean up servers.
  59. ps.Close()
  60. s.Close()
  61. }