etcd.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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.ResponseHeaderTimeout = defaultTickDuration * defaultHeartbeat
  66. client := &http.Client{Transport: tr}
  67. s := &Server{
  68. config: c,
  69. id: genId(),
  70. pubAddr: c.Addr,
  71. raftPubAddr: c.Peer.Addr,
  72. tickDuration: defaultTickDuration,
  73. mode: atomicInt(stopMode),
  74. client: newClient(tc),
  75. peerHub: newPeerHub(client),
  76. stopc: make(chan struct{}),
  77. }
  78. m := http.NewServeMux()
  79. m.HandleFunc("/", s.requestHandler)
  80. m.HandleFunc("/version", versionHandler)
  81. s.Handler = m
  82. log.Printf("id=%x server.new raftPubAddr=%s\n", s.id, s.raftPubAddr)
  83. if err = os.MkdirAll(s.config.DataDir, 0700); err != nil {
  84. if !os.IsExist(err) {
  85. return nil, err
  86. }
  87. }
  88. return s, nil
  89. }
  90. func (s *Server) SetTick(tick time.Duration) {
  91. s.tickDuration = tick
  92. log.Printf("id=%x server.setTick tick=%q\n", s.id, s.tickDuration)
  93. }
  94. // Stop stops the server elegently.
  95. func (s *Server) Stop() {
  96. if s.mode.Get() == stopMode {
  97. return
  98. }
  99. s.mu.Lock()
  100. s.stopped = true
  101. switch s.mode.Get() {
  102. case participantMode:
  103. s.p.stop()
  104. case standbyMode:
  105. s.s.stop()
  106. }
  107. s.mu.Unlock()
  108. <-s.stopc
  109. s.client.CloseConnections()
  110. s.peerHub.stop()
  111. log.Printf("id=%x server.stop\n", s.id)
  112. }
  113. func (s *Server) requestHandler(w http.ResponseWriter, r *http.Request) {
  114. switch s.mode.Get() {
  115. case participantMode:
  116. s.p.ServeHTTP(w, r)
  117. case standbyMode:
  118. s.s.ServeHTTP(w, r)
  119. default:
  120. http.NotFound(w, r)
  121. }
  122. }
  123. func (s *Server) RaftHandler() http.Handler {
  124. return http.HandlerFunc(s.ServeRaftHTTP)
  125. }
  126. func (s *Server) ServeRaftHTTP(w http.ResponseWriter, r *http.Request) {
  127. switch s.mode.Get() {
  128. case participantMode:
  129. s.p.raftHandler().ServeHTTP(w, r)
  130. default:
  131. http.NotFound(w, r)
  132. }
  133. }
  134. func (s *Server) Run() error {
  135. var d *discoverer
  136. var seeds []string
  137. durl := s.config.Discovery
  138. if durl != "" {
  139. u, err := url.Parse(durl)
  140. if err != nil {
  141. return fmt.Errorf("bad discovery URL error: %v", err)
  142. }
  143. d = newDiscoverer(u, fmt.Sprint(s.id), s.raftPubAddr)
  144. if seeds, err = d.discover(); err != nil {
  145. return err
  146. }
  147. log.Printf("id=%x server.run source=-discovery seeds=\"%v\"\n", s.id, seeds)
  148. } else {
  149. seeds = s.config.Peers
  150. log.Printf("id=%x server.run source=-peers seeds=\"%v\"\n", s.id, seeds)
  151. }
  152. s.peerHub.setSeeds(seeds)
  153. next := participantMode
  154. for {
  155. s.mu.Lock()
  156. if s.stopped {
  157. next = stopMode
  158. }
  159. switch next {
  160. case participantMode:
  161. p, err := newParticipant(s.id, s.pubAddr, s.raftPubAddr, s.config.DataDir, s.client, s.peerHub, s.tickDuration)
  162. if err != nil {
  163. log.Printf("id=%x server.run newParicipanteErr=\"%v\"\n", s.id, err)
  164. return err
  165. }
  166. s.p = p
  167. dStopc := make(chan struct{})
  168. if d != nil {
  169. go d.heartbeat(dStopc)
  170. }
  171. s.mode.Set(participantMode)
  172. log.Printf("id=%x server.run mode=participantMode\n", s.id)
  173. s.mu.Unlock()
  174. next = s.p.run()
  175. if d != nil {
  176. close(dStopc)
  177. }
  178. case standbyMode:
  179. s.s = newStandby(s.client, s.peerHub)
  180. s.mode.Set(standbyMode)
  181. log.Printf("id=%x server.run mode=standbyMode\n", s.id)
  182. s.mu.Unlock()
  183. next = s.s.run()
  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. if next != stopMode {
  194. s.id = genId()
  195. }
  196. }
  197. }
  198. // setId sets the id for the participant. This should only be used for testing.
  199. func (s *Server) setId(id int64) {
  200. log.Printf("id=%x server.setId oldId=%x\n", id, s.id)
  201. s.id = id
  202. }