etcd.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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/conf"
  24. )
  25. const (
  26. participantMode int64 = iota
  27. standbyMode
  28. stopMode
  29. )
  30. type Server struct {
  31. cfg *conf.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 *conf.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. cfg: 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. exited: make(chan error, 1),
  75. stopNotifyc: make(chan struct{}),
  76. }
  77. s.peerHub = newPeerHub(s.id, client)
  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.cfg.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. log.Printf("id=%x server.stop\n", s.id)
  101. return err
  102. }
  103. func (s *Server) requestHandler(w http.ResponseWriter, r *http.Request) {
  104. switch s.mode.Get() {
  105. case participantMode:
  106. s.p.ServeHTTP(w, r)
  107. case standbyMode:
  108. s.s.ServeHTTP(w, r)
  109. default:
  110. http.NotFound(w, r)
  111. }
  112. }
  113. func (s *Server) RaftHandler() http.Handler {
  114. return http.HandlerFunc(s.ServeRaftHTTP)
  115. }
  116. func (s *Server) ServeRaftHTTP(w http.ResponseWriter, r *http.Request) {
  117. switch s.mode.Get() {
  118. case participantMode:
  119. s.p.raftHandler().ServeHTTP(w, r)
  120. default:
  121. http.NotFound(w, r)
  122. }
  123. }
  124. func (s *Server) Run() error {
  125. var d *discoverer
  126. var seeds []string
  127. var exit error
  128. defer func() { s.exited <- exit }()
  129. durl := s.cfg.Discovery
  130. if durl != "" {
  131. u, err := url.Parse(durl)
  132. if err != nil {
  133. exit = err
  134. return fmt.Errorf("bad discovery URL error: %v", err)
  135. }
  136. d = newDiscoverer(u, fmt.Sprint(s.id), s.raftPubAddr)
  137. if seeds, err = d.discover(); err != nil {
  138. exit = err
  139. return err
  140. }
  141. log.Printf("id=%x server.run source=-discovery seeds=\"%v\"\n", s.id, seeds)
  142. } else {
  143. seeds = s.cfg.Peers
  144. log.Printf("id=%x server.run source=-peers seeds=\"%v\"\n", s.id, seeds)
  145. }
  146. s.peerHub.setSeeds(seeds)
  147. next := participantMode
  148. for {
  149. switch next {
  150. case participantMode:
  151. p, err := newParticipant(s.id, s.pubAddr, s.raftPubAddr, s.cfg.DataDir, s.client, s.peerHub, s.tickDuration)
  152. if err != nil {
  153. log.Printf("id=%x server.run newParicipanteErr=\"%v\"\n", s.id, err)
  154. exit = err
  155. return err
  156. }
  157. s.p = p
  158. s.mode.Set(participantMode)
  159. log.Printf("id=%x server.run mode=participantMode\n", s.id)
  160. dStopc := make(chan struct{})
  161. if d != nil {
  162. go d.heartbeat(dStopc)
  163. }
  164. s.p.run(s.stopNotifyc)
  165. if d != nil {
  166. close(dStopc)
  167. }
  168. next = standbyMode
  169. case standbyMode:
  170. s.s = newStandby(s.client, s.peerHub)
  171. s.mode.Set(standbyMode)
  172. log.Printf("id=%x server.run mode=standbyMode\n", s.id)
  173. s.s.run(s.stopNotifyc)
  174. next = participantMode
  175. default:
  176. panic("unsupport mode")
  177. }
  178. if s.mode.Get() == stopMode {
  179. return nil
  180. }
  181. s.id = genId()
  182. }
  183. }
  184. // setId sets the id for the participant. This should only be used for testing.
  185. func (s *Server) setId(id int64) {
  186. log.Printf("id=%x server.setId oldId=%x\n", id, s.id)
  187. s.id = id
  188. }