snapshot_sender.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. err := s.post(req)
  78. defer merged.CloseWithError(err)
  79. if err != nil {
  80. if s.tr.Logger != nil {
  81. s.tr.Logger.Warn(
  82. "failed to send database snapshot",
  83. zap.Uint64("snapshot-index", m.Snapshot.Metadata.Index),
  84. zap.String("remote-peer-id", to),
  85. zap.Int64("bytes", merged.TotalSize),
  86. zap.String("size", humanize.Bytes(uint64(merged.TotalSize))),
  87. zap.Error(err),
  88. )
  89. } else {
  90. plog.Warningf("database snapshot [index: %d, to: %s] failed to be sent out (%v)", m.Snapshot.Metadata.Index, types.ID(m.To), err)
  91. }
  92. // errMemberRemoved is a critical error since a removed member should
  93. // always be stopped. So we use reportCriticalError to report it to errorc.
  94. if err == errMemberRemoved {
  95. reportCriticalError(err, s.errorc)
  96. }
  97. s.picker.unreachable(u)
  98. s.status.deactivate(failureType{source: sendSnap, action: "post"}, err.Error())
  99. s.r.ReportUnreachable(m.To)
  100. // report SnapshotFailure to raft state machine. After raft state
  101. // machine knows about it, it would pause a while and retry sending
  102. // new snapshot message.
  103. s.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  104. sentFailures.WithLabelValues(to).Inc()
  105. snapshotSendFailures.WithLabelValues(to).Inc()
  106. return
  107. }
  108. s.status.activate()
  109. s.r.ReportSnapshot(m.To, raft.SnapshotFinish)
  110. if s.tr.Logger != nil {
  111. s.tr.Logger.Info(
  112. "sent database snapshot",
  113. zap.Uint64("snapshot-index", m.Snapshot.Metadata.Index),
  114. zap.String("remote-peer-id", to),
  115. zap.Int64("bytes", merged.TotalSize),
  116. zap.String("size", humanize.Bytes(uint64(merged.TotalSize))),
  117. )
  118. } else {
  119. plog.Infof("database snapshot [index: %d, to: %s] sent out successfully", m.Snapshot.Metadata.Index, types.ID(m.To))
  120. }
  121. sentBytes.WithLabelValues(to).Add(float64(merged.TotalSize))
  122. snapshotSend.WithLabelValues(to).Inc()
  123. snapshotSendSeconds.WithLabelValues(to).Observe(time.Since(start).Seconds())
  124. }
  125. // post posts the given request.
  126. // It returns nil when request is sent out and processed successfully.
  127. func (s *snapshotSender) post(req *http.Request) (err error) {
  128. ctx, cancel := context.WithCancel(context.Background())
  129. req = req.WithContext(ctx)
  130. defer cancel()
  131. type responseAndError struct {
  132. resp *http.Response
  133. body []byte
  134. err error
  135. }
  136. result := make(chan responseAndError, 1)
  137. go func() {
  138. resp, err := s.tr.pipelineRt.RoundTrip(req)
  139. if err != nil {
  140. result <- responseAndError{resp, nil, err}
  141. return
  142. }
  143. // close the response body when timeouts.
  144. // prevents from reading the body forever when the other side dies right after
  145. // successfully receives the request body.
  146. time.AfterFunc(snapResponseReadTimeout, func() { httputil.GracefulClose(resp) })
  147. body, err := ioutil.ReadAll(resp.Body)
  148. result <- responseAndError{resp, body, err}
  149. }()
  150. select {
  151. case <-s.stopc:
  152. return errStopped
  153. case r := <-result:
  154. if r.err != nil {
  155. return r.err
  156. }
  157. return checkPostResponse(r.resp, r.body, req, s.to)
  158. }
  159. }
  160. func createSnapBody(lg *zap.Logger, merged snap.Message) io.ReadCloser {
  161. buf := new(bytes.Buffer)
  162. enc := &messageEncoder{w: buf}
  163. // encode raft message
  164. if err := enc.encode(&merged.Message); err != nil {
  165. if lg != nil {
  166. lg.Panic("failed to encode message", zap.Error(err))
  167. } else {
  168. plog.Panicf("encode message error (%v)", err)
  169. }
  170. }
  171. return &pioutil.ReaderAndCloser{
  172. Reader: io.MultiReader(buf, merged.ReadCloser),
  173. Closer: merged.ReadCloser,
  174. }
  175. }