entry_writer.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package rafthttp
  14. import (
  15. "encoding/binary"
  16. "io"
  17. "github.com/coreos/etcd/pkg/metrics"
  18. "github.com/coreos/etcd/pkg/types"
  19. "github.com/coreos/etcd/raft/raftpb"
  20. )
  21. type entryWriter struct {
  22. w io.Writer
  23. id types.ID
  24. ents *metrics.Counter
  25. bytes *metrics.Counter
  26. lastIndex *metrics.Gauge
  27. }
  28. func newEntryWriter(w io.Writer, id types.ID) *entryWriter {
  29. ew := &entryWriter{
  30. w: w,
  31. id: id,
  32. ents: metrics.GetMap("rafthttp.stream.entries_sent").NewCounter(id.String()),
  33. bytes: metrics.GetMap("rafthttp.stream.bytes_sent").NewCounter(id.String()),
  34. lastIndex: metrics.GetMap("rafthttp.stream.last_index_sent").NewGauge(id.String()),
  35. }
  36. return ew
  37. }
  38. func (ew *entryWriter) writeEntries(ents []raftpb.Entry) error {
  39. l := len(ents)
  40. if l == 0 {
  41. return nil
  42. }
  43. if err := binary.Write(ew.w, binary.BigEndian, uint64(l)); err != nil {
  44. return err
  45. }
  46. ew.bytes.AddBy(8)
  47. for i := 0; i < l; i++ {
  48. if err := ew.writeEntry(&ents[i]); err != nil {
  49. return err
  50. }
  51. ew.ents.Add()
  52. }
  53. ew.lastIndex.Set(int64(ents[l-1].Index))
  54. return nil
  55. }
  56. func (ew *entryWriter) writeEntry(ent *raftpb.Entry) error {
  57. size := ent.Size()
  58. if err := binary.Write(ew.w, binary.BigEndian, uint64(size)); err != nil {
  59. return err
  60. }
  61. b, err := ent.Marshal()
  62. if err != nil {
  63. return err
  64. }
  65. _, err = ew.w.Write(b)
  66. ew.bytes.AddBy(8 + int64(size))
  67. return err
  68. }
  69. func (ew *entryWriter) stop() {
  70. metrics.GetMap("rafthttp.stream.entries_sent").Delete(ew.id.String())
  71. metrics.GetMap("rafthttp.stream.bytes_sent").Delete(ew.id.String())
  72. metrics.GetMap("rafthttp.stream.last_index_sent").Delete(ew.id.String())
  73. }