entry_reader.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package rafthttp
  14. import (
  15. "encoding/binary"
  16. "io"
  17. "github.com/coreos/etcd/pkg/metrics"
  18. "github.com/coreos/etcd/pkg/types"
  19. "github.com/coreos/etcd/raft/raftpb"
  20. )
  21. type entryReader struct {
  22. r io.Reader
  23. id types.ID
  24. ents *metrics.Counter
  25. bytes *metrics.Counter
  26. lastIndex *metrics.Gauge
  27. }
  28. func newEntryReader(r io.Reader, id types.ID) *entryReader {
  29. return &entryReader{
  30. r: r,
  31. id: id,
  32. ents: metrics.GetMap("rafthttp.stream.entries_received").NewCounter(id.String()),
  33. bytes: metrics.GetMap("rafthttp.stream.bytes_received").NewCounter(id.String()),
  34. lastIndex: metrics.GetMap("rafthttp.stream.last_index_received").NewGauge(id.String()),
  35. }
  36. }
  37. func (er *entryReader) readEntries() ([]raftpb.Entry, error) {
  38. var l uint64
  39. if err := binary.Read(er.r, binary.BigEndian, &l); err != nil {
  40. return nil, err
  41. }
  42. er.bytes.AddBy(8)
  43. ents := make([]raftpb.Entry, int(l))
  44. for i := 0; i < int(l); i++ {
  45. if err := er.readEntry(&ents[i]); err != nil {
  46. return nil, err
  47. }
  48. er.ents.Add()
  49. }
  50. er.lastIndex.Set(int64(ents[l-1].Index))
  51. return ents, nil
  52. }
  53. func (er *entryReader) readEntry(ent *raftpb.Entry) error {
  54. var l uint64
  55. if err := binary.Read(er.r, binary.BigEndian, &l); err != nil {
  56. return err
  57. }
  58. buf := make([]byte, int(l))
  59. if _, err := io.ReadFull(er.r, buf); err != nil {
  60. return err
  61. }
  62. er.bytes.AddBy(8 + int64(l))
  63. return ent.Unmarshal(buf)
  64. }
  65. func (er *entryReader) stop() {
  66. metrics.GetMap("rafthttp.stream.entries_received").Delete(er.id.String())
  67. metrics.GetMap("rafthttp.stream.bytes_received").Delete(er.id.String())
  68. metrics.GetMap("rafthttp.stream.last_index_received").Delete(er.id.String())
  69. }