entry_reader.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. if l > 0 {
  52. er.lastIndex.Set(int64(ents[l-1].Index))
  53. }
  54. return ents, nil
  55. }
  56. func (er *entryReader) readEntry(ent *raftpb.Entry) error {
  57. var l uint64
  58. if err := binary.Read(er.r, binary.BigEndian, &l); err != nil {
  59. return err
  60. }
  61. buf := make([]byte, int(l))
  62. if _, err := io.ReadFull(er.r, buf); err != nil {
  63. return err
  64. }
  65. er.bytes.AddBy(8 + int64(l))
  66. return ent.Unmarshal(buf)
  67. }
  68. func (er *entryReader) stop() {
  69. metrics.GetMap("rafthttp.stream.entries_received").Delete(er.id.String())
  70. metrics.GetMap("rafthttp.stream.bytes_received").Delete(er.id.String())
  71. metrics.GetMap("rafthttp.stream.last_index_received").Delete(er.id.String())
  72. }