wal.go 14 KB

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