transport.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // Copyright 2015 The etcd Authors
  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. "time"
  19. "github.com/coreos/etcd/etcdserver/stats"
  20. "github.com/coreos/etcd/pkg/logutil"
  21. "github.com/coreos/etcd/pkg/transport"
  22. "github.com/coreos/etcd/pkg/types"
  23. "github.com/coreos/etcd/raft"
  24. "github.com/coreos/etcd/raft/raftpb"
  25. "github.com/coreos/etcd/snap"
  26. "github.com/coreos/pkg/capnslog"
  27. "github.com/xiang90/probing"
  28. "golang.org/x/net/context"
  29. )
  30. var plog = logutil.NewMergeLogger(capnslog.NewPackageLogger("github.com/coreos/etcd", "rafthttp"))
  31. type Raft interface {
  32. Process(ctx context.Context, m raftpb.Message) error
  33. IsIDRemoved(id uint64) bool
  34. ReportUnreachable(id uint64)
  35. ReportSnapshot(id uint64, status raft.SnapshotStatus)
  36. }
  37. type Transporter interface {
  38. // Start starts the given Transporter.
  39. // Start MUST be called before calling other functions in the interface.
  40. Start() error
  41. // Handler returns the HTTP handler of the transporter.
  42. // A transporter HTTP handler handles the HTTP requests
  43. // from remote peers.
  44. // The handler MUST be used to handle RaftPrefix(/raft)
  45. // endpoint.
  46. Handler() http.Handler
  47. // Send sends out the given messages to the remote peers.
  48. // Each message has a To field, which is an id that maps
  49. // to an existing peer in the transport.
  50. // If the id cannot be found in the transport, the message
  51. // will be ignored.
  52. Send(m []raftpb.Message)
  53. // SendSnapshot sends out the given snapshot message to a remote peer.
  54. // The behavior of SendSnapshot is similar to Send.
  55. SendSnapshot(m snap.Message)
  56. // AddRemote adds a remote with given peer urls into the transport.
  57. // A remote helps newly joined member to catch up the progress of cluster,
  58. // and will not be used after that.
  59. // It is the caller's responsibility to ensure the urls are all valid,
  60. // or it panics.
  61. AddRemote(id types.ID, urls []string)
  62. // AddPeer adds a peer with given peer urls into the transport.
  63. // It is the caller's responsibility to ensure the urls are all valid,
  64. // or it panics.
  65. // Peer urls are used to connect to the remote peer.
  66. AddPeer(id types.ID, urls []string)
  67. // RemovePeer removes the peer with given id.
  68. RemovePeer(id types.ID)
  69. // RemoveAllPeers removes all the existing peers in the transport.
  70. RemoveAllPeers()
  71. // UpdatePeer updates the peer urls of the peer with the given id.
  72. // It is the caller's responsibility to ensure the urls are all valid,
  73. // or it panics.
  74. UpdatePeer(id types.ID, urls []string)
  75. // ActiveSince returns the time that the connection with the peer
  76. // of the given id becomes active.
  77. // If the connection is active since peer was added, it returns the adding time.
  78. // If the connection is currently inactive, it returns zero time.
  79. ActiveSince(id types.ID) time.Time
  80. // ActivePeers returns the number of active peers.
  81. ActivePeers() int
  82. // Stop closes the connections and stops the transporter.
  83. Stop()
  84. }
  85. // Transport implements Transporter interface. It provides the functionality
  86. // to send raft messages to peers, and receive raft messages from peers.
  87. // User should call Handler method to get a handler to serve requests
  88. // received from peerURLs.
  89. // User needs to call Start before calling other functions, and call
  90. // Stop when the Transport is no longer used.
  91. type Transport struct {
  92. DialTimeout time.Duration // maximum duration before timing out dial of the request
  93. TLSInfo transport.TLSInfo // TLS information used when creating connection
  94. ID types.ID // local member ID
  95. URLs types.URLs // local peer URLs
  96. ClusterID types.ID // raft cluster ID for request validation
  97. Raft Raft // raft state machine, to which the Transport forwards received messages and reports status
  98. Snapshotter *snap.Snapshotter
  99. ServerStats *stats.ServerStats // used to record general transportation statistics
  100. // used to record transportation statistics with followers when
  101. // performing as leader in raft protocol
  102. LeaderStats *stats.LeaderStats
  103. // ErrorC is used to report detected critical errors, e.g.,
  104. // the member has been permanently removed from the cluster
  105. // When an error is received from ErrorC, user should stop raft state
  106. // machine and thus stop the Transport.
  107. ErrorC chan error
  108. streamRt http.RoundTripper // roundTripper used by streams
  109. pipelineRt http.RoundTripper // roundTripper used by pipelines
  110. mu sync.RWMutex // protect the remote and peer map
  111. remotes map[types.ID]*remote // remotes map that helps newly joined member to catch up
  112. peers map[types.ID]Peer // peers map
  113. pipelineProber probing.Prober
  114. streamProber probing.Prober
  115. }
  116. func (t *Transport) Start() error {
  117. var err error
  118. t.streamRt, err = newStreamRoundTripper(t.TLSInfo, t.DialTimeout)
  119. if err != nil {
  120. return err
  121. }
  122. t.pipelineRt, err = NewRoundTripper(t.TLSInfo, t.DialTimeout)
  123. if err != nil {
  124. return err
  125. }
  126. t.remotes = make(map[types.ID]*remote)
  127. t.peers = make(map[types.ID]Peer)
  128. t.pipelineProber = probing.NewProber(t.pipelineRt)
  129. t.streamProber = probing.NewProber(t.streamRt)
  130. return nil
  131. }
  132. func (t *Transport) Handler() http.Handler {
  133. pipelineHandler := newPipelineHandler(t, t.Raft, t.ClusterID)
  134. streamHandler := newStreamHandler(t, t, t.Raft, t.ID, t.ClusterID)
  135. snapHandler := newSnapshotHandler(t, t.Raft, t.Snapshotter, t.ClusterID)
  136. mux := http.NewServeMux()
  137. mux.Handle(RaftPrefix, pipelineHandler)
  138. mux.Handle(RaftStreamPrefix+"/", streamHandler)
  139. mux.Handle(RaftSnapshotPrefix, snapHandler)
  140. mux.Handle(ProbingPrefix, probing.NewHandler())
  141. return mux
  142. }
  143. func (t *Transport) Get(id types.ID) Peer {
  144. t.mu.RLock()
  145. defer t.mu.RUnlock()
  146. return t.peers[id]
  147. }
  148. func (t *Transport) Send(msgs []raftpb.Message) {
  149. for _, m := range msgs {
  150. if m.To == 0 {
  151. // ignore intentionally dropped message
  152. continue
  153. }
  154. to := types.ID(m.To)
  155. t.mu.RLock()
  156. p, pok := t.peers[to]
  157. g, rok := t.remotes[to]
  158. t.mu.RUnlock()
  159. if pok {
  160. if m.Type == raftpb.MsgApp {
  161. t.ServerStats.SendAppendReq(m.Size())
  162. }
  163. p.send(m)
  164. continue
  165. }
  166. if rok {
  167. g.send(m)
  168. continue
  169. }
  170. plog.Debugf("ignored message %s (sent to unknown peer %s)", m.Type, to)
  171. }
  172. }
  173. func (t *Transport) Stop() {
  174. t.mu.Lock()
  175. defer t.mu.Unlock()
  176. for _, r := range t.remotes {
  177. r.stop()
  178. }
  179. for _, p := range t.peers {
  180. p.stop()
  181. }
  182. t.pipelineProber.RemoveAll()
  183. t.streamProber.RemoveAll()
  184. if tr, ok := t.streamRt.(*http.Transport); ok {
  185. tr.CloseIdleConnections()
  186. }
  187. if tr, ok := t.pipelineRt.(*http.Transport); ok {
  188. tr.CloseIdleConnections()
  189. }
  190. t.peers = nil
  191. t.remotes = nil
  192. }
  193. // CutPeer drops messages to the specified peer.
  194. func (t *Transport) CutPeer(id types.ID) {
  195. t.mu.RLock()
  196. p, pok := t.peers[id]
  197. g, gok := t.remotes[id]
  198. t.mu.RUnlock()
  199. if pok {
  200. p.(Pausable).Pause()
  201. }
  202. if gok {
  203. g.Pause()
  204. }
  205. }
  206. // MendPeer recovers the message dropping behavior of the given peer.
  207. func (t *Transport) MendPeer(id types.ID) {
  208. t.mu.RLock()
  209. p, pok := t.peers[id]
  210. g, gok := t.remotes[id]
  211. t.mu.RUnlock()
  212. if pok {
  213. p.(Pausable).Resume()
  214. }
  215. if gok {
  216. g.Resume()
  217. }
  218. }
  219. func (t *Transport) AddRemote(id types.ID, us []string) {
  220. t.mu.Lock()
  221. defer t.mu.Unlock()
  222. if t.remotes == nil {
  223. // there's no clean way to shutdown the golang http server
  224. // (see: https://github.com/golang/go/issues/4674) before
  225. // stopping the transport; ignore any new connections.
  226. return
  227. }
  228. if _, ok := t.peers[id]; ok {
  229. return
  230. }
  231. if _, ok := t.remotes[id]; ok {
  232. return
  233. }
  234. urls, err := types.NewURLs(us)
  235. if err != nil {
  236. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  237. }
  238. t.remotes[id] = startRemote(t, urls, id)
  239. }
  240. func (t *Transport) AddPeer(id types.ID, us []string) {
  241. t.mu.Lock()
  242. defer t.mu.Unlock()
  243. if t.peers == nil {
  244. panic("transport stopped")
  245. }
  246. if _, ok := t.peers[id]; ok {
  247. return
  248. }
  249. urls, err := types.NewURLs(us)
  250. if err != nil {
  251. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  252. }
  253. fs := t.LeaderStats.Follower(id.String())
  254. t.peers[id] = startPeer(t, urls, id, fs)
  255. addPeerToProber(t.pipelineProber, id.String(), us, RoundTripperNameSnapshot, rtts)
  256. addPeerToProber(t.streamProber, id.String(), us, RoundTripperNameRaftMessage, rtts)
  257. plog.Infof("added peer %s", id)
  258. }
  259. func (t *Transport) RemovePeer(id types.ID) {
  260. t.mu.Lock()
  261. defer t.mu.Unlock()
  262. t.removePeer(id)
  263. }
  264. func (t *Transport) RemoveAllPeers() {
  265. t.mu.Lock()
  266. defer t.mu.Unlock()
  267. for id := range t.peers {
  268. t.removePeer(id)
  269. }
  270. }
  271. // the caller of this function must have the peers mutex.
  272. func (t *Transport) removePeer(id types.ID) {
  273. if peer, ok := t.peers[id]; ok {
  274. peer.stop()
  275. } else {
  276. plog.Panicf("unexpected removal of unknown peer '%d'", id)
  277. }
  278. delete(t.peers, id)
  279. delete(t.LeaderStats.Followers, id.String())
  280. t.pipelineProber.Remove(id.String())
  281. t.streamProber.Remove(id.String())
  282. plog.Infof("removed peer %s", id)
  283. }
  284. func (t *Transport) UpdatePeer(id types.ID, us []string) {
  285. t.mu.Lock()
  286. defer t.mu.Unlock()
  287. // TODO: return error or just panic?
  288. if _, ok := t.peers[id]; !ok {
  289. return
  290. }
  291. urls, err := types.NewURLs(us)
  292. if err != nil {
  293. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  294. }
  295. t.peers[id].update(urls)
  296. t.pipelineProber.Remove(id.String())
  297. addPeerToProber(t.pipelineProber, id.String(), us, RoundTripperNameSnapshot, rtts)
  298. t.streamProber.Remove(id.String())
  299. addPeerToProber(t.streamProber, id.String(), us, RoundTripperNameRaftMessage, rtts)
  300. plog.Infof("updated peer %s", id)
  301. }
  302. func (t *Transport) ActiveSince(id types.ID) time.Time {
  303. t.mu.Lock()
  304. defer t.mu.Unlock()
  305. if p, ok := t.peers[id]; ok {
  306. return p.activeSince()
  307. }
  308. return time.Time{}
  309. }
  310. func (t *Transport) SendSnapshot(m snap.Message) {
  311. t.mu.Lock()
  312. defer t.mu.Unlock()
  313. p := t.peers[types.ID(m.To)]
  314. if p == nil {
  315. m.CloseWithError(errMemberNotFound)
  316. return
  317. }
  318. p.sendSnap(m)
  319. }
  320. // Pausable is a testing interface for pausing transport traffic.
  321. type Pausable interface {
  322. Pause()
  323. Resume()
  324. }
  325. func (t *Transport) Pause() {
  326. for _, p := range t.peers {
  327. p.(Pausable).Pause()
  328. }
  329. }
  330. func (t *Transport) Resume() {
  331. for _, p := range t.peers {
  332. p.(Pausable).Resume()
  333. }
  334. }
  335. // ActivePeers returns a channel that closes when an initial
  336. // peer connection has been established. Use this to wait until the
  337. // first peer connection becomes active.
  338. func (t *Transport) ActivePeers() (cnt int) {
  339. t.mu.RLock()
  340. defer t.mu.RUnlock()
  341. for _, p := range t.peers {
  342. if !p.activeSince().IsZero() {
  343. cnt++
  344. }
  345. }
  346. return cnt
  347. }
  348. type nopTransporter struct{}
  349. func NewNopTransporter() Transporter {
  350. return &nopTransporter{}
  351. }
  352. func (s *nopTransporter) Start() error { return nil }
  353. func (s *nopTransporter) Handler() http.Handler { return nil }
  354. func (s *nopTransporter) Send(m []raftpb.Message) {}
  355. func (s *nopTransporter) SendSnapshot(m snap.Message) {}
  356. func (s *nopTransporter) AddRemote(id types.ID, us []string) {}
  357. func (s *nopTransporter) AddPeer(id types.ID, us []string) {}
  358. func (s *nopTransporter) RemovePeer(id types.ID) {}
  359. func (s *nopTransporter) RemoveAllPeers() {}
  360. func (s *nopTransporter) UpdatePeer(id types.ID, us []string) {}
  361. func (s *nopTransporter) ActiveSince(id types.ID) time.Time { return time.Time{} }
  362. func (s *nopTransporter) ActivePeers() int { return 0 }
  363. func (s *nopTransporter) Stop() {}
  364. func (s *nopTransporter) Pause() {}
  365. func (s *nopTransporter) Resume() {}
  366. type snapTransporter struct {
  367. nopTransporter
  368. snapDoneC chan snap.Message
  369. snapDir string
  370. }
  371. func NewSnapTransporter(snapDir string) (Transporter, <-chan snap.Message) {
  372. ch := make(chan snap.Message, 1)
  373. tr := &snapTransporter{snapDoneC: ch, snapDir: snapDir}
  374. return tr, ch
  375. }
  376. func (s *snapTransporter) SendSnapshot(m snap.Message) {
  377. ss := snap.New(s.snapDir)
  378. ss.SaveDBFrom(m.ReadCloser, m.Snapshot.Metadata.Index+1)
  379. m.CloseWithError(nil)
  380. s.snapDoneC <- m
  381. }