entry_writer.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 entryWriter struct {
  23. w io.Writer
  24. id types.ID
  25. }
  26. func newEntryWriter(w io.Writer, id types.ID) *entryWriter {
  27. ew := &entryWriter{
  28. w: w,
  29. id: id,
  30. }
  31. return ew
  32. }
  33. func (ew *entryWriter) writeEntries(ents []raftpb.Entry) error {
  34. l := len(ents)
  35. if l == 0 {
  36. return nil
  37. }
  38. if err := binary.Write(ew.w, binary.BigEndian, uint64(l)); err != nil {
  39. return err
  40. }
  41. metrics.Counter("rafthttp.stream.bytes_sent." + ew.id.String()).AddN(8)
  42. for i := 0; i < l; i++ {
  43. if err := ew.writeEntry(&ents[i]); err != nil {
  44. return err
  45. }
  46. metrics.Counter("rafthttp.stream.entries_sent." + ew.id.String()).Add()
  47. }
  48. metrics.Gauge("rafthttp.stream.last_index_sent." + ew.id.String()).Set(int64(ents[l-1].Index))
  49. return nil
  50. }
  51. func (ew *entryWriter) writeEntry(ent *raftpb.Entry) error {
  52. size := ent.Size()
  53. if err := binary.Write(ew.w, binary.BigEndian, uint64(size)); err != nil {
  54. return err
  55. }
  56. b, err := ent.Marshal()
  57. if err != nil {
  58. return err
  59. }
  60. _, err = ew.w.Write(b)
  61. metrics.Counter("rafthttp.stream.bytes_sent." + ew.id.String()).AddN(8 + uint64(size))
  62. return err
  63. }
  64. func (ew *entryWriter) stop() {
  65. metrics.Counter("rafthttp.stream.bytes_sent." + ew.id.String()).Remove()
  66. metrics.Counter("rafthttp.stream.entries_sent." + ew.id.String()).Remove()
  67. metrics.Gauge("rafthttp.stream.last_index_sent." + ew.id.String()).Remove()
  68. }