wal.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. // Copyright 2015 The etcd Authors
  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. "bytes"
  17. "errors"
  18. "fmt"
  19. "hash/crc32"
  20. "io"
  21. "os"
  22. "path"
  23. "sync"
  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. "github.com/coreos/pkg/capnslog"
  31. )
  32. const (
  33. metadataType int64 = iota + 1
  34. entryType
  35. stateType
  36. crcType
  37. snapshotType
  38. // the expected size of each wal segment file.
  39. // the actual size might be bigger than it.
  40. segmentSizeBytes = 64 * 1000 * 1000 // 64MB
  41. // warnSyncDuration is the amount of time allotted to an fsync before
  42. // logging a warning
  43. warnSyncDuration = time.Second
  44. )
  45. var (
  46. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "wal")
  47. ErrMetadataConflict = errors.New("wal: conflicting metadata found")
  48. ErrFileNotFound = errors.New("wal: file not found")
  49. ErrCRCMismatch = errors.New("wal: crc mismatch")
  50. ErrSnapshotMismatch = errors.New("wal: snapshot mismatch")
  51. ErrSnapshotNotFound = errors.New("wal: snapshot not found")
  52. crcTable = crc32.MakeTable(crc32.Castagnoli)
  53. )
  54. // WAL is a logical representation of the stable storage.
  55. // WAL is either in read mode or append mode but not both.
  56. // A newly created WAL is in append mode, and ready for appending records.
  57. // A just opened WAL is in read mode, and ready for reading records.
  58. // The WAL will be ready for appending after reading out all the previous records.
  59. type WAL struct {
  60. dir string // the living directory of the underlay files
  61. // dirFile is a fd for the wal directory for syncing on Rename
  62. dirFile *os.File
  63. metadata []byte // metadata recorded at the head of each WAL
  64. state raftpb.HardState // hardstate recorded at the head of WAL
  65. start walpb.Snapshot // snapshot to start reading
  66. decoder *decoder // decoder to decode records
  67. readClose func() error // closer for decode reader
  68. mu sync.Mutex
  69. enti uint64 // index of the last entry saved to the wal
  70. encoder *encoder // encoder to encode records
  71. locks []*fileutil.LockedFile // the locked files the WAL holds (the name is increasing)
  72. fp *filePipeline
  73. }
  74. // Create creates a WAL ready for appending records. The given metadata is
  75. // recorded at the head of each WAL file, and can be retrieved with ReadAll.
  76. func Create(dirpath string, metadata []byte) (*WAL, error) {
  77. if Exist(dirpath) {
  78. return nil, os.ErrExist
  79. }
  80. // keep temporary wal directory so WAL initialization appears atomic
  81. tmpdirpath := path.Clean(dirpath) + ".tmp"
  82. if fileutil.Exist(tmpdirpath) {
  83. if err := os.RemoveAll(tmpdirpath); err != nil {
  84. return nil, err
  85. }
  86. }
  87. if err := fileutil.CreateDirAll(tmpdirpath); err != nil {
  88. return nil, err
  89. }
  90. p := path.Join(tmpdirpath, walName(0, 0))
  91. f, err := fileutil.LockFile(p, os.O_WRONLY|os.O_CREATE, fileutil.PrivateFileMode)
  92. if err != nil {
  93. return nil, err
  94. }
  95. if _, err = f.Seek(0, os.SEEK_END); err != nil {
  96. return nil, err
  97. }
  98. if err = fileutil.Preallocate(f.File, segmentSizeBytes, true); err != nil {
  99. return nil, err
  100. }
  101. w := &WAL{
  102. dir: dirpath,
  103. metadata: metadata,
  104. }
  105. w.encoder, err = newFileEncoder(f.File, 0)
  106. if err != nil {
  107. return nil, err
  108. }
  109. w.locks = append(w.locks, f)
  110. if err = w.saveCrc(0); err != nil {
  111. return nil, err
  112. }
  113. if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil {
  114. return nil, err
  115. }
  116. if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil {
  117. return nil, err
  118. }
  119. if w, err = w.renameWal(tmpdirpath); err != nil {
  120. return nil, err
  121. }
  122. // directory was renamed; sync parent dir to persist rename
  123. pdir, perr := fileutil.OpenDir(path.Dir(w.dir))
  124. if perr != nil {
  125. return nil, perr
  126. }
  127. if perr = fileutil.Fsync(pdir); perr != nil {
  128. return nil, perr
  129. }
  130. if perr = pdir.Close(); err != nil {
  131. return nil, perr
  132. }
  133. return w, nil
  134. }
  135. // Open opens the WAL at the given snap.
  136. // The snap SHOULD have been previously saved to the WAL, or the following
  137. // ReadAll will fail.
  138. // The returned WAL is ready to read and the first record will be the one after
  139. // the given snap. The WAL cannot be appended to before reading out all of its
  140. // previous records.
  141. func Open(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  142. w, err := openAtIndex(dirpath, snap, true)
  143. if err != nil {
  144. return nil, err
  145. }
  146. if w.dirFile, err = fileutil.OpenDir(w.dir); err != nil {
  147. return nil, err
  148. }
  149. return w, nil
  150. }
  151. // OpenForRead only opens the wal files for read.
  152. // Write on a read only wal panics.
  153. func OpenForRead(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  154. return openAtIndex(dirpath, snap, false)
  155. }
  156. func openAtIndex(dirpath string, snap walpb.Snapshot, write bool) (*WAL, error) {
  157. names, err := readWalNames(dirpath)
  158. if err != nil {
  159. return nil, err
  160. }
  161. nameIndex, ok := searchIndex(names, snap.Index)
  162. if !ok || !isValidSeq(names[nameIndex:]) {
  163. return nil, ErrFileNotFound
  164. }
  165. // open the wal files
  166. rcs := make([]io.ReadCloser, 0)
  167. rs := make([]io.Reader, 0)
  168. ls := make([]*fileutil.LockedFile, 0)
  169. for _, name := range names[nameIndex:] {
  170. p := path.Join(dirpath, name)
  171. if write {
  172. l, err := fileutil.TryLockFile(p, os.O_RDWR, fileutil.PrivateFileMode)
  173. if err != nil {
  174. closeAll(rcs...)
  175. return nil, err
  176. }
  177. ls = append(ls, l)
  178. rcs = append(rcs, l)
  179. } else {
  180. rf, err := os.OpenFile(p, os.O_RDONLY, fileutil.PrivateFileMode)
  181. if err != nil {
  182. closeAll(rcs...)
  183. return nil, err
  184. }
  185. ls = append(ls, nil)
  186. rcs = append(rcs, rf)
  187. }
  188. rs = append(rs, rcs[len(rcs)-1])
  189. }
  190. closer := func() error { return closeAll(rcs...) }
  191. // create a WAL ready for reading
  192. w := &WAL{
  193. dir: dirpath,
  194. start: snap,
  195. decoder: newDecoder(rs...),
  196. readClose: closer,
  197. locks: ls,
  198. }
  199. if write {
  200. // write reuses the file descriptors from read; don't close so
  201. // WAL can append without dropping the file lock
  202. w.readClose = nil
  203. if _, _, err := parseWalName(path.Base(w.tail().Name())); err != nil {
  204. closer()
  205. return nil, err
  206. }
  207. w.fp = newFilePipeline(w.dir, segmentSizeBytes)
  208. }
  209. return w, nil
  210. }
  211. // ReadAll reads out records of the current WAL.
  212. // If opened in write mode, it must read out all records until EOF. Or an error
  213. // will be returned.
  214. // If opened in read mode, it will try to read all records if possible.
  215. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
  216. // If loaded snap doesn't match with the expected one, it will return
  217. // all the records and error ErrSnapshotMismatch.
  218. // TODO: detect not-last-snap error.
  219. // TODO: maybe loose the checking of match.
  220. // After ReadAll, the WAL will be ready for appending new records.
  221. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  222. w.mu.Lock()
  223. defer w.mu.Unlock()
  224. rec := &walpb.Record{}
  225. decoder := w.decoder
  226. var match bool
  227. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  228. switch rec.Type {
  229. case entryType:
  230. e := mustUnmarshalEntry(rec.Data)
  231. if e.Index > w.start.Index {
  232. ents = append(ents[:e.Index-w.start.Index-1], e)
  233. }
  234. w.enti = e.Index
  235. case stateType:
  236. state = mustUnmarshalState(rec.Data)
  237. case metadataType:
  238. if metadata != nil && !bytes.Equal(metadata, rec.Data) {
  239. state.Reset()
  240. return nil, state, nil, ErrMetadataConflict
  241. }
  242. metadata = rec.Data
  243. case crcType:
  244. crc := decoder.crc.Sum32()
  245. // current crc of decoder must match the crc of the record.
  246. // do no need to match 0 crc, since the decoder is a new one at this case.
  247. if crc != 0 && rec.Validate(crc) != nil {
  248. state.Reset()
  249. return nil, state, nil, ErrCRCMismatch
  250. }
  251. decoder.updateCRC(rec.Crc)
  252. case snapshotType:
  253. var snap walpb.Snapshot
  254. pbutil.MustUnmarshal(&snap, rec.Data)
  255. if snap.Index == w.start.Index {
  256. if snap.Term != w.start.Term {
  257. state.Reset()
  258. return nil, state, nil, ErrSnapshotMismatch
  259. }
  260. match = true
  261. }
  262. default:
  263. state.Reset()
  264. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  265. }
  266. }
  267. switch w.tail() {
  268. case nil:
  269. // We do not have to read out all entries in read mode.
  270. // The last record maybe a partial written one, so
  271. // ErrunexpectedEOF might be returned.
  272. if err != io.EOF && err != io.ErrUnexpectedEOF {
  273. state.Reset()
  274. return nil, state, nil, err
  275. }
  276. default:
  277. // We must read all of the entries if WAL is opened in write mode.
  278. if err != io.EOF {
  279. state.Reset()
  280. return nil, state, nil, err
  281. }
  282. // decodeRecord() will return io.EOF if it detects a zero record,
  283. // but this zero record may be followed by non-zero records from
  284. // a torn write. Overwriting some of these non-zero records, but
  285. // not all, will cause CRC errors on WAL open. Since the records
  286. // were never fully synced to disk in the first place, it's safe
  287. // to zero them out to avoid any CRC errors from new writes.
  288. if _, err = w.tail().Seek(w.decoder.lastOffset(), os.SEEK_SET); err != nil {
  289. return nil, state, nil, err
  290. }
  291. if err = fileutil.ZeroToEnd(w.tail().File); err != nil {
  292. return nil, state, nil, err
  293. }
  294. }
  295. err = nil
  296. if !match {
  297. err = ErrSnapshotNotFound
  298. }
  299. // close decoder, disable reading
  300. if w.readClose != nil {
  301. w.readClose()
  302. w.readClose = nil
  303. }
  304. w.start = walpb.Snapshot{}
  305. w.metadata = metadata
  306. if w.tail() != nil {
  307. // create encoder (chain crc with the decoder), enable appending
  308. w.encoder, err = newFileEncoder(w.tail().File, w.decoder.lastCRC())
  309. if err != nil {
  310. return
  311. }
  312. }
  313. w.decoder = nil
  314. return metadata, state, ents, err
  315. }
  316. // cut closes current file written and creates a new one ready to append.
  317. // cut first creates a temp wal file and writes necessary headers into it.
  318. // Then cut atomically rename temp wal file to a wal file.
  319. func (w *WAL) cut() error {
  320. // close old wal file; truncate to avoid wasting space if an early cut
  321. off, serr := w.tail().Seek(0, os.SEEK_CUR)
  322. if serr != nil {
  323. return serr
  324. }
  325. if err := w.tail().Truncate(off); err != nil {
  326. return err
  327. }
  328. if err := w.sync(); err != nil {
  329. return err
  330. }
  331. fpath := path.Join(w.dir, walName(w.seq()+1, w.enti+1))
  332. // create a temp wal file with name sequence + 1, or truncate the existing one
  333. newTail, err := w.fp.Open()
  334. if err != nil {
  335. return err
  336. }
  337. // update writer and save the previous crc
  338. w.locks = append(w.locks, newTail)
  339. prevCrc := w.encoder.crc.Sum32()
  340. w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
  341. if err != nil {
  342. return err
  343. }
  344. if err = w.saveCrc(prevCrc); err != nil {
  345. return err
  346. }
  347. if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
  348. return err
  349. }
  350. if err = w.saveState(&w.state); err != nil {
  351. return err
  352. }
  353. // atomically move temp wal file to wal file
  354. if err = w.sync(); err != nil {
  355. return err
  356. }
  357. off, err = w.tail().Seek(0, os.SEEK_CUR)
  358. if err != nil {
  359. return err
  360. }
  361. if err = os.Rename(newTail.Name(), fpath); err != nil {
  362. return err
  363. }
  364. if err = fileutil.Fsync(w.dirFile); err != nil {
  365. return err
  366. }
  367. newTail.Close()
  368. if newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil {
  369. return err
  370. }
  371. if _, err = newTail.Seek(off, os.SEEK_SET); err != nil {
  372. return err
  373. }
  374. w.locks[len(w.locks)-1] = newTail
  375. prevCrc = w.encoder.crc.Sum32()
  376. w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
  377. if err != nil {
  378. return err
  379. }
  380. plog.Infof("segmented wal file %v is created", fpath)
  381. return nil
  382. }
  383. func (w *WAL) sync() error {
  384. if w.encoder != nil {
  385. if err := w.encoder.flush(); err != nil {
  386. return err
  387. }
  388. }
  389. start := time.Now()
  390. err := fileutil.Fdatasync(w.tail().File)
  391. duration := time.Since(start)
  392. if duration > warnSyncDuration {
  393. plog.Warningf("sync duration of %v, expected less than %v", duration, warnSyncDuration)
  394. }
  395. syncDurations.Observe(duration.Seconds())
  396. return err
  397. }
  398. // ReleaseLockTo releases the locks, which has smaller index than the given index
  399. // except the largest one among them.
  400. // For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release
  401. // lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4.
  402. func (w *WAL) ReleaseLockTo(index uint64) error {
  403. w.mu.Lock()
  404. defer w.mu.Unlock()
  405. var smaller int
  406. found := false
  407. for i, l := range w.locks {
  408. _, lockIndex, err := parseWalName(path.Base(l.Name()))
  409. if err != nil {
  410. return err
  411. }
  412. if lockIndex >= index {
  413. smaller = i - 1
  414. found = true
  415. break
  416. }
  417. }
  418. // if no lock index is greater than the release index, we can
  419. // release lock up to the last one(excluding).
  420. if !found && len(w.locks) != 0 {
  421. smaller = len(w.locks) - 1
  422. }
  423. if smaller <= 0 {
  424. return nil
  425. }
  426. for i := 0; i < smaller; i++ {
  427. if w.locks[i] == nil {
  428. continue
  429. }
  430. w.locks[i].Close()
  431. }
  432. w.locks = w.locks[smaller:]
  433. return nil
  434. }
  435. func (w *WAL) Close() error {
  436. w.mu.Lock()
  437. defer w.mu.Unlock()
  438. if w.fp != nil {
  439. w.fp.Close()
  440. w.fp = nil
  441. }
  442. if w.tail() != nil {
  443. if err := w.sync(); err != nil {
  444. return err
  445. }
  446. }
  447. for _, l := range w.locks {
  448. if l == nil {
  449. continue
  450. }
  451. if err := l.Close(); err != nil {
  452. plog.Errorf("failed to unlock during closing wal: %s", err)
  453. }
  454. }
  455. return w.dirFile.Close()
  456. }
  457. func (w *WAL) saveEntry(e *raftpb.Entry) error {
  458. // TODO: add MustMarshalTo to reduce one allocation.
  459. b := pbutil.MustMarshal(e)
  460. rec := &walpb.Record{Type: entryType, Data: b}
  461. if err := w.encoder.encode(rec); err != nil {
  462. return err
  463. }
  464. w.enti = e.Index
  465. return nil
  466. }
  467. func (w *WAL) saveState(s *raftpb.HardState) error {
  468. if raft.IsEmptyHardState(*s) {
  469. return nil
  470. }
  471. w.state = *s
  472. b := pbutil.MustMarshal(s)
  473. rec := &walpb.Record{Type: stateType, Data: b}
  474. return w.encoder.encode(rec)
  475. }
  476. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  477. w.mu.Lock()
  478. defer w.mu.Unlock()
  479. // short cut, do not call sync
  480. if raft.IsEmptyHardState(st) && len(ents) == 0 {
  481. return nil
  482. }
  483. mustSync := mustSync(st, w.state, len(ents))
  484. // TODO(xiangli): no more reference operator
  485. for i := range ents {
  486. if err := w.saveEntry(&ents[i]); err != nil {
  487. return err
  488. }
  489. }
  490. if err := w.saveState(&st); err != nil {
  491. return err
  492. }
  493. curOff, err := w.tail().Seek(0, os.SEEK_CUR)
  494. if err != nil {
  495. return err
  496. }
  497. if curOff < segmentSizeBytes {
  498. if mustSync {
  499. return w.sync()
  500. }
  501. return nil
  502. }
  503. // TODO: add a test for this code path when refactoring the tests
  504. return w.cut()
  505. }
  506. func (w *WAL) SaveSnapshot(e walpb.Snapshot) error {
  507. w.mu.Lock()
  508. defer w.mu.Unlock()
  509. b := pbutil.MustMarshal(&e)
  510. rec := &walpb.Record{Type: snapshotType, Data: b}
  511. if err := w.encoder.encode(rec); err != nil {
  512. return err
  513. }
  514. // update enti only when snapshot is ahead of last index
  515. if w.enti < e.Index {
  516. w.enti = e.Index
  517. }
  518. return w.sync()
  519. }
  520. func (w *WAL) saveCrc(prevCrc uint32) error {
  521. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  522. }
  523. func (w *WAL) tail() *fileutil.LockedFile {
  524. if len(w.locks) > 0 {
  525. return w.locks[len(w.locks)-1]
  526. }
  527. return nil
  528. }
  529. func (w *WAL) seq() uint64 {
  530. t := w.tail()
  531. if t == nil {
  532. return 0
  533. }
  534. seq, _, err := parseWalName(path.Base(t.Name()))
  535. if err != nil {
  536. plog.Fatalf("bad wal name %s (%v)", t.Name(), err)
  537. }
  538. return seq
  539. }
  540. func mustSync(st, prevst raftpb.HardState, entsnum int) bool {
  541. // Persistent state on all servers:
  542. // (Updated on stable storage before responding to RPCs)
  543. // currentTerm
  544. // votedFor
  545. // log entries[]
  546. return entsnum != 0 || st.Vote != prevst.Vote || st.Term != prevst.Term
  547. }
  548. func closeAll(rcs ...io.ReadCloser) error {
  549. for _, f := range rcs {
  550. if err := f.Close(); err != nil {
  551. return err
  552. }
  553. }
  554. return nil
  555. }