snapshot_sender.go 4.3 KB

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