wal.go 7.4 KB

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