repair_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. "io"
  17. "io/ioutil"
  18. "os"
  19. "testing"
  20. "github.com/coreos/etcd/raft/raftpb"
  21. "github.com/coreos/etcd/wal/walpb"
  22. )
  23. func TestRepair(t *testing.T) {
  24. p, err := ioutil.TempDir(os.TempDir(), "waltest")
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. defer os.RemoveAll(p)
  29. // create WAL
  30. w, err := Create(p, nil)
  31. defer w.Close()
  32. if err != nil {
  33. t.Fatal(err)
  34. }
  35. n := 10
  36. for i := 1; i <= n; i++ {
  37. es := []raftpb.Entry{{Index: uint64(i)}}
  38. if err = w.Save(raftpb.HardState{}, es); err != nil {
  39. t.Fatal(err)
  40. }
  41. }
  42. w.Close()
  43. // break the wal.
  44. f, err := openLast(p)
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. offset, err := f.Seek(-4, os.SEEK_END)
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. err = f.Truncate(offset)
  53. if err != nil {
  54. t.Fatal(err)
  55. }
  56. // verify we have broke the wal
  57. w, err = Open(p, walpb.Snapshot{})
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. _, _, _, err = w.ReadAll()
  62. if err != io.ErrUnexpectedEOF {
  63. t.Fatalf("err = %v, want %v", err, io.ErrUnexpectedEOF)
  64. }
  65. w.Close()
  66. // repair the wal
  67. ok := Repair(p)
  68. if !ok {
  69. t.Fatalf("fix = %t, want %t", ok, true)
  70. }
  71. w, err = Open(p, walpb.Snapshot{})
  72. if err != nil {
  73. t.Fatal(err)
  74. }
  75. _, _, ents, err := w.ReadAll()
  76. if err != nil {
  77. t.Fatalf("err = %v, want %v", err, nil)
  78. }
  79. if len(ents) != n-1 {
  80. t.Fatalf("len(ents) = %d, want %d", len(ents), n-1)
  81. }
  82. }