-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocker-ps.10s.go
463 lines (400 loc) · 11.1 KB
/
docker-ps.10s.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
// <bitbar.title>docker-ps</bitbar.title>
// <bitbar.version>v1.0</bitbar.version>
// <bitbar.author>Alexey Palazhchenko</bitbar.author>
// <bitbar.author.github>AlekSi</bitbar.author.github>
// <bitbar.desc>Displays statuses of local Docker containers.</bitbar.desc>
// <bitbar.dependencies>go,docker</bitbar.dependencies>
// <bitbar.abouturl>https://github.com/AlekSi/docker-ps-bitbar</bitbar.abouturl>
package main
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"sort"
"strings"
"time"
"golang.org/x/sync/errgroup"
)
const dockerBin = "/usr/local/bin/docker"
type containerType int
const (
Single containerType = iota
Group
Compose
Kubernetes
Minikube
Talos
)
type project struct {
typ containerType
name string
}
// container contains parsed `docker ps` output for a single container.
type container struct {
Command string `json:"Command"`
CreatedAt string `json:"CreatedAt"`
ID string `json:"ID"`
Image string `json:"Image"`
Labels string `json:"Labels"`
LocalVolumes string `json:"LocalVolumes"`
Mounts string `json:"Mounts"`
Names string `json:"Names"`
Networks string `json:"Networks"`
Ports string `json:"Ports"`
RunningFor string `json:"RunningFor"`
Size string `json:"Size"`
State string `json:"State"`
Status string `json:"Status"`
project project
}
// fill sets project field, and may also change other fields.
func (c *container) fill() {
c.project.typ = Single
for _, part := range strings.Split(c.Labels, ",") {
pair := strings.Split(part, "=")
if len(pair) != 2 {
continue
}
k, v := pair[0], pair[1]
switch k {
case "com.github.AlekSi.docker-ps.group":
c.project.typ = Group
c.project.name = v
case "com.docker.compose.project":
c.project.typ = Compose
c.project.name = v
case "io.kubernetes.pod.namespace":
c.project.typ = Kubernetes
c.project.name = v
c.Image = "" // remove very long image name with sha256 hash tag
case "name.minikube.sigs.k8s.io":
c.project.typ = Minikube
c.project.name = v
c.Image = "" // remove very long image name with sha256 hash tag
case "talos.cluster.name":
c.project.typ = Talos
c.project.name = v
}
if c.project.name != "" {
return
}
}
}
func (c *container) createdAt() time.Time {
t, _ := time.Parse("2006-01-02 15:04:05 -0700 MST", c.CreatedAt)
return t
}
func (c *container) running() bool {
return c.State == "running" || strings.HasPrefix(c.Status, "Up ")
}
// containerLs returns all containers sorted by "project" (Docker Compose project, Kubernetes namespace,
// Minikube profile name, Talos cluster) and name.
func containerLs() ([]container, error) {
cmd := exec.Command(dockerBin, "container", "ls", "--all", "--no-trunc", "--format={{json .}}")
cmd.Stderr = os.Stderr
b, err := cmd.Output()
if err != nil {
return nil, err
}
var containers []container
d := json.NewDecoder(bytes.NewReader(b))
for {
var c container
if err = d.Decode(&c); err != nil {
if err == io.EOF {
break
}
return nil, err
}
c.fill()
containers = append(containers, c)
}
sort.Slice(containers, func(i int, j int) bool {
if containers[i].project.typ != containers[j].project.typ {
return containers[i].project.typ < containers[j].project.typ
}
if containers[i].project.name != containers[j].project.name {
return containers[i].project.name < containers[j].project.name
}
return containers[i].Names < containers[j].Names
})
return containers, nil
}
// network contains parsed `docker network ls` output for a single network.
type network struct {
CreatedAt string `json:"CreatedAt"`
Driver string `json:"Driver"`
ID string `json:"ID"`
Name string `json:"Name"`
Scope string `json:"Scope"`
}
// networkLs returns all networks.
func networkLs() ([]network, error) {
cmd := exec.Command(dockerBin, "network", "ls", "--no-trunc", "--format={{json .}}")
cmd.Stderr = os.Stderr
b, err := cmd.Output()
if err != nil {
return nil, err
}
var networks []network
d := json.NewDecoder(bytes.NewReader(b))
for {
var n network
if err = d.Decode(&n); err != nil {
if err == io.EOF {
break
}
return nil, err
}
networks = append(networks, n)
}
sort.Slice(networks, func(i int, j int) bool {
if networks[i].Driver != networks[j].Driver {
return networks[i].Driver < networks[j].Driver
}
return networks[i].Name < networks[j].Name
})
return networks, nil
}
// volume contains parsed `docker volume ls` output for a single volume.
type volume struct {
Driver string `json:"Driver"`
Name string `json:"Name"`
}
func (v *volume) anonymous() bool {
if v.Driver != "local" {
return false
}
if len(v.Name) != 64 {
return false
}
_, err := hex.DecodeString(v.Name)
return err == nil
}
// volumeLs returns all volumes.
func volumeLs() ([]volume, error) {
cmd := exec.Command(dockerBin, "volume", "ls", "--format={{json .}}")
cmd.Stderr = os.Stderr
b, err := cmd.Output()
if err != nil {
return nil, err
}
var volumes []volume
d := json.NewDecoder(bytes.NewReader(b))
for {
var v volume
if err = d.Decode(&v); err != nil {
if err == io.EOF {
break
}
return nil, err
}
volumes = append(volumes, v)
}
sort.Slice(volumes, func(i int, j int) bool {
if volumes[i].Driver != volumes[j].Driver {
return volumes[i].Driver < volumes[j].Driver
}
return volumes[i].Name < volumes[j].Name
})
return volumes, nil
}
func containerCmd(command, projectName string) {
containers, err := containerLs()
if err != nil {
log.Fatal(err)
}
var ids []string
for _, c := range containers {
if projectName != "" && projectName != c.project.name {
continue
}
var add bool
switch command {
case "start", "rm":
add = !c.running()
case "restart":
add = true
case "stop", "kill":
add = c.running()
default:
log.Fatalf("Unexpected command %s.", command)
}
if add {
ids = append(ids, c.ID)
}
}
if len(ids) == 0 {
return
}
args := []string{command}
if command == "rm" {
args = append(args, "--force", "--volumes")
}
args = append(args, ids...)
cmd := exec.Command(dockerBin, args...)
log.Print(strings.Join(cmd.Args, " "))
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
log.Fatal(err)
}
}
func pruneCmd() {
for _, cmdline := range []string{
"buildx prune --force",
"system prune --force --volumes",
} {
cmd := exec.Command(dockerBin, strings.Split(cmdline, " ")...)
log.Print(strings.Join(cmd.Args, " "))
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Print(err)
}
}
}
func defaultCmd(ctx context.Context) {
bin, _ := os.Executable()
var containers []container
var networks []network
var volumes []volume
g, ctx := errgroup.WithContext(ctx)
_ = ctx // TODO
g.Go(func() error {
var err error
containers, err = containerLs()
return err
})
g.Go(func() error {
var err error
networks, err = networkLs()
return err
})
g.Go(func() error {
var err error
volumes, err = volumeLs()
return err
})
if err := g.Wait(); err != nil {
log.Fatal(err)
}
if len(containers) == 0 {
fmt.Println("🐳")
} else {
var total, running int
for _, c := range containers {
total++
if c.running() {
running++
}
}
fmt.Printf("🐳%d/%d\n", running, total)
}
fmt.Println("---")
var lastProjectName string
for _, c := range containers {
if lastProjectName != c.project.name {
lastProjectName = c.project.name
fmt.Println("---")
switch c.project.typ {
case Group:
fmt.Printf("🐳 %s\n", lastProjectName)
case Compose:
fmt.Printf("🐙 %s\n", lastProjectName)
fmt.Printf("-- ▶️ Start all | bash=%q param1=-project=%s param2=start terminal=false refresh=true\n", bin, lastProjectName)
fmt.Printf("-- 🔄 Restart all | bash=%q param1=-project=%s param2=restart terminal=false refresh=true\n", bin, lastProjectName)
fmt.Printf("-- ⏹ Stop all | bash=%q param1=-project=%s param2=stop terminal=false refresh=true\n", bin, lastProjectName)
fmt.Printf("-- ⏬ Stop and remove all | bash=%q param1=-project=%s param2=kill param3=rm terminal=false refresh=true\n", bin, lastProjectName)
case Kubernetes:
fmt.Printf("☸️ %s\n", lastProjectName)
case Minikube:
fmt.Printf("📦 %s\n", lastProjectName)
case Talos:
fmt.Printf("🔺 %s\n", lastProjectName)
fmt.Printf("-- ▶️ Start all | bash=%q param1=-project=%s param2=start terminal=false refresh=true\n", bin, lastProjectName)
fmt.Printf("-- ⏹ Stop all | bash=%q param1=-project=%s param2=stop terminal=false refresh=true\n", bin, lastProjectName)
fmt.Printf("-- 🔄 Restart all | bash=%q param1=-project=%s param2=restart terminal=false refresh=true\n", bin, lastProjectName)
fmt.Printf("-- ⏬ Stop and remove all | bash=%q param1=-project=%s param2=kill param3=rm terminal=false refresh=true\n", bin, lastProjectName)
default:
log.Fatalf("Unexpected project type %v.", c.project.typ)
}
}
icon := "🐳"
if strings.HasPrefix(c.Image, "moby/buildkit:") {
icon = "⚙️"
}
fmt.Printf("%s %s ", icon, c.Names)
if c.Image != "" {
fmt.Printf("(%s) ", c.Image)
}
if c.running() {
fmt.Printf("| color=green bash=%q param1=stop param2=%s terminal=false refresh=true\n", dockerBin, c.ID)
} else {
fmt.Printf("| color=red bash=%q param1=start param2=%s terminal=false refresh=true\n", dockerBin, c.ID)
}
}
if len(networks) != 0 {
fmt.Println("---")
msg := fmt.Sprintf("%d network", len(networks))
if len(networks) > 1 {
msg += "s"
}
fmt.Println(msg)
for _, n := range networks {
fmt.Printf("%s (%s)\n", n.Name, n.Driver)
}
}
if len(volumes) != 0 {
fmt.Println("---")
msg := fmt.Sprintf("%d volume", len(volumes))
if len(volumes) > 1 {
msg += "s"
}
fmt.Println(msg)
var anonymous int
for _, v := range volumes {
if v.anonymous() {
anonymous++
continue
}
fmt.Printf("%s (%s)\n", v.Name, v.Driver)
}
if anonymous != 0 {
fmt.Printf("%d anonymous\n", anonymous)
}
}
if bin != "" {
fmt.Println("---")
fmt.Printf("⭕️ Stop all containers | bash=%q param1=stop terminal=false refresh=true\n", bin)
fmt.Printf("🛑 Remove stopped containers | bash=%q param1=rm terminal=false refresh=true\n", bin)
fmt.Printf("⛔️ Prune orphan data | bash=%q param1=-prune terminal=false refresh=true\n", bin)
fmt.Printf("📛 Stop, remove and and prune everything | bash=%q param1=-prune param2=kill terminal=false refresh=true\n", bin)
}
}
func main() {
projectF := flag.String("project", "", `"project" (Docker Compose project, Kubernetes namespace, Minikube profile name, Talos cluster)`)
pruneF := flag.Bool("prune", false, `prune stopped containers, networks, volumes, and caches`)
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [flags] [command]\n\n", os.Args[0])
fmt.Fprintf(flag.CommandLine.Output(), "Commands: start, stop, restart, rm, kill.\n\n")
fmt.Fprintf(flag.CommandLine.Output(), "Flags:\n")
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() == 0 {
defaultCmd(context.TODO())
} else {
for _, c := range flag.Args() {
containerCmd(c, *projectF)
}
}
if *pruneF {
pruneCmd()
}
}