wal.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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/filepath"
  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. "go.uber.org/zap"
  32. )
  33. const (
  34. metadataType int64 = iota + 1
  35. entryType
  36. stateType
  37. crcType
  38. snapshotType
  39. // warnSyncDuration is the amount of time allotted to an fsync before
  40. // logging a warning
  41. warnSyncDuration = time.Second
  42. )
  43. var (
  44. // SegmentSizeBytes is the preallocated size of each wal segment file.
  45. // The actual size might be larger than this. In general, the default
  46. // value should be used, but this is defined as an exported variable
  47. // so that tests can set a different segment size.
  48. SegmentSizeBytes int64 = 64 * 1000 * 1000 // 64MB
  49. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "wal")
  50. ErrMetadataConflict = errors.New("wal: conflicting metadata found")
  51. ErrFileNotFound = errors.New("wal: file not found")
  52. ErrCRCMismatch = errors.New("wal: crc mismatch")
  53. ErrSnapshotMismatch = errors.New("wal: snapshot mismatch")
  54. ErrSnapshotNotFound = errors.New("wal: snapshot not found")
  55. crcTable = crc32.MakeTable(crc32.Castagnoli)
  56. )
  57. // WAL is a logical representation of the stable storage.
  58. // WAL is either in read mode or append mode but not both.
  59. // A newly created WAL is in append mode, and ready for appending records.
  60. // A just opened WAL is in read mode, and ready for reading records.
  61. // The WAL will be ready for appending after reading out all the previous records.
  62. type WAL struct {
  63. lg *zap.Logger
  64. dir string // the living directory of the underlay files
  65. // dirFile is a fd for the wal directory for syncing on Rename
  66. dirFile *os.File
  67. metadata []byte // metadata recorded at the head of each WAL
  68. state raftpb.HardState // hardstate recorded at the head of WAL
  69. start walpb.Snapshot // snapshot to start reading
  70. decoder *decoder // decoder to decode records
  71. readClose func() error // closer for decode reader
  72. mu sync.Mutex
  73. enti uint64 // index of the last entry saved to the wal
  74. encoder *encoder // encoder to encode records
  75. locks []*fileutil.LockedFile // the locked files the WAL holds (the name is increasing)
  76. fp *filePipeline
  77. }
  78. // Create creates a WAL ready for appending records. The given metadata is
  79. // recorded at the head of each WAL file, and can be retrieved with ReadAll.
  80. func Create(lg *zap.Logger, dirpath string, metadata []byte) (*WAL, error) {
  81. if Exist(dirpath) {
  82. return nil, os.ErrExist
  83. }
  84. // keep temporary wal directory so WAL initialization appears atomic
  85. tmpdirpath := filepath.Clean(dirpath) + ".tmp"
  86. if fileutil.Exist(tmpdirpath) {
  87. if err := os.RemoveAll(tmpdirpath); err != nil {
  88. return nil, err
  89. }
  90. }
  91. if err := fileutil.CreateDirAll(tmpdirpath); err != nil {
  92. if lg != nil {
  93. lg.Warn(
  94. "failed to create a temporary WAL directory",
  95. zap.String("tmp-dir-path", tmpdirpath),
  96. zap.String("dir-path", dirpath),
  97. zap.Error(err),
  98. )
  99. }
  100. return nil, err
  101. }
  102. p := filepath.Join(tmpdirpath, walName(0, 0))
  103. f, err := fileutil.LockFile(p, os.O_WRONLY|os.O_CREATE, fileutil.PrivateFileMode)
  104. if err != nil {
  105. if lg != nil {
  106. lg.Warn(
  107. "failed to flock an initial WAL file",
  108. zap.String("path", p),
  109. zap.Error(err),
  110. )
  111. }
  112. return nil, err
  113. }
  114. if _, err = f.Seek(0, io.SeekEnd); err != nil {
  115. if lg != nil {
  116. lg.Warn(
  117. "failed to seek an initial WAL file",
  118. zap.String("path", p),
  119. zap.Error(err),
  120. )
  121. }
  122. return nil, err
  123. }
  124. if err = fileutil.Preallocate(f.File, SegmentSizeBytes, true); err != nil {
  125. if lg != nil {
  126. lg.Warn(
  127. "failed to preallocate an initial WAL file",
  128. zap.String("path", p),
  129. zap.Int64("segment-bytes", SegmentSizeBytes),
  130. zap.Error(err),
  131. )
  132. }
  133. return nil, err
  134. }
  135. w := &WAL{
  136. lg: lg,
  137. dir: dirpath,
  138. metadata: metadata,
  139. }
  140. w.encoder, err = newFileEncoder(f.File, 0)
  141. if err != nil {
  142. return nil, err
  143. }
  144. w.locks = append(w.locks, f)
  145. if err = w.saveCrc(0); err != nil {
  146. return nil, err
  147. }
  148. if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil {
  149. return nil, err
  150. }
  151. if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil {
  152. return nil, err
  153. }
  154. if w, err = w.renameWAL(tmpdirpath); err != nil {
  155. if lg != nil {
  156. lg.Warn(
  157. "failed to rename the temporary WAL directory",
  158. zap.String("tmp-dir-path", tmpdirpath),
  159. zap.String("dir-path", w.dir),
  160. zap.Error(err),
  161. )
  162. }
  163. return nil, err
  164. }
  165. // directory was renamed; sync parent dir to persist rename
  166. pdir, perr := fileutil.OpenDir(filepath.Dir(w.dir))
  167. if perr != nil {
  168. if lg != nil {
  169. lg.Warn(
  170. "failed to open the parent data directory",
  171. zap.String("parent-dir-path", filepath.Dir(w.dir)),
  172. zap.String("dir-path", w.dir),
  173. zap.Error(perr),
  174. )
  175. }
  176. return nil, perr
  177. }
  178. if perr = fileutil.Fsync(pdir); perr != nil {
  179. if lg != nil {
  180. lg.Warn(
  181. "failed to fsync the parent data directory file",
  182. zap.String("parent-dir-path", filepath.Dir(w.dir)),
  183. zap.String("dir-path", w.dir),
  184. zap.Error(perr),
  185. )
  186. }
  187. return nil, perr
  188. }
  189. if perr = pdir.Close(); err != nil {
  190. if lg != nil {
  191. lg.Warn(
  192. "failed to close the parent data directory file",
  193. zap.String("parent-dir-path", filepath.Dir(w.dir)),
  194. zap.String("dir-path", w.dir),
  195. zap.Error(perr),
  196. )
  197. }
  198. return nil, perr
  199. }
  200. return w, nil
  201. }
  202. func (w *WAL) renameWAL(tmpdirpath string) (*WAL, error) {
  203. if err := os.RemoveAll(w.dir); err != nil {
  204. return nil, err
  205. }
  206. // On non-Windows platforms, hold the lock while renaming. Releasing
  207. // the lock and trying to reacquire it quickly can be flaky because
  208. // it's possible the process will fork to spawn a process while this is
  209. // happening. The fds are set up as close-on-exec by the Go runtime,
  210. // but there is a window between the fork and the exec where another
  211. // process holds the lock.
  212. if err := os.Rename(tmpdirpath, w.dir); err != nil {
  213. if _, ok := err.(*os.LinkError); ok {
  214. return w.renameWALUnlock(tmpdirpath)
  215. }
  216. return nil, err
  217. }
  218. w.fp = newFilePipeline(w.lg, w.dir, SegmentSizeBytes)
  219. df, err := fileutil.OpenDir(w.dir)
  220. w.dirFile = df
  221. return w, err
  222. }
  223. func (w *WAL) renameWALUnlock(tmpdirpath string) (*WAL, error) {
  224. // rename of directory with locked files doesn't work on windows/cifs;
  225. // close the WAL to release the locks so the directory can be renamed.
  226. if w.lg != nil {
  227. w.lg.Info(
  228. "closing WAL to release flock and retry directory renaming",
  229. zap.String("from", tmpdirpath),
  230. zap.String("to", w.dir),
  231. )
  232. } else {
  233. plog.Infof("releasing file lock to rename %q to %q", tmpdirpath, w.dir)
  234. }
  235. w.Close()
  236. if err := os.Rename(tmpdirpath, w.dir); err != nil {
  237. return nil, err
  238. }
  239. // reopen and relock
  240. newWAL, oerr := Open(w.lg, w.dir, walpb.Snapshot{})
  241. if oerr != nil {
  242. return nil, oerr
  243. }
  244. if _, _, _, err := newWAL.ReadAll(); err != nil {
  245. newWAL.Close()
  246. return nil, err
  247. }
  248. return newWAL, nil
  249. }
  250. // Open opens the WAL at the given snap.
  251. // The snap SHOULD have been previously saved to the WAL, or the following
  252. // ReadAll will fail.
  253. // The returned WAL is ready to read and the first record will be the one after
  254. // the given snap. The WAL cannot be appended to before reading out all of its
  255. // previous records.
  256. func Open(lg *zap.Logger, dirpath string, snap walpb.Snapshot) (*WAL, error) {
  257. w, err := openAtIndex(lg, dirpath, snap, true)
  258. if err != nil {
  259. return nil, err
  260. }
  261. if w.dirFile, err = fileutil.OpenDir(w.dir); err != nil {
  262. return nil, err
  263. }
  264. return w, nil
  265. }
  266. // OpenForRead only opens the wal files for read.
  267. // Write on a read only wal panics.
  268. func OpenForRead(lg *zap.Logger, dirpath string, snap walpb.Snapshot) (*WAL, error) {
  269. return openAtIndex(lg, dirpath, snap, false)
  270. }
  271. func openAtIndex(lg *zap.Logger, dirpath string, snap walpb.Snapshot, write bool) (*WAL, error) {
  272. names, err := readWALNames(lg, dirpath)
  273. if err != nil {
  274. return nil, err
  275. }
  276. nameIndex, ok := searchIndex(lg, names, snap.Index)
  277. if !ok || !isValidSeq(lg, names[nameIndex:]) {
  278. return nil, ErrFileNotFound
  279. }
  280. // open the wal files
  281. rcs := make([]io.ReadCloser, 0)
  282. rs := make([]io.Reader, 0)
  283. ls := make([]*fileutil.LockedFile, 0)
  284. for _, name := range names[nameIndex:] {
  285. p := filepath.Join(dirpath, name)
  286. if write {
  287. l, err := fileutil.TryLockFile(p, os.O_RDWR, fileutil.PrivateFileMode)
  288. if err != nil {
  289. closeAll(rcs...)
  290. return nil, err
  291. }
  292. ls = append(ls, l)
  293. rcs = append(rcs, l)
  294. } else {
  295. rf, err := os.OpenFile(p, os.O_RDONLY, fileutil.PrivateFileMode)
  296. if err != nil {
  297. closeAll(rcs...)
  298. return nil, err
  299. }
  300. ls = append(ls, nil)
  301. rcs = append(rcs, rf)
  302. }
  303. rs = append(rs, rcs[len(rcs)-1])
  304. }
  305. closer := func() error { return closeAll(rcs...) }
  306. // create a WAL ready for reading
  307. w := &WAL{
  308. lg: lg,
  309. dir: dirpath,
  310. start: snap,
  311. decoder: newDecoder(rs...),
  312. readClose: closer,
  313. locks: ls,
  314. }
  315. if write {
  316. // write reuses the file descriptors from read; don't close so
  317. // WAL can append without dropping the file lock
  318. w.readClose = nil
  319. if _, _, err := parseWALName(filepath.Base(w.tail().Name())); err != nil {
  320. closer()
  321. return nil, err
  322. }
  323. w.fp = newFilePipeline(w.lg, w.dir, SegmentSizeBytes)
  324. }
  325. return w, nil
  326. }
  327. // ReadAll reads out records of the current WAL.
  328. // If opened in write mode, it must read out all records until EOF. Or an error
  329. // will be returned.
  330. // If opened in read mode, it will try to read all records if possible.
  331. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
  332. // If loaded snap doesn't match with the expected one, it will return
  333. // all the records and error ErrSnapshotMismatch.
  334. // TODO: detect not-last-snap error.
  335. // TODO: maybe loose the checking of match.
  336. // After ReadAll, the WAL will be ready for appending new records.
  337. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  338. w.mu.Lock()
  339. defer w.mu.Unlock()
  340. rec := &walpb.Record{}
  341. decoder := w.decoder
  342. var match bool
  343. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  344. switch rec.Type {
  345. case entryType:
  346. e := mustUnmarshalEntry(rec.Data)
  347. if e.Index > w.start.Index {
  348. ents = append(ents[:e.Index-w.start.Index-1], e)
  349. }
  350. w.enti = e.Index
  351. case stateType:
  352. state = mustUnmarshalState(rec.Data)
  353. case metadataType:
  354. if metadata != nil && !bytes.Equal(metadata, rec.Data) {
  355. state.Reset()
  356. return nil, state, nil, ErrMetadataConflict
  357. }
  358. metadata = rec.Data
  359. case crcType:
  360. crc := decoder.crc.Sum32()
  361. // current crc of decoder must match the crc of the record.
  362. // do no need to match 0 crc, since the decoder is a new one at this case.
  363. if crc != 0 && rec.Validate(crc) != nil {
  364. state.Reset()
  365. return nil, state, nil, ErrCRCMismatch
  366. }
  367. decoder.updateCRC(rec.Crc)
  368. case snapshotType:
  369. var snap walpb.Snapshot
  370. pbutil.MustUnmarshal(&snap, rec.Data)
  371. if snap.Index == w.start.Index {
  372. if snap.Term != w.start.Term {
  373. state.Reset()
  374. return nil, state, nil, ErrSnapshotMismatch
  375. }
  376. match = true
  377. }
  378. default:
  379. state.Reset()
  380. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  381. }
  382. }
  383. switch w.tail() {
  384. case nil:
  385. // We do not have to read out all entries in read mode.
  386. // The last record maybe a partial written one, so
  387. // ErrunexpectedEOF might be returned.
  388. if err != io.EOF && err != io.ErrUnexpectedEOF {
  389. state.Reset()
  390. return nil, state, nil, err
  391. }
  392. default:
  393. // We must read all of the entries if WAL is opened in write mode.
  394. if err != io.EOF {
  395. state.Reset()
  396. return nil, state, nil, err
  397. }
  398. // decodeRecord() will return io.EOF if it detects a zero record,
  399. // but this zero record may be followed by non-zero records from
  400. // a torn write. Overwriting some of these non-zero records, but
  401. // not all, will cause CRC errors on WAL open. Since the records
  402. // were never fully synced to disk in the first place, it's safe
  403. // to zero them out to avoid any CRC errors from new writes.
  404. if _, err = w.tail().Seek(w.decoder.lastOffset(), io.SeekStart); err != nil {
  405. return nil, state, nil, err
  406. }
  407. if err = fileutil.ZeroToEnd(w.tail().File); err != nil {
  408. return nil, state, nil, err
  409. }
  410. }
  411. err = nil
  412. if !match {
  413. err = ErrSnapshotNotFound
  414. }
  415. // close decoder, disable reading
  416. if w.readClose != nil {
  417. w.readClose()
  418. w.readClose = nil
  419. }
  420. w.start = walpb.Snapshot{}
  421. w.metadata = metadata
  422. if w.tail() != nil {
  423. // create encoder (chain crc with the decoder), enable appending
  424. w.encoder, err = newFileEncoder(w.tail().File, w.decoder.lastCRC())
  425. if err != nil {
  426. return
  427. }
  428. }
  429. w.decoder = nil
  430. return metadata, state, ents, err
  431. }
  432. // cut closes current file written and creates a new one ready to append.
  433. // cut first creates a temp wal file and writes necessary headers into it.
  434. // Then cut atomically rename temp wal file to a wal file.
  435. func (w *WAL) cut() error {
  436. // close old wal file; truncate to avoid wasting space if an early cut
  437. off, serr := w.tail().Seek(0, io.SeekCurrent)
  438. if serr != nil {
  439. return serr
  440. }
  441. if err := w.tail().Truncate(off); err != nil {
  442. return err
  443. }
  444. if err := w.sync(); err != nil {
  445. return err
  446. }
  447. fpath := filepath.Join(w.dir, walName(w.seq()+1, w.enti+1))
  448. // create a temp wal file with name sequence + 1, or truncate the existing one
  449. newTail, err := w.fp.Open()
  450. if err != nil {
  451. return err
  452. }
  453. // update writer and save the previous crc
  454. w.locks = append(w.locks, newTail)
  455. prevCrc := w.encoder.crc.Sum32()
  456. w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
  457. if err != nil {
  458. return err
  459. }
  460. if err = w.saveCrc(prevCrc); err != nil {
  461. return err
  462. }
  463. if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
  464. return err
  465. }
  466. if err = w.saveState(&w.state); err != nil {
  467. return err
  468. }
  469. // atomically move temp wal file to wal file
  470. if err = w.sync(); err != nil {
  471. return err
  472. }
  473. off, err = w.tail().Seek(0, io.SeekCurrent)
  474. if err != nil {
  475. return err
  476. }
  477. if err = os.Rename(newTail.Name(), fpath); err != nil {
  478. return err
  479. }
  480. if err = fileutil.Fsync(w.dirFile); err != nil {
  481. return err
  482. }
  483. // reopen newTail with its new path so calls to Name() match the wal filename format
  484. newTail.Close()
  485. if newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil {
  486. return err
  487. }
  488. if _, err = newTail.Seek(off, io.SeekStart); err != nil {
  489. return err
  490. }
  491. w.locks[len(w.locks)-1] = newTail
  492. prevCrc = w.encoder.crc.Sum32()
  493. w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
  494. if err != nil {
  495. return err
  496. }
  497. if w.lg != nil {
  498. w.lg.Info("created a new WAL segment", zap.String("path", fpath))
  499. } else {
  500. plog.Infof("segmented wal file %v is created", fpath)
  501. }
  502. return nil
  503. }
  504. func (w *WAL) sync() error {
  505. if w.encoder != nil {
  506. if err := w.encoder.flush(); err != nil {
  507. return err
  508. }
  509. }
  510. start := time.Now()
  511. err := fileutil.Fdatasync(w.tail().File)
  512. took := time.Since(start)
  513. if took > warnSyncDuration {
  514. if w.lg != nil {
  515. w.lg.Warn(
  516. "slow fdatasync",
  517. zap.Duration("took", took),
  518. zap.Duration("expected-duration", warnSyncDuration),
  519. )
  520. } else {
  521. plog.Warningf("sync duration of %v, expected less than %v", took, warnSyncDuration)
  522. }
  523. }
  524. walFsyncSec.Observe(took.Seconds())
  525. return err
  526. }
  527. // ReleaseLockTo releases the locks, which has smaller index than the given index
  528. // except the largest one among them.
  529. // For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release
  530. // lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4.
  531. func (w *WAL) ReleaseLockTo(index uint64) error {
  532. w.mu.Lock()
  533. defer w.mu.Unlock()
  534. if len(w.locks) == 0 {
  535. return nil
  536. }
  537. var smaller int
  538. found := false
  539. for i, l := range w.locks {
  540. _, lockIndex, err := parseWALName(filepath.Base(l.Name()))
  541. if err != nil {
  542. return err
  543. }
  544. if lockIndex >= index {
  545. smaller = i - 1
  546. found = true
  547. break
  548. }
  549. }
  550. // if no lock index is greater than the release index, we can
  551. // release lock up to the last one(excluding).
  552. if !found {
  553. smaller = len(w.locks) - 1
  554. }
  555. if smaller <= 0 {
  556. return nil
  557. }
  558. for i := 0; i < smaller; i++ {
  559. if w.locks[i] == nil {
  560. continue
  561. }
  562. w.locks[i].Close()
  563. }
  564. w.locks = w.locks[smaller:]
  565. return nil
  566. }
  567. // Close closes the current WAL file and directory.
  568. func (w *WAL) Close() error {
  569. w.mu.Lock()
  570. defer w.mu.Unlock()
  571. if w.fp != nil {
  572. w.fp.Close()
  573. w.fp = nil
  574. }
  575. if w.tail() != nil {
  576. if err := w.sync(); err != nil {
  577. return err
  578. }
  579. }
  580. for _, l := range w.locks {
  581. if l == nil {
  582. continue
  583. }
  584. if err := l.Close(); err != nil {
  585. if w.lg != nil {
  586. w.lg.Warn("failed to close WAL", zap.Error(err))
  587. } else {
  588. plog.Errorf("failed to unlock during closing wal: %s", err)
  589. }
  590. }
  591. }
  592. return w.dirFile.Close()
  593. }
  594. func (w *WAL) saveEntry(e *raftpb.Entry) error {
  595. // TODO: add MustMarshalTo to reduce one allocation.
  596. b := pbutil.MustMarshal(e)
  597. rec := &walpb.Record{Type: entryType, Data: b}
  598. if err := w.encoder.encode(rec); err != nil {
  599. return err
  600. }
  601. w.enti = e.Index
  602. return nil
  603. }
  604. func (w *WAL) saveState(s *raftpb.HardState) error {
  605. if raft.IsEmptyHardState(*s) {
  606. return nil
  607. }
  608. w.state = *s
  609. b := pbutil.MustMarshal(s)
  610. rec := &walpb.Record{Type: stateType, Data: b}
  611. return w.encoder.encode(rec)
  612. }
  613. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  614. w.mu.Lock()
  615. defer w.mu.Unlock()
  616. // short cut, do not call sync
  617. if raft.IsEmptyHardState(st) && len(ents) == 0 {
  618. return nil
  619. }
  620. mustSync := raft.MustSync(st, w.state, len(ents))
  621. // TODO(xiangli): no more reference operator
  622. for i := range ents {
  623. if err := w.saveEntry(&ents[i]); err != nil {
  624. return err
  625. }
  626. }
  627. if err := w.saveState(&st); err != nil {
  628. return err
  629. }
  630. curOff, err := w.tail().Seek(0, io.SeekCurrent)
  631. if err != nil {
  632. return err
  633. }
  634. if curOff < SegmentSizeBytes {
  635. if mustSync {
  636. return w.sync()
  637. }
  638. return nil
  639. }
  640. return w.cut()
  641. }
  642. func (w *WAL) SaveSnapshot(e walpb.Snapshot) error {
  643. b := pbutil.MustMarshal(&e)
  644. w.mu.Lock()
  645. defer w.mu.Unlock()
  646. rec := &walpb.Record{Type: snapshotType, Data: b}
  647. if err := w.encoder.encode(rec); err != nil {
  648. return err
  649. }
  650. // update enti only when snapshot is ahead of last index
  651. if w.enti < e.Index {
  652. w.enti = e.Index
  653. }
  654. return w.sync()
  655. }
  656. func (w *WAL) saveCrc(prevCrc uint32) error {
  657. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  658. }
  659. func (w *WAL) tail() *fileutil.LockedFile {
  660. if len(w.locks) > 0 {
  661. return w.locks[len(w.locks)-1]
  662. }
  663. return nil
  664. }
  665. func (w *WAL) seq() uint64 {
  666. t := w.tail()
  667. if t == nil {
  668. return 0
  669. }
  670. seq, _, err := parseWALName(filepath.Base(t.Name()))
  671. if err != nil {
  672. if w.lg != nil {
  673. w.lg.Fatal("failed to parse WAL name", zap.String("name", t.Name()), zap.Error(err))
  674. } else {
  675. plog.Fatalf("bad wal name %s (%v)", t.Name(), err)
  676. }
  677. }
  678. return seq
  679. }
  680. func closeAll(rcs ...io.ReadCloser) error {
  681. for _, f := range rcs {
  682. if err := f.Close(); err != nil {
  683. return err
  684. }
  685. }
  686. return nil
  687. }