decoder.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 wal
  15. import (
  16. "bufio"
  17. "encoding/binary"
  18. "hash"
  19. "io"
  20. "sync"
  21. "github.com/coreos/etcd/pkg/crc"
  22. "github.com/coreos/etcd/pkg/pbutil"
  23. "github.com/coreos/etcd/raft/raftpb"
  24. "github.com/coreos/etcd/wal/walpb"
  25. )
  26. type decoder struct {
  27. mu sync.Mutex
  28. br *bufio.Reader
  29. c io.Closer
  30. crc hash.Hash32
  31. }
  32. func newDecoder(rc io.ReadCloser) *decoder {
  33. return &decoder{
  34. br: bufio.NewReader(rc),
  35. c: rc,
  36. crc: crc.New(0, crcTable),
  37. }
  38. }
  39. func (d *decoder) decode(rec *walpb.Record) error {
  40. d.mu.Lock()
  41. defer d.mu.Unlock()
  42. rec.Reset()
  43. l, err := readInt64(d.br)
  44. if err != nil {
  45. return err
  46. }
  47. data := make([]byte, l)
  48. if _, err = io.ReadFull(d.br, data); err != nil {
  49. // ReadFull returns io.EOF only if no bytes were read
  50. // the decoder should treat this as an ErrUnexpectedEOF instead.
  51. if err == io.EOF {
  52. err = io.ErrUnexpectedEOF
  53. }
  54. return err
  55. }
  56. if err := rec.Unmarshal(data); err != nil {
  57. return err
  58. }
  59. // skip crc checking if the record type is crcType
  60. if rec.Type == crcType {
  61. return nil
  62. }
  63. d.crc.Write(rec.Data)
  64. return rec.Validate(d.crc.Sum32())
  65. }
  66. func (d *decoder) updateCRC(prevCrc uint32) {
  67. d.crc = crc.New(prevCrc, crcTable)
  68. }
  69. func (d *decoder) lastCRC() uint32 {
  70. return d.crc.Sum32()
  71. }
  72. func (d *decoder) close() error {
  73. return d.c.Close()
  74. }
  75. func mustUnmarshalEntry(d []byte) raftpb.Entry {
  76. var e raftpb.Entry
  77. pbutil.MustUnmarshal(&e, d)
  78. return e
  79. }
  80. func mustUnmarshalState(d []byte) raftpb.HardState {
  81. var s raftpb.HardState
  82. pbutil.MustUnmarshal(&s, d)
  83. return s
  84. }
  85. func readInt64(r io.Reader) (int64, error) {
  86. var n int64
  87. err := binary.Read(r, binary.LittleEndian, &n)
  88. return n, err
  89. }