wal.go 7.5 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/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. w.Sync()
  86. return w, nil
  87. }
  88. // OpenAtIndex opens the WAL at the given index.
  89. // The index SHOULD have been previously committed to the WAL, or the following
  90. // ReadAll will fail.
  91. // The returned WAL is ready to read and the first record will be the given
  92. // index. The WAL cannot be appended to before reading out all of its
  93. // previous records.
  94. func OpenAtIndex(dirpath string, index uint64) (*WAL, error) {
  95. names, err := readDir(dirpath)
  96. if err != nil {
  97. return nil, err
  98. }
  99. names = checkWalNames(names)
  100. if len(names) == 0 {
  101. return nil, ErrFileNotFound
  102. }
  103. sort.Sort(sort.StringSlice(names))
  104. nameIndex, ok := searchIndex(names, index)
  105. if !ok || !isValidSeq(names[nameIndex:]) {
  106. return nil, ErrFileNotFound
  107. }
  108. // open the wal files for reading
  109. rcs := make([]io.ReadCloser, 0)
  110. for _, name := range names[nameIndex:] {
  111. f, err := os.Open(path.Join(dirpath, name))
  112. if err != nil {
  113. return nil, err
  114. }
  115. rcs = append(rcs, f)
  116. }
  117. rc := MultiReadCloser(rcs...)
  118. // open the lastest wal file for appending
  119. seq, _, err := parseWalName(names[len(names)-1])
  120. if err != nil {
  121. rc.Close()
  122. return nil, err
  123. }
  124. last := path.Join(dirpath, names[len(names)-1])
  125. f, err := os.OpenFile(last, os.O_WRONLY|os.O_APPEND, 0)
  126. if err != nil {
  127. rc.Close()
  128. return nil, err
  129. }
  130. // create a WAL ready for reading
  131. w := &WAL{
  132. dir: dirpath,
  133. ri: index,
  134. decoder: newDecoder(rc),
  135. f: f,
  136. seq: seq,
  137. }
  138. return w, nil
  139. }
  140. // ReadAll reads out all records of the current WAL.
  141. // If it cannot read out the expected entry, it will return ErrIndexNotFound.
  142. // After ReadAll, the WAL will be ready for appending new records.
  143. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  144. rec := &walpb.Record{}
  145. decoder := w.decoder
  146. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  147. switch rec.Type {
  148. case entryType:
  149. e := mustUnmarshalEntry(rec.Data)
  150. if e.Index >= w.ri {
  151. ents = append(ents[:e.Index-w.ri], e)
  152. }
  153. w.enti = e.Index
  154. case stateType:
  155. state = mustUnmarshalState(rec.Data)
  156. case metadataType:
  157. if metadata != nil && !reflect.DeepEqual(metadata, rec.Data) {
  158. state.Reset()
  159. return nil, state, nil, ErrMetadataConflict
  160. }
  161. metadata = rec.Data
  162. case crcType:
  163. crc := decoder.crc.Sum32()
  164. // current crc of decoder must match the crc of the record.
  165. // do no need to match 0 crc, since the decoder is a new one at this case.
  166. if crc != 0 && rec.Validate(crc) != nil {
  167. state.Reset()
  168. return nil, state, nil, ErrCRCMismatch
  169. }
  170. decoder.updateCRC(rec.Crc)
  171. default:
  172. state.Reset()
  173. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  174. }
  175. }
  176. if err != io.EOF {
  177. state.Reset()
  178. return nil, state, nil, err
  179. }
  180. if w.enti < w.ri {
  181. state.Reset()
  182. return nil, state, nil, ErrIndexNotFound
  183. }
  184. // close decoder, disable reading
  185. w.decoder.close()
  186. w.ri = 0
  187. w.metadata = metadata
  188. // create encoder (chain crc with the decoder), enable appending
  189. w.encoder = newEncoder(w.f, w.decoder.lastCRC())
  190. w.decoder = nil
  191. return metadata, state, ents, nil
  192. }
  193. // Cut closes current file written and creates a new one ready to append.
  194. func (w *WAL) Cut() error {
  195. // create a new wal file with name sequence + 1
  196. fpath := path.Join(w.dir, walName(w.seq+1, w.enti+1))
  197. f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  198. if err != nil {
  199. return err
  200. }
  201. w.Sync()
  202. w.f.Close()
  203. // update writer and save the previous crc
  204. w.f = f
  205. w.seq++
  206. prevCrc := w.encoder.crc.Sum32()
  207. w.encoder = newEncoder(w.f, prevCrc)
  208. if err := w.saveCrc(prevCrc); err != nil {
  209. return err
  210. }
  211. return w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata})
  212. }
  213. func (w *WAL) Sync() error {
  214. if w.encoder != nil {
  215. if err := w.encoder.flush(); err != nil {
  216. return err
  217. }
  218. }
  219. return w.f.Sync()
  220. }
  221. func (w *WAL) Close() {
  222. if w.f != nil {
  223. w.Sync()
  224. w.f.Close()
  225. }
  226. }
  227. func (w *WAL) SaveEntry(e *raftpb.Entry) error {
  228. b := pbutil.MustMarshal(e)
  229. rec := &walpb.Record{Type: entryType, Data: b}
  230. if err := w.encoder.encode(rec); err != nil {
  231. return err
  232. }
  233. w.enti = e.Index
  234. return nil
  235. }
  236. func (w *WAL) SaveState(s *raftpb.HardState) error {
  237. if raft.IsEmptyHardState(*s) {
  238. return nil
  239. }
  240. b := pbutil.MustMarshal(s)
  241. rec := &walpb.Record{Type: stateType, Data: b}
  242. return w.encoder.encode(rec)
  243. }
  244. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  245. // TODO(xiangli): no more reference operator
  246. if err := w.SaveState(&st); err != nil {
  247. return err
  248. }
  249. for i := range ents {
  250. if err := w.SaveEntry(&ents[i]); err != nil {
  251. return err
  252. }
  253. }
  254. return w.Sync()
  255. }
  256. func (w *WAL) saveCrc(prevCrc uint32) error {
  257. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  258. }