transport.go 13 KB

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