/
main.go
92 lines (79 loc) · 1.89 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
package docker
import (
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
log "github.com/sirupsen/logrus"
"time"
"github.com/urfave/cli/v2"
)
func GetCommand() *cli.Command {
return &cli.Command{
Name: "docker",
Usage: "some docker shortcuts",
Subcommands: []*cli.Command{
&cli.Command{
Name: "clean",
Usage: "free up some resources",
Subcommands: []*cli.Command{
&cli.Command{
Name: "procs",
Usage: "force kill all processes",
Action: procHandler,
},
&cli.Command{
Name: "images",
Usage: "remove any dangling images",
Action: imageHandler,
},
},
},
},
}
}
func procHandler(c *cli.Context) error {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
}
containers, err := cli.ContainerList(ctx, types.ContainerListOptions{All: true})
if err != nil {
return err
}
for _, container := range containers {
log.Warnf("Stopping, Killing and Removing: %s", container.Image)
to := time.Second * 5
err = cli.ContainerStop(ctx, container.ID, &to)
if err != nil {
return err
}
err = cli.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{})
if err != nil {
return err
}
}
return nil
}
func imageHandler(c *cli.Context) error {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
}
args := filters.NewArgs()
args.Add("dangling", "true")
images, err := cli.ImageList(ctx, types.ImageListOptions{
All: true,
Filters: args,
})
if err != nil {
return err
}
for _, image := range images {
log.Warnf("Removing %s", image.ID)
cli.ImageRemove(ctx, image.ID, types.ImageRemoveOptions{})
}
return nil
}