transport.go 12 KB

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