transport.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. "net/http"
  17. "sync"
  18. "time"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  20. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/xiang90/probing"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  22. "github.com/coreos/etcd/etcdserver/stats"
  23. "github.com/coreos/etcd/pkg/logutil"
  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. "github.com/coreos/etcd/snap"
  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. ClusterID types.ID // raft cluster ID for request validation
  94. Raft Raft // raft state machine, to which the Transport forwards received messages and reports status
  95. Snapshotter *snap.Snapshotter
  96. ServerStats *stats.ServerStats // used to record general transportation statistics
  97. // used to record transportation statistics with followers when
  98. // performing as leader in raft protocol
  99. LeaderStats *stats.LeaderStats
  100. // error channel used to report detected critical error, e.g.,
  101. // the member has been permanently removed from the cluster
  102. // When an error is received from ErrorC, user should stop raft state
  103. // machine and thus stop the Transport.
  104. ErrorC chan error
  105. V3demo bool
  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.Raft, t.ClusterID)
  130. streamHandler := newStreamHandler(t, t.Raft, t.ID, t.ClusterID)
  131. snapHandler := newSnapshotHandler(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, ok := t.peers[to]
  153. t.mu.RUnlock()
  154. if ok {
  155. if m.Type == raftpb.MsgApp {
  156. t.ServerStats.SendAppendReq(m.Size())
  157. }
  158. p.send(m)
  159. continue
  160. }
  161. g, ok := t.remotes[to]
  162. if ok {
  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. for _, r := range t.remotes {
  171. r.stop()
  172. }
  173. for _, p := range t.peers {
  174. p.stop()
  175. }
  176. t.prober.RemoveAll()
  177. if tr, ok := t.streamRt.(*http.Transport); ok {
  178. tr.CloseIdleConnections()
  179. }
  180. if tr, ok := t.pipelineRt.(*http.Transport); ok {
  181. tr.CloseIdleConnections()
  182. }
  183. }
  184. func (t *Transport) AddRemote(id types.ID, us []string) {
  185. t.mu.Lock()
  186. defer t.mu.Unlock()
  187. if _, ok := t.remotes[id]; ok {
  188. return
  189. }
  190. urls, err := types.NewURLs(us)
  191. if err != nil {
  192. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  193. }
  194. t.remotes[id] = startRemote(t.pipelineRt, urls, t.ID, id, t.ClusterID, t.Raft, t.ErrorC)
  195. }
  196. func (t *Transport) AddPeer(id types.ID, us []string) {
  197. t.mu.Lock()
  198. defer t.mu.Unlock()
  199. if _, ok := t.peers[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. fs := t.LeaderStats.Follower(id.String())
  207. t.peers[id] = startPeer(t.streamRt, t.pipelineRt, urls, t.ID, id, t.ClusterID, t.Raft, fs, t.ErrorC, t.V3demo)
  208. addPeerToProber(t.prober, id.String(), us)
  209. }
  210. func (t *Transport) RemovePeer(id types.ID) {
  211. t.mu.Lock()
  212. defer t.mu.Unlock()
  213. t.removePeer(id)
  214. }
  215. func (t *Transport) RemoveAllPeers() {
  216. t.mu.Lock()
  217. defer t.mu.Unlock()
  218. for id := range t.peers {
  219. t.removePeer(id)
  220. }
  221. }
  222. // the caller of this function must have the peers mutex.
  223. func (t *Transport) removePeer(id types.ID) {
  224. if peer, ok := t.peers[id]; ok {
  225. peer.stop()
  226. } else {
  227. plog.Panicf("unexpected removal of unknown peer '%d'", id)
  228. }
  229. delete(t.peers, id)
  230. delete(t.LeaderStats.Followers, id.String())
  231. t.prober.Remove(id.String())
  232. }
  233. func (t *Transport) UpdatePeer(id types.ID, us []string) {
  234. t.mu.Lock()
  235. defer t.mu.Unlock()
  236. // TODO: return error or just panic?
  237. if _, ok := t.peers[id]; !ok {
  238. return
  239. }
  240. urls, err := types.NewURLs(us)
  241. if err != nil {
  242. plog.Panicf("newURLs %+v should never fail: %+v", us, err)
  243. }
  244. t.peers[id].update(urls)
  245. t.prober.Remove(id.String())
  246. addPeerToProber(t.prober, id.String(), us)
  247. }
  248. func (t *Transport) ActiveSince(id types.ID) time.Time {
  249. t.mu.Lock()
  250. defer t.mu.Unlock()
  251. if p, ok := t.peers[id]; ok {
  252. return p.activeSince()
  253. }
  254. return time.Time{}
  255. }
  256. func (t *Transport) SendSnapshot(m snap.Message) {
  257. p := t.peers[types.ID(m.To)]
  258. if p == nil {
  259. m.CloseWithError(errMemberNotFound)
  260. return
  261. }
  262. p.sendSnap(m)
  263. }
  264. type Pausable interface {
  265. Pause()
  266. Resume()
  267. }
  268. // for testing
  269. func (t *Transport) Pause() {
  270. for _, p := range t.peers {
  271. p.(Pausable).Pause()
  272. }
  273. }
  274. func (t *Transport) Resume() {
  275. for _, p := range t.peers {
  276. p.(Pausable).Resume()
  277. }
  278. }
  279. type nopTransporter struct{}
  280. func NewNopTransporter() Transporter {
  281. return &nopTransporter{}
  282. }
  283. func (s *nopTransporter) Start() error { return nil }
  284. func (s *nopTransporter) Handler() http.Handler { return nil }
  285. func (s *nopTransporter) Send(m []raftpb.Message) {}
  286. func (s *nopTransporter) SendSnapshot(m snap.Message) {}
  287. func (s *nopTransporter) AddRemote(id types.ID, us []string) {}
  288. func (s *nopTransporter) AddPeer(id types.ID, us []string) {}
  289. func (s *nopTransporter) RemovePeer(id types.ID) {}
  290. func (s *nopTransporter) RemoveAllPeers() {}
  291. func (s *nopTransporter) UpdatePeer(id types.ID, us []string) {}
  292. func (s *nopTransporter) ActiveSince(id types.ID) time.Time { return time.Time{} }
  293. func (s *nopTransporter) Stop() {}
  294. func (s *nopTransporter) Pause() {}
  295. func (s *nopTransporter) Resume() {}
  296. type snapTransporter struct {
  297. nopTransporter
  298. snapDoneC chan snap.Message
  299. snapDir string
  300. }
  301. func NewSnapTransporter(snapDir string) (Transporter, <-chan snap.Message) {
  302. ch := make(chan snap.Message, 1)
  303. tr := &snapTransporter{snapDoneC: ch, snapDir: snapDir}
  304. return tr, ch
  305. }
  306. func (s *snapTransporter) SendSnapshot(m snap.Message) {
  307. ss := snap.New(s.snapDir)
  308. ss.SaveDBFrom(m.ReadCloser, m.Snapshot.Metadata.Index+1)
  309. m.CloseWithError(nil)
  310. s.snapDoneC <- m
  311. }