message.go 1.8 KB

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