ctl_v3_snapshot_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // Copyright 2016 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 e2e
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "os"
  21. "path/filepath"
  22. "strings"
  23. "testing"
  24. "time"
  25. "go.etcd.io/etcd/clientv3/snapshot"
  26. "go.etcd.io/etcd/pkg/expect"
  27. "go.etcd.io/etcd/pkg/testutil"
  28. )
  29. func TestCtlV3Snapshot(t *testing.T) { testCtl(t, snapshotTest) }
  30. func snapshotTest(cx ctlCtx) {
  31. maintenanceInitKeys(cx)
  32. leaseID, err := ctlV3LeaseGrant(cx, 100)
  33. if err != nil {
  34. cx.t.Fatalf("snapshot: ctlV3LeaseGrant error (%v)", err)
  35. }
  36. if err = ctlV3Put(cx, "withlease", "withlease", leaseID); err != nil {
  37. cx.t.Fatalf("snapshot: ctlV3Put error (%v)", err)
  38. }
  39. fpath := "test1.snapshot"
  40. defer os.RemoveAll(fpath)
  41. if err = ctlV3SnapshotSave(cx, fpath); err != nil {
  42. cx.t.Fatalf("snapshotTest ctlV3SnapshotSave error (%v)", err)
  43. }
  44. st, err := getSnapshotStatus(cx, fpath)
  45. if err != nil {
  46. cx.t.Fatalf("snapshotTest getSnapshotStatus error (%v)", err)
  47. }
  48. if st.Revision != 5 {
  49. cx.t.Fatalf("expected 4, got %d", st.Revision)
  50. }
  51. if st.TotalKey < 4 {
  52. cx.t.Fatalf("expected at least 4, got %d", st.TotalKey)
  53. }
  54. }
  55. func TestCtlV3SnapshotCorrupt(t *testing.T) { testCtl(t, snapshotCorruptTest) }
  56. func snapshotCorruptTest(cx ctlCtx) {
  57. fpath := "test2.snapshot"
  58. defer os.RemoveAll(fpath)
  59. if err := ctlV3SnapshotSave(cx, fpath); err != nil {
  60. cx.t.Fatalf("snapshotTest ctlV3SnapshotSave error (%v)", err)
  61. }
  62. // corrupt file
  63. f, oerr := os.OpenFile(fpath, os.O_WRONLY, 0)
  64. if oerr != nil {
  65. cx.t.Fatal(oerr)
  66. }
  67. if _, err := f.Write(make([]byte, 512)); err != nil {
  68. cx.t.Fatal(err)
  69. }
  70. f.Close()
  71. defer os.RemoveAll("snap.etcd")
  72. serr := spawnWithExpect(
  73. append(cx.PrefixArgs(), "snapshot", "restore",
  74. "--data-dir", "snap.etcd",
  75. fpath),
  76. "expected sha256")
  77. if serr != nil {
  78. cx.t.Fatal(serr)
  79. }
  80. }
  81. // This test ensures that the snapshot status does not modify the snapshot file
  82. func TestCtlV3SnapshotStatusBeforeRestore(t *testing.T) { testCtl(t, snapshotStatusBeforeRestoreTest) }
  83. func snapshotStatusBeforeRestoreTest(cx ctlCtx) {
  84. fpath := "test3.snapshot"
  85. defer os.RemoveAll(fpath)
  86. if err := ctlV3SnapshotSave(cx, fpath); err != nil {
  87. cx.t.Fatalf("snapshotTest ctlV3SnapshotSave error (%v)", err)
  88. }
  89. // snapshot status on the fresh snapshot file
  90. _, err := getSnapshotStatus(cx, fpath)
  91. if err != nil {
  92. cx.t.Fatalf("snapshotTest getSnapshotStatus error (%v)", err)
  93. }
  94. defer os.RemoveAll("snap.etcd")
  95. serr := spawnWithExpect(
  96. append(cx.PrefixArgs(), "snapshot", "restore",
  97. "--data-dir", "snap.etcd",
  98. fpath),
  99. "added member")
  100. if serr != nil {
  101. cx.t.Fatal(serr)
  102. }
  103. }
  104. func ctlV3SnapshotSave(cx ctlCtx, fpath string) error {
  105. cmdArgs := append(cx.PrefixArgs(), "snapshot", "save", fpath)
  106. return spawnWithExpect(cmdArgs, fmt.Sprintf("Snapshot saved at %s", fpath))
  107. }
  108. func getSnapshotStatus(cx ctlCtx, fpath string) (snapshot.Status, error) {
  109. cmdArgs := append(cx.PrefixArgs(), "--write-out", "json", "snapshot", "status", fpath)
  110. proc, err := spawnCmd(cmdArgs)
  111. if err != nil {
  112. return snapshot.Status{}, err
  113. }
  114. var txt string
  115. txt, err = proc.Expect("totalKey")
  116. if err != nil {
  117. return snapshot.Status{}, err
  118. }
  119. if err = proc.Close(); err != nil {
  120. return snapshot.Status{}, err
  121. }
  122. resp := snapshot.Status{}
  123. dec := json.NewDecoder(strings.NewReader(txt))
  124. if err := dec.Decode(&resp); err == io.EOF {
  125. return snapshot.Status{}, err
  126. }
  127. return resp, nil
  128. }
  129. // TestIssue6361 ensures new member that starts with snapshot correctly
  130. // syncs up with other members and serve correct data.
  131. func TestIssue6361(t *testing.T) {
  132. defer testutil.AfterTest(t)
  133. mustEtcdctl(t)
  134. os.Setenv("ETCDCTL_API", "3")
  135. defer os.Unsetenv("ETCDCTL_API")
  136. epc, err := newEtcdProcessCluster(&etcdProcessClusterConfig{
  137. clusterSize: 1,
  138. initialToken: "new",
  139. keepDataDir: true,
  140. })
  141. if err != nil {
  142. t.Fatalf("could not start etcd process cluster (%v)", err)
  143. }
  144. defer func() {
  145. if errC := epc.Close(); errC != nil {
  146. t.Fatalf("error closing etcd processes (%v)", errC)
  147. }
  148. }()
  149. dialTimeout := 7 * time.Second
  150. prefixArgs := []string{ctlBinPath, "--endpoints", strings.Join(epc.EndpointsV3(), ","), "--dial-timeout", dialTimeout.String()}
  151. // write some keys
  152. kvs := []kv{{"foo1", "val1"}, {"foo2", "val2"}, {"foo3", "val3"}}
  153. for i := range kvs {
  154. if err = spawnWithExpect(append(prefixArgs, "put", kvs[i].key, kvs[i].val), "OK"); err != nil {
  155. t.Fatal(err)
  156. }
  157. }
  158. fpath := filepath.Join(os.TempDir(), "test.snapshot")
  159. defer os.RemoveAll(fpath)
  160. // etcdctl save snapshot
  161. if err = spawnWithExpect(append(prefixArgs, "snapshot", "save", fpath), fmt.Sprintf("Snapshot saved at %s", fpath)); err != nil {
  162. t.Fatal(err)
  163. }
  164. if err = epc.procs[0].Stop(); err != nil {
  165. t.Fatal(err)
  166. }
  167. newDataDir := filepath.Join(os.TempDir(), "test.data")
  168. defer os.RemoveAll(newDataDir)
  169. // etcdctl restore the snapshot
  170. err = spawnWithExpect([]string{ctlBinPath, "snapshot", "restore", fpath, "--name", epc.procs[0].Config().name, "--initial-cluster", epc.procs[0].Config().initialCluster, "--initial-cluster-token", epc.procs[0].Config().initialToken, "--initial-advertise-peer-urls", epc.procs[0].Config().purl.String(), "--data-dir", newDataDir}, "added member")
  171. if err != nil {
  172. t.Fatal(err)
  173. }
  174. // start the etcd member using the restored snapshot
  175. epc.procs[0].Config().dataDirPath = newDataDir
  176. for i := range epc.procs[0].Config().args {
  177. if epc.procs[0].Config().args[i] == "--data-dir" {
  178. epc.procs[0].Config().args[i+1] = newDataDir
  179. }
  180. }
  181. if err = epc.procs[0].Restart(); err != nil {
  182. t.Fatal(err)
  183. }
  184. // ensure the restored member has the correct data
  185. for i := range kvs {
  186. if err = spawnWithExpect(append(prefixArgs, "get", kvs[i].key), kvs[i].val); err != nil {
  187. t.Fatal(err)
  188. }
  189. }
  190. // add a new member into the cluster
  191. clientURL := fmt.Sprintf("http://localhost:%d", etcdProcessBasePort+30)
  192. peerURL := fmt.Sprintf("http://localhost:%d", etcdProcessBasePort+31)
  193. err = spawnWithExpect(append(prefixArgs, "member", "add", "newmember", fmt.Sprintf("--peer-urls=%s", peerURL)), " added to cluster ")
  194. if err != nil {
  195. t.Fatal(err)
  196. }
  197. var newDataDir2 string
  198. newDataDir2, err = ioutil.TempDir("", "newdata2")
  199. if err != nil {
  200. t.Fatal(err)
  201. }
  202. defer os.RemoveAll(newDataDir2)
  203. name2 := "infra2"
  204. initialCluster2 := epc.procs[0].Config().initialCluster + fmt.Sprintf(",%s=%s", name2, peerURL)
  205. // start the new member
  206. var nepc *expect.ExpectProcess
  207. nepc, err = spawnCmd([]string{epc.procs[0].Config().execPath, "--name", name2,
  208. "--listen-client-urls", clientURL, "--advertise-client-urls", clientURL,
  209. "--listen-peer-urls", peerURL, "--initial-advertise-peer-urls", peerURL,
  210. "--initial-cluster", initialCluster2, "--initial-cluster-state", "existing", "--data-dir", newDataDir2})
  211. if err != nil {
  212. t.Fatal(err)
  213. }
  214. if _, err = nepc.Expect("enabled capabilities for version"); err != nil {
  215. t.Fatal(err)
  216. }
  217. prefixArgs = []string{ctlBinPath, "--endpoints", clientURL, "--dial-timeout", dialTimeout.String()}
  218. // ensure added member has data from incoming snapshot
  219. for i := range kvs {
  220. if err = spawnWithExpect(append(prefixArgs, "get", kvs[i].key), kvs[i].val); err != nil {
  221. t.Fatal(err)
  222. }
  223. }
  224. if err = nepc.Stop(); err != nil {
  225. t.Fatal(err)
  226. }
  227. }