transport.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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() http.Handler
  34. Send(m []raftpb.Message)
  35. AddPeer(id types.ID, urls []string)
  36. RemovePeer(id types.ID)
  37. RemoveAllPeers()
  38. UpdatePeer(id types.ID, urls []string)
  39. Stop()
  40. }
  41. type transport struct {
  42. roundTripper http.RoundTripper
  43. id types.ID
  44. clusterID types.ID
  45. raft Raft
  46. serverStats *stats.ServerStats
  47. leaderStats *stats.LeaderStats
  48. mu sync.RWMutex // protect the peer map
  49. peers map[types.ID]Peer // remote peers
  50. errorc chan error
  51. }
  52. func NewTransporter(rt http.RoundTripper, id, cid types.ID, r Raft, errorc chan error, ss *stats.ServerStats, ls *stats.LeaderStats) Transporter {
  53. return &transport{
  54. roundTripper: rt,
  55. id: id,
  56. clusterID: cid,
  57. raft: r,
  58. serverStats: ss,
  59. leaderStats: ls,
  60. peers: make(map[types.ID]Peer),
  61. errorc: errorc,
  62. }
  63. }
  64. func (t *transport) Handler() http.Handler {
  65. pipelineHandler := NewHandler(t.raft, t.clusterID)
  66. streamHandler := newStreamHandler(t, t.id, t.clusterID)
  67. mux := http.NewServeMux()
  68. mux.Handle(RaftPrefix, pipelineHandler)
  69. mux.Handle(RaftStreamPrefix+"/", streamHandler)
  70. return mux
  71. }
  72. func (t *transport) Get(id types.ID) Peer {
  73. t.mu.RLock()
  74. defer t.mu.RUnlock()
  75. return t.peers[id]
  76. }
  77. func (t *transport) Send(msgs []raftpb.Message) {
  78. for _, m := range msgs {
  79. // intentionally dropped message
  80. if m.To == 0 {
  81. continue
  82. }
  83. to := types.ID(m.To)
  84. p, ok := t.peers[to]
  85. if !ok {
  86. log.Printf("etcdserver: send message to unknown receiver %s", to)
  87. continue
  88. }
  89. if m.Type == raftpb.MsgApp {
  90. t.serverStats.SendAppendReq(m.Size())
  91. }
  92. p.Send(m)
  93. }
  94. }
  95. func (t *transport) Stop() {
  96. for _, p := range t.peers {
  97. p.Stop()
  98. }
  99. if tr, ok := t.roundTripper.(*http.Transport); ok {
  100. tr.CloseIdleConnections()
  101. }
  102. }
  103. func (t *transport) AddPeer(id types.ID, urls []string) {
  104. t.mu.Lock()
  105. defer t.mu.Unlock()
  106. if _, ok := t.peers[id]; ok {
  107. return
  108. }
  109. // TODO: considering how to switch between all available peer urls
  110. peerURL := urls[0]
  111. u, err := url.Parse(peerURL)
  112. if err != nil {
  113. log.Panicf("unexpect peer url %s", peerURL)
  114. }
  115. u.Path = path.Join(u.Path, RaftPrefix)
  116. fs := t.leaderStats.Follower(id.String())
  117. t.peers[id] = startPeer(t.roundTripper, u.String(), t.id, id, t.clusterID, t.raft, fs, t.errorc)
  118. }
  119. func (t *transport) RemovePeer(id types.ID) {
  120. t.mu.Lock()
  121. defer t.mu.Unlock()
  122. t.removePeer(id)
  123. }
  124. func (t *transport) RemoveAllPeers() {
  125. t.mu.Lock()
  126. defer t.mu.Unlock()
  127. for id, _ := range t.peers {
  128. t.removePeer(id)
  129. }
  130. }
  131. // the caller of this function must have the peers mutex.
  132. func (t *transport) removePeer(id types.ID) {
  133. if peer, ok := t.peers[id]; ok {
  134. peer.Stop()
  135. } else {
  136. log.Panicf("rafthttp: unexpected removal of unknown peer '%d'", id)
  137. }
  138. delete(t.peers, id)
  139. delete(t.leaderStats.Followers, id.String())
  140. }
  141. func (t *transport) UpdatePeer(id types.ID, urls []string) {
  142. t.mu.Lock()
  143. defer t.mu.Unlock()
  144. // TODO: return error or just panic?
  145. if _, ok := t.peers[id]; !ok {
  146. return
  147. }
  148. peerURL := urls[0]
  149. u, err := url.Parse(peerURL)
  150. if err != nil {
  151. log.Panicf("unexpect peer url %s", peerURL)
  152. }
  153. u.Path = path.Join(u.Path, RaftPrefix)
  154. t.peers[id].Update(u.String())
  155. }
  156. type Pausable interface {
  157. Pause()
  158. Resume()
  159. }
  160. // for testing
  161. func (t *transport) Pause() {
  162. for _, p := range t.peers {
  163. p.(Pausable).Pause()
  164. }
  165. }
  166. func (t *transport) Resume() {
  167. for _, p := range t.peers {
  168. p.(Pausable).Resume()
  169. }
  170. }