wal.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. "log"
  20. "os"
  21. "path"
  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. infoType 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. ErrIDMismatch = errors.New("wal: unmatch id")
  37. ErrNotFound = errors.New("wal: file is not found")
  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 int64 // 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 int64 // current sequence of the wal file
  52. encoder *encoder // encoder to encode records
  53. }
  54. // Create creates a WAL ready for appending records.
  55. func Create(dirpath string) (*WAL, error) {
  56. log.Printf("path=%s wal.create", dirpath)
  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, fmt.Sprintf("%016x-%016x.wal", 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. // OpenFromIndex opens the WAL files containing all the entries after
  80. // the given index.
  81. // The returned WAL is ready to read. The WAL cannot be appended to before
  82. // reading out all of its previous records.
  83. func OpenFromIndex(dirpath string, index int64) (*WAL, error) {
  84. log.Printf("path=%s wal.load index=%d", dirpath, index)
  85. names, err := readDir(dirpath)
  86. if err != nil {
  87. return nil, err
  88. }
  89. names = checkWalNames(names)
  90. if len(names) == 0 {
  91. return nil, ErrNotFound
  92. }
  93. sort.Sort(sort.StringSlice(names))
  94. nameIndex, ok := searchIndex(names, index)
  95. if !ok || !isValidSeq(names[nameIndex:]) {
  96. return nil, ErrNotFound
  97. }
  98. // open the wal files for reading
  99. rcs := make([]io.ReadCloser, 0)
  100. for _, name := range names[nameIndex:] {
  101. f, err := os.Open(path.Join(dirpath, name))
  102. if err != nil {
  103. return nil, err
  104. }
  105. rcs = append(rcs, f)
  106. }
  107. rc := MultiReadCloser(rcs...)
  108. // open the lastest wal file for appending
  109. last := path.Join(dirpath, names[len(names)-1])
  110. f, err := os.OpenFile(last, os.O_WRONLY|os.O_APPEND, 0)
  111. if err != nil {
  112. rc.Close()
  113. return nil, err
  114. }
  115. // create a WAL ready for reading
  116. w := &WAL{
  117. ri: index,
  118. decoder: newDecoder(rc),
  119. f: f,
  120. }
  121. return w, nil
  122. }
  123. // ReadAll reads out all records of the current WAL.
  124. // After ReadAll, the WAL will be ready for appending new records.
  125. func (w *WAL) ReadAll() (id int64, state raftpb.State, ents []raftpb.Entry, err error) {
  126. rec := &walpb.Record{}
  127. decoder := w.decoder
  128. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  129. switch rec.Type {
  130. case entryType:
  131. e := mustUnmarshalEntry(rec.Data)
  132. if e.Index > w.ri {
  133. ents = append(ents[:e.Index-w.ri-1], e)
  134. }
  135. case stateType:
  136. state = mustUnmarshalState(rec.Data)
  137. case infoType:
  138. i := mustUnmarshalInfo(rec.Data)
  139. if id != 0 && id != i.Id {
  140. state.Reset()
  141. return 0, state, nil, ErrIDMismatch
  142. }
  143. id = i.Id
  144. case crcType:
  145. crc := decoder.crc.Sum32()
  146. // current crc of decoder must match the crc of the record.
  147. // do no need to match 0 crc, since the decoder is a new one at this case.
  148. if crc != 0 && rec.Validate(crc) != nil {
  149. state.Reset()
  150. return 0, state, nil, ErrCRCMismatch
  151. }
  152. decoder.updateCRC(rec.Crc)
  153. default:
  154. state.Reset()
  155. return 0, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  156. }
  157. }
  158. if err != io.EOF {
  159. state.Reset()
  160. return 0, state, nil, err
  161. }
  162. // close decoder, disable reading
  163. w.decoder.close()
  164. w.ri = 0
  165. // create encoder (chain crc with the decoder), enable appending
  166. w.encoder = newEncoder(w.f, w.decoder.lastCRC())
  167. w.decoder = nil
  168. return id, state, ents, nil
  169. }
  170. // index should be the index of last log entry.
  171. // Cut closes current file written and creates a new one ready to append.
  172. func (w *WAL) Cut(index int64) error {
  173. log.Printf("wal.cut index=%d", index)
  174. // create a new wal file with name sequence + 1
  175. fpath := path.Join(w.dir, fmt.Sprintf("%016x-%016x.wal", w.seq+1, index))
  176. f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  177. if err != nil {
  178. return err
  179. }
  180. w.Sync()
  181. w.f.Close()
  182. // update writer and save the previous crc
  183. w.f = f
  184. w.seq++
  185. prevCrc := w.encoder.crc.Sum32()
  186. w.encoder = newEncoder(w.f, prevCrc)
  187. return w.saveCrc(prevCrc)
  188. }
  189. func (w *WAL) Sync() error {
  190. if w.encoder != nil {
  191. if err := w.encoder.flush(); err != nil {
  192. return err
  193. }
  194. }
  195. return w.f.Sync()
  196. }
  197. func (w *WAL) Close() {
  198. log.Printf("path=%s wal.close", w.f.Name())
  199. if w.f != nil {
  200. w.Sync()
  201. w.f.Close()
  202. }
  203. }
  204. func (w *WAL) SaveInfo(i *raftpb.Info) error {
  205. log.Printf("path=%s wal.saveInfo id=%d", w.f.Name(), i.Id)
  206. b, err := i.Marshal()
  207. if err != nil {
  208. panic(err)
  209. }
  210. rec := &walpb.Record{Type: infoType, Data: b}
  211. return w.encoder.encode(rec)
  212. }
  213. func (w *WAL) SaveEntry(e *raftpb.Entry) error {
  214. b, err := e.Marshal()
  215. if err != nil {
  216. panic(err)
  217. }
  218. rec := &walpb.Record{Type: entryType, Data: b}
  219. return w.encoder.encode(rec)
  220. }
  221. func (w *WAL) SaveState(s *raftpb.State) error {
  222. if raft.IsEmptyState(*s) {
  223. return nil
  224. }
  225. log.Printf("path=%s wal.saveState state=\"%+v\"", w.f.Name(), s)
  226. b, err := s.Marshal()
  227. if err != nil {
  228. panic(err)
  229. }
  230. rec := &walpb.Record{Type: stateType, Data: b}
  231. return w.encoder.encode(rec)
  232. }
  233. func (w *WAL) Save(st raftpb.State, ents []raftpb.Entry) {
  234. // TODO(xiangli): no more reference operator
  235. w.SaveState(&st)
  236. for i := range ents {
  237. w.SaveEntry(&ents[i])
  238. }
  239. w.Sync()
  240. }
  241. func (w *WAL) saveCrc(prevCrc uint32) error {
  242. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  243. }