wal.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. "github.com/coreos/etcd/pkg/fileutil"
  25. "github.com/coreos/etcd/pkg/pbutil"
  26. "github.com/coreos/etcd/raft"
  27. "github.com/coreos/etcd/raft/raftpb"
  28. "github.com/coreos/etcd/wal/walpb"
  29. )
  30. const (
  31. metadataType int64 = iota + 1
  32. entryType
  33. stateType
  34. crcType
  35. snapshotType
  36. // the owner can make/remove files inside the directory
  37. privateDirMode = 0700
  38. )
  39. var (
  40. ErrMetadataConflict = errors.New("wal: conflicting metadata found")
  41. ErrFileNotFound = errors.New("wal: file not found")
  42. ErrCRCMismatch = errors.New("wal: crc mismatch")
  43. ErrSnapshotMismatch = errors.New("wal: snapshot mismatch")
  44. ErrSnapshotNotFound = errors.New("wal: snapshot not found")
  45. crcTable = crc32.MakeTable(crc32.Castagnoli)
  46. )
  47. // WAL is a logical repersentation of the stable storage.
  48. // WAL is either in read mode or append mode but not both.
  49. // A newly created WAL is in append mode, and ready for appending records.
  50. // A just opened WAL is in read mode, and ready for reading records.
  51. // The WAL will be ready for appending after reading out all the previous records.
  52. type WAL struct {
  53. dir string // the living directory of the underlay files
  54. metadata []byte // metadata recorded at the head of each WAL
  55. state raftpb.HardState // hardstate recorded at the head of WAL
  56. start walpb.Snapshot // snapshot to start reading
  57. decoder *decoder // decoder to decode records
  58. f *os.File // underlay file opened for appending, sync
  59. seq uint64 // sequence of the wal file currently used for writes
  60. enti uint64 // index of the last entry saved to the wal
  61. encoder *encoder // encoder to encode records
  62. locks []fileutil.Lock // the file locks the WAL is holding (the name is increasing)
  63. }
  64. // Create creates a WAL ready for appending records. The given metadata is
  65. // recorded at the head of each WAL file, and can be retrieved with ReadAll.
  66. func Create(dirpath string, metadata []byte) (*WAL, error) {
  67. if Exist(dirpath) {
  68. return nil, os.ErrExist
  69. }
  70. if err := os.MkdirAll(dirpath, privateDirMode); err != nil {
  71. return nil, err
  72. }
  73. p := path.Join(dirpath, walName(0, 0))
  74. f, err := os.OpenFile(p, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
  75. if err != nil {
  76. return nil, err
  77. }
  78. l, err := fileutil.NewLock(f.Name())
  79. if err != nil {
  80. return nil, err
  81. }
  82. err = l.Lock()
  83. if err != nil {
  84. return nil, err
  85. }
  86. w := &WAL{
  87. dir: dirpath,
  88. metadata: metadata,
  89. seq: 0,
  90. f: f,
  91. encoder: newEncoder(f, 0),
  92. }
  93. w.locks = append(w.locks, l)
  94. if err := w.saveCrc(0); err != nil {
  95. return nil, err
  96. }
  97. if err := w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil {
  98. return nil, err
  99. }
  100. if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil {
  101. return nil, err
  102. }
  103. return w, nil
  104. }
  105. // Open opens the WAL at the given snap.
  106. // The snap SHOULD have been previously saved to the WAL, or the following
  107. // ReadAll will fail.
  108. // The returned WAL is ready to read and the first record will be the one after
  109. // the given snap. The WAL cannot be appended to before reading out all of its
  110. // previous records.
  111. func Open(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  112. return openAtIndex(dirpath, snap, true)
  113. }
  114. // OpenNotInUse only opens the wal files that are not in use.
  115. // Other than that, it is similar to Open.
  116. func OpenNotInUse(dirpath string, snap walpb.Snapshot) (*WAL, error) {
  117. return openAtIndex(dirpath, snap, false)
  118. }
  119. func openAtIndex(dirpath string, snap walpb.Snapshot, all bool) (*WAL, error) {
  120. names, err := fileutil.ReadDir(dirpath)
  121. if err != nil {
  122. return nil, err
  123. }
  124. names = checkWalNames(names)
  125. if len(names) == 0 {
  126. return nil, ErrFileNotFound
  127. }
  128. nameIndex, ok := searchIndex(names, snap.Index)
  129. if !ok || !isValidSeq(names[nameIndex:]) {
  130. return nil, ErrFileNotFound
  131. }
  132. // open the wal files for reading
  133. rcs := make([]io.ReadCloser, 0)
  134. ls := make([]fileutil.Lock, 0)
  135. for _, name := range names[nameIndex:] {
  136. f, err := os.Open(path.Join(dirpath, name))
  137. if err != nil {
  138. return nil, err
  139. }
  140. l, err := fileutil.NewLock(f.Name())
  141. if err != nil {
  142. return nil, err
  143. }
  144. err = l.TryLock()
  145. if err != nil {
  146. if all {
  147. return nil, err
  148. } else {
  149. log.Printf("wal: opened all the files until %s, since it is still in use by an etcd server", name)
  150. break
  151. }
  152. }
  153. rcs = append(rcs, f)
  154. ls = append(ls, l)
  155. }
  156. rc := MultiReadCloser(rcs...)
  157. // open the lastest wal file for appending
  158. seq, _, err := parseWalName(names[len(names)-1])
  159. if err != nil {
  160. rc.Close()
  161. return nil, err
  162. }
  163. last := path.Join(dirpath, names[len(names)-1])
  164. f, err := os.OpenFile(last, os.O_WRONLY|os.O_APPEND, 0)
  165. if err != nil {
  166. rc.Close()
  167. return nil, err
  168. }
  169. // create a WAL ready for reading
  170. w := &WAL{
  171. dir: dirpath,
  172. start: snap,
  173. decoder: newDecoder(rc),
  174. f: f,
  175. seq: seq,
  176. locks: ls,
  177. }
  178. return w, nil
  179. }
  180. // ReadAll reads out all records of the current WAL.
  181. // If it cannot read out the expected snap, it will return ErrSnapshotNotFound.
  182. // If loaded snap doesn't match with the expected one, it will return
  183. // all the records and error ErrSnapshotMismatch.
  184. // TODO: detect not-last-snap error.
  185. // TODO: maybe loose the checking of match.
  186. // After ReadAll, the WAL will be ready for appending new records.
  187. func (w *WAL) ReadAll() (metadata []byte, state raftpb.HardState, ents []raftpb.Entry, err error) {
  188. rec := &walpb.Record{}
  189. decoder := w.decoder
  190. var match bool
  191. for err = decoder.decode(rec); err == nil; err = decoder.decode(rec) {
  192. switch rec.Type {
  193. case entryType:
  194. e := mustUnmarshalEntry(rec.Data)
  195. if e.Index > w.start.Index {
  196. ents = append(ents[:e.Index-w.start.Index-1], e)
  197. }
  198. w.enti = e.Index
  199. case stateType:
  200. state = mustUnmarshalState(rec.Data)
  201. case metadataType:
  202. if metadata != nil && !reflect.DeepEqual(metadata, rec.Data) {
  203. state.Reset()
  204. return nil, state, nil, ErrMetadataConflict
  205. }
  206. metadata = rec.Data
  207. case crcType:
  208. crc := decoder.crc.Sum32()
  209. // current crc of decoder must match the crc of the record.
  210. // do no need to match 0 crc, since the decoder is a new one at this case.
  211. if crc != 0 && rec.Validate(crc) != nil {
  212. state.Reset()
  213. return nil, state, nil, ErrCRCMismatch
  214. }
  215. decoder.updateCRC(rec.Crc)
  216. case snapshotType:
  217. var snap walpb.Snapshot
  218. pbutil.MustUnmarshal(&snap, rec.Data)
  219. if snap.Index == w.start.Index {
  220. if snap.Term != w.start.Term {
  221. state.Reset()
  222. return nil, state, nil, ErrSnapshotMismatch
  223. }
  224. match = true
  225. }
  226. default:
  227. state.Reset()
  228. return nil, state, nil, fmt.Errorf("unexpected block type %d", rec.Type)
  229. }
  230. }
  231. if err != io.EOF {
  232. state.Reset()
  233. return nil, state, nil, err
  234. }
  235. err = nil
  236. if !match {
  237. err = ErrSnapshotNotFound
  238. }
  239. // close decoder, disable reading
  240. w.decoder.close()
  241. w.start = walpb.Snapshot{}
  242. w.metadata = metadata
  243. // create encoder (chain crc with the decoder), enable appending
  244. w.encoder = newEncoder(w.f, w.decoder.lastCRC())
  245. w.decoder = nil
  246. return metadata, state, ents, err
  247. }
  248. // Cut closes current file written and creates a new one ready to append.
  249. // cut first creates a temp wal file and writes necessary headers into it.
  250. // Then cut atomtically rename temp wal file to a wal file.
  251. func (w *WAL) Cut() error {
  252. // close old wal file
  253. if err := w.sync(); err != nil {
  254. return err
  255. }
  256. if err := w.f.Close(); err != nil {
  257. return err
  258. }
  259. fpath := path.Join(w.dir, walName(w.seq+1, w.enti+1))
  260. ftpath := fpath + ".tmp"
  261. // create a temp wal file with name sequence + 1, or tuncate the existing one
  262. ft, err := os.OpenFile(ftpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_TRUNC, 0600)
  263. if err != nil {
  264. return err
  265. }
  266. // update writer and save the previous crc
  267. w.f = ft
  268. prevCrc := w.encoder.crc.Sum32()
  269. w.encoder = newEncoder(w.f, prevCrc)
  270. if err := w.saveCrc(prevCrc); err != nil {
  271. return err
  272. }
  273. if err := w.encoder.encode(&walpb.Record{Type: metadataType, Data: w.metadata}); err != nil {
  274. return err
  275. }
  276. if err := w.saveState(&w.state); err != nil {
  277. return err
  278. }
  279. // close temp wal file
  280. if err := w.sync(); err != nil {
  281. return err
  282. }
  283. if err := w.f.Close(); err != nil {
  284. return err
  285. }
  286. // atomically move temp wal file to wal file
  287. if err := os.Rename(ftpath, fpath); err != nil {
  288. return err
  289. }
  290. // open the wal file and update writer again
  291. f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND, 0600)
  292. if err != nil {
  293. return err
  294. }
  295. w.f = f
  296. prevCrc = w.encoder.crc.Sum32()
  297. w.encoder = newEncoder(w.f, prevCrc)
  298. // lock the new wal file
  299. l, err := fileutil.NewLock(f.Name())
  300. if err != nil {
  301. return err
  302. }
  303. err = l.Lock()
  304. if err != nil {
  305. return err
  306. }
  307. w.locks = append(w.locks, l)
  308. // increase the wal seq
  309. w.seq++
  310. log.Printf("wal: segmented wal file %v is created", fpath)
  311. return nil
  312. }
  313. func (w *WAL) sync() error {
  314. if w.encoder != nil {
  315. if err := w.encoder.flush(); err != nil {
  316. return err
  317. }
  318. }
  319. return w.f.Sync()
  320. }
  321. // ReleaseLockTo releases the locks, which has smaller index than the given index
  322. // except the largest one among them.
  323. // For example, if WAL is holding lock 1,2,3,4,5,6, ReleaseLockTo(4) will release
  324. // lock 1,2 but keep 3. ReleaseLockTo(5) will release 1,2,3 but keep 4.
  325. func (w *WAL) ReleaseLockTo(index uint64) error {
  326. var smaller int
  327. found := false
  328. for i, l := range w.locks {
  329. _, lockIndex, err := parseWalName(path.Base(l.Name()))
  330. if err != nil {
  331. return err
  332. }
  333. if lockIndex >= index {
  334. smaller = i - 1
  335. found = true
  336. break
  337. }
  338. }
  339. // if no lock index is greater than the release index, we can
  340. // release lock upto the last one(excluding).
  341. if !found && len(w.locks) != 0 {
  342. smaller = len(w.locks) - 1
  343. }
  344. if smaller <= 0 {
  345. return nil
  346. }
  347. for i := 0; i < smaller; i++ {
  348. w.locks[i].Unlock()
  349. w.locks[i].Destroy()
  350. }
  351. w.locks = w.locks[smaller:]
  352. return nil
  353. }
  354. func (w *WAL) Close() error {
  355. if w.f != nil {
  356. if err := w.sync(); err != nil {
  357. return err
  358. }
  359. if err := w.f.Close(); err != nil {
  360. return err
  361. }
  362. }
  363. for _, l := range w.locks {
  364. // TODO: log the error
  365. l.Unlock()
  366. l.Destroy()
  367. }
  368. return nil
  369. }
  370. func (w *WAL) saveEntry(e *raftpb.Entry) error {
  371. b := pbutil.MustMarshal(e)
  372. rec := &walpb.Record{Type: entryType, Data: b}
  373. if err := w.encoder.encode(rec); err != nil {
  374. return err
  375. }
  376. w.enti = e.Index
  377. return nil
  378. }
  379. func (w *WAL) saveState(s *raftpb.HardState) error {
  380. if raft.IsEmptyHardState(*s) {
  381. return nil
  382. }
  383. w.state = *s
  384. b := pbutil.MustMarshal(s)
  385. rec := &walpb.Record{Type: stateType, Data: b}
  386. return w.encoder.encode(rec)
  387. }
  388. func (w *WAL) Save(st raftpb.HardState, ents []raftpb.Entry) error {
  389. // TODO(xiangli): no more reference operator
  390. if err := w.saveState(&st); err != nil {
  391. return err
  392. }
  393. for i := range ents {
  394. if err := w.saveEntry(&ents[i]); err != nil {
  395. return err
  396. }
  397. }
  398. return w.sync()
  399. }
  400. func (w *WAL) SaveSnapshot(e walpb.Snapshot) error {
  401. b := pbutil.MustMarshal(&e)
  402. rec := &walpb.Record{Type: snapshotType, Data: b}
  403. if err := w.encoder.encode(rec); err != nil {
  404. return err
  405. }
  406. // update enti only when snapshot is ahead of last index
  407. if w.enti < e.Index {
  408. w.enti = e.Index
  409. }
  410. return w.sync()
  411. }
  412. func (w *WAL) saveCrc(prevCrc uint32) error {
  413. return w.encoder.encode(&walpb.Record{Type: crcType, Crc: prevCrc})
  414. }