wal.go 14 KB

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