snapshot_sender.go 5.7 KB

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