etcd.go 4.8 KB

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