wal.go 20 KB

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