snapshot_sender.go 5.5 KB

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