transport.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. term uint64 // the latest term that has been observed
  75. mu sync.RWMutex // protect the remote and peer map
  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. if t.term >= term {
  108. return
  109. }
  110. t.term = term
  111. for _, p := range t.peers {
  112. p.setTerm(term)
  113. }
  114. }
  115. func (t *transport) Send(msgs []raftpb.Message) {
  116. for _, m := range msgs {
  117. // intentionally dropped message
  118. if m.To == 0 {
  119. continue
  120. }
  121. to := types.ID(m.To)
  122. if m.Type != raftpb.MsgProp { // proposal message does not have a valid term
  123. t.maybeUpdatePeersTerm(m.Term)
  124. }
  125. p, ok := t.peers[to]
  126. if ok {
  127. if m.Type == raftpb.MsgApp {
  128. t.serverStats.SendAppendReq(m.Size())
  129. }
  130. p.Send(m)
  131. continue
  132. }
  133. g, ok := t.remotes[to]
  134. if ok {
  135. g.Send(m)
  136. continue
  137. }
  138. plog.Debugf("ignored message %s (sent to unknown peer %s)", m.Type, to)
  139. }
  140. }
  141. func (t *transport) Stop() {
  142. for _, r := range t.remotes {
  143. r.Stop()
  144. }
  145. for _, p := range t.peers {
  146. p.Stop()
  147. }
  148. if tr, ok := t.roundTripper.(*http.Transport); ok {
  149. tr.CloseIdleConnections()
  150. }
  151. }
  152. func (t *transport) AddRemote(id types.ID, us []string) {
  153. t.mu.Lock()
  154. defer t.mu.Unlock()
  155. if _, ok := t.remotes[id]; ok {
  156. return
  157. }
  158. urls, err := types.NewURLs(us)
  159. if err != nil {
  160. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  161. }
  162. t.remotes[id] = startRemote(t.roundTripper, urls, t.id, id, t.clusterID, t.raft, t.errorc)
  163. }
  164. func (t *transport) AddPeer(id types.ID, us []string) {
  165. t.mu.Lock()
  166. defer t.mu.Unlock()
  167. if _, ok := t.peers[id]; ok {
  168. return
  169. }
  170. urls, err := types.NewURLs(us)
  171. if err != nil {
  172. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  173. }
  174. fs := t.leaderStats.Follower(id.String())
  175. t.peers[id] = startPeer(t.roundTripper, urls, t.id, id, t.clusterID, t.raft, fs, t.errorc)
  176. }
  177. func (t *transport) RemovePeer(id types.ID) {
  178. t.mu.Lock()
  179. defer t.mu.Unlock()
  180. t.removePeer(id)
  181. }
  182. func (t *transport) RemoveAllPeers() {
  183. t.mu.Lock()
  184. defer t.mu.Unlock()
  185. for id, _ := range t.peers {
  186. t.removePeer(id)
  187. }
  188. }
  189. // the caller of this function must have the peers mutex.
  190. func (t *transport) removePeer(id types.ID) {
  191. if peer, ok := t.peers[id]; ok {
  192. peer.Stop()
  193. } else {
  194. plog.Panicf("unexpected removal of unknown peer '%d'", id)
  195. }
  196. delete(t.peers, id)
  197. delete(t.leaderStats.Followers, id.String())
  198. }
  199. func (t *transport) UpdatePeer(id types.ID, us []string) {
  200. t.mu.Lock()
  201. defer t.mu.Unlock()
  202. // TODO: return error or just panic?
  203. if _, ok := t.peers[id]; !ok {
  204. return
  205. }
  206. urls, err := types.NewURLs(us)
  207. if err != nil {
  208. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  209. }
  210. t.peers[id].Update(urls)
  211. }
  212. type Pausable interface {
  213. Pause()
  214. Resume()
  215. }
  216. // for testing
  217. func (t *transport) Pause() {
  218. for _, p := range t.peers {
  219. p.(Pausable).Pause()
  220. }
  221. }
  222. func (t *transport) Resume() {
  223. for _, p := range t.peers {
  224. p.(Pausable).Resume()
  225. }
  226. }