forked from justone/dockviz
/
images.go
311 lines (254 loc) · 7.5 KB
/
images.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
package main
import (
"github.com/fsouza/go-dockerclient"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
)
type Image struct {
Id string
ParentId string `json:",omitempty"`
RepoTags []string `json:",omitempty"`
VirtualSize int64
Size int64
Created int64
}
type ImagesCommand struct {
Dot bool `short:"d" long:"dot" description:"Show image information as Graphviz dot."`
Tree bool `short:"t" long:"tree" description:"Show image information as tree."`
Short bool `short:"s" long:"short" description:"Show short summary of images (repo name and list of tags)."`
NoTruncate bool `short:"n" long:"no-trunc" description:"Don't truncate the image IDs."`
}
var imagesCommand ImagesCommand
func (x *ImagesCommand) Execute(args []string) error {
var images *[]Image
stat, err := os.Stdin.Stat()
if err != nil {
return fmt.Errorf("error reading stdin stat", err)
}
if (stat.Mode() & os.ModeCharDevice) == 0 {
// read in stdin
stdin, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("error reading all input", err)
}
images, err = parseImagesJSON(stdin)
if err != nil {
return err
}
} else {
client, err := connect()
if err != nil {
return err
}
clientImages, err := client.ListImages(docker.ListImagesOptions{All: true})
if err != nil {
if in_docker := os.Getenv("IN_DOCKER"); len(in_docker) > 0 {
return fmt.Errorf("Unable to access Docker socket, please run like this:\n docker run --rm -v /var/run/docker.sock:/var/run/docker.sock nate/dockviz images <args>\nFor more help, run 'dockviz help'")
} else {
return fmt.Errorf("Unable to connect: %s\nFor help, run 'dockviz help'", err)
}
}
var ims []Image
for _, image := range clientImages {
// fmt.Println(image)
ims = append(ims, Image{
image.ID,
image.ParentID,
image.RepoTags,
image.VirtualSize,
image.Size,
image.Created,
})
}
images = &ims
}
if imagesCommand.Dot {
fmt.Printf(jsonToDot(images))
} else if imagesCommand.Tree {
var startImage = ""
if len(args) > 0 {
// attempt to find the start image, which can be specified as an
// image ID or a repository name
startImageArg := args[0]
startImageRepo := args[0]
// in case a repo name was specified, append ":latest" if it isn't
// already there
if !strings.HasSuffix(startImageRepo, ":latest") {
startImageRepo = fmt.Sprintf("%s:latest", startImageRepo)
}
IMAGES:
for _, image := range *images {
// check if the start image arg matches an image id
if strings.Index(image.Id, startImageArg) == 0 {
startImage = image.Id
break IMAGES
}
// check if the start image arg matches an repository name
if image.RepoTags[0] != "<none>:<none>" {
for _, repotag := range image.RepoTags {
if repotag == startImageRepo {
startImage = image.Id
break IMAGES
}
}
}
}
if startImage == "" {
return fmt.Errorf("Unable to find image %s.", startImageArg)
}
}
fmt.Printf(jsonToTree(images, startImage, imagesCommand.NoTruncate))
} else if imagesCommand.Short {
fmt.Printf(jsonToShort(images))
} else {
return fmt.Errorf("Please specify either --dot, --tree, or --short")
}
return nil
}
func jsonToTree(images *[]Image, startImageArg string, noTrunc bool) string {
var buffer bytes.Buffer
var startImage Image
var roots []Image
var byParent = make(map[string][]Image)
for _, image := range *images {
if image.ParentId == "" {
roots = append(roots, image)
} else {
if children, exists := byParent[image.ParentId]; exists {
byParent[image.ParentId] = append(children, image)
} else {
byParent[image.ParentId] = []Image{image}
}
}
if startImageArg != "" {
if startImageArg == image.Id || startImageArg == truncate(image.Id) {
startImage = image
}
for _, repotag := range image.RepoTags {
if repotag == startImageArg {
startImage = image
}
}
}
}
if startImageArg != "" {
WalkTree(&buffer, noTrunc, []Image{startImage}, byParent, "")
} else {
WalkTree(&buffer, noTrunc, roots, byParent, "")
}
return buffer.String()
}
func WalkTree(buffer *bytes.Buffer, noTrunc bool, images []Image, byParent map[string][]Image, prefix string) {
if len(images) > 1 {
length := len(images)
for index, image := range images {
if index+1 == length {
PrintTreeNode(buffer, noTrunc, image, prefix+"└─")
if subimages, exists := byParent[image.Id]; exists {
WalkTree(buffer, noTrunc, subimages, byParent, prefix+" ")
}
} else {
PrintTreeNode(buffer, noTrunc, image, prefix+"├─")
if subimages, exists := byParent[image.Id]; exists {
WalkTree(buffer, noTrunc, subimages, byParent, prefix+"│ ")
}
}
}
} else {
for _, image := range images {
PrintTreeNode(buffer, noTrunc, image, prefix+"└─")
if subimages, exists := byParent[image.Id]; exists {
WalkTree(buffer, noTrunc, subimages, byParent, prefix+" ")
}
}
}
}
func PrintTreeNode(buffer *bytes.Buffer, noTrunc bool, image Image, prefix string) {
var imageID string
if noTrunc {
imageID = image.Id
} else {
imageID = truncate(image.Id)
}
buffer.WriteString(fmt.Sprintf("%s%s Virtual Size: %s", prefix, imageID, humanSize(image.VirtualSize)))
if image.RepoTags[0] != "<none>:<none>" {
buffer.WriteString(fmt.Sprintf(" Tags: %s\n", strings.Join(image.RepoTags, ", ")))
} else {
buffer.WriteString(fmt.Sprintf("\n"))
}
}
func humanSize(raw int64) string {
sizes := []string{"B", "KB", "MB", "GB", "TB"}
rawFloat := float64(raw)
ind := 0
for {
if rawFloat < 1000 {
break
} else {
rawFloat = rawFloat / 1000
ind = ind + 1
}
}
return fmt.Sprintf("%.01f %s", rawFloat, sizes[ind])
}
func truncate(id string) string {
return id[0:12]
}
func parseImagesJSON(rawJSON []byte) (*[]Image, error) {
var images []Image
err := json.Unmarshal(rawJSON, &images)
if err != nil {
return nil, fmt.Errorf("Error reading JSON: ", err)
}
return &images, nil
}
func jsonToDot(images *[]Image) string {
var buffer bytes.Buffer
buffer.WriteString("digraph docker {\n")
for _, image := range *images {
if image.ParentId == "" {
buffer.WriteString(fmt.Sprintf(" base -> \"%s\" [style=invis]\n", truncate(image.Id)))
} else {
buffer.WriteString(fmt.Sprintf(" \"%s\" -> \"%s\"\n", truncate(image.ParentId), truncate(image.Id)))
}
if image.RepoTags[0] != "<none>:<none>" {
buffer.WriteString(fmt.Sprintf(" \"%s\" [label=\"%s\\n%s\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n", truncate(image.Id), truncate(image.Id), strings.Join(image.RepoTags, "\\n")))
}
}
buffer.WriteString(" base [style=invisible]\n}\n")
return buffer.String()
}
func jsonToShort(images *[]Image) string {
var buffer bytes.Buffer
var byRepo = make(map[string][]string)
for _, image := range *images {
for _, repotag := range image.RepoTags {
if repotag != "<none>:<none>" {
// parse the repo name and tag name out
// tag is after the last colon
lastColonIndex := strings.LastIndex(repotag, ":")
tagname := repotag[lastColonIndex+1:]
reponame := repotag[0:lastColonIndex]
if tags, exists := byRepo[reponame]; exists {
byRepo[reponame] = append(tags, tagname)
} else {
byRepo[reponame] = []string{tagname}
}
}
}
}
for repo, tags := range byRepo {
buffer.WriteString(fmt.Sprintf("%s: %s\n", repo, strings.Join(tags, ", ")))
}
return buffer.String()
}
func init() {
parser.AddCommand("images",
"Visualize docker images.",
"",
&imagesCommand)
}