wal.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. mu sync.Mutex
  65. f *os.File // underlay file opened for appending, sync
  66. seq uint64 // sequence of the wal file currently used for writes
  67. enti uint64 // index of the last entry saved to the wal
  68. encoder *encoder // encoder to encode records
  69. locks []fileutil.Lock // the file locks the WAL is holding (the name is increasing)
  70. }
  71. // Create creates a WAL ready for appending records. The given metadata is
  72. // recorded at the head of each WAL file, and can be retrieved with ReadAll.
  73. func Create(dirpath string, metadata []byte) (*WAL, error) {
  74. if Exist(dirpath) {
  75. return nil, os.ErrExist
  76. }
  77. if err := os.MkdirAll(dirpath, privateDirMode); err != nil {
  78. return nil, err
  79. }
  80. p := path.Join(dirpath, walName(0, 0))
  81. f, err := os.OpenFile(p, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  82. if err != nil {
  83. return nil, err
  84. }
  85. l, err := fileutil.NewLock(f.Name())
  86. if err != nil {
  87. return nil, err
  88. }
  89. if err = l.Lock(); err != nil {
  90. return nil, err
  91. }
  92. w := &WAL{
  93. dir: dirpath,
  94. metadata: metadata,
  95. seq: 0,
  96. f: f,
  97. encoder: newEncoder(f, 0),
  98. }
  99. w.locks = append(w.locks, l)
  100. if err := w.saveCrc(0); err != nil {
  101. return nil, err
  102. }
  103. if err := w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil {
  104. return nil, err
  105. }
  106. if err := w.SaveSnapshot(walpb.Snapshot{}); err != nil {
  107. return nil, err
  108. }
  109. return w, nil
  110. }
  111. // Open opens the WAL at the given snap.
  112. // The snap SHOULD have been previously saved to the WAL, or the following
  113. // ReadAll will fail.
  114. // The returned WAL is ready to read and the first record will be the one after
  115. // the given snap. The WAL cannot be appended to before reading out all of its
  116. // previous records.
  117. func Open(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  118. return openAtIndex(dirpath, snap, true)
  119. }
  120. // OpenForRead only opens the wal files for read.
  121. // Write on a read only wal panics.
  122. func OpenForRead(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  123. return openAtIndex(dirpath, snap, false)
  124. }
  125. func openAtIndex(dirpath string, snap walpb.Snapshot, write bool) (*WAL, error) {
  126. names, err := fileutil.ReadDir(dirpath)
  127. if err != nil {
  128. return nil, err
  129. }
  130. names = checkWalNames(names)
  131. if len(names) == 0 {
  132. return nil, ErrFileNotFound
  133. }
  134. nameIndex, ok := searchIndex(names, snap.Index)
  135. if !ok || !isValidSeq(names[nameIndex:]) {
  136. return nil, ErrFileNotFound
  137. }
  138. // open the wal files for reading
  139. rcs := make([]io.ReadCloser, 0)
  140. ls := make([]fileutil.Lock, 0)
  141. for _, name := range names[nameIndex:] {
  142. f, err := os.Open(path.Join(dirpath, name))
  143. if err != nil {
  144. return nil, err
  145. }
  146. l, err := fileutil.NewLock(f.Name())
  147. if err != nil {
  148. return nil, err
  149. }
  150. err = l.TryLock()
  151. if err != nil {
  152. if write {
  153. return nil, err
  154. }
  155. }
  156. rcs = append(rcs, f)
  157. ls = append(ls, l)
  158. }
  159. rc := MultiReadCloser(rcs...)
  160. // create a WAL ready for reading
  161. w := &WAL{
  162. dir: dirpath,
  163. start: snap,
  164. decoder: newDecoder(rc),
  165. locks: ls,
  166. }
  167. if write {
  168. // open the last wal file for appending
  169. seq, _, err := parseWalName(names[len(names)-1])
  170. if err != nil {
  171. rc.Close()
  172. return nil, err
  173. }
  174. last := path.Join(dirpath, names[len(names)-1])
  175. f, err := os.OpenFile(last, os.O_WRONLY|os.O_APPEND, 0)
  176. if err != nil {
  177. rc.Close()
  178. return nil, err
  179. }
  180. err = fileutil.Preallocate(f, segmentSizeBytes)
  181. if err != nil {
  182. rc.Close()
  183. plog.Errorf("failed to allocate space when creating new wal file (%v)", err)
  184. return nil, err
  185. }
  186. w.f = f
  187. w.seq = seq
  188. }
  189. return w, nil
  190. }
  191. // ReadAll reads out records of the current WAL.
  192. // If opened in write mode, it must read out all records until EOF. Or an error
  193. // will be returned.
  194. // If opened in read mode, it will try to read all records if possible.
  195. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
  196. // If loaded snap doesn't match with the expected one, it will return
  197. // all the records and error ErrSnapshotMismatch.
  198. // TODO: detect not-last-snap error.
  199. // TODO: maybe loose the checking of match.
  200. // After ReadAll, the WAL will be ready for appending new records.
  201. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  202. w.mu.Lock()
  203. defer w.mu.Unlock()
  204. rec := &walpb.Record{}
  205. decoder := w.decoder
  206. var match bool
  207. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  208. switch rec.Type {
  209. case entryType:
  210. e := mustUnmarshalEntry(rec.Data)
  211. if e.Index > w.start.Index {
  212. ents = append(ents[:e.Index-w.start.Index-1], e)
  213. }
  214. w.enti = e.Index
  215. case stateType:
  216. state = mustUnmarshalState(rec.Data)
  217. case metadataType:
  218. if metadata != nil && !reflect.DeepEqual(metadata, rec.Data) {
  219. state.Reset()
  220. return nil, state, nil, ErrMetadataConflict
  221. }
  222. metadata = rec.Data
  223. case crcType:
  224. crc := decoder.crc.Sum32()
  225. // current crc of decoder must match the crc of the record.
  226. // do no need to match 0 crc, since the decoder is a new one at this case.
  227. if crc != 0 && rec.Validate(crc) != nil {
  228. state.Reset()
  229. return nil, state, nil, ErrCRCMismatch
  230. }
  231. decoder.updateCRC(rec.Crc)
  232. case snapshotType:
  233. var snap walpb.Snapshot
  234. pbutil.MustUnmarshal(&snap, rec.Data)
  235. if snap.Index == w.start.Index {
  236. if snap.Term != w.start.Term {
  237. state.Reset()
  238. return nil, state, nil, ErrSnapshotMismatch
  239. }
  240. match = true
  241. }
  242. default:
  243. state.Reset()
  244. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  245. }
  246. }
  247. switch w.f {
  248. case nil:
  249. // We do not have to read out all entries in read mode.
  250. // The last record maybe a partial written one, so
  251. // ErrunexpectedEOF might be returned.
  252. if err != io.EOF && err != io.ErrUnexpectedEOF {
  253. state.Reset()
  254. return nil, state, nil, err
  255. }
  256. default:
  257. // We must read all of the entries if WAL is opened in write mode.
  258. if err != io.EOF {
  259. state.Reset()
  260. return nil, state, nil, err
  261. }
  262. }
  263. err = nil
  264. if !match {
  265. err = ErrSnapshotNotFound
  266. }
  267. // close decoder, disable reading
  268. w.decoder.close()
  269. w.start = walpb.Snapshot{}
  270. w.metadata = metadata
  271. if w.f != nil {
  272. // create encoder (chain crc with the decoder), enable appending
  273. w.encoder = newEncoder(w.f, w.decoder.lastCRC())
  274. w.decoder = nil
  275. lastIndexSaved.Set(float64(w.enti))
  276. }
  277. return metadata, state, ents, err
  278. }
  279. // cut closes current file written and creates a new one ready to append.
  280. // cut first creates a temp wal file and writes necessary headers into it.
  281. // Then cut atomically rename temp wal file to a wal file.
  282. func (w *WAL) cut() error {
  283. // close old wal file
  284. if err := w.sync(); err != nil {
  285. return err
  286. }
  287. if err := w.f.Close(); err != nil {
  288. return err
  289. }
  290. fpath := path.Join(w.dir, walName(w.seq+1, w.enti+1))
  291. ftpath := fpath + ".tmp"
  292. // create a temp wal file with name sequence + 1, or truncate the existing one
  293. ft, err := os.OpenFile(ftpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_TRUNC, 0600)
  294. if err != nil {
  295. return err
  296. }
  297. // update writer and save the previous crc
  298. w.f = ft
  299. prevCrc := w.encoder.crc.Sum32()
  300. w.encoder = newEncoder(w.f, prevCrc)
  301. if err = w.saveCrc(prevCrc); err != nil {
  302. return err
  303. }
  304. if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
  305. return err
  306. }
  307. if err = w.saveState(&w.state); err != nil {
  308. return err
  309. }
  310. // close temp wal file
  311. if err = w.sync(); err != nil {
  312. return err
  313. }
  314. if err = w.f.Close(); err != nil {
  315. return err
  316. }
  317. // atomically move temp wal file to wal file
  318. if err = os.Rename(ftpath, fpath); err != nil {
  319. return err
  320. }
  321. // open the wal file and update writer again
  322. f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND, 0600)
  323. if err != nil {
  324. return err
  325. }
  326. if err = fileutil.Preallocate(f, segmentSizeBytes); err != nil {
  327. plog.Errorf("failed to allocate space when creating new wal file (%v)", err)
  328. return err
  329. }
  330. w.f = f
  331. prevCrc = w.encoder.crc.Sum32()
  332. w.encoder = newEncoder(w.f, prevCrc)
  333. // lock the new wal file
  334. l, err := fileutil.NewLock(f.Name())
  335. if err != nil {
  336. return err
  337. }
  338. if err := l.Lock(); err != nil {
  339. return err
  340. }
  341. w.locks = append(w.locks, l)
  342. // increase the wal seq
  343. w.seq++
  344. plog.Infof("segmented wal file %v is created", fpath)
  345. return nil
  346. }
  347. func (w *WAL) sync() error {
  348. if w.encoder != nil {
  349. if err := w.encoder.flush(); err != nil {
  350. return err
  351. }
  352. }
  353. start := time.Now()
  354. err := fileutil.Fdatasync(w.f)
  355. syncDurations.Observe(float64(time.Since(start)) / float64(time.Second))
  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. w.locks[i].Unlock()
  388. w.locks[i].Destroy()
  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.f != nil {
  397. if err := w.sync(); err != nil {
  398. return err
  399. }
  400. if err := w.f.Close(); err != nil {
  401. return err
  402. }
  403. }
  404. for _, l := range w.locks {
  405. err := l.Unlock()
  406. if err != nil {
  407. plog.Errorf("failed to unlock during closing wal: %s", err)
  408. }
  409. err = l.Destroy()
  410. if err != nil {
  411. plog.Errorf("failed to destroy lock during closing wal: %s", err)
  412. }
  413. }
  414. return nil
  415. }
  416. func (w *WAL) saveEntry(e *raftpb.Entry) error {
  417. // TODO: add MustMarshalTo to reduce one allocation.
  418. b := pbutil.MustMarshal(e)
  419. rec := &walpb.Record{Type: entryType, Data: b}
  420. if err := w.encoder.encode(rec); err != nil {
  421. return err
  422. }
  423. w.enti = e.Index
  424. lastIndexSaved.Set(float64(w.enti))
  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. fstat, err := w.f.Stat()
  454. if err != nil {
  455. return err
  456. }
  457. if fstat.Size() < 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. lastIndexSaved.Set(float64(w.enti))
  479. return w.sync()
  480. }
  481. func (w *WAL) saveCrc(prevCrc uint32) error {
  482. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  483. }
  484. func mustSync(st, prevst raftpb.HardState, entsnum int) bool {
  485. // Persistent state on all servers:
  486. // (Updated on stable storage before responding to RPCs)
  487. // currentTerm
  488. // votedFor
  489. // log entries[]
  490. if entsnum != 0 || st.Vote != prevst.Vote || st.Term != prevst.Term {
  491. return true
  492. }
  493. return false
  494. }