transport.go 5.1 KB

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