etcd.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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/http"
  19. "net/url"
  20. "os"
  21. "sync"
  22. "time"
  23. "github.com/coreos/etcd/config"
  24. )
  25. const (
  26. participantMode int64 = iota
  27. standbyMode
  28. stopMode
  29. )
  30. type Server struct {
  31. config *config.Config
  32. id int64
  33. pubAddr string
  34. raftPubAddr string
  35. tickDuration time.Duration
  36. mode atomicInt
  37. p *participant
  38. s *standby
  39. client *v2client
  40. peerHub *peerHub
  41. stopped bool
  42. mu sync.Mutex
  43. stopc chan struct{}
  44. log *log.Logger
  45. http.Handler
  46. }
  47. func New(c *config.Config) (*Server, error) {
  48. if err := c.Sanitize(); err != nil {
  49. log.Fatalf("server.new sanitizeErr=\"%v\"\n", err)
  50. }
  51. tc := &tls.Config{
  52. InsecureSkipVerify: true,
  53. }
  54. var err error
  55. if c.PeerTLSInfo().Scheme() == "https" {
  56. tc, err = c.PeerTLSInfo().ClientConfig()
  57. if err != nil {
  58. log.Fatalf("server.new ClientConfigErr=\"%v\"\n", err)
  59. }
  60. }
  61. tr := new(http.Transport)
  62. tr.TLSClientConfig = tc
  63. client := &http.Client{Transport: tr}
  64. s := &Server{
  65. config: c,
  66. id: genId(),
  67. pubAddr: c.Addr,
  68. raftPubAddr: c.Peer.Addr,
  69. tickDuration: defaultTickDuration,
  70. mode: atomicInt(stopMode),
  71. client: newClient(tc),
  72. peerHub: newPeerHub(client),
  73. stopc: make(chan struct{}),
  74. }
  75. m := http.NewServeMux()
  76. m.HandleFunc("/", s.requestHandler)
  77. m.HandleFunc("/version", versionHandler)
  78. s.Handler = m
  79. log.Printf("id=%x server.new raftPubAddr=%s\n", s.id, s.raftPubAddr)
  80. if err = os.MkdirAll(s.config.DataDir, 0700); err != nil {
  81. if !os.IsExist(err) {
  82. return nil, err
  83. }
  84. }
  85. return s, nil
  86. }
  87. func (s *Server) SetTick(tick time.Duration) {
  88. s.tickDuration = tick
  89. log.Printf("id=%x server.setTick tick=%q\n", s.id, s.tickDuration)
  90. }
  91. // Stop stops the server elegently.
  92. func (s *Server) Stop() {
  93. if s.mode.Get() == stopMode {
  94. return
  95. }
  96. s.mu.Lock()
  97. s.stopped = true
  98. switch s.mode.Get() {
  99. case participantMode:
  100. s.p.stop()
  101. case standbyMode:
  102. s.s.stop()
  103. }
  104. s.mu.Unlock()
  105. <-s.stopc
  106. s.client.CloseConnections()
  107. s.peerHub.stop()
  108. log.Printf("id=%x server.stop\n", s.id)
  109. }
  110. func (s *Server) requestHandler(w http.ResponseWriter, r *http.Request) {
  111. switch s.mode.Get() {
  112. case participantMode:
  113. s.p.ServeHTTP(w, r)
  114. case standbyMode:
  115. s.s.ServeHTTP(w, r)
  116. default:
  117. http.NotFound(w, r)
  118. }
  119. }
  120. func (s *Server) RaftHandler() http.Handler {
  121. return http.HandlerFunc(s.ServeRaftHTTP)
  122. }
  123. func (s *Server) ServeRaftHTTP(w http.ResponseWriter, r *http.Request) {
  124. switch s.mode.Get() {
  125. case participantMode:
  126. s.p.raftHandler().ServeHTTP(w, r)
  127. default:
  128. http.NotFound(w, r)
  129. }
  130. }
  131. func (s *Server) Run() error {
  132. var d *discoverer
  133. var seeds []string
  134. durl := s.config.Discovery
  135. if durl != "" {
  136. u, err := url.Parse(durl)
  137. if err != nil {
  138. return fmt.Errorf("bad discovery URL error: %v", err)
  139. }
  140. d = newDiscoverer(u, fmt.Sprint(s.id), s.raftPubAddr)
  141. if seeds, err = d.discover(); err != nil {
  142. return err
  143. }
  144. log.Printf("id=%x server.run source=-discovery seeds=\"%v\"\n", s.id, seeds)
  145. } else {
  146. seeds = s.config.Peers
  147. log.Printf("id=%x server.run source=-peers seeds=\"%v\"\n", s.id, seeds)
  148. }
  149. s.peerHub.setSeeds(seeds)
  150. next := participantMode
  151. for {
  152. s.mu.Lock()
  153. if s.stopped {
  154. next = stopMode
  155. }
  156. switch next {
  157. case participantMode:
  158. p, err := newParticipant(s.id, s.pubAddr, s.raftPubAddr, s.config.DataDir, s.client, s.peerHub, s.tickDuration)
  159. if err != nil {
  160. log.Printf("id=%x server.run newParicipanteErr=\"%v\"\n", s.id, err)
  161. return err
  162. }
  163. s.p = p
  164. dStopc := make(chan struct{})
  165. if d != nil {
  166. go d.heartbeat(dStopc)
  167. }
  168. s.mode.Set(participantMode)
  169. log.Printf("id=%x server.run mode=participantMode\n", s.id)
  170. s.mu.Unlock()
  171. next = s.p.run()
  172. if d != nil {
  173. close(dStopc)
  174. }
  175. case standbyMode:
  176. s.s = newStandby(s.client, s.peerHub)
  177. s.mode.Set(standbyMode)
  178. log.Printf("id=%x server.run mode=standbyMode\n", s.id)
  179. s.mu.Unlock()
  180. next = s.s.run()
  181. case stopMode:
  182. s.mode.Set(stopMode)
  183. log.Printf("id=%x server.run mode=stopMode\n", s.id)
  184. s.mu.Unlock()
  185. s.stopc <- struct{}{}
  186. return nil
  187. default:
  188. panic("unsupport mode")
  189. }
  190. s.id = genId()
  191. }
  192. }
  193. // setId sets the id for the participant. This should only be used for testing.
  194. func (s *Server) setId(id int64) {
  195. log.Printf("id=%x server.setId oldId=%x\n", id, s.id)
  196. s.id = id
  197. }