transport.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. "io"
  17. "net/http"
  18. "sync"
  19. "time"
  20. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/xiang90/probing"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  23. "github.com/coreos/etcd/etcdserver/stats"
  24. "github.com/coreos/etcd/pkg/transport"
  25. "github.com/coreos/etcd/pkg/types"
  26. "github.com/coreos/etcd/raft"
  27. "github.com/coreos/etcd/raft/raftpb"
  28. )
  29. var plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "rafthttp")
  30. type Raft interface {
  31. Process(ctx context.Context, m raftpb.Message) error
  32. IsIDRemoved(id uint64) bool
  33. ReportUnreachable(id uint64)
  34. ReportSnapshot(id uint64, status raft.SnapshotStatus)
  35. }
  36. // SnapshotSaver is the interface that wraps the SaveFrom method.
  37. type SnapshotSaver interface {
  38. // SaveFrom saves the snapshot data at the given index from the given reader.
  39. SaveFrom(r io.Reader, index uint64) error
  40. }
  41. type Transporter interface {
  42. // Start starts the given Transporter.
  43. // Start MUST be called before calling other functions in the interface.
  44. Start() error
  45. // Handler returns the HTTP handler of the transporter.
  46. // A transporter HTTP handler handles the HTTP requests
  47. // from remote peers.
  48. // The handler MUST be used to handle RaftPrefix(/raft)
  49. // endpoint.
  50. Handler() http.Handler
  51. // Send sends out the given messages to the remote peers.
  52. // Each message has a To field, which is an id that maps
  53. // to an existing peer in the transport.
  54. // If the id cannot be found in the transport, the message
  55. // will be ignored.
  56. Send(m []raftpb.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. // SnapshotReady accepts a snapshot at the given index that is ready to send out.
  82. // It is expected that caller sends a raft snapshot message with
  83. // the given index soon, and the accepted snapshot will be sent out
  84. // together. After sending, snapshot sent status is reported
  85. // through Raft.SnapshotStatus.
  86. // SnapshotReady MUST not be called when the snapshot sent status of previous
  87. // accepted one has not been reported.
  88. SnapshotReady(rc io.ReadCloser, index uint64)
  89. // Stop closes the connections and stops the transporter.
  90. Stop()
  91. }
  92. // Transport implements Transporter interface. It provides the functionality
  93. // to send raft messages to peers, and receive raft messages from peers.
  94. // User should call Handler method to get a handler to serve requests
  95. // received from peerURLs.
  96. // User needs to call Start before calling other functions, and call
  97. // Stop when the Transport is no longer used.
  98. type Transport struct {
  99. DialTimeout time.Duration // maximum duration before timing out dial of the request
  100. TLSInfo transport.TLSInfo // TLS information used when creating connection
  101. ID types.ID // local member ID
  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. SnapSaver SnapshotSaver // used to save snapshot in v3 snapshot messages
  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. // error channel used to report detected critical error, 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. V3demo bool
  115. streamRt http.RoundTripper // roundTripper used by streams
  116. pipelineRt http.RoundTripper // roundTripper used by pipelines
  117. mu sync.RWMutex // protect the remote and peer map
  118. remotes map[types.ID]*remote // remotes map that helps newly joined member to catch up
  119. peers map[types.ID]Peer // peers map
  120. snapst *snapshotStore
  121. prober probing.Prober
  122. }
  123. func (t *Transport) Start() error {
  124. var err error
  125. // Read/write timeout is set for stream roundTripper to promptly
  126. // find out broken status, which minimizes the number of messages
  127. // sent on broken connection.
  128. t.streamRt, err = transport.NewTimeoutTransport(t.TLSInfo, t.DialTimeout, ConnReadTimeout, ConnWriteTimeout)
  129. if err != nil {
  130. return err
  131. }
  132. t.pipelineRt, err = transport.NewTransport(t.TLSInfo, t.DialTimeout)
  133. if err != nil {
  134. return err
  135. }
  136. t.remotes = make(map[types.ID]*remote)
  137. t.peers = make(map[types.ID]Peer)
  138. t.snapst = &snapshotStore{}
  139. t.prober = probing.NewProber(t.pipelineRt)
  140. return nil
  141. }
  142. func (t *Transport) Handler() http.Handler {
  143. pipelineHandler := newPipelineHandler(t.Raft, t.ClusterID)
  144. streamHandler := newStreamHandler(t, t.Raft, t.ID, t.ClusterID)
  145. snapHandler := newSnapshotHandler(t.Raft, t.SnapSaver, 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. p, ok := t.peers[to]
  166. if ok {
  167. if m.Type == raftpb.MsgApp {
  168. t.ServerStats.SendAppendReq(m.Size())
  169. }
  170. p.send(m)
  171. continue
  172. }
  173. g, ok := t.remotes[to]
  174. if ok {
  175. g.send(m)
  176. continue
  177. }
  178. plog.Debugf("ignored message %s (sent to unknown peer %s)", m.Type, to)
  179. }
  180. }
  181. func (t *Transport) Stop() {
  182. for _, r := range t.remotes {
  183. r.stop()
  184. }
  185. for _, p := range t.peers {
  186. p.stop()
  187. }
  188. t.prober.RemoveAll()
  189. if tr, ok := t.streamRt.(*http.Transport); ok {
  190. tr.CloseIdleConnections()
  191. }
  192. if tr, ok := t.pipelineRt.(*http.Transport); ok {
  193. tr.CloseIdleConnections()
  194. }
  195. }
  196. func (t *Transport) AddRemote(id types.ID, us []string) {
  197. t.mu.Lock()
  198. defer t.mu.Unlock()
  199. if _, ok := t.remotes[id]; ok {
  200. return
  201. }
  202. urls, err := types.NewURLs(us)
  203. if err != nil {
  204. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  205. }
  206. t.remotes[id] = startRemote(t.pipelineRt, urls, t.ID, id, t.ClusterID, t.Raft, t.ErrorC)
  207. }
  208. func (t *Transport) AddPeer(id types.ID, us []string) {
  209. t.mu.Lock()
  210. defer t.mu.Unlock()
  211. if _, ok := t.peers[id]; ok {
  212. return
  213. }
  214. urls, err := types.NewURLs(us)
  215. if err != nil {
  216. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  217. }
  218. fs := t.LeaderStats.Follower(id.String())
  219. t.peers[id] = startPeer(t.streamRt, t.pipelineRt, urls, t.ID, id, t.ClusterID, t.snapst, t.Raft, fs, t.ErrorC, t.V3demo)
  220. addPeerToProber(t.prober, id.String(), us)
  221. }
  222. func (t *Transport) RemovePeer(id types.ID) {
  223. t.mu.Lock()
  224. defer t.mu.Unlock()
  225. t.removePeer(id)
  226. }
  227. func (t *Transport) RemoveAllPeers() {
  228. t.mu.Lock()
  229. defer t.mu.Unlock()
  230. for id := range t.peers {
  231. t.removePeer(id)
  232. }
  233. }
  234. // the caller of this function must have the peers mutex.
  235. func (t *Transport) removePeer(id types.ID) {
  236. if peer, ok := t.peers[id]; ok {
  237. peer.stop()
  238. } else {
  239. plog.Panicf("unexpected removal of unknown peer '%d'", id)
  240. }
  241. delete(t.peers, id)
  242. delete(t.LeaderStats.Followers, id.String())
  243. t.prober.Remove(id.String())
  244. }
  245. func (t *Transport) UpdatePeer(id types.ID, us []string) {
  246. t.mu.Lock()
  247. defer t.mu.Unlock()
  248. // TODO: return error or just panic?
  249. if _, ok := t.peers[id]; !ok {
  250. return
  251. }
  252. urls, err := types.NewURLs(us)
  253. if err != nil {
  254. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  255. }
  256. t.peers[id].update(urls)
  257. t.prober.Remove(id.String())
  258. addPeerToProber(t.prober, id.String(), us)
  259. }
  260. func (t *Transport) ActiveSince(id types.ID) time.Time {
  261. t.mu.Lock()
  262. defer t.mu.Unlock()
  263. if p, ok := t.peers[id]; ok {
  264. return p.activeSince()
  265. }
  266. return time.Time{}
  267. }
  268. func (t *Transport) SnapshotReady(rc io.ReadCloser, index uint64) {
  269. t.snapst.put(rc, index)
  270. }
  271. type Pausable interface {
  272. Pause()
  273. Resume()
  274. }
  275. // for testing
  276. func (t *Transport) Pause() {
  277. for _, p := range t.peers {
  278. p.(Pausable).Pause()
  279. }
  280. }
  281. func (t *Transport) Resume() {
  282. for _, p := range t.peers {
  283. p.(Pausable).Resume()
  284. }
  285. }