transport.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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/logutil"
  25. "github.com/coreos/etcd/pkg/transport"
  26. "github.com/coreos/etcd/pkg/types"
  27. "github.com/coreos/etcd/raft"
  28. "github.com/coreos/etcd/raft/raftpb"
  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. // SnapshotSaver is the interface that wraps the SaveFrom method.
  38. type SnapshotSaver interface {
  39. // SaveFrom saves the snapshot data at the given index from the given reader.
  40. SaveFrom(r io.Reader, index uint64) error
  41. }
  42. type Transporter interface {
  43. // Start starts the given Transporter.
  44. // Start MUST be called before calling other functions in the interface.
  45. Start() error
  46. // Handler returns the HTTP handler of the transporter.
  47. // A transporter HTTP handler handles the HTTP requests
  48. // from remote peers.
  49. // The handler MUST be used to handle RaftPrefix(/raft)
  50. // endpoint.
  51. Handler() http.Handler
  52. // Send sends out the given messages to the remote peers.
  53. // Each message has a To field, which is an id that maps
  54. // to an existing peer in the transport.
  55. // If the id cannot be found in the transport, the message
  56. // will be ignored.
  57. Send(m []raftpb.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. // SnapshotReady accepts a snapshot at the given index that is ready to send out.
  83. // It is expected that caller sends a raft snapshot message with
  84. // the given index soon, and the accepted snapshot will be sent out
  85. // together. After sending, snapshot sent status is reported
  86. // through Raft.SnapshotStatus.
  87. // SnapshotReady MUST not be called when the snapshot sent status of previous
  88. // accepted one has not been reported.
  89. SnapshotReady(rc io.ReadCloser, index uint64)
  90. // Stop closes the connections and stops the transporter.
  91. Stop()
  92. }
  93. // Transport implements Transporter interface. It provides the functionality
  94. // to send raft messages to peers, and receive raft messages from peers.
  95. // User should call Handler method to get a handler to serve requests
  96. // received from peerURLs.
  97. // User needs to call Start before calling other functions, and call
  98. // Stop when the Transport is no longer used.
  99. type Transport struct {
  100. DialTimeout time.Duration // maximum duration before timing out dial of the request
  101. TLSInfo transport.TLSInfo // TLS information used when creating connection
  102. ID types.ID // local member ID
  103. ClusterID types.ID // raft cluster ID for request validation
  104. Raft Raft // raft state machine, to which the Transport forwards received messages and reports status
  105. SnapSaver SnapshotSaver // used to save snapshot in v3 snapshot messages
  106. ServerStats *stats.ServerStats // used to record general transportation statistics
  107. // used to record transportation statistics with followers when
  108. // performing as leader in raft protocol
  109. LeaderStats *stats.LeaderStats
  110. // error channel used to report detected critical error, e.g.,
  111. // the member has been permanently removed from the cluster
  112. // When an error is received from ErrorC, user should stop raft state
  113. // machine and thus stop the Transport.
  114. ErrorC chan error
  115. V3demo bool
  116. streamRt http.RoundTripper // roundTripper used by streams
  117. pipelineRt http.RoundTripper // roundTripper used by pipelines
  118. mu sync.RWMutex // protect the remote and peer map
  119. remotes map[types.ID]*remote // remotes map that helps newly joined member to catch up
  120. peers map[types.ID]Peer // peers map
  121. snapst *snapshotStore
  122. prober probing.Prober
  123. }
  124. func (t *Transport) Start() error {
  125. var err error
  126. t.streamRt, err = newStreamRoundTripper(t.TLSInfo, t.DialTimeout)
  127. if err != nil {
  128. return err
  129. }
  130. t.pipelineRt, err = NewRoundTripper(t.TLSInfo, t.DialTimeout)
  131. if err != nil {
  132. return err
  133. }
  134. t.remotes = make(map[types.ID]*remote)
  135. t.peers = make(map[types.ID]Peer)
  136. t.snapst = &snapshotStore{}
  137. t.prober = probing.NewProber(t.pipelineRt)
  138. return nil
  139. }
  140. func (t *Transport) Handler() http.Handler {
  141. pipelineHandler := newPipelineHandler(t.Raft, t.ClusterID)
  142. streamHandler := newStreamHandler(t, t.Raft, t.ID, t.ClusterID)
  143. snapHandler := newSnapshotHandler(t.Raft, t.SnapSaver, t.ClusterID)
  144. mux := http.NewServeMux()
  145. mux.Handle(RaftPrefix, pipelineHandler)
  146. mux.Handle(RaftStreamPrefix+"/", streamHandler)
  147. mux.Handle(RaftSnapshotPrefix, snapHandler)
  148. mux.Handle(ProbingPrefix, probing.NewHandler())
  149. return mux
  150. }
  151. func (t *Transport) Get(id types.ID) Peer {
  152. t.mu.RLock()
  153. defer t.mu.RUnlock()
  154. return t.peers[id]
  155. }
  156. func (t *Transport) Send(msgs []raftpb.Message) {
  157. for _, m := range msgs {
  158. if m.To == 0 {
  159. // ignore intentionally dropped message
  160. continue
  161. }
  162. to := types.ID(m.To)
  163. t.mu.RLock()
  164. p, ok := t.peers[to]
  165. t.mu.RUnlock()
  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. }