wal.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. "go.etcd.io/etcd/pkg/fileutil"
  26. "go.etcd.io/etcd/pkg/pbutil"
  27. "go.etcd.io/etcd/raft"
  28. "go.etcd.io/etcd/raft/raftpb"
  29. "go.etcd.io/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("go.etcd.io/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. var perr error
  166. defer func() {
  167. if perr != nil {
  168. w.cleanupWAL(lg)
  169. }
  170. }()
  171. // directory was renamed; sync parent dir to persist rename
  172. pdir, perr := fileutil.OpenDir(filepath.Dir(w.dir))
  173. if perr != nil {
  174. if lg != nil {
  175. lg.Warn(
  176. "failed to open the parent data directory",
  177. zap.String("parent-dir-path", filepath.Dir(w.dir)),
  178. zap.String("dir-path", w.dir),
  179. zap.Error(perr),
  180. )
  181. }
  182. return nil, perr
  183. }
  184. if perr = fileutil.Fsync(pdir); perr != nil {
  185. if lg != nil {
  186. lg.Warn(
  187. "failed to fsync the parent data directory file",
  188. zap.String("parent-dir-path", filepath.Dir(w.dir)),
  189. zap.String("dir-path", w.dir),
  190. zap.Error(perr),
  191. )
  192. }
  193. return nil, perr
  194. }
  195. if perr = pdir.Close(); perr != nil {
  196. if lg != nil {
  197. lg.Warn(
  198. "failed to close the parent data directory file",
  199. zap.String("parent-dir-path", filepath.Dir(w.dir)),
  200. zap.String("dir-path", w.dir),
  201. zap.Error(perr),
  202. )
  203. }
  204. return nil, perr
  205. }
  206. return w, nil
  207. }
  208. func (w *WAL) cleanupWAL(lg *zap.Logger) {
  209. var err error
  210. if err = w.Close(); err != nil {
  211. if lg != nil {
  212. lg.Panic("failed to close WAL during cleanup", zap.Error(err))
  213. } else {
  214. plog.Panicf("failed to close WAL during cleanup: %v", err)
  215. }
  216. }
  217. brokenDirName := fmt.Sprintf("%s.broken.%v", w.dir, time.Now().Format("20060102.150405.999999"))
  218. if err = os.Rename(w.dir, brokenDirName); err != nil {
  219. if lg != nil {
  220. lg.Panic(
  221. "failed to rename WAL during cleanup",
  222. zap.Error(err),
  223. zap.String("source-path", w.dir),
  224. zap.String("rename-path", brokenDirName),
  225. )
  226. } else {
  227. plog.Panicf("failed to rename WAL during cleanup: %v", err)
  228. }
  229. }
  230. }
  231. func (w *WAL) renameWAL(tmpdirpath string) (*WAL, error) {
  232. if err := os.RemoveAll(w.dir); err != nil {
  233. return nil, err
  234. }
  235. // On non-Windows platforms, hold the lock while renaming. Releasing
  236. // the lock and trying to reacquire it quickly can be flaky because
  237. // it's possible the process will fork to spawn a process while this is
  238. // happening. The fds are set up as close-on-exec by the Go runtime,
  239. // but there is a window between the fork and the exec where another
  240. // process holds the lock.
  241. if err := os.Rename(tmpdirpath, w.dir); err != nil {
  242. if _, ok := err.(*os.LinkError); ok {
  243. return w.renameWALUnlock(tmpdirpath)
  244. }
  245. return nil, err
  246. }
  247. w.fp = newFilePipeline(w.lg, w.dir, SegmentSizeBytes)
  248. df, err := fileutil.OpenDir(w.dir)
  249. w.dirFile = df
  250. return w, err
  251. }
  252. func (w *WAL) renameWALUnlock(tmpdirpath string) (*WAL, error) {
  253. // rename of directory with locked files doesn't work on windows/cifs;
  254. // close the WAL to release the locks so the directory can be renamed.
  255. if w.lg != nil {
  256. w.lg.Info(
  257. "closing WAL to release flock and retry directory renaming",
  258. zap.String("from", tmpdirpath),
  259. zap.String("to", w.dir),
  260. )
  261. } else {
  262. plog.Infof("releasing file lock to rename %q to %q", tmpdirpath, w.dir)
  263. }
  264. w.Close()
  265. if err := os.Rename(tmpdirpath, w.dir); err != nil {
  266. return nil, err
  267. }
  268. // reopen and relock
  269. newWAL, oerr := Open(w.lg, w.dir, walpb.Snapshot{})
  270. if oerr != nil {
  271. return nil, oerr
  272. }
  273. if _, _, _, err := newWAL.ReadAll(); err != nil {
  274. newWAL.Close()
  275. return nil, err
  276. }
  277. return newWAL, nil
  278. }
  279. // Open opens the WAL at the given snap.
  280. // The snap SHOULD have been previously saved to the WAL, or the following
  281. // ReadAll will fail.
  282. // The returned WAL is ready to read and the first record will be the one after
  283. // the given snap. The WAL cannot be appended to before reading out all of its
  284. // previous records.
  285. func Open(lg *zap.Logger, dirpath string, snap walpb.Snapshot) (*WAL, error) {
  286. w, err := openAtIndex(lg, dirpath, snap, true)
  287. if err != nil {
  288. return nil, err
  289. }
  290. if w.dirFile, err = fileutil.OpenDir(w.dir); err != nil {
  291. return nil, err
  292. }
  293. return w, nil
  294. }
  295. // OpenForRead only opens the wal files for read.
  296. // Write on a read only wal panics.
  297. func OpenForRead(lg *zap.Logger, dirpath string, snap walpb.Snapshot) (*WAL, error) {
  298. return openAtIndex(lg, dirpath, snap, false)
  299. }
  300. func openAtIndex(lg *zap.Logger, dirpath string, snap walpb.Snapshot, write bool) (*WAL, error) {
  301. names, nameIndex, err := selectWALFiles(lg, dirpath, snap)
  302. if err != nil {
  303. return nil, err
  304. }
  305. rs, ls, closer, err := openWALFiles(lg, dirpath, names, nameIndex, write)
  306. if err != nil {
  307. return nil, err
  308. }
  309. // create a WAL ready for reading
  310. w := &WAL{
  311. lg: lg,
  312. dir: dirpath,
  313. start: snap,
  314. decoder: newDecoder(rs...),
  315. readClose: closer,
  316. locks: ls,
  317. }
  318. if write {
  319. // write reuses the file descriptors from read; don't close so
  320. // WAL can append without dropping the file lock
  321. w.readClose = nil
  322. if _, _, err := parseWALName(filepath.Base(w.tail().Name())); err != nil {
  323. closer()
  324. return nil, err
  325. }
  326. w.fp = newFilePipeline(lg, w.dir, SegmentSizeBytes)
  327. }
  328. return w, nil
  329. }
  330. func selectWALFiles(lg *zap.Logger, dirpath string, snap walpb.Snapshot) ([]string, int, error) {
  331. names, err := readWALNames(lg, dirpath)
  332. if err != nil {
  333. return nil, -1, err
  334. }
  335. nameIndex, ok := searchIndex(lg, names, snap.Index)
  336. if !ok || !isValidSeq(lg, names[nameIndex:]) {
  337. err = ErrFileNotFound
  338. return nil, -1, err
  339. }
  340. return names, nameIndex, nil
  341. }
  342. func openWALFiles(lg *zap.Logger, dirpath string, names []string, nameIndex int, write bool) ([]io.Reader, []*fileutil.LockedFile, func() error, error) {
  343. rcs := make([]io.ReadCloser, 0)
  344. rs := make([]io.Reader, 0)
  345. ls := make([]*fileutil.LockedFile, 0)
  346. for _, name := range names[nameIndex:] {
  347. p := filepath.Join(dirpath, name)
  348. if write {
  349. l, err := fileutil.TryLockFile(p, os.O_RDWR, fileutil.PrivateFileMode)
  350. if err != nil {
  351. closeAll(rcs...)
  352. return nil, nil, nil, err
  353. }
  354. ls = append(ls, l)
  355. rcs = append(rcs, l)
  356. } else {
  357. rf, err := os.OpenFile(p, os.O_RDONLY, fileutil.PrivateFileMode)
  358. if err != nil {
  359. closeAll(rcs...)
  360. return nil, nil, nil, err
  361. }
  362. ls = append(ls, nil)
  363. rcs = append(rcs, rf)
  364. }
  365. rs = append(rs, rcs[len(rcs)-1])
  366. }
  367. closer := func() error { return closeAll(rcs...) }
  368. return rs, ls, closer, nil
  369. }
  370. // ReadAll reads out records of the current WAL.
  371. // If opened in write mode, it must read out all records until EOF. Or an error
  372. // will be returned.
  373. // If opened in read mode, it will try to read all records if possible.
  374. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
  375. // If loaded snap doesn't match with the expected one, it will return
  376. // all the records and error ErrSnapshotMismatch.
  377. // TODO: detect not-last-snap error.
  378. // TODO: maybe loose the checking of match.
  379. // After ReadAll, the WAL will be ready for appending new records.
  380. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  381. w.mu.Lock()
  382. defer w.mu.Unlock()
  383. rec := &walpb.Record{}
  384. decoder := w.decoder
  385. var match bool
  386. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  387. switch rec.Type {
  388. case entryType:
  389. e := mustUnmarshalEntry(rec.Data)
  390. if e.Index > w.start.Index {
  391. ents = append(ents[:e.Index-w.start.Index-1], e)
  392. }
  393. w.enti = e.Index
  394. case stateType:
  395. state = mustUnmarshalState(rec.Data)
  396. case metadataType:
  397. if metadata != nil && !bytes.Equal(metadata, rec.Data) {
  398. state.Reset()
  399. return nil, state, nil, ErrMetadataConflict
  400. }
  401. metadata = rec.Data
  402. case crcType:
  403. crc := decoder.crc.Sum32()
  404. // current crc of decoder must match the crc of the record.
  405. // do no need to match 0 crc, since the decoder is a new one at this case.
  406. if crc != 0 && rec.Validate(crc) != nil {
  407. state.Reset()
  408. return nil, state, nil, ErrCRCMismatch
  409. }
  410. decoder.updateCRC(rec.Crc)
  411. case snapshotType:
  412. var snap walpb.Snapshot
  413. pbutil.MustUnmarshal(&snap, rec.Data)
  414. if snap.Index == w.start.Index {
  415. if snap.Term != w.start.Term {
  416. state.Reset()
  417. return nil, state, nil, ErrSnapshotMismatch
  418. }
  419. match = true
  420. }
  421. default:
  422. state.Reset()
  423. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  424. }
  425. }
  426. switch w.tail() {
  427. case nil:
  428. // We do not have to read out all entries in read mode.
  429. // The last record maybe a partial written one, so
  430. // ErrunexpectedEOF might be returned.
  431. if err != io.EOF && err != io.ErrUnexpectedEOF {
  432. state.Reset()
  433. return nil, state, nil, err
  434. }
  435. default:
  436. // We must read all of the entries if WAL is opened in write mode.
  437. if err != io.EOF {
  438. state.Reset()
  439. return nil, state, nil, err
  440. }
  441. // decodeRecord() will return io.EOF if it detects a zero record,
  442. // but this zero record may be followed by non-zero records from
  443. // a torn write. Overwriting some of these non-zero records, but
  444. // not all, will cause CRC errors on WAL open. Since the records
  445. // were never fully synced to disk in the first place, it's safe
  446. // to zero them out to avoid any CRC errors from new writes.
  447. if _, err = w.tail().Seek(w.decoder.lastOffset(), io.SeekStart); err != nil {
  448. return nil, state, nil, err
  449. }
  450. if err = fileutil.ZeroToEnd(w.tail().File); err != nil {
  451. return nil, state, nil, err
  452. }
  453. }
  454. err = nil
  455. if !match {
  456. err = ErrSnapshotNotFound
  457. }
  458. // close decoder, disable reading
  459. if w.readClose != nil {
  460. w.readClose()
  461. w.readClose = nil
  462. }
  463. w.start = walpb.Snapshot{}
  464. w.metadata = metadata
  465. if w.tail() != nil {
  466. // create encoder (chain crc with the decoder), enable appending
  467. w.encoder, err = newFileEncoder(w.tail().File, w.decoder.lastCRC())
  468. if err != nil {
  469. return
  470. }
  471. }
  472. w.decoder = nil
  473. return metadata, state, ents, err
  474. }
  475. // Verify reads through the given WAL and verifies that it is not corrupted.
  476. // It creates a new decoder to read through the records of the given WAL.
  477. // It does not conflict with any open WAL, but it is recommended not to
  478. // call this function after opening the WAL for writing.
  479. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
  480. // If the loaded snap doesn't match with the expected one, it will
  481. // return error ErrSnapshotMismatch.
  482. func Verify(lg *zap.Logger, walDir string, snap walpb.Snapshot) error {
  483. var metadata []byte
  484. var err error
  485. var match bool
  486. rec := &walpb.Record{}
  487. names, nameIndex, err := selectWALFiles(lg, walDir, snap)
  488. if err != nil {
  489. return err
  490. }
  491. // open wal files in read mode, so that there is no conflict
  492. // when the same WAL is opened elsewhere in write mode
  493. rs, _, closer, err := openWALFiles(lg, walDir, names, nameIndex, false)
  494. if err != nil {
  495. return err
  496. }
  497. defer func() {
  498. if closer != nil {
  499. closer()
  500. }
  501. }()
  502. // create a new decoder from the readers on the WAL files
  503. decoder := newDecoder(rs...)
  504. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  505. switch rec.Type {
  506. case metadataType:
  507. if metadata != nil && !bytes.Equal(metadata, rec.Data) {
  508. return ErrMetadataConflict
  509. }
  510. metadata = rec.Data
  511. case crcType:
  512. crc := decoder.crc.Sum32()
  513. // Current crc of decoder must match the crc of the record.
  514. // We need not match 0 crc, since the decoder is a new one at this point.
  515. if crc != 0 && rec.Validate(crc) != nil {
  516. return ErrCRCMismatch
  517. }
  518. decoder.updateCRC(rec.Crc)
  519. case snapshotType:
  520. var loadedSnap walpb.Snapshot
  521. pbutil.MustUnmarshal(&loadedSnap, rec.Data)
  522. if loadedSnap.Index == snap.Index {
  523. if loadedSnap.Term != snap.Term {
  524. return ErrSnapshotMismatch
  525. }
  526. match = true
  527. }
  528. // We ignore all entry and state type records as these
  529. // are not necessary for validating the WAL contents
  530. case entryType:
  531. case stateType:
  532. default:
  533. return fmt.Errorf("unexpected block type %d", rec.Type)
  534. }
  535. }
  536. // We do not have to read out all the WAL entries
  537. // as the decoder is opened in read mode.
  538. if err != io.EOF && err != io.ErrUnexpectedEOF {
  539. return err
  540. }
  541. if !match {
  542. return ErrSnapshotNotFound
  543. }
  544. return nil
  545. }
  546. // cut closes current file written and creates a new one ready to append.
  547. // cut first creates a temp wal file and writes necessary headers into it.
  548. // Then cut atomically rename temp wal file to a wal file.
  549. func (w *WAL) cut() error {
  550. // close old wal file; truncate to avoid wasting space if an early cut
  551. off, serr := w.tail().Seek(0, io.SeekCurrent)
  552. if serr != nil {
  553. return serr
  554. }
  555. if err := w.tail().Truncate(off); err != nil {
  556. return err
  557. }
  558. if err := w.sync(); err != nil {
  559. return err
  560. }
  561. fpath := filepath.Join(w.dir, walName(w.seq()+1, w.enti+1))
  562. // create a temp wal file with name sequence + 1, or truncate the existing one
  563. newTail, err := w.fp.Open()
  564. if err != nil {
  565. return err
  566. }
  567. // update writer and save the previous crc
  568. w.locks = append(w.locks, newTail)
  569. prevCrc := w.encoder.crc.Sum32()
  570. w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
  571. if err != nil {
  572. return err
  573. }
  574. if err = w.saveCrc(prevCrc); err != nil {
  575. return err
  576. }
  577. if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
  578. return err
  579. }
  580. if err = w.saveState(&w.state); err != nil {
  581. return err
  582. }
  583. // atomically move temp wal file to wal file
  584. if err = w.sync(); err != nil {
  585. return err
  586. }
  587. off, err = w.tail().Seek(0, io.SeekCurrent)
  588. if err != nil {
  589. return err
  590. }
  591. if err = os.Rename(newTail.Name(), fpath); err != nil {
  592. return err
  593. }
  594. if err = fileutil.Fsync(w.dirFile); err != nil {
  595. return err
  596. }
  597. // reopen newTail with its new path so calls to Name() match the wal filename format
  598. newTail.Close()
  599. if newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil {
  600. return err
  601. }
  602. if _, err = newTail.Seek(off, io.SeekStart); err != nil {
  603. return err
  604. }
  605. w.locks[len(w.locks)-1] = newTail
  606. prevCrc = w.encoder.crc.Sum32()
  607. w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
  608. if err != nil {
  609. return err
  610. }
  611. if w.lg != nil {
  612. w.lg.Info("created a new WAL segment", zap.String("path", fpath))
  613. } else {
  614. plog.Infof("segmented wal file %v is created", fpath)
  615. }
  616. return nil
  617. }
  618. func (w *WAL) sync() error {
  619. if w.encoder != nil {
  620. if err := w.encoder.flush(); err != nil {
  621. return err
  622. }
  623. }
  624. start := time.Now()
  625. err := fileutil.Fdatasync(w.tail().File)
  626. took := time.Since(start)
  627. if took > warnSyncDuration {
  628. if w.lg != nil {
  629. w.lg.Warn(
  630. "slow fdatasync",
  631. zap.Duration("took", took),
  632. zap.Duration("expected-duration", warnSyncDuration),
  633. )
  634. } else {
  635. plog.Warningf("sync duration of %v, expected less than %v", took, warnSyncDuration)
  636. }
  637. }
  638. walFsyncSec.Observe(took.Seconds())
  639. return err
  640. }
  641. // ReleaseLockTo releases the locks, which has smaller index than the given index
  642. // except the largest one among them.
  643. // For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release
  644. // lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4.
  645. func (w *WAL) ReleaseLockTo(index uint64) error {
  646. w.mu.Lock()
  647. defer w.mu.Unlock()
  648. if len(w.locks) == 0 {
  649. return nil
  650. }
  651. var smaller int
  652. found := false
  653. for i, l := range w.locks {
  654. _, lockIndex, err := parseWALName(filepath.Base(l.Name()))
  655. if err != nil {
  656. return err
  657. }
  658. if lockIndex >= index {
  659. smaller = i - 1
  660. found = true
  661. break
  662. }
  663. }
  664. // if no lock index is greater than the release index, we can
  665. // release lock up to the last one(excluding).
  666. if !found {
  667. smaller = len(w.locks) - 1
  668. }
  669. if smaller <= 0 {
  670. return nil
  671. }
  672. for i := 0; i < smaller; i++ {
  673. if w.locks[i] == nil {
  674. continue
  675. }
  676. w.locks[i].Close()
  677. }
  678. w.locks = w.locks[smaller:]
  679. return nil
  680. }
  681. // Close closes the current WAL file and directory.
  682. func (w *WAL) Close() error {
  683. w.mu.Lock()
  684. defer w.mu.Unlock()
  685. if w.fp != nil {
  686. w.fp.Close()
  687. w.fp = nil
  688. }
  689. if w.tail() != nil {
  690. if err := w.sync(); err != nil {
  691. return err
  692. }
  693. }
  694. for _, l := range w.locks {
  695. if l == nil {
  696. continue
  697. }
  698. if err := l.Close(); err != nil {
  699. if w.lg != nil {
  700. w.lg.Warn("failed to close WAL", zap.Error(err))
  701. } else {
  702. plog.Errorf("failed to unlock during closing wal: %s", err)
  703. }
  704. }
  705. }
  706. return w.dirFile.Close()
  707. }
  708. func (w *WAL) saveEntry(e *raftpb.Entry) error {
  709. // TODO: add MustMarshalTo to reduce one allocation.
  710. b := pbutil.MustMarshal(e)
  711. rec := &walpb.Record{Type: entryType, Data: b}
  712. if err := w.encoder.encode(rec); err != nil {
  713. return err
  714. }
  715. w.enti = e.Index
  716. return nil
  717. }
  718. func (w *WAL) saveState(s *raftpb.HardState) error {
  719. if raft.IsEmptyHardState(*s) {
  720. return nil
  721. }
  722. w.state = *s
  723. b := pbutil.MustMarshal(s)
  724. rec := &walpb.Record{Type: stateType, Data: b}
  725. return w.encoder.encode(rec)
  726. }
  727. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  728. w.mu.Lock()
  729. defer w.mu.Unlock()
  730. // short cut, do not call sync
  731. if raft.IsEmptyHardState(st) && len(ents) == 0 {
  732. return nil
  733. }
  734. mustSync := raft.MustSync(st, w.state, len(ents))
  735. // TODO(xiangli): no more reference operator
  736. for i := range ents {
  737. if err := w.saveEntry(&ents[i]); err != nil {
  738. return err
  739. }
  740. }
  741. if err := w.saveState(&st); err != nil {
  742. return err
  743. }
  744. curOff, err := w.tail().Seek(0, io.SeekCurrent)
  745. if err != nil {
  746. return err
  747. }
  748. if curOff < SegmentSizeBytes {
  749. if mustSync {
  750. return w.sync()
  751. }
  752. return nil
  753. }
  754. return w.cut()
  755. }
  756. func (w *WAL) SaveSnapshot(e walpb.Snapshot) error {
  757. b := pbutil.MustMarshal(&e)
  758. w.mu.Lock()
  759. defer w.mu.Unlock()
  760. rec := &walpb.Record{Type: snapshotType, Data: b}
  761. if err := w.encoder.encode(rec); err != nil {
  762. return err
  763. }
  764. // update enti only when snapshot is ahead of last index
  765. if w.enti < e.Index {
  766. w.enti = e.Index
  767. }
  768. return w.sync()
  769. }
  770. func (w *WAL) saveCrc(prevCrc uint32) error {
  771. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  772. }
  773. func (w *WAL) tail() *fileutil.LockedFile {
  774. if len(w.locks) > 0 {
  775. return w.locks[len(w.locks)-1]
  776. }
  777. return nil
  778. }
  779. func (w *WAL) seq() uint64 {
  780. t := w.tail()
  781. if t == nil {
  782. return 0
  783. }
  784. seq, _, err := parseWALName(filepath.Base(t.Name()))
  785. if err != nil {
  786. if w.lg != nil {
  787. w.lg.Fatal("failed to parse WAL name", zap.String("name", t.Name()), zap.Error(err))
  788. } else {
  789. plog.Fatalf("bad wal name %s (%v)", t.Name(), err)
  790. }
  791. }
  792. return seq
  793. }
  794. func closeAll(rcs ...io.ReadCloser) error {
  795. for _, f := range rcs {
  796. if err := f.Close(); err != nil {
  797. return err
  798. }
  799. }
  800. return nil
  801. }