snapshot_sender.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. "bytes"
  17. "context"
  18. "io"
  19. "io/ioutil"
  20. "net/http"
  21. "time"
  22. "github.com/coreos/etcd/pkg/httputil"
  23. pioutil "github.com/coreos/etcd/pkg/ioutil"
  24. "github.com/coreos/etcd/pkg/types"
  25. "github.com/coreos/etcd/raft"
  26. "github.com/coreos/etcd/raftsnap"
  27. "go.uber.org/zap"
  28. )
  29. var (
  30. // timeout for reading snapshot response body
  31. snapResponseReadTimeout = 5 * time.Second
  32. )
  33. type snapshotSender struct {
  34. from, to types.ID
  35. cid types.ID
  36. tr *Transport
  37. picker *urlPicker
  38. status *peerStatus
  39. r Raft
  40. errorc chan error
  41. stopc chan struct{}
  42. }
  43. func newSnapshotSender(tr *Transport, picker *urlPicker, to types.ID, status *peerStatus) *snapshotSender {
  44. return &snapshotSender{
  45. from: tr.ID,
  46. to: to,
  47. cid: tr.ClusterID,
  48. tr: tr,
  49. picker: picker,
  50. status: status,
  51. r: tr.Raft,
  52. errorc: tr.ErrorC,
  53. stopc: make(chan struct{}),
  54. }
  55. }
  56. func (s *snapshotSender) stop() { close(s.stopc) }
  57. func (s *snapshotSender) send(merged raftsnap.Message) {
  58. m := merged.Message
  59. body := createSnapBody(s.tr.Logger, merged)
  60. defer body.Close()
  61. u := s.picker.pick()
  62. req := createPostRequest(u, RaftSnapshotPrefix, body, "application/octet-stream", s.tr.URLs, s.from, s.cid)
  63. if s.tr.Logger != nil {
  64. s.tr.Logger.Info(
  65. "sending database snapshot",
  66. zap.Uint64("snapshot-index", m.Snapshot.Metadata.Index),
  67. zap.String("remote-peer-id", types.ID(m.To).String()),
  68. )
  69. } else {
  70. plog.Infof("start to send database snapshot [index: %d, to %s]...", m.Snapshot.Metadata.Index, types.ID(m.To))
  71. }
  72. err := s.post(req)
  73. defer merged.CloseWithError(err)
  74. if err != nil {
  75. if s.tr.Logger != nil {
  76. s.tr.Logger.Warn(
  77. "failed to send database snapshot",
  78. zap.Uint64("snapshot-index", m.Snapshot.Metadata.Index),
  79. zap.String("remote-peer-id", types.ID(m.To).String()),
  80. zap.Error(err),
  81. )
  82. } else {
  83. plog.Warningf("database snapshot [index: %d, to: %s] failed to be sent out (%v)", m.Snapshot.Metadata.Index, types.ID(m.To), err)
  84. }
  85. // errMemberRemoved is a critical error since a removed member should
  86. // always be stopped. So we use reportCriticalError to report it to errorc.
  87. if err == errMemberRemoved {
  88. reportCriticalError(err, s.errorc)
  89. }
  90. s.picker.unreachable(u)
  91. s.status.deactivate(failureType{source: sendSnap, action: "post"}, err.Error())
  92. s.r.ReportUnreachable(m.To)
  93. // report SnapshotFailure to raft state machine. After raft state
  94. // machine knows about it, it would pause a while and retry sending
  95. // new snapshot message.
  96. s.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  97. sentFailures.WithLabelValues(types.ID(m.To).String()).Inc()
  98. return
  99. }
  100. s.status.activate()
  101. s.r.ReportSnapshot(m.To, raft.SnapshotFinish)
  102. if s.tr.Logger != nil {
  103. s.tr.Logger.Info(
  104. "sent database snapshot",
  105. zap.Uint64("snapshot-index", m.Snapshot.Metadata.Index),
  106. zap.String("remote-peer-id", types.ID(m.To).String()),
  107. )
  108. } else {
  109. plog.Infof("database snapshot [index: %d, to: %s] sent out successfully", m.Snapshot.Metadata.Index, types.ID(m.To))
  110. }
  111. sentBytes.WithLabelValues(types.ID(m.To).String()).Add(float64(merged.TotalSize))
  112. }
  113. // post posts the given request.
  114. // It returns nil when request is sent out and processed successfully.
  115. func (s *snapshotSender) post(req *http.Request) (err error) {
  116. ctx, cancel := context.WithCancel(context.Background())
  117. req = req.WithContext(ctx)
  118. defer cancel()
  119. type responseAndError struct {
  120. resp *http.Response
  121. body []byte
  122. err error
  123. }
  124. result := make(chan responseAndError, 1)
  125. go func() {
  126. resp, err := s.tr.pipelineRt.RoundTrip(req)
  127. if err != nil {
  128. result <- responseAndError{resp, nil, err}
  129. return
  130. }
  131. // close the response body when timeouts.
  132. // prevents from reading the body forever when the other side dies right after
  133. // successfully receives the request body.
  134. time.AfterFunc(snapResponseReadTimeout, func() { httputil.GracefulClose(resp) })
  135. body, err := ioutil.ReadAll(resp.Body)
  136. result <- responseAndError{resp, body, err}
  137. }()
  138. select {
  139. case <-s.stopc:
  140. return errStopped
  141. case r := <-result:
  142. if r.err != nil {
  143. return r.err
  144. }
  145. return checkPostResponse(r.resp, r.body, req, s.to)
  146. }
  147. }
  148. func createSnapBody(lg *zap.Logger, merged raftsnap.Message) io.ReadCloser {
  149. buf := new(bytes.Buffer)
  150. enc := &messageEncoder{w: buf}
  151. // encode raft message
  152. if err := enc.encode(&merged.Message); err != nil {
  153. if lg != nil {
  154. lg.Panic("failed to encode message", zap.Error(err))
  155. } else {
  156. plog.Panicf("encode message error (%v)", err)
  157. }
  158. }
  159. return &pioutil.ReaderAndCloser{
  160. Reader: io.MultiReader(buf, merged.ReadCloser),
  161. Closer: merged.ReadCloser,
  162. }
  163. }