transport.go 6.6 KB

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