wal.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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/etcd221/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. )
  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 repersentation 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. err = l.Lock()
  90. if err != nil {
  91. return nil, err
  92. }
  93. w := &WAL{
  94. dir: dirpath,
  95. metadata: metadata,
  96. seq: 0,
  97. f: f,
  98. encoder: newEncoder(f, 0),
  99. }
  100. w.locks = append(w.locks, l)
  101. if err := w.saveCrc(0); err != nil {
  102. return nil, err
  103. }
  104. if err := w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil {
  105. return nil, err
  106. }
  107. if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil {
  108. return nil, err
  109. }
  110. return w, nil
  111. }
  112. // Open opens the WAL at the given snap.
  113. // The snap SHOULD have been previously saved to the WAL, or the following
  114. // ReadAll will fail.
  115. // The returned WAL is ready to read and the first record will be the one after
  116. // the given snap. The WAL cannot be appended to before reading out all of its
  117. // previous records.
  118. func Open(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  119. return openAtIndex(dirpath, snap, true)
  120. }
  121. // OpenForRead only opens the wal files for read.
  122. // Write on a read only wal panics.
  123. func OpenForRead(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  124. return openAtIndex(dirpath, snap, false)
  125. }
  126. func openAtIndex(dirpath string, snap walpb.Snapshot, write bool) (*WAL, error) {
  127. names, err := fileutil.ReadDir(dirpath)
  128. if err != nil {
  129. return nil, err
  130. }
  131. names = checkWalNames(names)
  132. if len(names) == 0 {
  133. return nil, ErrFileNotFound
  134. }
  135. nameIndex, ok := searchIndex(names, snap.Index)
  136. if !ok || !isValidSeq(names[nameIndex:]) {
  137. return nil, ErrFileNotFound
  138. }
  139. // open the wal files for reading
  140. rcs := make([]io.ReadCloser, 0)
  141. ls := make([]fileutil.Lock, 0)
  142. for _, name := range names[nameIndex:] {
  143. f, err := os.Open(path.Join(dirpath, name))
  144. if err != nil {
  145. return nil, err
  146. }
  147. l, err := fileutil.NewLock(f.Name())
  148. if err != nil {
  149. return nil, err
  150. }
  151. err = l.TryLock()
  152. if err != nil {
  153. if write {
  154. return nil, err
  155. }
  156. }
  157. rcs = append(rcs, f)
  158. ls = append(ls, l)
  159. }
  160. rc := MultiReadCloser(rcs...)
  161. // create a WAL ready for reading
  162. w := &WAL{
  163. dir: dirpath,
  164. start: snap,
  165. decoder: newDecoder(rc),
  166. locks: ls,
  167. }
  168. if write {
  169. // open the lastest wal file for appending
  170. seq, _, err := parseWalName(names[len(names)-1])
  171. if err != nil {
  172. rc.Close()
  173. return nil, err
  174. }
  175. last := path.Join(dirpath, names[len(names)-1])
  176. f, err := os.OpenFile(last, os.O_WRONLY|os.O_APPEND, 0)
  177. if err != nil {
  178. rc.Close()
  179. return nil, err
  180. }
  181. err = fileutil.Preallocate(f, segmentSizeBytes)
  182. if err != nil {
  183. rc.Close()
  184. plog.Errorf("failed to allocate space when creating new wal file (%v)", err)
  185. return nil, err
  186. }
  187. w.f = f
  188. w.seq = seq
  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.f {
  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. w.decoder.close()
  270. w.start = walpb.Snapshot{}
  271. w.metadata = metadata
  272. if w.f != nil {
  273. // create encoder (chain crc with the decoder), enable appending
  274. w.encoder = newEncoder(w.f, w.decoder.lastCRC())
  275. w.decoder = nil
  276. lastIndexSaved.Set(float64(w.enti))
  277. }
  278. return metadata, state, ents, err
  279. }
  280. // cut closes current file written and creates a new one ready to append.
  281. // cut first creates a temp wal file and writes necessary headers into it.
  282. // Then cut atomtically rename temp wal file to a wal file.
  283. func (w *WAL) cut() error {
  284. // close old wal file
  285. if err := w.sync(); err != nil {
  286. return err
  287. }
  288. if err := w.f.Close(); err != nil {
  289. return err
  290. }
  291. fpath := path.Join(w.dir, walName(w.seq+1, w.enti+1))
  292. ftpath := fpath + ".tmp"
  293. // create a temp wal file with name sequence + 1, or tuncate the existing one
  294. ft, err := os.OpenFile(ftpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_TRUNC, 0600)
  295. if err != nil {
  296. return err
  297. }
  298. // update writer and save the previous crc
  299. w.f = ft
  300. prevCrc := w.encoder.crc.Sum32()
  301. w.encoder = newEncoder(w.f, prevCrc)
  302. if err := w.saveCrc(prevCrc); err != nil {
  303. return err
  304. }
  305. if err := w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
  306. return err
  307. }
  308. if err := w.saveState(&w.state); err != nil {
  309. return err
  310. }
  311. // close temp wal file
  312. if err := w.sync(); err != nil {
  313. return err
  314. }
  315. if err := w.f.Close(); err != nil {
  316. return err
  317. }
  318. // atomically move temp wal file to wal file
  319. if err := os.Rename(ftpath, fpath); err != nil {
  320. return err
  321. }
  322. // open the wal file and update writer again
  323. f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND, 0600)
  324. if err != nil {
  325. return err
  326. }
  327. err = fileutil.Preallocate(f, segmentSizeBytes)
  328. if err != nil {
  329. plog.Errorf("failed to allocate space when creating new wal file (%v)", err)
  330. return err
  331. }
  332. w.f = f
  333. prevCrc = w.encoder.crc.Sum32()
  334. w.encoder = newEncoder(w.f, prevCrc)
  335. // lock the new wal file
  336. l, err := fileutil.NewLock(f.Name())
  337. if err != nil {
  338. return err
  339. }
  340. err = l.Lock()
  341. if err != nil {
  342. return err
  343. }
  344. w.locks = append(w.locks, l)
  345. // increase the wal seq
  346. w.seq++
  347. plog.Infof("segmented wal file %v is created", fpath)
  348. return nil
  349. }
  350. func (w *WAL) sync() error {
  351. if w.encoder != nil {
  352. if err := w.encoder.flush(); err != nil {
  353. return err
  354. }
  355. }
  356. start := time.Now()
  357. err := w.f.Sync()
  358. syncDurations.Observe(float64(time.Since(start).Nanoseconds() / int64(time.Microsecond)))
  359. return err
  360. }
  361. // ReleaseLockTo releases the locks, which has smaller index than the given index
  362. // except the largest one among them.
  363. // For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release
  364. // lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4.
  365. func (w *WAL) ReleaseLockTo(index uint64) error {
  366. w.mu.Lock()
  367. defer w.mu.Unlock()
  368. var smaller int
  369. found := false
  370. for i, l := range w.locks {
  371. _, lockIndex, err := parseWalName(path.Base(l.Name()))
  372. if err != nil {
  373. return err
  374. }
  375. if lockIndex >= index {
  376. smaller = i - 1
  377. found = true
  378. break
  379. }
  380. }
  381. // if no lock index is greater than the release index, we can
  382. // release lock upto the last one(excluding).
  383. if !found && len(w.locks) != 0 {
  384. smaller = len(w.locks) - 1
  385. }
  386. if smaller <= 0 {
  387. return nil
  388. }
  389. for i := 0; i < smaller; i++ {
  390. w.locks[i].Unlock()
  391. w.locks[i].Destroy()
  392. }
  393. w.locks = w.locks[smaller:]
  394. return nil
  395. }
  396. func (w *WAL) Close() error {
  397. w.mu.Lock()
  398. defer w.mu.Unlock()
  399. if w.f != nil {
  400. if err := w.sync(); err != nil {
  401. return err
  402. }
  403. if err := w.f.Close(); err != nil {
  404. return err
  405. }
  406. }
  407. for _, l := range w.locks {
  408. err := l.Unlock()
  409. if err != nil {
  410. plog.Errorf("failed to unlock during closing wal: %s", err)
  411. }
  412. err = l.Destroy()
  413. if err != nil {
  414. plog.Errorf("failed to destroy lock during closing wal: %s", err)
  415. }
  416. }
  417. return nil
  418. }
  419. func (w *WAL) saveEntry(e *raftpb.Entry) error {
  420. // TODO: add MustMarshalTo to reduce one allocation.
  421. b := pbutil.MustMarshal(e)
  422. rec := &walpb.Record{Type: entryType, Data: b}
  423. if err := w.encoder.encode(rec); err != nil {
  424. return err
  425. }
  426. w.enti = e.Index
  427. lastIndexSaved.Set(float64(w.enti))
  428. return nil
  429. }
  430. func (w *WAL) saveState(s *raftpb.HardState) error {
  431. if raft.IsEmptyHardState(*s) {
  432. return nil
  433. }
  434. w.state = *s
  435. b := pbutil.MustMarshal(s)
  436. rec := &walpb.Record{Type: stateType, Data: b}
  437. return w.encoder.encode(rec)
  438. }
  439. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  440. w.mu.Lock()
  441. defer w.mu.Unlock()
  442. // short cut, do not call sync
  443. if raft.IsEmptyHardState(st) && len(ents) == 0 {
  444. return nil
  445. }
  446. // TODO(xiangli): no more reference operator
  447. for i := range ents {
  448. if err := w.saveEntry(&ents[i]); err != nil {
  449. return err
  450. }
  451. }
  452. if err := w.saveState(&st); err != nil {
  453. return err
  454. }
  455. fstat, err := w.f.Stat()
  456. if err != nil {
  457. return err
  458. }
  459. if fstat.Size() < segmentSizeBytes {
  460. return w.sync()
  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. }