snapshot_sender.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. "github.com/coreos/etcd/pkg/types"
  23. "github.com/coreos/etcd/raft"
  24. "github.com/coreos/etcd/raft/raftpb"
  25. )
  26. type snapshotSender struct {
  27. from, to types.ID
  28. cid types.ID
  29. tr http.RoundTripper
  30. picker *urlPicker
  31. status *peerStatus
  32. snapst *snapshotStore
  33. r Raft
  34. errorc chan error
  35. stopc chan struct{}
  36. }
  37. func newSnapshotSender(tr http.RoundTripper, picker *urlPicker, from, to, cid types.ID, status *peerStatus, snapst *snapshotStore, r Raft, errorc chan error) *snapshotSender {
  38. return &snapshotSender{
  39. from: from,
  40. to: to,
  41. cid: cid,
  42. tr: tr,
  43. picker: picker,
  44. status: status,
  45. snapst: snapst,
  46. r: r,
  47. errorc: errorc,
  48. stopc: make(chan struct{}),
  49. }
  50. }
  51. func (s *snapshotSender) stop() { close(s.stopc) }
  52. func (s *snapshotSender) send(m raftpb.Message) {
  53. start := time.Now()
  54. body := createSnapBody(m, s.snapst)
  55. defer body.Close()
  56. u := s.picker.pick()
  57. req := createPostRequest(u, RaftSnapshotPrefix, body, "application/octet-stream", s.from, s.cid)
  58. err := s.post(req)
  59. if err != nil {
  60. // errMemberRemoved is a critical error since a removed member should
  61. // always be stopped. So we use reportCriticalError to report it to errorc.
  62. if err == errMemberRemoved {
  63. reportCriticalError(err, s.errorc)
  64. }
  65. s.picker.unreachable(u)
  66. reportSentFailure(sendSnap, m)
  67. s.status.deactivate(failureType{source: sendSnap, action: "post"}, err.Error())
  68. s.r.ReportUnreachable(m.To)
  69. // report SnapshotFailure to raft state machine. After raft state
  70. // machine knows about it, it would pause a while and retry sending
  71. // new snapshot message.
  72. s.r.ReportSnapshot(m.To, raft.SnapshotFailure)
  73. if s.status.isActive() {
  74. plog.Warningf("snapshot [index: %d, to: %s] failed to be sent out (%v)", m.Snapshot.Metadata.Index, types.ID(m.To), err)
  75. } else {
  76. plog.Debugf("snapshot [index: %d, to: %s] failed to be sent out (%v)", m.Snapshot.Metadata.Index, types.ID(m.To), err)
  77. }
  78. return
  79. }
  80. reportSentDuration(sendSnap, m, time.Since(start))
  81. s.status.activate()
  82. s.r.ReportSnapshot(m.To, raft.SnapshotFinish)
  83. plog.Infof("snapshot [index: %d, to: %s] sent out successfully", m.Snapshot.Metadata.Index, types.ID(m.To))
  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, 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. // TODO: cancel the request if it has waited for a long time(~5s) after
  97. // it has write out the full request body, which helps to avoid receiver
  98. // dies when sender is waiting for response
  99. // TODO: the snapshot could be large and eat up all resources when writing
  100. // it out. Send it block by block and rest some time between to give the
  101. // time for main loop to run.
  102. resp, err := s.tr.RoundTrip(req)
  103. if err != nil {
  104. result <- responseAndError{resp, nil, err}
  105. return
  106. }
  107. body, err := ioutil.ReadAll(resp.Body)
  108. resp.Body.Close()
  109. result <- responseAndError{resp, body, err}
  110. }()
  111. select {
  112. case <-s.stopc:
  113. cancel()
  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. // readCloser implements io.ReadCloser interface.
  123. type readCloser struct {
  124. io.Reader
  125. io.Closer
  126. }
  127. // createSnapBody creates the request body for the given raft snapshot message.
  128. // Callers should close body when done reading from it.
  129. func createSnapBody(m raftpb.Message, snapst *snapshotStore) io.ReadCloser {
  130. buf := new(bytes.Buffer)
  131. enc := &messageEncoder{w: buf}
  132. // encode raft message
  133. if err := enc.encode(m); err != nil {
  134. plog.Panicf("encode message error (%v)", err)
  135. }
  136. // get snapshot
  137. rc := snapst.get(m.Snapshot.Metadata.Index)
  138. return &readCloser{
  139. Reader: io.MultiReader(buf, rc),
  140. Closer: rc,
  141. }
  142. }