wal.go 7.0 KB

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