defrag_command.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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/coreos/etcd/mvcc/backend"
  21. "github.com/spf13/cobra"
  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.Flags().StringVar(&defragDataDir, "data-dir", "", "Optional. If present, defragments a data directory not in use by etcd.")
  34. return cmd
  35. }
  36. func defragCommandFunc(cmd *cobra.Command, args []string) {
  37. if len(defragDataDir) > 0 {
  38. err := defragData(defragDataDir)
  39. if err != nil {
  40. fmt.Fprintf(os.Stderr, "Failed to defragment etcd data[%s] (%v)\n", defragDataDir, err)
  41. os.Exit(ExitError)
  42. }
  43. return
  44. }
  45. failures := 0
  46. c := mustClientFromCmd(cmd)
  47. for _, ep := range c.Endpoints() {
  48. ctx, cancel := commandCtx(cmd)
  49. _, err := c.Defragment(ctx, ep)
  50. cancel()
  51. if err != nil {
  52. fmt.Fprintf(os.Stderr, "Failed to defragment etcd member[%s] (%v)\n", ep, err)
  53. failures++
  54. } else {
  55. fmt.Printf("Finished defragmenting etcd member[%s]\n", ep)
  56. }
  57. }
  58. if failures != 0 {
  59. os.Exit(ExitError)
  60. }
  61. }
  62. func defragData(dataDir string) error {
  63. var be backend.Backend
  64. bch := make(chan struct{})
  65. dbDir := filepath.Join(dataDir, "member", "snap", "db")
  66. go func() {
  67. defer close(bch)
  68. be = backend.NewDefaultBackend(dbDir)
  69. }()
  70. select {
  71. case <-bch:
  72. case <-time.After(time.Second):
  73. fmt.Fprintf(os.Stderr, "waiting for etcd to close and release its lock on %q. "+
  74. "To defrag a running etcd instance, omit --data-dir.\n", dbDir)
  75. <-bch
  76. }
  77. return be.Defrag()
  78. }