snapshot_command.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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 command
  15. import (
  16. "context"
  17. "fmt"
  18. "path/filepath"
  19. "strings"
  20. "go.etcd.io/etcd/clientv3/snapshot"
  21. "github.com/spf13/cobra"
  22. "go.uber.org/zap"
  23. )
  24. const (
  25. defaultName = "default"
  26. defaultInitialAdvertisePeerURLs = "http://localhost:2380"
  27. )
  28. var (
  29. restoreCluster string
  30. restoreClusterToken string
  31. restoreDataDir string
  32. restoreWalDir string
  33. restorePeerURLs string
  34. restoreName string
  35. skipHashCheck bool
  36. )
  37. // NewSnapshotCommand returns the cobra command for "snapshot".
  38. func NewSnapshotCommand() *cobra.Command {
  39. cmd := &cobra.Command{
  40. Use: "snapshot <subcommand>",
  41. Short: "Manages etcd node snapshots",
  42. }
  43. cmd.AddCommand(NewSnapshotSaveCommand())
  44. cmd.AddCommand(NewSnapshotRestoreCommand())
  45. cmd.AddCommand(newSnapshotStatusCommand())
  46. return cmd
  47. }
  48. func NewSnapshotSaveCommand() *cobra.Command {
  49. return &cobra.Command{
  50. Use: "save <filename>",
  51. Short: "Stores an etcd node backend snapshot to a given file",
  52. Run: snapshotSaveCommandFunc,
  53. }
  54. }
  55. func newSnapshotStatusCommand() *cobra.Command {
  56. return &cobra.Command{
  57. Use: "status <filename>",
  58. Short: "Gets backend snapshot status of a given file",
  59. Long: `When --write-out is set to simple, this command prints out comma-separated status lists for each endpoint.
  60. The items in the lists are hash, revision, total keys, total size.
  61. `,
  62. Run: snapshotStatusCommandFunc,
  63. }
  64. }
  65. func NewSnapshotRestoreCommand() *cobra.Command {
  66. cmd := &cobra.Command{
  67. Use: "restore <filename> [options]",
  68. Short: "Restores an etcd member snapshot to an etcd directory",
  69. Run: snapshotRestoreCommandFunc,
  70. }
  71. cmd.Flags().StringVar(&restoreDataDir, "data-dir", "", "Path to the data directory")
  72. cmd.Flags().StringVar(&restoreWalDir, "wal-dir", "", "Path to the WAL directory (use --data-dir if none given)")
  73. cmd.Flags().StringVar(&restoreCluster, "initial-cluster", initialClusterFromName(defaultName), "Initial cluster configuration for restore bootstrap")
  74. cmd.Flags().StringVar(&restoreClusterToken, "initial-cluster-token", "etcd-cluster", "Initial cluster token for the etcd cluster during restore bootstrap")
  75. cmd.Flags().StringVar(&restorePeerURLs, "initial-advertise-peer-urls", defaultInitialAdvertisePeerURLs, "List of this member's peer URLs to advertise to the rest of the cluster")
  76. cmd.Flags().StringVar(&restoreName, "name", defaultName, "Human-readable name for this member")
  77. cmd.Flags().BoolVar(&skipHashCheck, "skip-hash-check", false, "Ignore snapshot integrity hash value (required if copied from data directory)")
  78. return cmd
  79. }
  80. func snapshotSaveCommandFunc(cmd *cobra.Command, args []string) {
  81. if len(args) != 1 {
  82. err := fmt.Errorf("snapshot save expects one argument")
  83. ExitWithError(ExitBadArgs, err)
  84. }
  85. lg, err := zap.NewProduction()
  86. if err != nil {
  87. ExitWithError(ExitError, err)
  88. }
  89. sp := snapshot.NewV3(lg)
  90. cfg := mustClientCfgFromCmd(cmd)
  91. // if user does not specify "--command-timeout" flag, there will be no timeout for snapshot save command
  92. ctx, cancel := context.WithCancel(context.Background())
  93. if isCommandTimeoutFlagSet(cmd) {
  94. ctx, cancel = commandCtx(cmd)
  95. }
  96. defer cancel()
  97. path := args[0]
  98. if err := sp.Save(ctx, *cfg, path); err != nil {
  99. ExitWithError(ExitInterrupted, err)
  100. }
  101. fmt.Printf("Snapshot saved at %s\n", path)
  102. }
  103. func snapshotStatusCommandFunc(cmd *cobra.Command, args []string) {
  104. if len(args) != 1 {
  105. err := fmt.Errorf("snapshot status requires exactly one argument")
  106. ExitWithError(ExitBadArgs, err)
  107. }
  108. initDisplayFromCmd(cmd)
  109. lg, err := zap.NewProduction()
  110. if err != nil {
  111. ExitWithError(ExitError, err)
  112. }
  113. sp := snapshot.NewV3(lg)
  114. ds, err := sp.Status(args[0])
  115. if err != nil {
  116. ExitWithError(ExitError, err)
  117. }
  118. display.DBStatus(ds)
  119. }
  120. func snapshotRestoreCommandFunc(cmd *cobra.Command, args []string) {
  121. if len(args) != 1 {
  122. err := fmt.Errorf("snapshot restore requires exactly one argument")
  123. ExitWithError(ExitBadArgs, err)
  124. }
  125. dataDir := restoreDataDir
  126. if dataDir == "" {
  127. dataDir = restoreName + ".etcd"
  128. }
  129. walDir := restoreWalDir
  130. if walDir == "" {
  131. walDir = filepath.Join(dataDir, "member", "wal")
  132. }
  133. lg, err := zap.NewProduction()
  134. if err != nil {
  135. ExitWithError(ExitError, err)
  136. }
  137. sp := snapshot.NewV3(lg)
  138. if err := sp.Restore(snapshot.RestoreConfig{
  139. SnapshotPath: args[0],
  140. Name: restoreName,
  141. OutputDataDir: dataDir,
  142. OutputWALDir: walDir,
  143. PeerURLs: strings.Split(restorePeerURLs, ","),
  144. InitialCluster: restoreCluster,
  145. InitialClusterToken: restoreClusterToken,
  146. SkipHashCheck: skipHashCheck,
  147. }); err != nil {
  148. ExitWithError(ExitError, err)
  149. }
  150. }
  151. func initialClusterFromName(name string) string {
  152. n := name
  153. if name == "" {
  154. n = defaultName
  155. }
  156. return fmt.Sprintf("%s=http://localhost:2380", n)
  157. }