decoder.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // Copyright 2015 The etcd Authors
  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. const minSectorSize = 512
  27. type decoder struct {
  28. mu sync.Mutex
  29. brs []*bufio.Reader
  30. // lastValidOff file offset following the last valid decoded record
  31. lastValidOff int64
  32. crc hash.Hash32
  33. }
  34. func newDecoder(r ...io.Reader) *decoder {
  35. readers := make([]*bufio.Reader, len(r))
  36. for i := range r {
  37. readers[i] = bufio.NewReader(r[i])
  38. }
  39. return &decoder{
  40. brs: readers,
  41. crc: crc.New(0, crcTable),
  42. }
  43. }
  44. func (d *decoder) decode(rec *walpb.Record) error {
  45. rec.Reset()
  46. d.mu.Lock()
  47. defer d.mu.Unlock()
  48. return d.decodeRecord(rec)
  49. }
  50. func (d *decoder) decodeRecord(rec *walpb.Record) error {
  51. if len(d.brs) == 0 {
  52. return io.EOF
  53. }
  54. l, err := readInt64(d.brs[0])
  55. if err == io.EOF || (err == nil && l == 0) {
  56. // hit end of file or preallocated space
  57. d.brs = d.brs[1:]
  58. if len(d.brs) == 0 {
  59. return io.EOF
  60. }
  61. d.lastValidOff = 0
  62. return d.decodeRecord(rec)
  63. }
  64. if err != nil {
  65. return err
  66. }
  67. recBytes, padBytes := decodeFrameSize(l)
  68. data := make([]byte, recBytes+padBytes)
  69. if _, err = io.ReadFull(d.brs[0], data); err != nil {
  70. // ReadFull returns io.EOF only if no bytes were read
  71. // the decoder should treat this as an ErrUnexpectedEOF instead.
  72. if err == io.EOF {
  73. err = io.ErrUnexpectedEOF
  74. }
  75. return err
  76. }
  77. if err := rec.Unmarshal(data[:recBytes]); err != nil {
  78. if d.isTornEntry(data) {
  79. return io.ErrUnexpectedEOF
  80. }
  81. return err
  82. }
  83. // skip crc checking if the record type is crcType
  84. if rec.Type != crcType {
  85. d.crc.Write(rec.Data)
  86. if err := rec.Validate(d.crc.Sum32()); err != nil {
  87. if d.isTornEntry(data) {
  88. return io.ErrUnexpectedEOF
  89. }
  90. return err
  91. }
  92. }
  93. // record decoded as valid; point last valid offset to end of record
  94. d.lastValidOff += recBytes + padBytes + 8
  95. return nil
  96. }
  97. func decodeFrameSize(lenField int64) (recBytes int64, padBytes int64) {
  98. // the record size is stored in the lower 56 bits of the 64-bit length
  99. recBytes = int64(uint64(lenField) & ^(uint64(0xff) << 56))
  100. // non-zero padding is indicated by set MSb / a negative length
  101. if lenField < 0 {
  102. // padding is stored in lower 3 bits of length MSB
  103. padBytes = int64((uint64(lenField) >> 56) & 0x7)
  104. }
  105. return
  106. }
  107. // isTornEntry determines whether the last entry of the WAL was partially written
  108. // and corrupted because of a torn write.
  109. func (d *decoder) isTornEntry(data []byte) bool {
  110. if len(d.brs) != 1 {
  111. return false
  112. }
  113. fileOff := d.lastValidOff + 8
  114. curOff := 0
  115. chunks := [][]byte{}
  116. // split data on sector boundaries
  117. for curOff < len(data) {
  118. chunkLen := int(minSectorSize - (fileOff % minSectorSize))
  119. if chunkLen > len(data)-curOff {
  120. chunkLen = len(data) - curOff
  121. }
  122. chunks = append(chunks, data[curOff:curOff+chunkLen])
  123. fileOff += int64(chunkLen)
  124. curOff += chunkLen
  125. }
  126. // if any data for a sector chunk is all 0, it's a torn write
  127. for _, sect := range chunks {
  128. isZero := true
  129. for _, v := range sect {
  130. if v != 0 {
  131. isZero = false
  132. break
  133. }
  134. }
  135. if isZero {
  136. return true
  137. }
  138. }
  139. return false
  140. }
  141. func (d *decoder) updateCRC(prevCrc uint32) {
  142. d.crc = crc.New(prevCrc, crcTable)
  143. }
  144. func (d *decoder) lastCRC() uint32 {
  145. return d.crc.Sum32()
  146. }
  147. func (d *decoder) lastOffset() int64 { return d.lastValidOff }
  148. func mustUnmarshalEntry(d []byte) raftpb.Entry {
  149. var e raftpb.Entry
  150. pbutil.MustUnmarshal(&e, d)
  151. return e
  152. }
  153. func mustUnmarshalState(d []byte) raftpb.HardState {
  154. var s raftpb.HardState
  155. pbutil.MustUnmarshal(&s, d)
  156. return s
  157. }
  158. func readInt64(r io.Reader) (int64, error) {
  159. var n int64
  160. err := binary.Read(r, binary.LittleEndian, &n)
  161. return n, err
  162. }