etcd.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /*
  2. Copyright 2014 CoreOS Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package etcd
  14. import (
  15. "crypto/tls"
  16. "fmt"
  17. "log"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "sync"
  23. "time"
  24. "github.com/coreos/etcd/config"
  25. )
  26. const (
  27. participantMode int64 = iota
  28. standbyMode
  29. stopMode
  30. )
  31. type Server struct {
  32. config *config.Config
  33. id int64
  34. pubAddr string
  35. raftPubAddr string
  36. tickDuration time.Duration
  37. mode atomicInt
  38. p *participant
  39. s *standby
  40. client *v2client
  41. peerHub *peerHub
  42. stopped bool
  43. mu sync.Mutex
  44. stopc chan struct{}
  45. log *log.Logger
  46. http.Handler
  47. }
  48. func New(c *config.Config) (*Server, error) {
  49. if err := c.Sanitize(); err != nil {
  50. log.Fatalf("server.new sanitizeErr=\"%v\"\n", err)
  51. }
  52. tc := &tls.Config{
  53. InsecureSkipVerify: true,
  54. }
  55. var err error
  56. if c.PeerTLSInfo().Scheme() == "https" {
  57. tc, err = c.PeerTLSInfo().ClientConfig()
  58. if err != nil {
  59. log.Fatalf("server.new ClientConfigErr=\"%v\"\n", err)
  60. }
  61. }
  62. tr := new(http.Transport)
  63. tr.TLSClientConfig = tc
  64. tr.Dial = (&net.Dialer{Timeout: 200 * time.Millisecond}).Dial
  65. tr.TLSHandshakeTimeout = 10 * time.Second
  66. tr.ResponseHeaderTimeout = defaultTickDuration * defaultHeartbeat
  67. client := &http.Client{Transport: tr}
  68. s := &Server{
  69. config: c,
  70. id: genId(),
  71. pubAddr: c.Addr,
  72. raftPubAddr: c.Peer.Addr,
  73. tickDuration: defaultTickDuration,
  74. mode: atomicInt(stopMode),
  75. client: newClient(tc),
  76. peerHub: newPeerHub(client),
  77. stopc: make(chan struct{}),
  78. }
  79. m := http.NewServeMux()
  80. m.HandleFunc("/", s.requestHandler)
  81. m.HandleFunc("/version", versionHandler)
  82. s.Handler = m
  83. log.Printf("id=%x server.new raftPubAddr=%s\n", s.id, s.raftPubAddr)
  84. if err = os.MkdirAll(s.config.DataDir, 0700); err != nil {
  85. if !os.IsExist(err) {
  86. return nil, err
  87. }
  88. }
  89. return s, nil
  90. }
  91. func (s *Server) SetTick(tick time.Duration) {
  92. s.tickDuration = tick
  93. log.Printf("id=%x server.setTick tick=%q\n", s.id, s.tickDuration)
  94. }
  95. // Stop stops the server elegently.
  96. func (s *Server) Stop() {
  97. s.mu.Lock()
  98. s.stopped = true
  99. switch s.mode.Get() {
  100. case participantMode:
  101. s.p.stop()
  102. case standbyMode:
  103. s.s.stop()
  104. }
  105. s.mu.Unlock()
  106. <-s.stopc
  107. s.client.CloseConnections()
  108. s.peerHub.stop()
  109. log.Printf("id=%x server.stop\n", s.id)
  110. }
  111. func (s *Server) requestHandler(w http.ResponseWriter, r *http.Request) {
  112. switch s.mode.Get() {
  113. case participantMode:
  114. s.p.ServeHTTP(w, r)
  115. case standbyMode:
  116. s.s.ServeHTTP(w, r)
  117. default:
  118. http.NotFound(w, r)
  119. }
  120. }
  121. func (s *Server) RaftHandler() http.Handler {
  122. return http.HandlerFunc(s.ServeRaftHTTP)
  123. }
  124. func (s *Server) ServeRaftHTTP(w http.ResponseWriter, r *http.Request) {
  125. switch s.mode.Get() {
  126. case participantMode:
  127. s.p.raftHandler().ServeHTTP(w, r)
  128. default:
  129. http.NotFound(w, r)
  130. }
  131. }
  132. func (s *Server) Run() error {
  133. var d *discoverer
  134. var seeds []string
  135. durl := s.config.Discovery
  136. if durl != "" {
  137. u, err := url.Parse(durl)
  138. if err != nil {
  139. return fmt.Errorf("bad discovery URL error: %v", err)
  140. }
  141. d = newDiscoverer(u, fmt.Sprint(s.id), s.raftPubAddr)
  142. if seeds, err = d.discover(); err != nil {
  143. return err
  144. }
  145. log.Printf("id=%x server.run source=-discovery seeds=\"%v\"\n", s.id, seeds)
  146. } else {
  147. seeds = s.config.Peers
  148. log.Printf("id=%x server.run source=-peers seeds=\"%v\"\n", s.id, seeds)
  149. }
  150. s.peerHub.setSeeds(seeds)
  151. next := participantMode
  152. for {
  153. s.mu.Lock()
  154. if s.stopped {
  155. next = stopMode
  156. }
  157. switch next {
  158. case participantMode:
  159. p, err := newParticipant(s.id, s.pubAddr, s.raftPubAddr, s.config.DataDir, s.client, s.peerHub, s.tickDuration)
  160. if err != nil {
  161. log.Printf("id=%x server.run newParicipanteErr=\"%v\"\n", s.id, err)
  162. return err
  163. }
  164. s.p = p
  165. dStopc := make(chan struct{})
  166. if d != nil {
  167. go d.heartbeat(dStopc)
  168. }
  169. s.mode.Set(participantMode)
  170. log.Printf("id=%x server.run mode=participantMode\n", s.id)
  171. s.mu.Unlock()
  172. s.p.run()
  173. next = standbyMode
  174. if d != nil {
  175. close(dStopc)
  176. }
  177. case standbyMode:
  178. s.s = newStandby(s.client, s.peerHub)
  179. s.mode.Set(standbyMode)
  180. log.Printf("id=%x server.run mode=standbyMode\n", s.id)
  181. s.mu.Unlock()
  182. s.s.run()
  183. next = participantMode
  184. case stopMode:
  185. s.mode.Set(stopMode)
  186. log.Printf("id=%x server.run mode=stopMode\n", s.id)
  187. s.mu.Unlock()
  188. s.stopc <- struct{}{}
  189. return nil
  190. default:
  191. panic("unsupport mode")
  192. }
  193. s.mu.Lock()
  194. if !s.stopped {
  195. s.id = genId()
  196. }
  197. s.mu.Unlock()
  198. }
  199. }
  200. // setId sets the id for the participant. This should only be used for testing.
  201. func (s *Server) setId(id int64) {
  202. log.Printf("id=%x server.setId oldId=%x\n", id, s.id)
  203. s.id = id
  204. }