/
du-main.go
201 lines (173 loc) · 4.97 KB
/
du-main.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/*
* MinIO Client (C) 2019 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"fmt"
"net/url"
"strings"
humanize "github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/minio/cli"
json "github.com/minio/mc/pkg/colorjson"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio/pkg/console"
)
// du specific flags.
var (
duFlags = []cli.Flag{
cli.IntFlag{
Name: "depth, d",
Usage: "print the total for a folder prefix only if it is N or fewer levels below the command line argument",
},
cli.BoolFlag{
Name: "recursive, r",
Usage: "recursively print the total for a folder prefix",
},
}
)
// Summarize disk usage.
var duCmd = cli.Command{
Name: "du",
Usage: "summarize disk usage recursively",
Action: mainDu,
Before: setGlobalsFromContext,
Flags: append(append(duFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
ENVIRONMENT VARIABLES:
OSS_ENCRYPT_KEY: list of comma delimited prefix=secret values
EXAMPLES:
1. Summarize disk usage of 'jazz-songs' bucket recursively.
{{.Prompt}} {{.HelpName}} s3/jazz-songs
2. Summarize disk usage of 'louis' prefix in 'jazz-songs' bucket upto two levels.
{{.Prompt}} {{.HelpName}} --depth=2 s3/jazz-songs/louis/
`,
}
// Structured message depending on the type of console.
type duMessage struct {
Prefix string `json:"prefix"`
Size int64 `json:"size"`
Status string `json:"status"`
}
// Colorized message for console printing.
func (r duMessage) String() string {
humanSize := strings.Join(strings.Fields(humanize.IBytes(uint64(r.Size))), "")
return fmt.Sprintf("%s\t%s", console.Colorize("Size", humanSize),
console.Colorize("Prefix", r.Prefix))
}
// JSON'ified message for scripting.
func (r duMessage) JSON() string {
msgBytes, e := json.MarshalIndent(r, "", " ")
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(msgBytes)
}
func du(urlStr string, depth int, encKeyDB map[string][]prefixSSEPair) (int64, error) {
targetAlias, targetURL, _ := mustExpandAlias(urlStr)
if !strings.HasSuffix(targetURL, "/") {
targetURL += "/"
}
clnt, pErr := newClientFromAlias(targetAlias, targetURL)
if pErr != nil {
errorIf(pErr.Trace(urlStr), "Failed to summarize disk usage `"+urlStr+"`.")
return 0, exitStatus(globalErrorExitStatus) // End of journey.
}
isRecursive := false
isIncomplete := false
contentCh := clnt.List(globalContext, isRecursive, isIncomplete, false, DirFirst)
size := int64(0)
for content := range contentCh {
if content.Err != nil {
switch content.Err.ToGoError().(type) {
// handle this specifically for filesystem related errors.
case BrokenSymlink, TooManyLevelsSymlink, PathNotFound, ObjectOnGlacier:
continue
case PathInsufficientPermission:
errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.")
continue
}
errorIf(content.Err.Trace(urlStr), "Failed to find disk usage of `"+urlStr+"` recursively.")
return 0, exitStatus(globalErrorExitStatus)
}
if content.URL.String() == targetURL {
continue
}
if content.Type.IsDir() {
depth := depth
if depth > 0 {
depth--
}
subDirAlias := content.URL.Path
if targetAlias != "" {
subDirAlias = targetAlias + "/" + content.URL.Path
}
used, err := du(subDirAlias, depth, encKeyDB)
if err != nil {
return 0, err
}
size += used
} else {
size += content.Size
}
}
if depth != 0 {
u, err := url.Parse(targetURL)
if err != nil {
panic(err)
}
printMsg(duMessage{
Prefix: strings.Trim(u.Path, "/"),
Size: size,
Status: "success",
})
}
return size, nil
}
// main for du command.
func mainDu(ctx *cli.Context) error {
if !ctx.Args().Present() {
cli.ShowCommandHelpAndExit(ctx, "du", 1)
}
console.SetColor("Prefix", color.New(color.FgCyan, color.Bold))
console.SetColor("Size", color.New(color.FgYellow))
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// du specific flags.
depth := ctx.Int("depth")
if depth == 0 {
if ctx.Bool("recursive") {
if !ctx.IsSet("depth") {
depth = -1
}
} else {
depth = 1
}
}
// Set color.
console.SetColor("Remove", color.New(color.FgGreen, color.Bold))
var duErr error
for _, urlStr := range ctx.Args() {
if _, err := du(urlStr, depth, encKeyDB); duErr == nil {
duErr = err
}
}
return duErr
}