transport.go 6.1 KB

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