entry_reader.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/Godeps/_workspace/src/github.com/codahale/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. }
  26. func newEntryReader(r io.Reader, id types.ID) *entryReader {
  27. return &entryReader{
  28. r: r,
  29. id: id,
  30. }
  31. }
  32. func (er *entryReader) readEntries() ([]raftpb.Entry, error) {
  33. var l uint64
  34. if err := binary.Read(er.r, binary.BigEndian, &l); err != nil {
  35. return nil, err
  36. }
  37. metrics.Counter("rafthttp.stream.bytes_received." + er.id.String()).AddN(8)
  38. ents := make([]raftpb.Entry, int(l))
  39. for i := 0; i < int(l); i++ {
  40. if err := er.readEntry(&ents[i]); err != nil {
  41. return nil, err
  42. }
  43. metrics.Counter("rafthttp.stream.entries_received." + er.id.String()).AddN(8)
  44. }
  45. if l > 0 {
  46. metrics.Gauge("rafthttp.stream.last_index_received." + er.id.String()).Set(int64(ents[l-1].Index))
  47. }
  48. return ents, nil
  49. }
  50. func (er *entryReader) readEntry(ent *raftpb.Entry) error {
  51. var l uint64
  52. if err := binary.Read(er.r, binary.BigEndian, &l); err != nil {
  53. return err
  54. }
  55. buf := make([]byte, int(l))
  56. if _, err := io.ReadFull(er.r, buf); err != nil {
  57. return err
  58. }
  59. metrics.Counter("rafthttp.stream.bytes_received." + er.id.String()).AddN(8 + uint64(l))
  60. return ent.Unmarshal(buf)
  61. }
  62. func (er *entryReader) stop() {
  63. metrics.Counter("rafthttp.stream.bytes_received." + er.id.String()).Remove()
  64. metrics.Counter("rafthttp.stream.entries_received." + er.id.String()).Remove()
  65. metrics.Gauge("rafthttp.stream.last_index_received." + er.id.String()).Remove()
  66. }