wal_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. // Copyright 2015 The etcd Authors
  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. "bytes"
  17. "io"
  18. "io/ioutil"
  19. "os"
  20. "path/filepath"
  21. "reflect"
  22. "testing"
  23. "github.com/coreos/etcd/pkg/fileutil"
  24. "github.com/coreos/etcd/pkg/pbutil"
  25. "github.com/coreos/etcd/raft/raftpb"
  26. "github.com/coreos/etcd/wal/walpb"
  27. )
  28. func TestNew(t *testing.T) {
  29. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  30. if err != nil {
  31. t.Fatal(err)
  32. }
  33. defer os.RemoveAll(p)
  34. w, err := Create(p, []byte("somedata"))
  35. if err != nil {
  36. t.Fatalf("err = %v, want nil", err)
  37. }
  38. if g := filepath.Base(w.tail().Name()); g != walName(0, 0) {
  39. t.Errorf("name = %+v, want %+v", g, walName(0, 0))
  40. }
  41. defer w.Close()
  42. // file is preallocated to segment size; only read data written by wal
  43. off, err := w.tail().Seek(0, io.SeekCurrent)
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. gd := make([]byte, off)
  48. f, err := os.Open(filepath.Join(p, filepath.Base(w.tail().Name())))
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. defer f.Close()
  53. if _, err = io.ReadFull(f, gd); err != nil {
  54. t.Fatalf("err = %v, want nil", err)
  55. }
  56. var wb bytes.Buffer
  57. e := newEncoder(&wb, 0, 0)
  58. err = e.encode(&walpb.Record{Type: crcType, Crc: 0})
  59. if err != nil {
  60. t.Fatalf("err = %v, want nil", err)
  61. }
  62. err = e.encode(&walpb.Record{Type: metadataType, Data: []byte("somedata")})
  63. if err != nil {
  64. t.Fatalf("err = %v, want nil", err)
  65. }
  66. r := &walpb.Record{
  67. Type: snapshotType,
  68. Data: pbutil.MustMarshal(&walpb.Snapshot{}),
  69. }
  70. if err = e.encode(r); err != nil {
  71. t.Fatalf("err = %v, want nil", err)
  72. }
  73. e.flush()
  74. if !bytes.Equal(gd, wb.Bytes()) {
  75. t.Errorf("data = %v, want %v", gd, wb.Bytes())
  76. }
  77. }
  78. func TestNewForInitedDir(t *testing.T) {
  79. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  80. if err != nil {
  81. t.Fatal(err)
  82. }
  83. defer os.RemoveAll(p)
  84. os.Create(filepath.Join(p, walName(0, 0)))
  85. if _, err = Create(p, nil); err == nil || err != os.ErrExist {
  86. t.Errorf("err = %v, want %v", err, os.ErrExist)
  87. }
  88. }
  89. func TestOpenAtIndex(t *testing.T) {
  90. dir, err := ioutil.TempDir(os.TempDir(), "waltest")
  91. if err != nil {
  92. t.Fatal(err)
  93. }
  94. defer os.RemoveAll(dir)
  95. f, err := os.Create(filepath.Join(dir, walName(0, 0)))
  96. if err != nil {
  97. t.Fatal(err)
  98. }
  99. f.Close()
  100. w, err := Open(dir, walpb.Snapshot{})
  101. if err != nil {
  102. t.Fatalf("err = %v, want nil", err)
  103. }
  104. if g := filepath.Base(w.tail().Name()); g != walName(0, 0) {
  105. t.Errorf("name = %+v, want %+v", g, walName(0, 0))
  106. }
  107. if w.seq() != 0 {
  108. t.Errorf("seq = %d, want %d", w.seq(), 0)
  109. }
  110. w.Close()
  111. wname := walName(2, 10)
  112. f, err = os.Create(filepath.Join(dir, wname))
  113. if err != nil {
  114. t.Fatal(err)
  115. }
  116. f.Close()
  117. w, err = Open(dir, walpb.Snapshot{Index: 5})
  118. if err != nil {
  119. t.Fatalf("err = %v, want nil", err)
  120. }
  121. if g := filepath.Base(w.tail().Name()); g != wname {
  122. t.Errorf("name = %+v, want %+v", g, wname)
  123. }
  124. if w.seq() != 2 {
  125. t.Errorf("seq = %d, want %d", w.seq(), 2)
  126. }
  127. w.Close()
  128. emptydir, err := ioutil.TempDir(os.TempDir(), "waltestempty")
  129. if err != nil {
  130. t.Fatal(err)
  131. }
  132. defer os.RemoveAll(emptydir)
  133. if _, err = Open(emptydir, walpb.Snapshot{}); err != ErrFileNotFound {
  134. t.Errorf("err = %v, want %v", err, ErrFileNotFound)
  135. }
  136. }
  137. // TODO: split it into smaller tests for better readability
  138. func TestCut(t *testing.T) {
  139. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  140. if err != nil {
  141. t.Fatal(err)
  142. }
  143. defer os.RemoveAll(p)
  144. w, err := Create(p, nil)
  145. if err != nil {
  146. t.Fatal(err)
  147. }
  148. defer w.Close()
  149. state := raftpb.HardState{Term: 1}
  150. if err = w.Save(state, nil); err != nil {
  151. t.Fatal(err)
  152. }
  153. if err = w.cut(); err != nil {
  154. t.Fatal(err)
  155. }
  156. wname := walName(1, 1)
  157. if g := filepath.Base(w.tail().Name()); g != wname {
  158. t.Errorf("name = %s, want %s", g, wname)
  159. }
  160. es := []raftpb.Entry{{Index: 1, Term: 1, Data: []byte{1}}}
  161. if err = w.Save(raftpb.HardState{}, es); err != nil {
  162. t.Fatal(err)
  163. }
  164. if err = w.cut(); err != nil {
  165. t.Fatal(err)
  166. }
  167. snap := walpb.Snapshot{Index: 2, Term: 1}
  168. if err = w.SaveSnapshot(snap); err != nil {
  169. t.Fatal(err)
  170. }
  171. wname = walName(2, 2)
  172. if g := filepath.Base(w.tail().Name()); g != wname {
  173. t.Errorf("name = %s, want %s", g, wname)
  174. }
  175. // check the state in the last WAL
  176. // We do check before closing the WAL to ensure that Cut syncs the data
  177. // into the disk.
  178. f, err := os.Open(filepath.Join(p, wname))
  179. if err != nil {
  180. t.Fatal(err)
  181. }
  182. defer f.Close()
  183. nw := &WAL{
  184. decoder: newDecoder(f),
  185. start: snap,
  186. }
  187. _, gst, _, err := nw.ReadAll()
  188. if err != nil {
  189. t.Fatal(err)
  190. }
  191. if !reflect.DeepEqual(gst, state) {
  192. t.Errorf("state = %+v, want %+v", gst, state)
  193. }
  194. }
  195. func TestSaveWithCut(t *testing.T) {
  196. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  197. if err != nil {
  198. t.Fatal(err)
  199. }
  200. defer os.RemoveAll(p)
  201. w, err := Create(p, []byte("metadata"))
  202. if err != nil {
  203. t.Fatal(err)
  204. }
  205. state := raftpb.HardState{Term: 1}
  206. if err = w.Save(state, nil); err != nil {
  207. t.Fatal(err)
  208. }
  209. bigData := make([]byte, 500)
  210. strdata := "Hello World!!"
  211. copy(bigData, strdata)
  212. // set a lower value for SegmentSizeBytes, else the test takes too long to complete
  213. restoreLater := SegmentSizeBytes
  214. const EntrySize int = 500
  215. SegmentSizeBytes = 2 * 1024
  216. defer func() { SegmentSizeBytes = restoreLater }()
  217. var index uint64 = 0
  218. for totalSize := 0; totalSize < int(SegmentSizeBytes); totalSize += EntrySize {
  219. ents := []raftpb.Entry{{Index: index, Term: 1, Data: bigData}}
  220. if err = w.Save(state, ents); err != nil {
  221. t.Fatal(err)
  222. }
  223. index++
  224. }
  225. w.Close()
  226. neww, err := Open(p, walpb.Snapshot{})
  227. if err != nil {
  228. t.Fatalf("err = %v, want nil", err)
  229. }
  230. defer neww.Close()
  231. wname := walName(1, index)
  232. if g := filepath.Base(neww.tail().Name()); g != wname {
  233. t.Errorf("name = %s, want %s", g, wname)
  234. }
  235. _, newhardstate, entries, err := neww.ReadAll()
  236. if err != nil {
  237. t.Fatal(err)
  238. }
  239. if !reflect.DeepEqual(newhardstate, state) {
  240. t.Errorf("Hard State = %+v, want %+v", newhardstate, state)
  241. }
  242. if len(entries) != int(SegmentSizeBytes/int64(EntrySize)) {
  243. t.Errorf("Number of entries = %d, expected = %d", len(entries), int(SegmentSizeBytes/int64(EntrySize)))
  244. }
  245. for _, oneent := range entries {
  246. if !bytes.Equal(oneent.Data, bigData) {
  247. t.Errorf("the saved data does not match at Index %d : found: %s , want :%s", oneent.Index, oneent.Data, bigData)
  248. }
  249. }
  250. }
  251. func TestRecover(t *testing.T) {
  252. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  253. if err != nil {
  254. t.Fatal(err)
  255. }
  256. defer os.RemoveAll(p)
  257. w, err := Create(p, []byte("metadata"))
  258. if err != nil {
  259. t.Fatal(err)
  260. }
  261. if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil {
  262. t.Fatal(err)
  263. }
  264. ents := []raftpb.Entry{{Index: 1, Term: 1, Data: []byte{1}}, {Index: 2, Term: 2, Data: []byte{2}}}
  265. if err = w.Save(raftpb.HardState{}, ents); err != nil {
  266. t.Fatal(err)
  267. }
  268. sts := []raftpb.HardState{{Term: 1, Vote: 1, Commit: 1}, {Term: 2, Vote: 2, Commit: 2}}
  269. for _, s := range sts {
  270. if err = w.Save(s, nil); err != nil {
  271. t.Fatal(err)
  272. }
  273. }
  274. w.Close()
  275. if w, err = Open(p, walpb.Snapshot{}); err != nil {
  276. t.Fatal(err)
  277. }
  278. metadata, state, entries, err := w.ReadAll()
  279. if err != nil {
  280. t.Fatal(err)
  281. }
  282. if !bytes.Equal(metadata, []byte("metadata")) {
  283. t.Errorf("metadata = %s, want %s", metadata, "metadata")
  284. }
  285. if !reflect.DeepEqual(entries, ents) {
  286. t.Errorf("ents = %+v, want %+v", entries, ents)
  287. }
  288. // only the latest state is recorded
  289. s := sts[len(sts)-1]
  290. if !reflect.DeepEqual(state, s) {
  291. t.Errorf("state = %+v, want %+v", state, s)
  292. }
  293. w.Close()
  294. }
  295. func TestSearchIndex(t *testing.T) {
  296. tests := []struct {
  297. names []string
  298. index uint64
  299. widx int
  300. wok bool
  301. }{
  302. {
  303. []string{
  304. "0000000000000000-0000000000000000.wal",
  305. "0000000000000001-0000000000001000.wal",
  306. "0000000000000002-0000000000002000.wal",
  307. },
  308. 0x1000, 1, true,
  309. },
  310. {
  311. []string{
  312. "0000000000000001-0000000000004000.wal",
  313. "0000000000000002-0000000000003000.wal",
  314. "0000000000000003-0000000000005000.wal",
  315. },
  316. 0x4000, 1, true,
  317. },
  318. {
  319. []string{
  320. "0000000000000001-0000000000002000.wal",
  321. "0000000000000002-0000000000003000.wal",
  322. "0000000000000003-0000000000005000.wal",
  323. },
  324. 0x1000, -1, false,
  325. },
  326. }
  327. for i, tt := range tests {
  328. idx, ok := searchIndex(tt.names, tt.index)
  329. if idx != tt.widx {
  330. t.Errorf("#%d: idx = %d, want %d", i, idx, tt.widx)
  331. }
  332. if ok != tt.wok {
  333. t.Errorf("#%d: ok = %v, want %v", i, ok, tt.wok)
  334. }
  335. }
  336. }
  337. func TestScanWalName(t *testing.T) {
  338. tests := []struct {
  339. str string
  340. wseq, windex uint64
  341. wok bool
  342. }{
  343. {"0000000000000000-0000000000000000.wal", 0, 0, true},
  344. {"0000000000000000.wal", 0, 0, false},
  345. {"0000000000000000-0000000000000000.snap", 0, 0, false},
  346. }
  347. for i, tt := range tests {
  348. s, index, err := parseWalName(tt.str)
  349. if g := err == nil; g != tt.wok {
  350. t.Errorf("#%d: ok = %v, want %v", i, g, tt.wok)
  351. }
  352. if s != tt.wseq {
  353. t.Errorf("#%d: seq = %d, want %d", i, s, tt.wseq)
  354. }
  355. if index != tt.windex {
  356. t.Errorf("#%d: index = %d, want %d", i, index, tt.windex)
  357. }
  358. }
  359. }
  360. func TestRecoverAfterCut(t *testing.T) {
  361. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  362. if err != nil {
  363. t.Fatal(err)
  364. }
  365. defer os.RemoveAll(p)
  366. md, err := Create(p, []byte("metadata"))
  367. if err != nil {
  368. t.Fatal(err)
  369. }
  370. for i := 0; i < 10; i++ {
  371. if err = md.SaveSnapshot(walpb.Snapshot{Index: uint64(i)}); err != nil {
  372. t.Fatal(err)
  373. }
  374. es := []raftpb.Entry{{Index: uint64(i)}}
  375. if err = md.Save(raftpb.HardState{}, es); err != nil {
  376. t.Fatal(err)
  377. }
  378. if err = md.cut(); err != nil {
  379. t.Fatal(err)
  380. }
  381. }
  382. md.Close()
  383. if err := os.Remove(filepath.Join(p, walName(4, 4))); err != nil {
  384. t.Fatal(err)
  385. }
  386. for i := 0; i < 10; i++ {
  387. w, err := Open(p, walpb.Snapshot{Index: uint64(i)})
  388. if err != nil {
  389. if i <= 4 {
  390. if err != ErrFileNotFound {
  391. t.Errorf("#%d: err = %v, want %v", i, err, ErrFileNotFound)
  392. }
  393. } else {
  394. t.Errorf("#%d: err = %v, want nil", i, err)
  395. }
  396. continue
  397. }
  398. metadata, _, entries, err := w.ReadAll()
  399. if err != nil {
  400. t.Errorf("#%d: err = %v, want nil", i, err)
  401. continue
  402. }
  403. if !bytes.Equal(metadata, []byte("metadata")) {
  404. t.Errorf("#%d: metadata = %s, want %s", i, metadata, "metadata")
  405. }
  406. for j, e := range entries {
  407. if e.Index != uint64(j+i+1) {
  408. t.Errorf("#%d: ents[%d].Index = %+v, want %+v", i, j, e.Index, j+i+1)
  409. }
  410. }
  411. w.Close()
  412. }
  413. }
  414. func TestOpenAtUncommittedIndex(t *testing.T) {
  415. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  416. if err != nil {
  417. t.Fatal(err)
  418. }
  419. defer os.RemoveAll(p)
  420. w, err := Create(p, nil)
  421. if err != nil {
  422. t.Fatal(err)
  423. }
  424. if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil {
  425. t.Fatal(err)
  426. }
  427. if err = w.Save(raftpb.HardState{}, []raftpb.Entry{{Index: 0}}); err != nil {
  428. t.Fatal(err)
  429. }
  430. w.Close()
  431. w, err = Open(p, walpb.Snapshot{})
  432. if err != nil {
  433. t.Fatal(err)
  434. }
  435. // commit up to index 0, try to read index 1
  436. if _, _, _, err = w.ReadAll(); err != nil {
  437. t.Errorf("err = %v, want nil", err)
  438. }
  439. w.Close()
  440. }
  441. // TestOpenForRead tests that OpenForRead can load all files.
  442. // The tests creates WAL directory, and cut out multiple WAL files. Then
  443. // it releases the lock of part of data, and excepts that OpenForRead
  444. // can read out all files even if some are locked for write.
  445. func TestOpenForRead(t *testing.T) {
  446. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  447. if err != nil {
  448. t.Fatal(err)
  449. }
  450. defer os.RemoveAll(p)
  451. // create WAL
  452. w, err := Create(p, nil)
  453. if err != nil {
  454. t.Fatal(err)
  455. }
  456. defer w.Close()
  457. // make 10 separate files
  458. for i := 0; i < 10; i++ {
  459. es := []raftpb.Entry{{Index: uint64(i)}}
  460. if err = w.Save(raftpb.HardState{}, es); err != nil {
  461. t.Fatal(err)
  462. }
  463. if err = w.cut(); err != nil {
  464. t.Fatal(err)
  465. }
  466. }
  467. // release the lock to 5
  468. unlockIndex := uint64(5)
  469. w.ReleaseLockTo(unlockIndex)
  470. // All are available for read
  471. w2, err := OpenForRead(p, walpb.Snapshot{})
  472. if err != nil {
  473. t.Fatal(err)
  474. }
  475. defer w2.Close()
  476. _, _, ents, err := w2.ReadAll()
  477. if err != nil {
  478. t.Fatalf("err = %v, want nil", err)
  479. }
  480. if g := ents[len(ents)-1].Index; g != 9 {
  481. t.Errorf("last index read = %d, want %d", g, 9)
  482. }
  483. }
  484. func TestSaveEmpty(t *testing.T) {
  485. var buf bytes.Buffer
  486. var est raftpb.HardState
  487. w := WAL{
  488. encoder: newEncoder(&buf, 0, 0),
  489. }
  490. if err := w.saveState(&est); err != nil {
  491. t.Errorf("err = %v, want nil", err)
  492. }
  493. if len(buf.Bytes()) != 0 {
  494. t.Errorf("buf.Bytes = %d, want 0", len(buf.Bytes()))
  495. }
  496. }
  497. func TestReleaseLockTo(t *testing.T) {
  498. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  499. if err != nil {
  500. t.Fatal(err)
  501. }
  502. defer os.RemoveAll(p)
  503. // create WAL
  504. w, err := Create(p, nil)
  505. defer func() {
  506. if err = w.Close(); err != nil {
  507. t.Fatal(err)
  508. }
  509. }()
  510. if err != nil {
  511. t.Fatal(err)
  512. }
  513. // make 10 separate files
  514. for i := 0; i < 10; i++ {
  515. es := []raftpb.Entry{{Index: uint64(i)}}
  516. if err = w.Save(raftpb.HardState{}, es); err != nil {
  517. t.Fatal(err)
  518. }
  519. if err = w.cut(); err != nil {
  520. t.Fatal(err)
  521. }
  522. }
  523. // release the lock to 5
  524. unlockIndex := uint64(5)
  525. w.ReleaseLockTo(unlockIndex)
  526. // expected remaining are 4,5,6,7,8,9,10
  527. if len(w.locks) != 7 {
  528. t.Errorf("len(w.locks) = %d, want %d", len(w.locks), 7)
  529. }
  530. for i, l := range w.locks {
  531. var lockIndex uint64
  532. _, lockIndex, err = parseWalName(filepath.Base(l.Name()))
  533. if err != nil {
  534. t.Fatal(err)
  535. }
  536. if lockIndex != uint64(i+4) {
  537. t.Errorf("#%d: lockindex = %d, want %d", i, lockIndex, uint64(i+4))
  538. }
  539. }
  540. // release the lock to 15
  541. unlockIndex = uint64(15)
  542. w.ReleaseLockTo(unlockIndex)
  543. // expected remaining is 10
  544. if len(w.locks) != 1 {
  545. t.Errorf("len(w.locks) = %d, want %d", len(w.locks), 1)
  546. }
  547. _, lockIndex, err := parseWalName(filepath.Base(w.locks[0].Name()))
  548. if err != nil {
  549. t.Fatal(err)
  550. }
  551. if lockIndex != uint64(10) {
  552. t.Errorf("lockindex = %d, want %d", lockIndex, 10)
  553. }
  554. }
  555. // TestTailWriteNoSlackSpace ensures that tail writes append if there's no preallocated space.
  556. func TestTailWriteNoSlackSpace(t *testing.T) {
  557. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  558. if err != nil {
  559. t.Fatal(err)
  560. }
  561. defer os.RemoveAll(p)
  562. // create initial WAL
  563. w, err := Create(p, []byte("metadata"))
  564. if err != nil {
  565. t.Fatal(err)
  566. }
  567. // write some entries
  568. for i := 1; i <= 5; i++ {
  569. es := []raftpb.Entry{{Index: uint64(i), Term: 1, Data: []byte{byte(i)}}}
  570. if err = w.Save(raftpb.HardState{Term: 1}, es); err != nil {
  571. t.Fatal(err)
  572. }
  573. }
  574. // get rid of slack space by truncating file
  575. off, serr := w.tail().Seek(0, io.SeekCurrent)
  576. if serr != nil {
  577. t.Fatal(serr)
  578. }
  579. if terr := w.tail().Truncate(off); terr != nil {
  580. t.Fatal(terr)
  581. }
  582. w.Close()
  583. // open, write more
  584. w, err = Open(p, walpb.Snapshot{})
  585. if err != nil {
  586. t.Fatal(err)
  587. }
  588. _, _, ents, rerr := w.ReadAll()
  589. if rerr != nil {
  590. t.Fatal(rerr)
  591. }
  592. if len(ents) != 5 {
  593. t.Fatalf("got entries %+v, expected 5 entries", ents)
  594. }
  595. // write more entries
  596. for i := 6; i <= 10; i++ {
  597. es := []raftpb.Entry{{Index: uint64(i), Term: 1, Data: []byte{byte(i)}}}
  598. if err = w.Save(raftpb.HardState{Term: 1}, es); err != nil {
  599. t.Fatal(err)
  600. }
  601. }
  602. w.Close()
  603. // confirm all writes
  604. w, err = Open(p, walpb.Snapshot{})
  605. if err != nil {
  606. t.Fatal(err)
  607. }
  608. _, _, ents, rerr = w.ReadAll()
  609. if rerr != nil {
  610. t.Fatal(rerr)
  611. }
  612. if len(ents) != 10 {
  613. t.Fatalf("got entries %+v, expected 10 entries", ents)
  614. }
  615. w.Close()
  616. }
  617. // TestRestartCreateWal ensures that an interrupted WAL initialization is clobbered on restart
  618. func TestRestartCreateWal(t *testing.T) {
  619. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  620. if err != nil {
  621. t.Fatal(err)
  622. }
  623. defer os.RemoveAll(p)
  624. // make temporary directory so it looks like initialization is interrupted
  625. tmpdir := filepath.Clean(p) + ".tmp"
  626. if err = os.Mkdir(tmpdir, fileutil.PrivateDirMode); err != nil {
  627. t.Fatal(err)
  628. }
  629. if _, err = os.OpenFile(filepath.Join(tmpdir, "test"), os.O_WRONLY|os.O_CREATE, fileutil.PrivateFileMode); err != nil {
  630. t.Fatal(err)
  631. }
  632. w, werr := Create(p, []byte("abc"))
  633. if werr != nil {
  634. t.Fatal(werr)
  635. }
  636. w.Close()
  637. if Exist(tmpdir) {
  638. t.Fatalf("got %q exists, expected it to not exist", tmpdir)
  639. }
  640. if w, err = OpenForRead(p, walpb.Snapshot{}); err != nil {
  641. t.Fatal(err)
  642. }
  643. defer w.Close()
  644. if meta, _, _, rerr := w.ReadAll(); rerr != nil || string(meta) != "abc" {
  645. t.Fatalf("got error %v and meta %q, expected nil and %q", rerr, meta, "abc")
  646. }
  647. }
  648. // TestOpenOnTornWrite ensures that entries past the torn write are truncated.
  649. func TestOpenOnTornWrite(t *testing.T) {
  650. maxEntries := 40
  651. clobberIdx := 20
  652. overwriteEntries := 5
  653. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  654. if err != nil {
  655. t.Fatal(err)
  656. }
  657. defer os.RemoveAll(p)
  658. w, err := Create(p, nil)
  659. defer func() {
  660. if err = w.Close(); err != nil && err != os.ErrInvalid {
  661. t.Fatal(err)
  662. }
  663. }()
  664. if err != nil {
  665. t.Fatal(err)
  666. }
  667. // get offset of end of each saved entry
  668. offsets := make([]int64, maxEntries)
  669. for i := range offsets {
  670. es := []raftpb.Entry{{Index: uint64(i)}}
  671. if err = w.Save(raftpb.HardState{}, es); err != nil {
  672. t.Fatal(err)
  673. }
  674. if offsets[i], err = w.tail().Seek(0, io.SeekCurrent); err != nil {
  675. t.Fatal(err)
  676. }
  677. }
  678. fn := filepath.Join(p, filepath.Base(w.tail().Name()))
  679. w.Close()
  680. // clobber some entry with 0's to simulate a torn write
  681. f, ferr := os.OpenFile(fn, os.O_WRONLY, fileutil.PrivateFileMode)
  682. if ferr != nil {
  683. t.Fatal(ferr)
  684. }
  685. defer f.Close()
  686. _, err = f.Seek(offsets[clobberIdx], io.SeekStart)
  687. if err != nil {
  688. t.Fatal(err)
  689. }
  690. zeros := make([]byte, offsets[clobberIdx+1]-offsets[clobberIdx])
  691. _, err = f.Write(zeros)
  692. if err != nil {
  693. t.Fatal(err)
  694. }
  695. f.Close()
  696. w, err = Open(p, walpb.Snapshot{})
  697. if err != nil {
  698. t.Fatal(err)
  699. }
  700. // seek up to clobbered entry
  701. _, _, _, err = w.ReadAll()
  702. if err != nil {
  703. t.Fatal(err)
  704. }
  705. // write a few entries past the clobbered entry
  706. for i := 0; i < overwriteEntries; i++ {
  707. // Index is different from old, truncated entries
  708. es := []raftpb.Entry{{Index: uint64(i + clobberIdx), Data: []byte("new")}}
  709. if err = w.Save(raftpb.HardState{}, es); err != nil {
  710. t.Fatal(err)
  711. }
  712. }
  713. w.Close()
  714. // read back the entries, confirm number of entries matches expectation
  715. w, err = OpenForRead(p, walpb.Snapshot{})
  716. if err != nil {
  717. t.Fatal(err)
  718. }
  719. _, _, ents, rerr := w.ReadAll()
  720. if rerr != nil {
  721. // CRC error? the old entries were likely never truncated away
  722. t.Fatal(rerr)
  723. }
  724. wEntries := (clobberIdx - 1) + overwriteEntries
  725. if len(ents) != wEntries {
  726. t.Fatalf("expected len(ents) = %d, got %d", wEntries, len(ents))
  727. }
  728. }