wal.go 15 KB

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