snapshot_sender.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. // Copyright 2015 CoreOS, Inc.
  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 http.RoundTripper
  35. picker *urlPicker
  36. status *peerStatus
  37. r Raft
  38. errorc chan error
  39. stopc chan struct{}
  40. }
  41. func newSnapshotSender(tr http.RoundTripper, picker *urlPicker, from, to, cid types.ID, status *peerStatus, r Raft, errorc chan error) *snapshotSender {
  42. return &snapshotSender{
  43. from: from,
  44. to: to,
  45. cid: cid,
  46. tr: tr,
  47. picker: picker,
  48. status: status,
  49. r: r,
  50. errorc: 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. start := time.Now()
  58. body := createSnapBody(merged)
  59. defer body.Close()
  60. u := s.picker.pick()
  61. req := createPostRequest(u, RaftSnapshotPrefix, body, "application/octet-stream", s.from, s.cid)
  62. err := s.post(req)
  63. if err != nil {
  64. // errMemberRemoved is a critical error since a removed member should
  65. // always be stopped. So we use reportCriticalError to report it to errorc.
  66. if err == errMemberRemoved {
  67. reportCriticalError(err, s.errorc)
  68. }
  69. s.picker.unreachable(u)
  70. reportSentFailure(sendSnap, m)
  71. s.status.deactivate(failureType{source: sendSnap, action: "post"}, err.Error())
  72. s.r.ReportUnreachable(m.To)
  73. // report SnapshotFailure to raft state machine. After raft state
  74. // machine knows about it, it would pause a while and retry sending
  75. // new snapshot message.
  76. s.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  77. if s.status.isActive() {
  78. plog.Warningf("snapshot [index: %d, to: %s] failed to be sent out (%v)", m.Snapshot.Metadata.Index, types.ID(m.To), err)
  79. } else {
  80. plog.Debugf("snapshot [index: %d, to: %s] failed to be sent out (%v)", m.Snapshot.Metadata.Index, types.ID(m.To), err)
  81. }
  82. return
  83. }
  84. reportSentDuration(sendSnap, m, time.Since(start))
  85. s.status.activate()
  86. s.r.ReportSnapshot(m.To, raft.SnapshotFinish)
  87. plog.Infof("snapshot [index: %d, to: %s] sent out successfully", m.Snapshot.Metadata.Index, types.ID(m.To))
  88. }
  89. // post posts the given request.
  90. // It returns nil when request is sent out and processed successfully.
  91. func (s *snapshotSender) post(req *http.Request) (err error) {
  92. cancel := httputil.RequestCanceler(s.tr, req)
  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.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() { resp.Body.Close() })
  109. body, err := ioutil.ReadAll(resp.Body)
  110. result <- responseAndError{resp, body, err}
  111. }()
  112. select {
  113. case <-s.stopc:
  114. cancel()
  115. return errStopped
  116. case r := <-result:
  117. if r.err != nil {
  118. return r.err
  119. }
  120. return checkPostResponse(r.resp, r.body, req, s.to)
  121. }
  122. }
  123. func createSnapBody(merged snap.Message) io.ReadCloser {
  124. buf := new(bytes.Buffer)
  125. enc := &messageEncoder{w: buf}
  126. // encode raft message
  127. if err := enc.encode(merged.Message); err != nil {
  128. plog.Panicf("encode message error (%v)", err)
  129. }
  130. return &pioutil.ReaderAndCloser{
  131. Reader: io.MultiReader(buf, merged.ReadCloser),
  132. Closer: merged.ReadCloser,
  133. }
  134. }