entry_reader.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. "encoding/binary"
  17. "io"
  18. "github.com/coreos/etcd/pkg/metrics"
  19. "github.com/coreos/etcd/pkg/types"
  20. "github.com/coreos/etcd/raft/raftpb"
  21. )
  22. type entryReader struct {
  23. r io.Reader
  24. id types.ID
  25. ents *metrics.Counter
  26. bytes *metrics.Counter
  27. lastIndex *metrics.Gauge
  28. }
  29. func newEntryReader(r io.Reader, id types.ID) *entryReader {
  30. return &entryReader{
  31. r: r,
  32. id: id,
  33. ents: metrics.GetMap("rafthttp.stream.entries_received").NewCounter(id.String()),
  34. bytes: metrics.GetMap("rafthttp.stream.bytes_received").NewCounter(id.String()),
  35. lastIndex: metrics.GetMap("rafthttp.stream.last_index_received").NewGauge(id.String()),
  36. }
  37. }
  38. func (er *entryReader) readEntries() ([]raftpb.Entry, error) {
  39. var l uint64
  40. if err := binary.Read(er.r, binary.BigEndian, &l); err != nil {
  41. return nil, err
  42. }
  43. er.bytes.AddBy(8)
  44. ents := make([]raftpb.Entry, int(l))
  45. for i := 0; i < int(l); i++ {
  46. if err := er.readEntry(&ents[i]); err != nil {
  47. return nil, err
  48. }
  49. er.ents.Add()
  50. }
  51. er.lastIndex.Set(int64(ents[l-1].Index))
  52. return ents, nil
  53. }
  54. func (er *entryReader) readEntry(ent *raftpb.Entry) error {
  55. var l uint64
  56. if err := binary.Read(er.r, binary.BigEndian, &l); err != nil {
  57. return err
  58. }
  59. buf := make([]byte, int(l))
  60. if _, err := io.ReadFull(er.r, buf); err != nil {
  61. return err
  62. }
  63. er.bytes.AddBy(8 + int64(l))
  64. return ent.Unmarshal(buf)
  65. }
  66. func (er *entryReader) stop() {
  67. metrics.GetMap("rafthttp.stream.entries_received").Delete(er.id.String())
  68. metrics.GetMap("rafthttp.stream.bytes_received").Delete(er.id.String())
  69. metrics.GetMap("rafthttp.stream.last_index_received").Delete(er.id.String())
  70. }