wal.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 wal
  14. import (
  15. "errors"
  16. "fmt"
  17. "hash/crc32"
  18. "io"
  19. "os"
  20. "path"
  21. "reflect"
  22. "sort"
  23. "github.com/coreos/etcd/pkg/pbutil"
  24. "github.com/coreos/etcd/raft"
  25. "github.com/coreos/etcd/raft/raftpb"
  26. "github.com/coreos/etcd/wal/walpb"
  27. )
  28. const (
  29. metadataType int64 = iota + 1
  30. entryType
  31. stateType
  32. crcType
  33. // the owner can make/remove files inside the directory
  34. privateDirMode = 0700
  35. )
  36. var (
  37. ErrMetadataConflict = errors.New("wal: conflicting metadata found")
  38. ErrFileNotFound = errors.New("wal: file not found")
  39. ErrIndexNotFound = errors.New("wal: index not found in file")
  40. ErrCRCMismatch = errors.New("wal: crc mismatch")
  41. crcTable = crc32.MakeTable(crc32.Castagnoli)
  42. )
  43. // WAL is a logical repersentation of the stable storage.
  44. // WAL is either in read mode or append mode but not both.
  45. // A newly created WAL is in append mode, and ready for appending records.
  46. // A just opened WAL is in read mode, and ready for reading records.
  47. // The WAL will be ready for appending after reading out all the previous records.
  48. type WAL struct {
  49. dir string // the living directory of the underlay files
  50. metadata []byte // metadata recorded at the head of each WAL
  51. ri uint64 // index of entry to start reading
  52. decoder *decoder // decoder to decode records
  53. f *os.File // underlay file opened for appending, sync
  54. seq uint64 // sequence of the wal file currently used for writes
  55. enti uint64 // index of the last entry saved to the wal
  56. encoder *encoder // encoder to encode records
  57. }
  58. // Create creates a WAL ready for appending records. The given metadata is
  59. // recorded at the head of each WAL file, and can be retrieved with ReadAll.
  60. func Create(dirpath string, metadata []byte) (*WAL, error) {
  61. if Exist(dirpath) {
  62. return nil, os.ErrExist
  63. }
  64. if err := os.MkdirAll(dirpath, privateDirMode); err != nil {
  65. return nil, err
  66. }
  67. p := path.Join(dirpath, walName(0, 0))
  68. f, err := os.OpenFile(p, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  69. if err != nil {
  70. return nil, err
  71. }
  72. w := &WAL{
  73. dir: dirpath,
  74. metadata: metadata,
  75. seq: 0,
  76. f: f,
  77. encoder: newEncoder(f, 0),
  78. }
  79. if err := w.saveCrc(0); err != nil {
  80. return nil, err
  81. }
  82. if err := w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil {
  83. return nil, err
  84. }
  85. return w, nil
  86. }
  87. // OpenAtIndex opens the WAL at the given index.
  88. // The index SHOULD have been previously committed to the WAL, or the following
  89. // ReadAll will fail.
  90. // The returned WAL is ready to read and the first record will be the given
  91. // index. The WAL cannot be appended to before reading out all of its
  92. // previous records.
  93. func OpenAtIndex(dirpath string, index uint64) (*WAL, error) {
  94. names, err := readDir(dirpath)
  95. if err != nil {
  96. return nil, err
  97. }
  98. names = checkWalNames(names)
  99. if len(names) == 0 {
  100. return nil, ErrFileNotFound
  101. }
  102. sort.Sort(sort.StringSlice(names))
  103. nameIndex, ok := searchIndex(names, index)
  104. if !ok || !isValidSeq(names[nameIndex:]) {
  105. return nil, ErrFileNotFound
  106. }
  107. // open the wal files for reading
  108. rcs := make([]io.ReadCloser, 0)
  109. for _, name := range names[nameIndex:] {
  110. f, err := os.Open(path.Join(dirpath, name))
  111. if err != nil {
  112. return nil, err
  113. }
  114. rcs = append(rcs, f)
  115. }
  116. rc := MultiReadCloser(rcs...)
  117. // open the lastest wal file for appending
  118. seq, _, err := parseWalName(names[len(names)-1])
  119. if err != nil {
  120. rc.Close()
  121. return nil, err
  122. }
  123. last := path.Join(dirpath, names[len(names)-1])
  124. f, err := os.OpenFile(last, os.O_WRONLY|os.O_APPEND, 0)
  125. if err != nil {
  126. rc.Close()
  127. return nil, err
  128. }
  129. // create a WAL ready for reading
  130. w := &WAL{
  131. dir: dirpath,
  132. ri: index,
  133. decoder: newDecoder(rc),
  134. f: f,
  135. seq: seq,
  136. }
  137. return w, nil
  138. }
  139. // ReadAll reads out all records of the current WAL.
  140. // If it cannot read out the expected entry, it will return ErrIndexNotFound.
  141. // After ReadAll, the WAL will be ready for appending new records.
  142. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  143. rec := &walpb.Record{}
  144. decoder := w.decoder
  145. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  146. switch rec.Type {
  147. case entryType:
  148. e := mustUnmarshalEntry(rec.Data)
  149. if e.Index >= w.ri {
  150. ents = append(ents[:e.Index-w.ri], e)
  151. }
  152. w.enti = e.Index
  153. case stateType:
  154. state = mustUnmarshalState(rec.Data)
  155. case metadataType:
  156. if metadata != nil && !reflect.DeepEqual(metadata, rec.Data) {
  157. state.Reset()
  158. return nil, state, nil, ErrMetadataConflict
  159. }
  160. metadata = rec.Data
  161. case crcType:
  162. crc := decoder.crc.Sum32()
  163. // current crc of decoder must match the crc of the record.
  164. // do no need to match 0 crc, since the decoder is a new one at this case.
  165. if crc != 0 && rec.Validate(crc) != nil {
  166. state.Reset()
  167. return nil, state, nil, ErrCRCMismatch
  168. }
  169. decoder.updateCRC(rec.Crc)
  170. default:
  171. state.Reset()
  172. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  173. }
  174. }
  175. if err != io.EOF {
  176. state.Reset()
  177. return nil, state, nil, err
  178. }
  179. if w.enti < w.ri {
  180. state.Reset()
  181. return nil, state, nil, ErrIndexNotFound
  182. }
  183. // close decoder, disable reading
  184. w.decoder.close()
  185. w.ri = 0
  186. w.metadata = metadata
  187. // create encoder (chain crc with the decoder), enable appending
  188. w.encoder = newEncoder(w.f, w.decoder.lastCRC())
  189. w.decoder = nil
  190. return metadata, state, ents, nil
  191. }
  192. // Cut closes current file written and creates a new one ready to append.
  193. func (w *WAL) Cut() error {
  194. // create a new wal file with name sequence + 1
  195. fpath := path.Join(w.dir, walName(w.seq+1, w.enti+1))
  196. f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  197. if err != nil {
  198. return err
  199. }
  200. w.Sync()
  201. w.f.Close()
  202. // update writer and save the previous crc
  203. w.f = f
  204. w.seq++
  205. prevCrc := w.encoder.crc.Sum32()
  206. w.encoder = newEncoder(w.f, prevCrc)
  207. if err := w.saveCrc(prevCrc); err != nil {
  208. return err
  209. }
  210. return w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata})
  211. }
  212. func (w *WAL) Sync() error {
  213. if w.encoder != nil {
  214. if err := w.encoder.flush(); err != nil {
  215. return err
  216. }
  217. }
  218. return w.f.Sync()
  219. }
  220. func (w *WAL) Close() {
  221. if w.f != nil {
  222. w.Sync()
  223. w.f.Close()
  224. }
  225. }
  226. func (w *WAL) SaveEntry(e *raftpb.Entry) error {
  227. b := pbutil.MustMarshal(e)
  228. rec := &walpb.Record{Type: entryType, Data: b}
  229. if err := w.encoder.encode(rec); err != nil {
  230. return err
  231. }
  232. w.enti = e.Index
  233. return nil
  234. }
  235. func (w *WAL) SaveState(s *raftpb.HardState) error {
  236. if raft.IsEmptyHardState(*s) {
  237. return nil
  238. }
  239. b := pbutil.MustMarshal(s)
  240. rec := &walpb.Record{Type: stateType, Data: b}
  241. return w.encoder.encode(rec)
  242. }
  243. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) {
  244. // TODO(xiangli): no more reference operator
  245. w.SaveState(&st)
  246. for i := range ents {
  247. w.SaveEntry(&ents[i])
  248. }
  249. w.Sync()
  250. }
  251. func (w *WAL) saveCrc(prevCrc uint32) error {
  252. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  253. }