decoder.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. crc hash.Hash32
  30. }
  31. func newDecoder(r io.Reader) *decoder {
  32. return &decoder{
  33. br: bufio.NewReader(r),
  34. crc: crc.New(0, crcTable),
  35. }
  36. }
  37. func (d *decoder) decode(rec *walpb.Record) error {
  38. d.mu.Lock()
  39. defer d.mu.Unlock()
  40. rec.Reset()
  41. l, err := readInt64(d.br)
  42. if err != nil {
  43. return err
  44. }
  45. data := make([]byte, l)
  46. if _, err = io.ReadFull(d.br, data); err != nil {
  47. // ReadFull returns io.EOF only if no bytes were read
  48. // the decoder should treat this as an ErrUnexpectedEOF instead.
  49. if err == io.EOF {
  50. err = io.ErrUnexpectedEOF
  51. }
  52. return err
  53. }
  54. if err := rec.Unmarshal(data); err != nil {
  55. return err
  56. }
  57. // skip crc checking if the record type is crcType
  58. if rec.Type == crcType {
  59. return nil
  60. }
  61. d.crc.Write(rec.Data)
  62. return rec.Validate(d.crc.Sum32())
  63. }
  64. func (d *decoder) updateCRC(prevCrc uint32) {
  65. d.crc = crc.New(prevCrc, crcTable)
  66. }
  67. func (d *decoder) lastCRC() uint32 {
  68. return d.crc.Sum32()
  69. }
  70. func mustUnmarshalEntry(d []byte) raftpb.Entry {
  71. var e raftpb.Entry
  72. pbutil.MustUnmarshal(&e, d)
  73. return e
  74. }
  75. func mustUnmarshalState(d []byte) raftpb.HardState {
  76. var s raftpb.HardState
  77. pbutil.MustUnmarshal(&s, d)
  78. return s
  79. }
  80. func readInt64(r io.Reader) (int64, error) {
  81. var n int64
  82. err := binary.Read(r, binary.LittleEndian, &n)
  83. return n, err
  84. }