transport.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. IsIDRemoved(id uint64) bool
  28. ReportUnreachable(id uint64)
  29. ReportSnapshot(id uint64, status raft.SnapshotStatus)
  30. }
  31. type Transporter interface {
  32. // Handler returns the HTTP handler of the transporter.
  33. // A transporter HTTP handler handles the HTTP requests
  34. // from remote peers.
  35. // The handler MUST be used to handle RaftPrefix(/raft)
  36. // endpoint.
  37. Handler() http.Handler
  38. // Send sends out the given messages to the remote peers.
  39. // Each message has a To field, which is an id that maps
  40. // to an existing peer in the transport.
  41. // If the id cannot be found in the transport, the message
  42. // will be ignored.
  43. Send(m []raftpb.Message)
  44. // AddRemote adds a remote with given peer urls into the transport.
  45. // A remote helps newly joined member to catch up the progress of cluster,
  46. // and will not be used after that.
  47. // It is the caller's responsibility to ensure the urls are all vaild,
  48. // or it panics.
  49. AddRemote(id types.ID, urls []string)
  50. // AddPeer adds a peer with given peer urls into the transport.
  51. // It is the caller's responsibility to ensure the urls are all vaild,
  52. // or it panics.
  53. // Peer urls are used to connect to the remote peer.
  54. AddPeer(id types.ID, urls []string)
  55. // RemovePeer removes the peer with given id.
  56. RemovePeer(id types.ID)
  57. // RemoveAllPeers removes all the existing peers in the transport.
  58. RemoveAllPeers()
  59. // UpdatePeer updates the peer urls of the peer with the given id.
  60. // It is the caller's responsibility to ensure the urls are all vaild,
  61. // or it panics.
  62. UpdatePeer(id types.ID, urls []string)
  63. // Stop closes the connections and stops the transporter.
  64. Stop()
  65. }
  66. type transport struct {
  67. roundTripper http.RoundTripper
  68. id types.ID
  69. clusterID types.ID
  70. raft Raft
  71. serverStats *stats.ServerStats
  72. leaderStats *stats.LeaderStats
  73. term uint64 // the latest term that has been observed
  74. mu sync.RWMutex // protect the remote and peer map
  75. remotes map[types.ID]*remote // remotes map that helps newly joined member to catch up
  76. peers map[types.ID]Peer // peers map
  77. errorc chan error
  78. }
  79. func NewTransporter(rt http.RoundTripper, id, cid types.ID, r Raft, errorc chan error, ss *stats.ServerStats, ls *stats.LeaderStats) Transporter {
  80. return &transport{
  81. roundTripper: rt,
  82. id: id,
  83. clusterID: cid,
  84. raft: r,
  85. serverStats: ss,
  86. leaderStats: ls,
  87. remotes: make(map[types.ID]*remote),
  88. peers: make(map[types.ID]Peer),
  89. errorc: errorc,
  90. }
  91. }
  92. func (t *transport) Handler() http.Handler {
  93. pipelineHandler := NewHandler(t.raft, t.clusterID)
  94. streamHandler := newStreamHandler(t, t.raft, t.id, t.clusterID)
  95. mux := http.NewServeMux()
  96. mux.Handle(RaftPrefix, pipelineHandler)
  97. mux.Handle(RaftStreamPrefix+"/", streamHandler)
  98. return mux
  99. }
  100. func (t *transport) Get(id types.ID) Peer {
  101. t.mu.RLock()
  102. defer t.mu.RUnlock()
  103. return t.peers[id]
  104. }
  105. func (t *transport) maybeUpdatePeersTerm(term uint64) {
  106. if t.term >= term {
  107. return
  108. }
  109. t.term = term
  110. for _, p := range t.peers {
  111. p.setTerm(term)
  112. }
  113. }
  114. func (t *transport) Send(msgs []raftpb.Message) {
  115. for _, m := range msgs {
  116. // intentionally dropped message
  117. if m.To == 0 {
  118. continue
  119. }
  120. to := types.ID(m.To)
  121. if m.Type != raftpb.MsgProp { // proposal message does not have a valid term
  122. t.maybeUpdatePeersTerm(m.Term)
  123. }
  124. p, ok := t.peers[to]
  125. if ok {
  126. if m.Type == raftpb.MsgApp {
  127. t.serverStats.SendAppendReq(m.Size())
  128. }
  129. p.Send(m)
  130. continue
  131. }
  132. g, ok := t.remotes[to]
  133. if ok {
  134. g.Send(m)
  135. continue
  136. }
  137. log.Printf("etcdserver: send message to unknown receiver %s", to)
  138. }
  139. }
  140. func (t *transport) Stop() {
  141. for _, r := range t.remotes {
  142. r.Stop()
  143. }
  144. for _, p := range t.peers {
  145. p.Stop()
  146. }
  147. if tr, ok := t.roundTripper.(*http.Transport); ok {
  148. tr.CloseIdleConnections()
  149. }
  150. }
  151. func (t *transport) AddRemote(id types.ID, us []string) {
  152. t.mu.Lock()
  153. defer t.mu.Unlock()
  154. if _, ok := t.remotes[id]; ok {
  155. return
  156. }
  157. urls, err := types.NewURLs(us)
  158. if err != nil {
  159. log.Panicf("newURLs %+v should never fail: %+v", us, err)
  160. }
  161. t.remotes[id] = startRemote(t.roundTripper, urls, t.id, id, t.clusterID, t.raft, t.errorc)
  162. }
  163. func (t *transport) AddPeer(id types.ID, us []string) {
  164. t.mu.Lock()
  165. defer t.mu.Unlock()
  166. if _, ok := t.peers[id]; ok {
  167. return
  168. }
  169. urls, err := types.NewURLs(us)
  170. if err != nil {
  171. log.Panicf("newURLs %+v should never fail: %+v", us, err)
  172. }
  173. fs := t.leaderStats.Follower(id.String())
  174. t.peers[id] = startPeer(t.roundTripper, urls, t.id, id, t.clusterID, t.raft, fs, t.errorc)
  175. }
  176. func (t *transport) RemovePeer(id types.ID) {
  177. t.mu.Lock()
  178. defer t.mu.Unlock()
  179. t.removePeer(id)
  180. }
  181. func (t *transport) RemoveAllPeers() {
  182. t.mu.Lock()
  183. defer t.mu.Unlock()
  184. for id, _ := range t.peers {
  185. t.removePeer(id)
  186. }
  187. }
  188. // the caller of this function must have the peers mutex.
  189. func (t *transport) removePeer(id types.ID) {
  190. if peer, ok := t.peers[id]; ok {
  191. peer.Stop()
  192. } else {
  193. log.Panicf("rafthttp: unexpected removal of unknown peer '%d'", id)
  194. }
  195. delete(t.peers, id)
  196. delete(t.leaderStats.Followers, id.String())
  197. }
  198. func (t *transport) UpdatePeer(id types.ID, us []string) {
  199. t.mu.Lock()
  200. defer t.mu.Unlock()
  201. // TODO: return error or just panic?
  202. if _, ok := t.peers[id]; !ok {
  203. return
  204. }
  205. urls, err := types.NewURLs(us)
  206. if err != nil {
  207. log.Panicf("newURLs %+v should never fail: %+v", us, err)
  208. }
  209. t.peers[id].Update(urls)
  210. }
  211. type Pausable interface {
  212. Pause()
  213. Resume()
  214. }
  215. // for testing
  216. func (t *transport) Pause() {
  217. for _, p := range t.peers {
  218. p.(Pausable).Pause()
  219. }
  220. }
  221. func (t *transport) Resume() {
  222. for _, p := range t.peers {
  223. p.(Pausable).Resume()
  224. }
  225. }