entry_writer.go 2.2 KB

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