etcd.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. "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. exited chan error
  42. stopNotifyc chan struct{}
  43. log *log.Logger
  44. http.Handler
  45. }
  46. func New(c *config.Config) (*Server, error) {
  47. if err := c.Sanitize(); err != nil {
  48. log.Fatalf("server.new sanitizeErr=\"%v\"\n", err)
  49. }
  50. tc := &tls.Config{
  51. InsecureSkipVerify: true,
  52. }
  53. var err error
  54. if c.PeerTLSInfo().Scheme() == "https" {
  55. tc, err = c.PeerTLSInfo().ClientConfig()
  56. if err != nil {
  57. log.Fatalf("server.new ClientConfigErr=\"%v\"\n", err)
  58. }
  59. }
  60. tr := new(http.Transport)
  61. tr.TLSClientConfig = tc
  62. tr.Dial = (&net.Dialer{Timeout: 200 * time.Millisecond}).Dial
  63. tr.TLSHandshakeTimeout = 10 * time.Second
  64. tr.ResponseHeaderTimeout = defaultTickDuration * defaultHeartbeat
  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. exited: make(chan error, 1),
  76. stopNotifyc: 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() error {
  96. s.mode.Set(stopMode)
  97. close(s.stopNotifyc)
  98. err := <-s.exited
  99. s.client.CloseConnections()
  100. s.peerHub.stop()
  101. log.Printf("id=%x server.stop\n", s.id)
  102. return err
  103. }
  104. func (s *Server) requestHandler(w http.ResponseWriter, r *http.Request) {
  105. switch s.mode.Get() {
  106. case participantMode:
  107. s.p.ServeHTTP(w, r)
  108. case standbyMode:
  109. s.s.ServeHTTP(w, r)
  110. default:
  111. http.NotFound(w, r)
  112. }
  113. }
  114. func (s *Server) RaftHandler() http.Handler {
  115. return http.HandlerFunc(s.ServeRaftHTTP)
  116. }
  117. func (s *Server) ServeRaftHTTP(w http.ResponseWriter, r *http.Request) {
  118. switch s.mode.Get() {
  119. case participantMode:
  120. s.p.raftHandler().ServeHTTP(w, r)
  121. default:
  122. http.NotFound(w, r)
  123. }
  124. }
  125. func (s *Server) Run() error {
  126. var d *discoverer
  127. var seeds []string
  128. var exit error
  129. defer func() { s.exited <- exit }()
  130. durl := s.config.Discovery
  131. if durl != "" {
  132. u, err := url.Parse(durl)
  133. if err != nil {
  134. exit = err
  135. return fmt.Errorf("bad discovery URL error: %v", err)
  136. }
  137. d = newDiscoverer(u, fmt.Sprint(s.id), s.raftPubAddr)
  138. if seeds, err = d.discover(); err != nil {
  139. exit = err
  140. return err
  141. }
  142. log.Printf("id=%x server.run source=-discovery seeds=\"%v\"\n", s.id, seeds)
  143. } else {
  144. seeds = s.config.Peers
  145. log.Printf("id=%x server.run source=-peers seeds=\"%v\"\n", s.id, seeds)
  146. }
  147. s.peerHub.setSeeds(seeds)
  148. next := participantMode
  149. for {
  150. switch next {
  151. case participantMode:
  152. p, err := newParticipant(s.id, s.pubAddr, s.raftPubAddr, s.config.DataDir, s.client, s.peerHub, s.tickDuration)
  153. if err != nil {
  154. log.Printf("id=%x server.run newParicipanteErr=\"%v\"\n", s.id, err)
  155. exit = err
  156. return err
  157. }
  158. s.p = p
  159. s.mode.Set(participantMode)
  160. log.Printf("id=%x server.run mode=participantMode\n", s.id)
  161. dStopc := make(chan struct{})
  162. if d != nil {
  163. go d.heartbeat(dStopc)
  164. }
  165. s.p.run(s.stopNotifyc)
  166. if d != nil {
  167. close(dStopc)
  168. }
  169. next = standbyMode
  170. case standbyMode:
  171. s.s = newStandby(s.client, s.peerHub)
  172. s.mode.Set(standbyMode)
  173. log.Printf("id=%x server.run mode=standbyMode\n", s.id)
  174. s.s.run(s.stopNotifyc)
  175. next = participantMode
  176. default:
  177. panic("unsupport mode")
  178. }
  179. if s.mode.Get() == stopMode {
  180. return nil
  181. }
  182. s.id = genId()
  183. }
  184. }
  185. // setId sets the id for the participant. This should only be used for testing.
  186. func (s *Server) setId(id int64) {
  187. log.Printf("id=%x server.setId oldId=%x\n", id, s.id)
  188. s.id = id
  189. }