transport.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. "net/url"
  19. "path"
  20. "sync"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  22. "github.com/coreos/etcd/etcdserver/stats"
  23. "github.com/coreos/etcd/pkg/types"
  24. "github.com/coreos/etcd/raft"
  25. "github.com/coreos/etcd/raft/raftpb"
  26. )
  27. type Raft interface {
  28. Process(ctx context.Context, m raftpb.Message) error
  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. // AddPeer adds a peer with given peer urls into the transport.
  46. // It is the caller's responsibility to ensure the urls are all vaild,
  47. // or it panics.
  48. // Peer urls are used to connect to the remote peer.
  49. AddPeer(id types.ID, urls []string)
  50. // RemovePeer removes the peer with given id.
  51. RemovePeer(id types.ID)
  52. // RemoveAllPeers removes all the existing peers in the transport.
  53. RemoveAllPeers()
  54. // UpdatePeer updates the peer urls of the peer with the given id.
  55. // It is the caller's responsibility to ensure the urls are all vaild,
  56. // or it panics.
  57. UpdatePeer(id types.ID, urls []string)
  58. // Stop closes the connections and stops the transporter.
  59. Stop()
  60. }
  61. type transport struct {
  62. roundTripper http.RoundTripper
  63. id types.ID
  64. clusterID types.ID
  65. raft Raft
  66. serverStats *stats.ServerStats
  67. leaderStats *stats.LeaderStats
  68. mu sync.RWMutex // protect the peer map
  69. peers map[types.ID]Peer // remote peers
  70. errorc chan error
  71. }
  72. func NewTransporter(rt http.RoundTripper, id, cid types.ID, r Raft, errorc chan error, ss *stats.ServerStats, ls *stats.LeaderStats) Transporter {
  73. return &transport{
  74. roundTripper: rt,
  75. id: id,
  76. clusterID: cid,
  77. raft: r,
  78. serverStats: ss,
  79. leaderStats: ls,
  80. peers: make(map[types.ID]Peer),
  81. errorc: errorc,
  82. }
  83. }
  84. func (t *transport) Handler() http.Handler {
  85. pipelineHandler := NewHandler(t.raft, t.clusterID)
  86. streamHandler := newStreamHandler(t, t.id, t.clusterID)
  87. mux := http.NewServeMux()
  88. mux.Handle(RaftPrefix, pipelineHandler)
  89. mux.Handle(RaftStreamPrefix+"/", streamHandler)
  90. return mux
  91. }
  92. func (t *transport) Get(id types.ID) Peer {
  93. t.mu.RLock()
  94. defer t.mu.RUnlock()
  95. return t.peers[id]
  96. }
  97. func (t *transport) Send(msgs []raftpb.Message) {
  98. for _, m := range msgs {
  99. // intentionally dropped message
  100. if m.To == 0 {
  101. continue
  102. }
  103. to := types.ID(m.To)
  104. p, ok := t.peers[to]
  105. if !ok {
  106. log.Printf("etcdserver: send message to unknown receiver %s", to)
  107. continue
  108. }
  109. if m.Type == raftpb.MsgApp {
  110. t.serverStats.SendAppendReq(m.Size())
  111. }
  112. p.Send(m)
  113. }
  114. }
  115. func (t *transport) Stop() {
  116. for _, p := range t.peers {
  117. p.Stop()
  118. }
  119. if tr, ok := t.roundTripper.(*http.Transport); ok {
  120. tr.CloseIdleConnections()
  121. }
  122. }
  123. func (t *transport) AddPeer(id types.ID, urls []string) {
  124. t.mu.Lock()
  125. defer t.mu.Unlock()
  126. if _, ok := t.peers[id]; ok {
  127. return
  128. }
  129. // TODO: considering how to switch between all available peer urls
  130. peerURL := urls[0]
  131. u, err := url.Parse(peerURL)
  132. if err != nil {
  133. log.Panicf("unexpect peer url %s", peerURL)
  134. }
  135. u.Path = path.Join(u.Path, RaftPrefix)
  136. fs := t.leaderStats.Follower(id.String())
  137. t.peers[id] = startPeer(t.roundTripper, u.String(), t.id, id, t.clusterID, t.raft, fs, t.errorc)
  138. }
  139. func (t *transport) RemovePeer(id types.ID) {
  140. t.mu.Lock()
  141. defer t.mu.Unlock()
  142. t.removePeer(id)
  143. }
  144. func (t *transport) RemoveAllPeers() {
  145. t.mu.Lock()
  146. defer t.mu.Unlock()
  147. for id, _ := range t.peers {
  148. t.removePeer(id)
  149. }
  150. }
  151. // the caller of this function must have the peers mutex.
  152. func (t *transport) removePeer(id types.ID) {
  153. if peer, ok := t.peers[id]; ok {
  154. peer.Stop()
  155. } else {
  156. log.Panicf("rafthttp: unexpected removal of unknown peer '%d'", id)
  157. }
  158. delete(t.peers, id)
  159. delete(t.leaderStats.Followers, id.String())
  160. }
  161. func (t *transport) UpdatePeer(id types.ID, urls []string) {
  162. t.mu.Lock()
  163. defer t.mu.Unlock()
  164. // TODO: return error or just panic?
  165. if _, ok := t.peers[id]; !ok {
  166. return
  167. }
  168. peerURL := urls[0]
  169. u, err := url.Parse(peerURL)
  170. if err != nil {
  171. log.Panicf("unexpect peer url %s", peerURL)
  172. }
  173. u.Path = path.Join(u.Path, RaftPrefix)
  174. t.peers[id].Update(u.String())
  175. }
  176. type Pausable interface {
  177. Pause()
  178. Resume()
  179. }
  180. // for testing
  181. func (t *transport) Pause() {
  182. for _, p := range t.peers {
  183. p.(Pausable).Pause()
  184. }
  185. }
  186. func (t *transport) Resume() {
  187. for _, p := range t.peers {
  188. p.(Pausable).Resume()
  189. }
  190. }