wal.go 15 KB

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