wal.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. "log"
  21. "os"
  22. "path"
  23. "reflect"
  24. "sync"
  25. "time"
  26. "github.com/coreos/etcd/pkg/fileutil"
  27. "github.com/coreos/etcd/pkg/pbutil"
  28. "github.com/coreos/etcd/raft"
  29. "github.com/coreos/etcd/raft/raftpb"
  30. "github.com/coreos/etcd/wal/walpb"
  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. 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 repersentation 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. err = l.Lock()
  89. if 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. // OpenNotInUse only opens the wal files that are not in use.
  121. // Other than that, it is similar to Open.
  122. func OpenNotInUse(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  123. return openAtIndex(dirpath, snap, false)
  124. }
  125. func openAtIndex(dirpath string, snap walpb.Snapshot, all 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 all {
  153. return nil, err
  154. } else {
  155. log.Printf("wal: opened all the files until %s, since it is still in use by an etcd server", name)
  156. break
  157. }
  158. }
  159. rcs = append(rcs, f)
  160. ls = append(ls, l)
  161. }
  162. rc := MultiReadCloser(rcs...)
  163. // open the lastest wal file for appending
  164. seq, _, err := parseWalName(names[len(names)-1])
  165. if err != nil {
  166. rc.Close()
  167. return nil, err
  168. }
  169. last := path.Join(dirpath, names[len(names)-1])
  170. f, err := os.OpenFile(last, os.O_WRONLY|os.O_APPEND, 0)
  171. if err != nil {
  172. rc.Close()
  173. return nil, err
  174. }
  175. // create a WAL ready for reading
  176. w := &WAL{
  177. dir: dirpath,
  178. start: snap,
  179. decoder: newDecoder(rc),
  180. f: f,
  181. seq: seq,
  182. locks: ls,
  183. }
  184. return w, nil
  185. }
  186. // ReadAll reads out all records of the current WAL.
  187. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
  188. // If loaded snap doesn't match with the expected one, it will return
  189. // all the records and error ErrSnapshotMismatch.
  190. // TODO: detect not-last-snap error.
  191. // TODO: maybe loose the checking of match.
  192. // After ReadAll, the WAL will be ready for appending new records.
  193. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  194. w.mu.Lock()
  195. defer w.mu.Unlock()
  196. rec := &walpb.Record{}
  197. decoder := w.decoder
  198. var match bool
  199. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  200. switch rec.Type {
  201. case entryType:
  202. e := mustUnmarshalEntry(rec.Data)
  203. if e.Index > w.start.Index {
  204. ents = append(ents[:e.Index-w.start.Index-1], e)
  205. }
  206. w.enti = e.Index
  207. case stateType:
  208. state = mustUnmarshalState(rec.Data)
  209. case metadataType:
  210. if metadata != nil && !reflect.DeepEqual(metadata, rec.Data) {
  211. state.Reset()
  212. return nil, state, nil, ErrMetadataConflict
  213. }
  214. metadata = rec.Data
  215. case crcType:
  216. crc := decoder.crc.Sum32()
  217. // current crc of decoder must match the crc of the record.
  218. // do no need to match 0 crc, since the decoder is a new one at this case.
  219. if crc != 0 && rec.Validate(crc) != nil {
  220. state.Reset()
  221. return nil, state, nil, ErrCRCMismatch
  222. }
  223. decoder.updateCRC(rec.Crc)
  224. case snapshotType:
  225. var snap walpb.Snapshot
  226. pbutil.MustUnmarshal(&snap, rec.Data)
  227. if snap.Index == w.start.Index {
  228. if snap.Term != w.start.Term {
  229. state.Reset()
  230. return nil, state, nil, ErrSnapshotMismatch
  231. }
  232. match = true
  233. }
  234. default:
  235. state.Reset()
  236. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  237. }
  238. }
  239. if err != io.EOF {
  240. state.Reset()
  241. return nil, state, nil, err
  242. }
  243. err = nil
  244. if !match {
  245. err = ErrSnapshotNotFound
  246. }
  247. // close decoder, disable reading
  248. w.decoder.close()
  249. w.start = walpb.Snapshot{}
  250. w.metadata = metadata
  251. // create encoder (chain crc with the decoder), enable appending
  252. w.encoder = newEncoder(w.f, w.decoder.lastCRC())
  253. w.decoder = nil
  254. lastIndexSaved.Set(float64(w.enti))
  255. return metadata, state, ents, err
  256. }
  257. // cut closes current file written and creates a new one ready to append.
  258. // cut first creates a temp wal file and writes necessary headers into it.
  259. // Then cut atomtically rename temp wal file to a wal file.
  260. func (w *WAL) cut() error {
  261. // close old wal file
  262. if err := w.sync(); err != nil {
  263. return err
  264. }
  265. if err := w.f.Close(); err != nil {
  266. return err
  267. }
  268. fpath := path.Join(w.dir, walName(w.seq+1, w.enti+1))
  269. ftpath := fpath + ".tmp"
  270. // create a temp wal file with name sequence + 1, or tuncate the existing one
  271. ft, err := os.OpenFile(ftpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_TRUNC, 0600)
  272. if err != nil {
  273. return err
  274. }
  275. // update writer and save the previous crc
  276. w.f = ft
  277. prevCrc := w.encoder.crc.Sum32()
  278. w.encoder = newEncoder(w.f, prevCrc)
  279. if err := w.saveCrc(prevCrc); err != nil {
  280. return err
  281. }
  282. if err := w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
  283. return err
  284. }
  285. if err := w.saveState(&w.state); err != nil {
  286. return err
  287. }
  288. // close temp wal file
  289. if err := w.sync(); err != nil {
  290. return err
  291. }
  292. if err := w.f.Close(); err != nil {
  293. return err
  294. }
  295. // atomically move temp wal file to wal file
  296. if err := os.Rename(ftpath, fpath); err != nil {
  297. return err
  298. }
  299. // open the wal file and update writer again
  300. f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND, 0600)
  301. if err != nil {
  302. return err
  303. }
  304. w.f = f
  305. prevCrc = w.encoder.crc.Sum32()
  306. w.encoder = newEncoder(w.f, prevCrc)
  307. // lock the new wal file
  308. l, err := fileutil.NewLock(f.Name())
  309. if err != nil {
  310. return err
  311. }
  312. err = l.Lock()
  313. if err != nil {
  314. return err
  315. }
  316. w.locks = append(w.locks, l)
  317. // increase the wal seq
  318. w.seq++
  319. log.Printf("wal: segmented wal file %v is created", fpath)
  320. return nil
  321. }
  322. func (w *WAL) sync() error {
  323. if w.encoder != nil {
  324. if err := w.encoder.flush(); err != nil {
  325. return err
  326. }
  327. }
  328. start := time.Now()
  329. err := w.f.Sync()
  330. syncDurations.Observe(float64(time.Since(start).Nanoseconds() / int64(time.Microsecond)))
  331. return err
  332. }
  333. // ReleaseLockTo releases the locks, which has smaller index than the given index
  334. // except the largest one among them.
  335. // For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release
  336. // lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4.
  337. func (w *WAL) ReleaseLockTo(index uint64) error {
  338. w.mu.Lock()
  339. defer w.mu.Unlock()
  340. var smaller int
  341. found := false
  342. for i, l := range w.locks {
  343. _, lockIndex, err := parseWalName(path.Base(l.Name()))
  344. if err != nil {
  345. return err
  346. }
  347. if lockIndex >= index {
  348. smaller = i - 1
  349. found = true
  350. break
  351. }
  352. }
  353. // if no lock index is greater than the release index, we can
  354. // release lock upto the last one(excluding).
  355. if !found && len(w.locks) != 0 {
  356. smaller = len(w.locks) - 1
  357. }
  358. if smaller <= 0 {
  359. return nil
  360. }
  361. for i := 0; i < smaller; i++ {
  362. w.locks[i].Unlock()
  363. w.locks[i].Destroy()
  364. }
  365. w.locks = w.locks[smaller:]
  366. return nil
  367. }
  368. func (w *WAL) Close() error {
  369. w.mu.Lock()
  370. defer w.mu.Unlock()
  371. if w.f != nil {
  372. if err := w.sync(); err != nil {
  373. return err
  374. }
  375. if err := w.f.Close(); err != nil {
  376. return err
  377. }
  378. }
  379. for _, l := range w.locks {
  380. // TODO: log the error
  381. l.Unlock()
  382. l.Destroy()
  383. }
  384. return nil
  385. }
  386. func (w *WAL) saveEntry(e *raftpb.Entry) error {
  387. // TODO: add MustMarshalTo to reduce one allocation.
  388. b := pbutil.MustMarshal(e)
  389. rec := &walpb.Record{Type: entryType, Data: b}
  390. if err := w.encoder.encode(rec); err != nil {
  391. return err
  392. }
  393. w.enti = e.Index
  394. lastIndexSaved.Set(float64(w.enti))
  395. return nil
  396. }
  397. func (w *WAL) saveState(s *raftpb.HardState) error {
  398. if raft.IsEmptyHardState(*s) {
  399. return nil
  400. }
  401. w.state = *s
  402. b := pbutil.MustMarshal(s)
  403. rec := &walpb.Record{Type: stateType, Data: b}
  404. return w.encoder.encode(rec)
  405. }
  406. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  407. w.mu.Lock()
  408. defer w.mu.Unlock()
  409. // short cut, do not call sync
  410. if raft.IsEmptyHardState(st) && len(ents) == 0 {
  411. return nil
  412. }
  413. // TODO(xiangli): no more reference operator
  414. for i := range ents {
  415. if err := w.saveEntry(&ents[i]); err != nil {
  416. return err
  417. }
  418. }
  419. if err := w.saveState(&st); err != nil {
  420. return err
  421. }
  422. fstat, err := w.f.Stat()
  423. if err != nil {
  424. return err
  425. }
  426. if fstat.Size() < segmentSizeBytes {
  427. return w.sync()
  428. }
  429. // TODO: add a test for this code path when refactoring the tests
  430. return w.cut()
  431. }
  432. func (w *WAL) SaveSnapshot(e walpb.Snapshot) error {
  433. w.mu.Lock()
  434. defer w.mu.Unlock()
  435. b := pbutil.MustMarshal(&e)
  436. rec := &walpb.Record{Type: snapshotType, Data: b}
  437. if err := w.encoder.encode(rec); err != nil {
  438. return err
  439. }
  440. // update enti only when snapshot is ahead of last index
  441. if w.enti < e.Index {
  442. w.enti = e.Index
  443. }
  444. lastIndexSaved.Set(float64(w.enti))
  445. return w.sync()
  446. }
  447. func (w *WAL) saveCrc(prevCrc uint32) error {
  448. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  449. }