snapshot_command.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. // Copyright 2016 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 command
  15. import (
  16. "fmt"
  17. "io"
  18. "os"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra"
  20. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  21. "github.com/coreos/etcd/clientv3"
  22. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  23. )
  24. // NewSnapshotCommand returns the cobra command for "snapshot".
  25. func NewSnapshotCommand() *cobra.Command {
  26. return &cobra.Command{
  27. Use: "snapshot [filename]",
  28. Short: "Snapshot streams a point-in-time snapshot of the store",
  29. Run: snapshotCommandFunc,
  30. }
  31. }
  32. // snapshotCommandFunc watches for the length of the entire store and records
  33. // to a file.
  34. func snapshotCommandFunc(cmd *cobra.Command, args []string) {
  35. switch {
  36. case len(args) == 0:
  37. snapshotToStdout(mustClient(cmd))
  38. case len(args) == 1:
  39. snapshotToFile(mustClient(cmd), args[0])
  40. default:
  41. err := fmt.Errorf("snapshot takes at most one argument")
  42. ExitWithError(ExitBadArgs, err)
  43. }
  44. }
  45. // snapshotToStdout streams a snapshot over stdout
  46. func snapshotToStdout(c *clientv3.Client) {
  47. // must explicitly fetch first revision since no retry on stdout
  48. wapi := clientv3.NewWatcher(c)
  49. defer wapi.Close()
  50. wr := <-wapi.WatchPrefix(context.TODO(), "", 1)
  51. if len(wr.Events) > 0 {
  52. wr.CompactRevision = 1
  53. }
  54. if rev := snapshot(os.Stdout, c, wr.CompactRevision); rev != 0 {
  55. err := fmt.Errorf("snapshot interrupted by compaction %v", rev)
  56. ExitWithError(ExitInterrupted, err)
  57. }
  58. }
  59. // snapshotToFile atomically writes a snapshot to a file
  60. func snapshotToFile(c *clientv3.Client, path string) {
  61. partpath := path + ".part"
  62. f, err := os.Create(partpath)
  63. defer f.Close()
  64. if err != nil {
  65. exiterr := fmt.Errorf("could not open %s (%v)", partpath, err)
  66. ExitWithError(ExitBadArgs, exiterr)
  67. }
  68. rev := int64(1)
  69. for rev != 0 {
  70. f.Seek(0, 0)
  71. f.Truncate(0)
  72. rev = snapshot(f, c, rev)
  73. }
  74. f.Sync()
  75. if err := os.Rename(partpath, path); err != nil {
  76. exiterr := fmt.Errorf("could not rename %s to %s (%v)", partpath, path, err)
  77. ExitWithError(ExitIO, exiterr)
  78. }
  79. }
  80. // snapshot reads all of a watcher; returns compaction revision if incomplete
  81. // TODO: stabilize snapshot format
  82. func snapshot(w io.Writer, c *clientv3.Client, rev int64) int64 {
  83. wapi := clientv3.NewWatcher(c)
  84. defer wapi.Close()
  85. // get all events since revision (or get non-compacted revision, if
  86. // rev is too far behind)
  87. wch := wapi.WatchPrefix(context.TODO(), "", rev)
  88. for wr := range wch {
  89. if len(wr.Events) == 0 {
  90. return wr.CompactRevision
  91. }
  92. for _, ev := range wr.Events {
  93. fmt.Fprintln(w, ev)
  94. }
  95. rev := wr.Events[len(wr.Events)-1].Kv.ModRevision
  96. if rev >= wr.Header.Revision {
  97. break
  98. }
  99. }
  100. // get base state at rev
  101. kapi := clientv3.NewKV(c)
  102. key := "\x00"
  103. for {
  104. kvs, err := kapi.Get(
  105. context.TODO(),
  106. key,
  107. clientv3.WithFromKey(),
  108. clientv3.WithRev(rev+1),
  109. clientv3.WithLimit(1000))
  110. if err == v3rpc.ErrCompacted {
  111. // will get correct compact revision on retry
  112. return rev + 1
  113. } else if err != nil {
  114. // failed for some unknown reason, retry on same revision
  115. return rev
  116. }
  117. for _, kv := range kvs.Kvs {
  118. fmt.Fprintln(w, kv)
  119. }
  120. if !kvs.More {
  121. break
  122. }
  123. // move to next key
  124. key = string(append(kvs.Kvs[len(kvs.Kvs)-1].Key, 0))
  125. }
  126. return 0
  127. }