defrag_command.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. "fmt"
  17. "os"
  18. "path/filepath"
  19. "time"
  20. "github.com/spf13/cobra"
  21. "go.etcd.io/etcd/mvcc/backend"
  22. )
  23. var (
  24. defragDataDir string
  25. )
  26. // NewDefragCommand returns the cobra command for "Defrag".
  27. func NewDefragCommand() *cobra.Command {
  28. cmd := &cobra.Command{
  29. Use: "defrag",
  30. Short: "Defragments the storage of the etcd members with given endpoints",
  31. Run: defragCommandFunc,
  32. }
  33. cmd.PersistentFlags().BoolVar(&epClusterEndpoints, "cluster", false, "use all endpoints from the cluster member list")
  34. cmd.Flags().StringVar(&defragDataDir, "data-dir", "", "Optional. If present, defragments a data directory not in use by etcd.")
  35. return cmd
  36. }
  37. func defragCommandFunc(cmd *cobra.Command, args []string) {
  38. if len(defragDataDir) > 0 {
  39. err := defragData(defragDataDir)
  40. if err != nil {
  41. fmt.Fprintf(os.Stderr, "Failed to defragment etcd data[%s] (%v)\n", defragDataDir, err)
  42. os.Exit(ExitError)
  43. }
  44. return
  45. }
  46. failures := 0
  47. c := mustClientFromCmd(cmd)
  48. for _, ep := range endpointsFromCluster(cmd) {
  49. ctx, cancel := commandCtx(cmd)
  50. _, err := c.Defragment(ctx, ep)
  51. cancel()
  52. if err != nil {
  53. fmt.Fprintf(os.Stderr, "Failed to defragment etcd member[%s] (%v)\n", ep, err)
  54. failures++
  55. } else {
  56. fmt.Printf("Finished defragmenting etcd member[%s]\n", ep)
  57. }
  58. }
  59. if failures != 0 {
  60. os.Exit(ExitError)
  61. }
  62. }
  63. func defragData(dataDir string) error {
  64. var be backend.Backend
  65. bch := make(chan struct{})
  66. dbDir := filepath.Join(dataDir, "member", "snap", "db")
  67. go func() {
  68. defer close(bch)
  69. be = backend.NewDefaultBackend(dbDir)
  70. }()
  71. select {
  72. case <-bch:
  73. case <-time.After(time.Second):
  74. fmt.Fprintf(os.Stderr, "waiting for etcd to close and release its lock on %q. "+
  75. "To defrag a running etcd instance, omit --data-dir.\n", dbDir)
  76. <-bch
  77. }
  78. return be.Defrag()
  79. }