transport.go 7.0 KB

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