transport.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package rafthttp
  15. import (
  16. "log"
  17. "net/http"
  18. "sync"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  20. "github.com/coreos/etcd/etcdserver/stats"
  21. "github.com/coreos/etcd/pkg/types"
  22. "github.com/coreos/etcd/raft"
  23. "github.com/coreos/etcd/raft/raftpb"
  24. )
  25. type Raft interface {
  26. Process(ctx context.Context, m raftpb.Message) error
  27. ReportUnreachable(id uint64)
  28. ReportSnapshot(id uint64, status raft.SnapshotStatus)
  29. }
  30. type Transporter interface {
  31. // Handler returns the HTTP handler of the transporter.
  32. // A transporter HTTP handler handles the HTTP requests
  33. // from remote peers.
  34. // The handler MUST be used to handle RaftPrefix(/raft)
  35. // endpoint.
  36. Handler() http.Handler
  37. // Send sends out the given messages to the remote peers.
  38. // Each message has a To field, which is an id that maps
  39. // to an existing peer in the transport.
  40. // If the id cannot be found in the transport, the message
  41. // will be ignored.
  42. Send(m []raftpb.Message)
  43. // AddPeer adds a peer with given peer urls into the transport.
  44. // It is the caller's responsibility to ensure the urls are all vaild,
  45. // or it panics.
  46. // Peer urls are used to connect to the remote peer.
  47. AddPeer(id types.ID, urls []string)
  48. // RemovePeer removes the peer with given id.
  49. RemovePeer(id types.ID)
  50. // RemoveAllPeers removes all the existing peers in the transport.
  51. RemoveAllPeers()
  52. // UpdatePeer updates the peer urls of the peer with the given id.
  53. // It is the caller's responsibility to ensure the urls are all vaild,
  54. // or it panics.
  55. UpdatePeer(id types.ID, urls []string)
  56. // Stop closes the connections and stops the transporter.
  57. Stop()
  58. }
  59. type transport struct {
  60. roundTripper http.RoundTripper
  61. id types.ID
  62. clusterID types.ID
  63. raft Raft
  64. serverStats *stats.ServerStats
  65. leaderStats *stats.LeaderStats
  66. mu sync.RWMutex // protect the peer map
  67. peers map[types.ID]Peer // remote peers
  68. errorc chan error
  69. }
  70. func NewTransporter(rt http.RoundTripper, id, cid types.ID, r Raft, errorc chan error, ss *stats.ServerStats, ls *stats.LeaderStats) Transporter {
  71. return &transport{
  72. roundTripper: rt,
  73. id: id,
  74. clusterID: cid,
  75. raft: r,
  76. serverStats: ss,
  77. leaderStats: ls,
  78. peers: make(map[types.ID]Peer),
  79. errorc: errorc,
  80. }
  81. }
  82. func (t *transport) Handler() http.Handler {
  83. pipelineHandler := NewHandler(t.raft, t.clusterID)
  84. streamHandler := newStreamHandler(t, t.id, t.clusterID)
  85. mux := http.NewServeMux()
  86. mux.Handle(RaftPrefix, pipelineHandler)
  87. mux.Handle(RaftStreamPrefix+"/", streamHandler)
  88. return mux
  89. }
  90. func (t *transport) Get(id types.ID) Peer {
  91. t.mu.RLock()
  92. defer t.mu.RUnlock()
  93. return t.peers[id]
  94. }
  95. func (t *transport) Send(msgs []raftpb.Message) {
  96. for _, m := range msgs {
  97. // intentionally dropped message
  98. if m.To == 0 {
  99. continue
  100. }
  101. to := types.ID(m.To)
  102. p, ok := t.peers[to]
  103. if !ok {
  104. log.Printf("etcdserver: send message to unknown receiver %s", to)
  105. continue
  106. }
  107. if m.Type == raftpb.MsgApp {
  108. t.serverStats.SendAppendReq(m.Size())
  109. }
  110. p.Send(m)
  111. }
  112. }
  113. func (t *transport) Stop() {
  114. for _, p := range t.peers {
  115. p.Stop()
  116. }
  117. if tr, ok := t.roundTripper.(*http.Transport); ok {
  118. tr.CloseIdleConnections()
  119. }
  120. }
  121. func (t *transport) AddPeer(id types.ID, us []string) {
  122. t.mu.Lock()
  123. defer t.mu.Unlock()
  124. if _, ok := t.peers[id]; ok {
  125. return
  126. }
  127. urls, err := types.NewURLs(us)
  128. if err != nil {
  129. log.Panicf("newURLs %+v should never fail: %+v", us, err)
  130. }
  131. fs := t.leaderStats.Follower(id.String())
  132. t.peers[id] = startPeer(t.roundTripper, urls, t.id, id, t.clusterID, t.raft, fs, t.errorc)
  133. }
  134. func (t *transport) RemovePeer(id types.ID) {
  135. t.mu.Lock()
  136. defer t.mu.Unlock()
  137. t.removePeer(id)
  138. }
  139. func (t *transport) RemoveAllPeers() {
  140. t.mu.Lock()
  141. defer t.mu.Unlock()
  142. for id, _ := range t.peers {
  143. t.removePeer(id)
  144. }
  145. }
  146. // the caller of this function must have the peers mutex.
  147. func (t *transport) removePeer(id types.ID) {
  148. if peer, ok := t.peers[id]; ok {
  149. peer.Stop()
  150. } else {
  151. log.Panicf("rafthttp: unexpected removal of unknown peer '%d'", id)
  152. }
  153. delete(t.peers, id)
  154. delete(t.leaderStats.Followers, id.String())
  155. }
  156. func (t *transport) UpdatePeer(id types.ID, us []string) {
  157. t.mu.Lock()
  158. defer t.mu.Unlock()
  159. // TODO: return error or just panic?
  160. if _, ok := t.peers[id]; !ok {
  161. return
  162. }
  163. urls, err := types.NewURLs(us)
  164. if err != nil {
  165. log.Panicf("newURLs %+v should never fail: %+v", us, err)
  166. }
  167. t.peers[id].Update(urls)
  168. }
  169. type Pausable interface {
  170. Pause()
  171. Resume()
  172. }
  173. // for testing
  174. func (t *transport) Pause() {
  175. for _, p := range t.peers {
  176. p.(Pausable).Pause()
  177. }
  178. }
  179. func (t *transport) Resume() {
  180. for _, p := range t.peers {
  181. p.(Pausable).Resume()
  182. }
  183. }