message.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 snap
  15. import (
  16. "io"
  17. "github.com/coreos/etcd/pkg/ioutil"
  18. "github.com/coreos/etcd/raft/raftpb"
  19. )
  20. // Message is a struct that contains a raft Message and a ReadCloser. The type
  21. // of raft message MUST be MsgSnap, which contains the raft meta-data and an
  22. // additional data []byte field that contains the snapshot of the actual state
  23. // machine.
  24. // Message contains the ReadCloser field for handling large snapshot. This avoid
  25. // copying the entire snapshot into a byte array, which consumes a lot of memory.
  26. //
  27. // User of Message should close the Message after sending it.
  28. type Message struct {
  29. raftpb.Message
  30. ReadCloser io.ReadCloser
  31. TotalSize int64
  32. closeC chan bool
  33. }
  34. func NewMessage(rs raftpb.Message, rc io.ReadCloser, rcSize int64) *Message {
  35. return &Message{
  36. Message: rs,
  37. ReadCloser: ioutil.NewExactReadCloser(rc, rcSize),
  38. TotalSize: int64(rs.Size()) + rcSize,
  39. closeC: make(chan bool, 1),
  40. }
  41. }
  42. // CloseNotify returns a channel that receives a single value
  43. // when the message sent is finished. true indicates the sent
  44. // is successful.
  45. func (m Message) CloseNotify() <-chan bool {
  46. return m.closeC
  47. }
  48. func (m Message) CloseWithError(err error) {
  49. if cerr := m.ReadCloser.Close(); cerr != nil {
  50. err = cerr
  51. }
  52. if err == nil {
  53. m.closeC <- true
  54. } else {
  55. m.closeC <- false
  56. }
  57. }