snapshot_sender.go 4.2 KB

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