transport.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. // Stop closes the connections and stops the transporter.
  81. Stop()
  82. }
  83. // Transport implements Transporter interface. It provides the functionality
  84. // to send raft messages to peers, and receive raft messages from peers.
  85. // User should call Handler method to get a handler to serve requests
  86. // received from peerURLs.
  87. // User needs to call Start before calling other functions, and call
  88. // Stop when the Transport is no longer used.
  89. type Transport struct {
  90. DialTimeout time.Duration // maximum duration before timing out dial of the request
  91. TLSInfo transport.TLSInfo // TLS information used when creating connection
  92. ID types.ID // local member ID
  93. URLs types.URLs // local peer URLs
  94. ClusterID types.ID // raft cluster ID for request validation
  95. Raft Raft // raft state machine, to which the Transport forwards received messages and reports status
  96. Snapshotter *snap.Snapshotter
  97. ServerStats *stats.ServerStats // used to record general transportation statistics
  98. // used to record transportation statistics with followers when
  99. // performing as leader in raft protocol
  100. LeaderStats *stats.LeaderStats
  101. // ErrorC is used to report detected critical errors, e.g.,
  102. // the member has been permanently removed from the cluster
  103. // When an error is received from ErrorC, user should stop raft state
  104. // machine and thus stop the Transport.
  105. ErrorC chan error
  106. streamRt http.RoundTripper // roundTripper used by streams
  107. pipelineRt http.RoundTripper // roundTripper used by pipelines
  108. mu sync.RWMutex // protect the remote and peer map
  109. remotes map[types.ID]*remote // remotes map that helps newly joined member to catch up
  110. peers map[types.ID]Peer // peers map
  111. prober probing.Prober
  112. }
  113. func (t *Transport) Start() error {
  114. var err error
  115. t.streamRt, err = newStreamRoundTripper(t.TLSInfo, t.DialTimeout)
  116. if err != nil {
  117. return err
  118. }
  119. t.pipelineRt, err = NewRoundTripper(t.TLSInfo, t.DialTimeout)
  120. if err != nil {
  121. return err
  122. }
  123. t.remotes = make(map[types.ID]*remote)
  124. t.peers = make(map[types.ID]Peer)
  125. t.prober = probing.NewProber(t.pipelineRt)
  126. return nil
  127. }
  128. func (t *Transport) Handler() http.Handler {
  129. pipelineHandler := newPipelineHandler(t, t.Raft, t.ClusterID)
  130. streamHandler := newStreamHandler(t, t, t.Raft, t.ID, t.ClusterID)
  131. snapHandler := newSnapshotHandler(t, t.Raft, t.Snapshotter, t.ClusterID)
  132. mux := http.NewServeMux()
  133. mux.Handle(RaftPrefix, pipelineHandler)
  134. mux.Handle(RaftStreamPrefix+"/", streamHandler)
  135. mux.Handle(RaftSnapshotPrefix, snapHandler)
  136. mux.Handle(ProbingPrefix, probing.NewHandler())
  137. return mux
  138. }
  139. func (t *Transport) Get(id types.ID) Peer {
  140. t.mu.RLock()
  141. defer t.mu.RUnlock()
  142. return t.peers[id]
  143. }
  144. func (t *Transport) Send(msgs []raftpb.Message) {
  145. for _, m := range msgs {
  146. if m.To == 0 {
  147. // ignore intentionally dropped message
  148. continue
  149. }
  150. to := types.ID(m.To)
  151. t.mu.RLock()
  152. p, pok := t.peers[to]
  153. g, rok := t.remotes[to]
  154. t.mu.RUnlock()
  155. if pok {
  156. if m.Type == raftpb.MsgApp {
  157. t.ServerStats.SendAppendReq(m.Size())
  158. }
  159. p.send(m)
  160. continue
  161. }
  162. if rok {
  163. g.send(m)
  164. continue
  165. }
  166. plog.Debugf("ignored message %s (sent to unknown peer %s)", m.Type, to)
  167. }
  168. }
  169. func (t *Transport) Stop() {
  170. t.mu.Lock()
  171. defer t.mu.Unlock()
  172. for _, r := range t.remotes {
  173. r.stop()
  174. }
  175. for _, p := range t.peers {
  176. p.stop()
  177. }
  178. t.prober.RemoveAll()
  179. if tr, ok := t.streamRt.(*http.Transport); ok {
  180. tr.CloseIdleConnections()
  181. }
  182. if tr, ok := t.pipelineRt.(*http.Transport); ok {
  183. tr.CloseIdleConnections()
  184. }
  185. t.peers = nil
  186. t.remotes = nil
  187. }
  188. func (t *Transport) AddRemote(id types.ID, us []string) {
  189. t.mu.Lock()
  190. defer t.mu.Unlock()
  191. if t.remotes == nil {
  192. // there's no clean way to shutdown the golang http server
  193. // (see: https://github.com/golang/go/issues/4674) before
  194. // stopping the transport; ignore any new connections.
  195. return
  196. }
  197. if _, ok := t.peers[id]; ok {
  198. return
  199. }
  200. if _, ok := t.remotes[id]; ok {
  201. return
  202. }
  203. urls, err := types.NewURLs(us)
  204. if err != nil {
  205. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  206. }
  207. t.remotes[id] = startRemote(t, urls, id)
  208. }
  209. func (t *Transport) AddPeer(id types.ID, us []string) {
  210. t.mu.Lock()
  211. defer t.mu.Unlock()
  212. if t.peers == nil {
  213. panic("transport stopped")
  214. }
  215. if _, ok := t.peers[id]; ok {
  216. return
  217. }
  218. urls, err := types.NewURLs(us)
  219. if err != nil {
  220. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  221. }
  222. fs := t.LeaderStats.Follower(id.String())
  223. t.peers[id] = startPeer(t, urls, id, fs)
  224. addPeerToProber(t.prober, id.String(), us)
  225. plog.Infof("added peer %s", id)
  226. }
  227. func (t *Transport) RemovePeer(id types.ID) {
  228. t.mu.Lock()
  229. defer t.mu.Unlock()
  230. t.removePeer(id)
  231. }
  232. func (t *Transport) RemoveAllPeers() {
  233. t.mu.Lock()
  234. defer t.mu.Unlock()
  235. for id := range t.peers {
  236. t.removePeer(id)
  237. }
  238. }
  239. // the caller of this function must have the peers mutex.
  240. func (t *Transport) removePeer(id types.ID) {
  241. if peer, ok := t.peers[id]; ok {
  242. peer.stop()
  243. } else {
  244. plog.Panicf("unexpected removal of unknown peer '%d'", id)
  245. }
  246. delete(t.peers, id)
  247. delete(t.LeaderStats.Followers, id.String())
  248. t.prober.Remove(id.String())
  249. plog.Infof("removed peer %s", id)
  250. }
  251. func (t *Transport) UpdatePeer(id types.ID, us []string) {
  252. t.mu.Lock()
  253. defer t.mu.Unlock()
  254. // TODO: return error or just panic?
  255. if _, ok := t.peers[id]; !ok {
  256. return
  257. }
  258. urls, err := types.NewURLs(us)
  259. if err != nil {
  260. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  261. }
  262. t.peers[id].update(urls)
  263. t.prober.Remove(id.String())
  264. addPeerToProber(t.prober, id.String(), us)
  265. plog.Infof("updated peer %s", id)
  266. }
  267. func (t *Transport) ActiveSince(id types.ID) time.Time {
  268. t.mu.Lock()
  269. defer t.mu.Unlock()
  270. if p, ok := t.peers[id]; ok {
  271. return p.activeSince()
  272. }
  273. return time.Time{}
  274. }
  275. func (t *Transport) SendSnapshot(m snap.Message) {
  276. t.mu.Lock()
  277. defer t.mu.Unlock()
  278. p := t.peers[types.ID(m.To)]
  279. if p == nil {
  280. m.CloseWithError(errMemberNotFound)
  281. return
  282. }
  283. p.sendSnap(m)
  284. }
  285. // Pausable is a testing interface for pausing transport traffic.
  286. type Pausable interface {
  287. Pause()
  288. Resume()
  289. }
  290. func (t *Transport) Pause() {
  291. for _, p := range t.peers {
  292. p.(Pausable).Pause()
  293. }
  294. }
  295. func (t *Transport) Resume() {
  296. for _, p := range t.peers {
  297. p.(Pausable).Resume()
  298. }
  299. }
  300. type nopTransporter struct{}
  301. func NewNopTransporter() Transporter {
  302. return &nopTransporter{}
  303. }
  304. func (s *nopTransporter) Start() error { return nil }
  305. func (s *nopTransporter) Handler() http.Handler { return nil }
  306. func (s *nopTransporter) Send(m []raftpb.Message) {}
  307. func (s *nopTransporter) SendSnapshot(m snap.Message) {}
  308. func (s *nopTransporter) AddRemote(id types.ID, us []string) {}
  309. func (s *nopTransporter) AddPeer(id types.ID, us []string) {}
  310. func (s *nopTransporter) RemovePeer(id types.ID) {}
  311. func (s *nopTransporter) RemoveAllPeers() {}
  312. func (s *nopTransporter) UpdatePeer(id types.ID, us []string) {}
  313. func (s *nopTransporter) ActiveSince(id types.ID) time.Time { return time.Time{} }
  314. func (s *nopTransporter) Stop() {}
  315. func (s *nopTransporter) Pause() {}
  316. func (s *nopTransporter) Resume() {}
  317. type snapTransporter struct {
  318. nopTransporter
  319. snapDoneC chan snap.Message
  320. snapDir string
  321. }
  322. func NewSnapTransporter(snapDir string) (Transporter, <-chan snap.Message) {
  323. ch := make(chan snap.Message, 1)
  324. tr := &snapTransporter{snapDoneC: ch, snapDir: snapDir}
  325. return tr, ch
  326. }
  327. func (s *snapTransporter) SendSnapshot(m snap.Message) {
  328. ss := snap.New(s.snapDir)
  329. ss.SaveDBFrom(m.ReadCloser, m.Snapshot.Metadata.Index+1)
  330. m.CloseWithError(nil)
  331. s.snapDoneC <- m
  332. }