wal.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package wal
  15. import (
  16. "errors"
  17. "fmt"
  18. "hash/crc32"
  19. "io"
  20. "log"
  21. "os"
  22. "path"
  23. "reflect"
  24. "time"
  25. "github.com/coreos/etcd/pkg/fileutil"
  26. "github.com/coreos/etcd/pkg/pbutil"
  27. "github.com/coreos/etcd/raft"
  28. "github.com/coreos/etcd/raft/raftpb"
  29. "github.com/coreos/etcd/wal/walpb"
  30. )
  31. const (
  32. metadataType int64 = iota + 1
  33. entryType
  34. stateType
  35. crcType
  36. snapshotType
  37. // the owner can make/remove files inside the directory
  38. privateDirMode = 0700
  39. // the expected size of each wal segment file.
  40. // the actual size might be bigger than it.
  41. segmentSizeBytes = 64 * 1000 * 1000 // 64MB
  42. )
  43. var (
  44. ErrMetadataConflict = errors.New("wal: conflicting metadata found")
  45. ErrFileNotFound = errors.New("wal: file not found")
  46. ErrCRCMismatch = errors.New("wal: crc mismatch")
  47. ErrSnapshotMismatch = errors.New("wal: snapshot mismatch")
  48. ErrSnapshotNotFound = errors.New("wal: snapshot not found")
  49. crcTable = crc32.MakeTable(crc32.Castagnoli)
  50. )
  51. // WAL is a logical repersentation of the stable storage.
  52. // WAL is either in read mode or append mode but not both.
  53. // A newly created WAL is in append mode, and ready for appending records.
  54. // A just opened WAL is in read mode, and ready for reading records.
  55. // The WAL will be ready for appending after reading out all the previous records.
  56. type WAL struct {
  57. dir string // the living directory of the underlay files
  58. metadata []byte // metadata recorded at the head of each WAL
  59. state raftpb.HardState // hardstate recorded at the head of WAL
  60. start walpb.Snapshot // snapshot to start reading
  61. decoder *decoder // decoder to decode records
  62. f *os.File // underlay file opened for appending, sync
  63. seq uint64 // sequence of the wal file currently used for writes
  64. enti uint64 // index of the last entry saved to the wal
  65. encoder *encoder // encoder to encode records
  66. locks []fileutil.Lock // the file locks the WAL is holding (the name is increasing)
  67. }
  68. // Create creates a WAL ready for appending records. The given metadata is
  69. // recorded at the head of each WAL file, and can be retrieved with ReadAll.
  70. func Create(dirpath string, metadata []byte) (*WAL, error) {
  71. if Exist(dirpath) {
  72. return nil, os.ErrExist
  73. }
  74. if err := os.MkdirAll(dirpath, privateDirMode); err != nil {
  75. return nil, err
  76. }
  77. p := path.Join(dirpath, walName(0, 0))
  78. f, err := os.OpenFile(p, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  79. if err != nil {
  80. return nil, err
  81. }
  82. l, err := fileutil.NewLock(f.Name())
  83. if err != nil {
  84. return nil, err
  85. }
  86. err = l.Lock()
  87. if err != nil {
  88. return nil, err
  89. }
  90. w := &WAL{
  91. dir: dirpath,
  92. metadata: metadata,
  93. seq: 0,
  94. f: f,
  95. encoder: newEncoder(f, 0),
  96. }
  97. w.locks = append(w.locks, l)
  98. if err := w.saveCrc(0); err != nil {
  99. return nil, err
  100. }
  101. if err := w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil {
  102. return nil, err
  103. }
  104. if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil {
  105. return nil, err
  106. }
  107. return w, nil
  108. }
  109. // Open opens the WAL at the given snap.
  110. // The snap SHOULD have been previously saved to the WAL, or the following
  111. // ReadAll will fail.
  112. // The returned WAL is ready to read and the first record will be the one after
  113. // the given snap. The WAL cannot be appended to before reading out all of its
  114. // previous records.
  115. func Open(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  116. return openAtIndex(dirpath, snap, true)
  117. }
  118. // OpenNotInUse only opens the wal files that are not in use.
  119. // Other than that, it is similar to Open.
  120. func OpenNotInUse(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  121. return openAtIndex(dirpath, snap, false)
  122. }
  123. func openAtIndex(dirpath string, snap walpb.Snapshot, all bool) (*WAL, error) {
  124. names, err := fileutil.ReadDir(dirpath)
  125. if err != nil {
  126. return nil, err
  127. }
  128. names = checkWalNames(names)
  129. if len(names) == 0 {
  130. return nil, ErrFileNotFound
  131. }
  132. nameIndex, ok := searchIndex(names, snap.Index)
  133. if !ok || !isValidSeq(names[nameIndex:]) {
  134. return nil, ErrFileNotFound
  135. }
  136. // open the wal files for reading
  137. rcs := make([]io.ReadCloser, 0)
  138. ls := make([]fileutil.Lock, 0)
  139. for _, name := range names[nameIndex:] {
  140. f, err := os.Open(path.Join(dirpath, name))
  141. if err != nil {
  142. return nil, err
  143. }
  144. l, err := fileutil.NewLock(f.Name())
  145. if err != nil {
  146. return nil, err
  147. }
  148. err = l.TryLock()
  149. if err != nil {
  150. if all {
  151. return nil, err
  152. } else {
  153. log.Printf("wal: opened all the files until %s, since it is still in use by an etcd server", name)
  154. break
  155. }
  156. }
  157. rcs = append(rcs, f)
  158. ls = append(ls, l)
  159. }
  160. rc := MultiReadCloser(rcs...)
  161. // open the lastest wal file for appending
  162. seq, _, err := parseWalName(names[len(names)-1])
  163. if err != nil {
  164. rc.Close()
  165. return nil, err
  166. }
  167. last := path.Join(dirpath, names[len(names)-1])
  168. f, err := os.OpenFile(last, os.O_WRONLY|os.O_APPEND, 0)
  169. if err != nil {
  170. rc.Close()
  171. return nil, err
  172. }
  173. // create a WAL ready for reading
  174. w := &WAL{
  175. dir: dirpath,
  176. start: snap,
  177. decoder: newDecoder(rc),
  178. f: f,
  179. seq: seq,
  180. locks: ls,
  181. }
  182. return w, nil
  183. }
  184. // ReadAll reads out all records of the current WAL.
  185. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
  186. // If loaded snap doesn't match with the expected one, it will return
  187. // all the records and error ErrSnapshotMismatch.
  188. // TODO: detect not-last-snap error.
  189. // TODO: maybe loose the checking of match.
  190. // After ReadAll, the WAL will be ready for appending new records.
  191. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  192. rec := &walpb.Record{}
  193. decoder := w.decoder
  194. var match bool
  195. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  196. switch rec.Type {
  197. case entryType:
  198. e := mustUnmarshalEntry(rec.Data)
  199. if e.Index > w.start.Index {
  200. ents = append(ents[:e.Index-w.start.Index-1], e)
  201. }
  202. w.enti = e.Index
  203. case stateType:
  204. state = mustUnmarshalState(rec.Data)
  205. case metadataType:
  206. if metadata != nil && !reflect.DeepEqual(metadata, rec.Data) {
  207. state.Reset()
  208. return nil, state, nil, ErrMetadataConflict
  209. }
  210. metadata = rec.Data
  211. case crcType:
  212. crc := decoder.crc.Sum32()
  213. // current crc of decoder must match the crc of the record.
  214. // do no need to match 0 crc, since the decoder is a new one at this case.
  215. if crc != 0 && rec.Validate(crc) != nil {
  216. state.Reset()
  217. return nil, state, nil, ErrCRCMismatch
  218. }
  219. decoder.updateCRC(rec.Crc)
  220. case snapshotType:
  221. var snap walpb.Snapshot
  222. pbutil.MustUnmarshal(&snap, rec.Data)
  223. if snap.Index == w.start.Index {
  224. if snap.Term != w.start.Term {
  225. state.Reset()
  226. return nil, state, nil, ErrSnapshotMismatch
  227. }
  228. match = true
  229. }
  230. default:
  231. state.Reset()
  232. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  233. }
  234. }
  235. if err != io.EOF {
  236. state.Reset()
  237. return nil, state, nil, err
  238. }
  239. err = nil
  240. if !match {
  241. err = ErrSnapshotNotFound
  242. }
  243. // close decoder, disable reading
  244. w.decoder.close()
  245. w.start = walpb.Snapshot{}
  246. w.metadata = metadata
  247. // create encoder (chain crc with the decoder), enable appending
  248. w.encoder = newEncoder(w.f, w.decoder.lastCRC())
  249. w.decoder = nil
  250. lastIndexSaved.Set(float64(w.enti))
  251. return metadata, state, ents, err
  252. }
  253. // cut closes current file written and creates a new one ready to append.
  254. func (w *WAL) cut() error {
  255. // create a new wal file with name sequence + 1
  256. fpath := path.Join(w.dir, walName(w.seq+1, w.enti+1))
  257. f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  258. if err != nil {
  259. return err
  260. }
  261. log.Printf("wal: segmented wal file %v is created", fpath)
  262. l, err := fileutil.NewLock(f.Name())
  263. if err != nil {
  264. return err
  265. }
  266. err = l.Lock()
  267. if err != nil {
  268. return err
  269. }
  270. w.locks = append(w.locks, l)
  271. if err = w.sync(); err != nil {
  272. return err
  273. }
  274. w.f.Close()
  275. // update writer and save the previous crc
  276. w.f = f
  277. w.seq++
  278. prevCrc := w.encoder.crc.Sum32()
  279. w.encoder = newEncoder(w.f, prevCrc)
  280. if err := w.saveCrc(prevCrc); err != nil {
  281. return err
  282. }
  283. if err := w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
  284. return err
  285. }
  286. if err := w.saveState(&w.state); err != nil {
  287. return err
  288. }
  289. return w.sync()
  290. }
  291. func (w *WAL) sync() error {
  292. if w.encoder != nil {
  293. if err := w.encoder.flush(); err != nil {
  294. return err
  295. }
  296. }
  297. start := time.Now()
  298. err := w.f.Sync()
  299. syncDurations.Observe(float64(time.Since(start).Nanoseconds() / int64(time.Microsecond)))
  300. return err
  301. }
  302. // ReleaseLockTo releases the locks w is holding, which
  303. // have index smaller or equal to the given index.
  304. func (w *WAL) ReleaseLockTo(index uint64) error {
  305. for _, l := range w.locks {
  306. _, i, err := parseWalName(path.Base(l.Name()))
  307. if err != nil {
  308. return err
  309. }
  310. if i > index {
  311. return nil
  312. }
  313. err = l.Unlock()
  314. if err != nil {
  315. return err
  316. }
  317. err = l.Destroy()
  318. if err != nil {
  319. return err
  320. }
  321. w.locks = w.locks[1:]
  322. }
  323. return nil
  324. }
  325. func (w *WAL) Close() error {
  326. if w.f != nil {
  327. if err := w.sync(); err != nil {
  328. return err
  329. }
  330. if err := w.f.Close(); err != nil {
  331. return err
  332. }
  333. }
  334. for _, l := range w.locks {
  335. // TODO: log the error
  336. l.Unlock()
  337. l.Destroy()
  338. }
  339. return nil
  340. }
  341. func (w *WAL) saveEntry(e *raftpb.Entry) error {
  342. b := pbutil.MustMarshal(e)
  343. rec := &walpb.Record{Type: entryType, Data: b}
  344. if err := w.encoder.encode(rec); err != nil {
  345. return err
  346. }
  347. w.enti = e.Index
  348. lastIndexSaved.Set(float64(w.enti))
  349. return nil
  350. }
  351. func (w *WAL) saveState(s *raftpb.HardState) error {
  352. if raft.IsEmptyHardState(*s) {
  353. return nil
  354. }
  355. w.state = *s
  356. b := pbutil.MustMarshal(s)
  357. rec := &walpb.Record{Type: stateType, Data: b}
  358. return w.encoder.encode(rec)
  359. }
  360. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  361. // short cut, do not call sync
  362. if raft.IsEmptyHardState(st) && len(ents) == 0 {
  363. return nil
  364. }
  365. // TODO(xiangli): no more reference operator
  366. if err := w.saveState(&st); err != nil {
  367. return err
  368. }
  369. for i := range ents {
  370. if err := w.saveEntry(&ents[i]); err != nil {
  371. return err
  372. }
  373. }
  374. fstat, err := w.f.Stat()
  375. if err != nil {
  376. return err
  377. }
  378. if fstat.Size() < segmentSizeBytes {
  379. return w.sync()
  380. }
  381. // TODO: add a test for this code path when refactoring the tests
  382. return w.cut()
  383. }
  384. func (w *WAL) SaveSnapshot(e walpb.Snapshot) error {
  385. b := pbutil.MustMarshal(&e)
  386. rec := &walpb.Record{Type: snapshotType, Data: b}
  387. if err := w.encoder.encode(rec); err != nil {
  388. return err
  389. }
  390. // update enti only when snapshot is ahead of last index
  391. if w.enti < e.Index {
  392. w.enti = e.Index
  393. }
  394. lastIndexSaved.Set(float64(w.enti))
  395. return w.sync()
  396. }
  397. func (w *WAL) saveCrc(prevCrc uint32) error {
  398. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  399. }