wal.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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. // Open opens the WAL at the given snap.
  138. // The snap SHOULD have been previously saved to the WAL, or the following
  139. // ReadAll will fail.
  140. // The returned WAL is ready to read and the first record will be the one after
  141. // the given snap. The WAL cannot be appended to before reading out all of its
  142. // previous records.
  143. func Open(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  144. w, err := openAtIndex(dirpath, snap, true)
  145. if err != nil {
  146. return nil, err
  147. }
  148. if w.dirFile, err = fileutil.OpenDir(w.dir); err != nil {
  149. return nil, err
  150. }
  151. return w, nil
  152. }
  153. // OpenForRead only opens the wal files for read.
  154. // Write on a read only wal panics.
  155. func OpenForRead(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  156. return openAtIndex(dirpath, snap, false)
  157. }
  158. func openAtIndex(dirpath string, snap walpb.Snapshot, write bool) (*WAL, error) {
  159. names, err := readWalNames(dirpath)
  160. if err != nil {
  161. return nil, err
  162. }
  163. nameIndex, ok := searchIndex(names, snap.Index)
  164. if !ok || !isValidSeq(names[nameIndex:]) {
  165. return nil, ErrFileNotFound
  166. }
  167. // open the wal files
  168. rcs := make([]io.ReadCloser, 0)
  169. rs := make([]io.Reader, 0)
  170. ls := make([]*fileutil.LockedFile, 0)
  171. for _, name := range names[nameIndex:] {
  172. p := filepath.Join(dirpath, name)
  173. if write {
  174. l, err := fileutil.TryLockFile(p, os.O_RDWR, fileutil.PrivateFileMode)
  175. if err != nil {
  176. closeAll(rcs...)
  177. return nil, err
  178. }
  179. ls = append(ls, l)
  180. rcs = append(rcs, l)
  181. } else {
  182. rf, err := os.OpenFile(p, os.O_RDONLY, fileutil.PrivateFileMode)
  183. if err != nil {
  184. closeAll(rcs...)
  185. return nil, err
  186. }
  187. ls = append(ls, nil)
  188. rcs = append(rcs, rf)
  189. }
  190. rs = append(rs, rcs[len(rcs)-1])
  191. }
  192. closer := func() error { return closeAll(rcs...) }
  193. // create a WAL ready for reading
  194. w := &WAL{
  195. dir: dirpath,
  196. start: snap,
  197. decoder: newDecoder(rs...),
  198. readClose: closer,
  199. locks: ls,
  200. }
  201. if write {
  202. // write reuses the file descriptors from read; don't close so
  203. // WAL can append without dropping the file lock
  204. w.readClose = nil
  205. if _, _, err := parseWalName(filepath.Base(w.tail().Name())); err != nil {
  206. closer()
  207. return nil, err
  208. }
  209. w.fp = newFilePipeline(w.dir, SegmentSizeBytes)
  210. }
  211. return w, nil
  212. }
  213. // ReadAll reads out records of the current WAL.
  214. // If opened in write mode, it must read out all records until EOF. Or an error
  215. // will be returned.
  216. // If opened in read mode, it will try to read all records if possible.
  217. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
  218. // If loaded snap doesn't match with the expected one, it will return
  219. // all the records and error ErrSnapshotMismatch.
  220. // TODO: detect not-last-snap error.
  221. // TODO: maybe loose the checking of match.
  222. // After ReadAll, the WAL will be ready for appending new records.
  223. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  224. w.mu.Lock()
  225. defer w.mu.Unlock()
  226. rec := &walpb.Record{}
  227. decoder := w.decoder
  228. var match bool
  229. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  230. switch rec.Type {
  231. case entryType:
  232. e := mustUnmarshalEntry(rec.Data)
  233. if e.Index > w.start.Index {
  234. ents = append(ents[:e.Index-w.start.Index-1], e)
  235. }
  236. w.enti = e.Index
  237. case stateType:
  238. state = mustUnmarshalState(rec.Data)
  239. case metadataType:
  240. if metadata != nil && !bytes.Equal(metadata, rec.Data) {
  241. state.Reset()
  242. return nil, state, nil, ErrMetadataConflict
  243. }
  244. metadata = rec.Data
  245. case crcType:
  246. crc := decoder.crc.Sum32()
  247. // current crc of decoder must match the crc of the record.
  248. // do no need to match 0 crc, since the decoder is a new one at this case.
  249. if crc != 0 && rec.Validate(crc) != nil {
  250. state.Reset()
  251. return nil, state, nil, ErrCRCMismatch
  252. }
  253. decoder.updateCRC(rec.Crc)
  254. case snapshotType:
  255. var snap walpb.Snapshot
  256. pbutil.MustUnmarshal(&snap, rec.Data)
  257. if snap.Index == w.start.Index {
  258. if snap.Term != w.start.Term {
  259. state.Reset()
  260. return nil, state, nil, ErrSnapshotMismatch
  261. }
  262. match = true
  263. }
  264. default:
  265. state.Reset()
  266. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  267. }
  268. }
  269. switch w.tail() {
  270. case nil:
  271. // We do not have to read out all entries in read mode.
  272. // The last record maybe a partial written one, so
  273. // ErrunexpectedEOF might be returned.
  274. if err != io.EOF && err != io.ErrUnexpectedEOF {
  275. state.Reset()
  276. return nil, state, nil, err
  277. }
  278. default:
  279. // We must read all of the entries if WAL is opened in write mode.
  280. if err != io.EOF {
  281. state.Reset()
  282. return nil, state, nil, err
  283. }
  284. // decodeRecord() will return io.EOF if it detects a zero record,
  285. // but this zero record may be followed by non-zero records from
  286. // a torn write. Overwriting some of these non-zero records, but
  287. // not all, will cause CRC errors on WAL open. Since the records
  288. // were never fully synced to disk in the first place, it's safe
  289. // to zero them out to avoid any CRC errors from new writes.
  290. if _, err = w.tail().Seek(w.decoder.lastOffset(), io.SeekStart); err != nil {
  291. return nil, state, nil, err
  292. }
  293. if err = fileutil.ZeroToEnd(w.tail().File); err != nil {
  294. return nil, state, nil, err
  295. }
  296. }
  297. err = nil
  298. if !match {
  299. err = ErrSnapshotNotFound
  300. }
  301. // close decoder, disable reading
  302. if w.readClose != nil {
  303. w.readClose()
  304. w.readClose = nil
  305. }
  306. w.start = walpb.Snapshot{}
  307. w.metadata = metadata
  308. if w.tail() != nil {
  309. // create encoder (chain crc with the decoder), enable appending
  310. w.encoder, err = newFileEncoder(w.tail().File, w.decoder.lastCRC())
  311. if err != nil {
  312. return
  313. }
  314. }
  315. w.decoder = nil
  316. return metadata, state, ents, err
  317. }
  318. // cut closes current file written and creates a new one ready to append.
  319. // cut first creates a temp wal file and writes necessary headers into it.
  320. // Then cut atomically rename temp wal file to a wal file.
  321. func (w *WAL) cut() error {
  322. // close old wal file; truncate to avoid wasting space if an early cut
  323. off, serr := w.tail().Seek(0, io.SeekCurrent)
  324. if serr != nil {
  325. return serr
  326. }
  327. if err := w.tail().Truncate(off); err != nil {
  328. return err
  329. }
  330. if err := w.sync(); err != nil {
  331. return err
  332. }
  333. fpath := filepath.Join(w.dir, walName(w.seq()+1, w.enti+1))
  334. // create a temp wal file with name sequence + 1, or truncate the existing one
  335. newTail, err := w.fp.Open()
  336. if err != nil {
  337. return err
  338. }
  339. // update writer and save the previous crc
  340. w.locks = append(w.locks, newTail)
  341. prevCrc := w.encoder.crc.Sum32()
  342. w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
  343. if err != nil {
  344. return err
  345. }
  346. if err = w.saveCrc(prevCrc); err != nil {
  347. return err
  348. }
  349. if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
  350. return err
  351. }
  352. if err = w.saveState(&w.state); err != nil {
  353. return err
  354. }
  355. // atomically move temp wal file to wal file
  356. if err = w.sync(); err != nil {
  357. return err
  358. }
  359. off, err = w.tail().Seek(0, io.SeekCurrent)
  360. if err != nil {
  361. return err
  362. }
  363. if err = os.Rename(newTail.Name(), fpath); err != nil {
  364. return err
  365. }
  366. if err = fileutil.Fsync(w.dirFile); err != nil {
  367. return err
  368. }
  369. newTail.Close()
  370. if newTail, err = fileutil.LockFile(fpath, os.O_WRONLY, fileutil.PrivateFileMode); err != nil {
  371. return err
  372. }
  373. if _, err = newTail.Seek(off, io.SeekStart); err != nil {
  374. return err
  375. }
  376. w.locks[len(w.locks)-1] = newTail
  377. prevCrc = w.encoder.crc.Sum32()
  378. w.encoder, err = newFileEncoder(w.tail().File, prevCrc)
  379. if err != nil {
  380. return err
  381. }
  382. plog.Infof("segmented wal file %v is created", fpath)
  383. return nil
  384. }
  385. func (w *WAL) sync() error {
  386. if w.encoder != nil {
  387. if err := w.encoder.flush(); err != nil {
  388. return err
  389. }
  390. }
  391. start := time.Now()
  392. err := fileutil.Fdatasync(w.tail().File)
  393. duration := time.Since(start)
  394. if duration > warnSyncDuration {
  395. plog.Warningf("sync duration of %v, expected less than %v", duration, warnSyncDuration)
  396. }
  397. syncDurations.Observe(duration.Seconds())
  398. return err
  399. }
  400. // ReleaseLockTo releases the locks, which has smaller index than the given index
  401. // except the largest one among them.
  402. // For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release
  403. // lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4.
  404. func (w *WAL) ReleaseLockTo(index uint64) error {
  405. w.mu.Lock()
  406. defer w.mu.Unlock()
  407. var smaller int
  408. found := false
  409. for i, l := range w.locks {
  410. _, lockIndex, err := parseWalName(filepath.Base(l.Name()))
  411. if err != nil {
  412. return err
  413. }
  414. if lockIndex >= index {
  415. smaller = i - 1
  416. found = true
  417. break
  418. }
  419. }
  420. // if no lock index is greater than the release index, we can
  421. // release lock up to the last one(excluding).
  422. if !found && len(w.locks) != 0 {
  423. smaller = len(w.locks) - 1
  424. }
  425. if smaller <= 0 {
  426. return nil
  427. }
  428. for i := 0; i < smaller; i++ {
  429. if w.locks[i] == nil {
  430. continue
  431. }
  432. w.locks[i].Close()
  433. }
  434. w.locks = w.locks[smaller:]
  435. return nil
  436. }
  437. func (w *WAL) Close() error {
  438. w.mu.Lock()
  439. defer w.mu.Unlock()
  440. if w.fp != nil {
  441. w.fp.Close()
  442. w.fp = nil
  443. }
  444. if w.tail() != nil {
  445. if err := w.sync(); err != nil {
  446. return err
  447. }
  448. }
  449. for _, l := range w.locks {
  450. if l == nil {
  451. continue
  452. }
  453. if err := l.Close(); err != nil {
  454. plog.Errorf("failed to unlock during closing wal: %s", err)
  455. }
  456. }
  457. return w.dirFile.Close()
  458. }
  459. func (w *WAL) saveEntry(e *raftpb.Entry) error {
  460. // TODO: add MustMarshalTo to reduce one allocation.
  461. b := pbutil.MustMarshal(e)
  462. rec := &walpb.Record{Type: entryType, Data: b}
  463. if err := w.encoder.encode(rec); err != nil {
  464. return err
  465. }
  466. w.enti = e.Index
  467. return nil
  468. }
  469. func (w *WAL) saveState(s *raftpb.HardState) error {
  470. if raft.IsEmptyHardState(*s) {
  471. return nil
  472. }
  473. w.state = *s
  474. b := pbutil.MustMarshal(s)
  475. rec := &walpb.Record{Type: stateType, Data: b}
  476. return w.encoder.encode(rec)
  477. }
  478. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  479. w.mu.Lock()
  480. defer w.mu.Unlock()
  481. // short cut, do not call sync
  482. if raft.IsEmptyHardState(st) && len(ents) == 0 {
  483. return nil
  484. }
  485. mustSync := raft.MustSync(st, w.state, len(ents))
  486. // TODO(xiangli): no more reference operator
  487. for i := range ents {
  488. if err := w.saveEntry(&ents[i]); err != nil {
  489. return err
  490. }
  491. }
  492. if err := w.saveState(&st); err != nil {
  493. return err
  494. }
  495. curOff, err := w.tail().Seek(0, io.SeekCurrent)
  496. if err != nil {
  497. return err
  498. }
  499. if curOff < SegmentSizeBytes {
  500. if mustSync {
  501. return w.sync()
  502. }
  503. return nil
  504. }
  505. return w.cut()
  506. }
  507. func (w *WAL) SaveSnapshot(e walpb.Snapshot) error {
  508. b := pbutil.MustMarshal(&e)
  509. w.mu.Lock()
  510. defer w.mu.Unlock()
  511. rec := &walpb.Record{Type: snapshotType, Data: b}
  512. if err := w.encoder.encode(rec); err != nil {
  513. return err
  514. }
  515. // update enti only when snapshot is ahead of last index
  516. if w.enti < e.Index {
  517. w.enti = e.Index
  518. }
  519. return w.sync()
  520. }
  521. func (w *WAL) saveCrc(prevCrc uint32) error {
  522. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  523. }
  524. func (w *WAL) tail() *fileutil.LockedFile {
  525. if len(w.locks) > 0 {
  526. return w.locks[len(w.locks)-1]
  527. }
  528. return nil
  529. }
  530. func (w *WAL) seq() uint64 {
  531. t := w.tail()
  532. if t == nil {
  533. return 0
  534. }
  535. seq, _, err := parseWalName(filepath.Base(t.Name()))
  536. if err != nil {
  537. plog.Fatalf("bad wal name %s (%v)", t.Name(), err)
  538. }
  539. return seq
  540. }
  541. func closeAll(rcs ...io.ReadCloser) error {
  542. for _, f := range rcs {
  543. if err := f.Close(); err != nil {
  544. return err
  545. }
  546. }
  547. return nil
  548. }