-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
476 lines (403 loc) · 11.4 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"runtime"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/gorilla/mux"
"github.com/manifoldco/promptui"
cmap "github.com/orcaman/concurrent-map/v2"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"github.com/wagoodman/dive/dive"
"github.com/wagoodman/dive/dive/filetree"
"github.com/wagoodman/dive/dive/image"
)
func main() {
app := &cli.App{
Name: "docker-phobia",
Usage: "Analyze a Docker image",
Action: func(c *cli.Context) error {
var selectedImage string
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
}
if c.NArg() > 0 {
selectedImage = c.Args().Get(0)
} else {
images, err := cli.ImageList(ctx, types.ImageListOptions{})
if err != nil {
return err
}
sort.Slice(images, func(i, j int) bool {
return images[i].Created > images[j].Created
})
imageNames := make([]string, 0)
for _, image := range images {
if len(image.RepoTags) > 0 {
imageNames = append(imageNames, image.RepoTags[0])
}
}
searcher := func(input string, index int) bool {
image := imageNames[index]
name := strings.Replace(strings.ToLower(image), " ", "", -1)
input = strings.Replace(strings.ToLower(input), " ", "", -1)
return strings.Contains(name, input)
}
prompt := promptui.Select{
Label: "Select a Docker image",
Size: 20,
Searcher: searcher,
Items: imageNames,
}
_, selectedImage, err = prompt.Run()
if err != nil {
return err
}
}
selectedImage = strings.TrimSpace(selectedImage)
serveWebsite(selectedImage)
// Process the chosen Docker image
return nil
},
}
err := app.Run(os.Args)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func serveWebsite(imageStr string) {
router := mux.NewRouter()
router.Use(enableCORS)
router.HandleFunc("/analyze/{image:.*}", imageAnalyzerHandler).Methods("POST", "GET")
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(struct {
Version string `json:"version"`
Name string `json:"name"`
}{
Version: "1.0.0",
Name: "docker-phobia",
})
}).Methods("GET")
port, err := findOpenPort()
if err != nil {
log.Fatal(err)
}
go func() {
fmt.Printf("internal server listening on http://localhost:%d\n", port)
if err := http.ListenAndServe(":"+strconv.Itoa(port), router); err != nil {
log.Fatal(err)
}
}()
// Open the browser
baseURL := os.Getenv("DOCKER_PHOBIA_BASE_URL")
if baseURL == "" {
baseURL = "https://docker-phobia.vercel.app"
}
path := "/image/" + imageStr + "?port=" + strconv.Itoa(port)
println("opening the browser at", baseURL+path)
err = openBrowser(baseURL + path)
if err != nil {
// print the error but continue
logrus.Error(err)
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
os.Exit(0)
}
func openBrowser(url string) error {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
return err
}
func imageAnalyzerHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
_userImage := vars["image"]
_userImage = strings.TrimSpace(_userImage)
userImage, err := url.QueryUnescape(_userImage)
if err != nil {
logrus.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
println("analyzing image:", userImage)
output, err := analyzeImage(userImage)
if err != nil {
logrus.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
println("analyzed image:", userImage)
// Send a response with the json
w.Header().Set("Content-Type", "application/json")
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetIndent("", " ") // Use two spaces for indentation
enc.SetEscapeHTML(false)
// node.ComputeSize()
err = enc.Encode(output)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(buf.Bytes())
// finish
return
}
var imgCache = make(map[string]*image.Image)
var currentlyAnalyzing = cmap.New[bool]()
func analyzeImage(userImage string) (*JsonOutput, error) {
// Get the "image" parameter from the URL path
sourceStr := "docker"
value, ok := currentlyAnalyzing.Get(userImage)
if ok && value {
// wait until the image is done being analyzed
for {
value, ok := currentlyAnalyzing.Get(userImage)
if !ok || !value {
break
}
time.Sleep(1 * time.Second)
}
}
currentlyAnalyzing.Set(userImage, true)
defer func() {
currentlyAnalyzing.Remove(userImage)
}()
sourceType, imageStr := dive.DeriveImageSource(userImage)
if sourceType == dive.SourceUnknown {
sourceType = dive.ParseImageSource(sourceStr)
if sourceType == dive.SourceUnknown {
return nil, errors.Errorf("unable to determine image source: %v\n", sourceStr)
}
println("parsing image source", sourceStr, userImage)
imageStr = userImage
}
imageResolver, err := dive.GetImageResolver(sourceType)
if err != nil {
return nil, errors.Wrap(err, "unable to determine image provider")
}
var img *image.Image = imgCache[userImage]
// log the time it takes to fetch in seconds
start := time.Now()
if img == nil {
println("fetching image with resolver", sourceType.String())
img, err = imageResolver.Fetch(imageStr)
if err != nil {
return nil, errors.Wrap(err, "unable to resolve image")
}
imgCache[userImage] = img
}
fmt.Printf("fetched image in %d seconds\n", int(time.Since(start).Seconds()))
println("analyzing")
result, err := img.Analyze()
if err != nil {
return nil, fmt.Errorf("unable to analyze: %v", err)
}
// cache := filetree.NewComparer(result.RefTrees)
// errors := cache.BuildCache()
// if len(errors) > 0 {
// return nil, fmt.Errorf("unable to build cache: %d errors", len(errors))
// }
println("stacking trees")
newTree, pathErrors, err := filetree.StackTreeRange(result.RefTrees, 0, len(result.RefTrees)-1)
pathsToLayersIndex := make(map[string]int)
for idx := 1; idx < len(result.RefTrees)-1; idx++ {
// mergedTree.VisitDepthChildFirst(func(node *filetree.FileNode) error {
// node.Data.DiffType = filetree.Unmodified
// return nil
// }, nil)
mergedTree, pathErrors, err := filetree.StackTreeRange(result.RefTrees, 0, idx-1)
markPathErrors, err := mergedTree.CompareAndMark(result.RefTrees[idx])
pathErrors = append(pathErrors, markPathErrors...)
if err != nil {
logrus.Errorf("error while building tree: %+v", err)
return nil, err
}
mergedTree.VisitDepthChildFirst(func(node *filetree.FileNode) error {
if node.Data.DiffType == filetree.Added || node.Data.DiffType == filetree.Removed {
pathsToLayersIndex[node.Path()] = idx
}
return nil
}, nil)
}
if len(pathErrors) > 0 {
return nil, fmt.Errorf("expected no filepath errors, got %d", len(pathErrors))
}
// if err != nil {
// return nil, fmt.Errorf("unable to stack trees: %v", err)
// }
println("removing cycles")
node := RemoveCycles(newTree.Root)
allNodes := bfs(node)
for _, node := range allNodes {
if idx, ok := pathsToLayersIndex[node.Path]; ok {
node.Layer = idx
}
}
// sort layers by command
sort.Slice(result.Layers, func(i, j int) bool {
// if result.Layers[i].Index == result.Layers[j].Index {
// return result.Layers[i].Size < result.Layers[j].Size
// }
return result.Layers[i].Index < result.Layers[j].Index
})
layers := make([]Layer, len(result.Layers))
for i, layer := range result.Layers {
layers[i] = Layer{
Command: layer.Command,
}
}
output := JsonOutput{
Layers: layers,
Tree: node,
}
if output.Tree.Name == "" {
output.Tree.Name = "root"
}
return &output, nil
}
type Layer struct {
Command string `json:"command"`
}
func bfs(node *Node) []*Node {
var queue []*Node
var result []*Node
queue = append(queue, node)
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
result = append(result, current)
for _, child := range current.Children {
queue = append(queue, child)
}
}
return result
}
type JsonOutput struct {
Layers []Layer `json:"layers"`
Tree *Node `json:"tree"`
}
// Node represents a node in the new tree without cycles.
// rename all fields to lowercase in json output
type Node struct {
Size int32 `json:"value,omitempty"`
Name string `json:"name"`
Deleted bool `json:"deleted,omitempty"`
// omit this in json
Data filetree.NodeData `json:"-"`
Path string `json:"-"`
Children []*Node `json:"children,omitempty"`
Layer int `json:"layer,omitempty"`
}
// func (node *Node) ComputeSize() {
// for _, child := range node.Children {
// child.ComputeSize()
// node.Size += child.Size
// }
// if len(node.Children) == 0 {
// node.Size += int32(node.Data.FileInfo.Size)
// }
// }
func RemoveCycles(root *filetree.FileNode) *Node {
visited := make(map[*filetree.FileNode]bool)
return removeCyclesRecursive(root, visited, nil)[0]
}
func removeCyclesRecursive(node *filetree.FileNode, visited map[*filetree.FileNode]bool, parent *filetree.FileNode) []*Node {
if _, ok := visited[node]; ok {
return []*Node{}
}
if len(node.Children) == 0 && node.Data.DiffType != filetree.Removed && node.Data.FileInfo.Size < 100 {
return []*Node{}
}
visited[node] = true
defer delete(visited, node)
// if node.Data.DiffType == filetree.Removed {
// return nil
// }
size := int32(node.Data.FileInfo.Size)
if node.Data.FileInfo.IsDir {
size = 0
}
newNode := &Node{
Size: size,
Name: node.Name,
Data: node.Data,
Path: node.Path(),
Deleted: node.Data.DiffType == filetree.Removed,
}
for _, child := range node.Children {
childNodes := removeCyclesRecursive(child, visited, node)
newNode.Children = append(newNode.Children, childNodes...)
sort.Slice(newNode.Children, func(i, j int) bool {
return newNode.Children[i].Name < newNode.Children[j].Name
})
}
return []*Node{newNode}
}
func enableCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
// Preflight request
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func findOpenPort() (int, error) {
// Check if port 8080 is available
addr, err := net.ResolveTCPAddr("tcp", "localhost:8080")
if err != nil {
return 0, err
}
l, err := net.ListenTCP("tcp", addr)
if err == nil {
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
// If port 8080 is not available, find an open port using the zero trick
addr, err = net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}
l, err = net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}