forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recycle.go
70 lines (61 loc) · 1.87 KB
/
recycle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package recycle
import (
"fmt"
"io"
"os"
"github.com/spf13/cobra"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)
var (
recyclerLong = templates.LongDesc(`
Recycle a volume
This command will recycle a single volume provided as an argument.`)
)
// NewCommandRecycle provides a CLI handler for recycling volumes
func NewCommandRecycle(name string, out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: fmt.Sprintf("%s DIRNAME", name),
Short: "Recycle a directory",
Long: recyclerLong,
Run: func(c *cobra.Command, args []string) {
if len(args) != 1 {
kcmdutil.CheckErr(kcmdutil.UsageErrorf(c, "a directory to recycle is required as the only argument"))
}
if err := Recycle(args[0]); err != nil {
kcmdutil.CheckErr(fmt.Errorf("recycle failed: %v", err))
}
if err := CheckEmpty(args[0]); err != nil {
// Recycler did not delete everything, some other pod has
// probably written some data there. Report an error and
// Kubernetes will try to recycle the volume again in few
// seconds.
kcmdutil.CheckErr(fmt.Errorf("recycle failed: %v", err))
}
fmt.Fprintln(out, "Scrub ok")
},
}
return cmd
}
// Recycle recursively deletes files and folders within the given path. It does not delete the path itself.
func Recycle(dir string) error {
return newWalker(func(path string, info os.FileInfo) error {
// Leave the root dir alone
if path == dir {
return nil
}
// Delete all subfiles/subdirs
return os.Remove(path)
}).Walk(dir)
}
// CheckEmpty returns error if specified directory is not empty.
func CheckEmpty(dir string) error {
return newWalker(func(path string, info os.FileInfo) error {
// Leave the root dir alone
if path == dir {
return nil
}
// Report any other existing file as error
return fmt.Errorf("Recycled volume is not empty")
}).Walk(dir)
}