-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
299 lines (253 loc) · 6.28 KB
/
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package main
import (
"context"
"embed"
"encoding/json"
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"sync"
"time"
"github.com/dustin/go-humanize"
"github.com/jonboulle/clockwork"
"github.com/patrickmn/go-cache"
)
var (
stdout = flag.Bool("stdout", false, "Output root dir to stdout and quit")
basePath = flag.String("base_path", ".", "Base path")
port = flag.Int("port", 8099, "Listening port")
cacheDuration = flag.Duration("cache_duration", 30*time.Second, "Cache duration")
apologyTimeout = flag.Duration("apology_timeout", 2*time.Second, "Time after which to show 'this is taking a while'")
)
var pathCache *cache.Cache
var clock = clockwork.NewRealClock()
type reportEntry struct {
name string
bytes uint64
ratio float64
subdirs report
isDir bool
}
type report []reportEntry
type d3Data struct {
Name string `json:"name"`
Value uint64 `json:"value,omitempty"`
Children []d3Data `json:"children,omitempty"`
}
func (r report) toParentsAndValues(parent string, parents map[string]string, values map[string]uint64) {
for _, re := range r {
parents[re.name] = parent
if re.subdirs == nil {
values[re.name] = re.bytes
} else {
re.subdirs.toParentsAndValues(re.name, parents, values)
}
}
}
func (r report) toD3Data(name string) d3Data {
var result = d3Data{Name: name}
for _, child := range r {
var entry d3Data
if len(child.subdirs) == 0 {
entry.Name = child.name
entry.Value = child.bytes
} else {
entry = child.subdirs.toD3Data(child.name)
}
result.Children = append(result.Children, entry)
}
return result
}
func (r report) sum() uint64 {
var result uint64
for _, re := range r {
result += uint64(re.bytes)
}
return result
}
func walk(basePath, subPath string) report {
p := filepath.Join(basePath, subPath)
if pathCache != nil {
if result, found := pathCache.Get(p); found {
return result.(report)
}
}
dir, err := os.Open(p)
if err != nil {
log.Printf("Failed to open %s: %v", p, err)
return nil
}
defer dir.Close()
files, err := dir.Readdir(-1)
if err != nil {
log.Printf("Failed to readdir %s: %v", p, err)
return nil
}
result := make(report, len(files))
for i, file := range files {
result[i].name = filepath.Join(subPath, file.Name())
result[i].isDir = file.IsDir()
if file.IsDir() {
result[i].subdirs = walk(basePath, path.Join(subPath, file.Name()))
result[i].bytes = result[i].subdirs.sum()
} else {
result[i].bytes = uint64(file.Size())
}
}
sort.Slice(result, func(i, j int) bool { return result[i].bytes > result[j].bytes })
result.computeRatios()
if pathCache != nil {
pathCache.Set(p, result, cache.DefaultExpiration)
}
return result
}
func (r report) computeRatios() {
sum := float64(r.sum())
for i := range r {
r[i].ratio = float64(r[i].bytes) / sum
}
}
func fmtPercent(ratio float64) string {
return fmt.Sprintf("%.1f%%", ratio*100)
}
func main() {
flag.Parse()
pathCache = cache.New(*cacheDuration, *cacheDuration)
if *stdout {
walk(*basePath, "").output(os.Stdout)
return
}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticFiles))))
http.Handle("/", handler{basePath: *basePath})
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
}
//go:embed header.html table.html
var templateFiles embed.FS
var templates = template.Must(template.ParseFS(templateFiles, "*.html"))
//go:embed icicle.js
var staticFiles embed.FS
type humanReport []struct {
Name string
Percentage string
Size string
IsDir bool
}
func (r report) humanize() humanReport {
result := make(humanReport, len(r))
for i := range r {
result[i].Name = filepath.Base(r[i].name)
result[i].Percentage = fmtPercent(r[i].ratio)
result[i].Size = humanize.Bytes(r[i].bytes)
result[i].IsDir = r[i].isDir
}
return result
}
type handler struct {
basePath string
// For testing
artificialDelay time.Duration
}
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var wm sync.Mutex
requestedPath := r.FormValue("path")
if requestedPath == "" {
requestedPath = "/"
}
actualPath := path.Join(h.basePath, requestedPath)
var loadD3 = false
if r.FormValue("json") != "" {
w.Header().Add("Content-Type", "text/json")
rep := walk(actualPath, "").toD3Data(requestedPath)
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
if err := enc.Encode(rep); err != nil {
log.Printf("Internal error: %v", err)
http.Error(w, "Internal server error (see log)", http.StatusInternalServerError)
}
return
}
if r.FormValue("d3") != "" {
loadD3 = true
}
flusher := w.(http.Flusher)
if flusher == nil {
log.Println("Flusher not available for chunked encoding")
}
wm.Lock()
err := templates.ExecuteTemplate(w, "header.html", struct {
Path string
LoadD3 bool
}{
Path: requestedPath,
LoadD3: loadD3,
})
if err != nil {
log.Printf("Internal error: %v", err)
http.Error(w, "Internal server error (see log)", http.StatusInternalServerError)
}
if flusher != nil {
flusher.Flush()
}
wm.Unlock()
ctx, cancel := context.WithCancel(r.Context())
var wg sync.WaitGroup
defer wg.Wait()
wg.Add(1)
go func() {
defer wg.Done()
rep := walk(actualPath, "")
if h.artificialDelay > 0 {
clock.Sleep(h.artificialDelay)
}
var d3 d3Data
if loadD3 {
d3 = rep.toD3Data(requestedPath)
}
cancel()
wm.Lock()
err = templates.ExecuteTemplate(w, "table.html", struct {
Path string
Parent string
Report humanReport
D3Data d3Data
Total string
}{
Path: requestedPath,
Parent: path.Dir(requestedPath),
Report: rep.humanize(),
D3Data: d3,
Total: humanize.Bytes(rep.sum()),
})
if err != nil {
log.Printf("Internal error: %v", err)
http.Error(w, "Internal server error (see log)", http.StatusInternalServerError)
}
wm.Unlock()
}()
select {
case <-clock.After(*apologyTimeout):
wm.Lock()
fmt.Fprintln(w, "<p>Please wait, caches are cold...</p>")
if flusher != nil {
flusher.Flush()
}
wm.Unlock()
if h.artificialDelay > 0 {
// Allow fakeClock to block until we're done writing apology
clock.Sleep(1 * time.Second)
}
case <-ctx.Done():
}
}
func (r report) output(w io.Writer) {
for _, re := range r {
fmt.Fprintln(w, re.name, fmtPercent(re.ratio), humanize.Bytes(re.bytes))
}
}