forked from testcontainers/moby-ryuk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
250 lines (207 loc) · 6.1 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
package main
import (
"bufio"
"context"
"flag"
"fmt"
"log"
"net"
"net/url"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"gopkg.in/matryer/try.v1"
)
var (
port = flag.Int("p", 8080, "Port to bind at")
initialConnectTimeout = 1 * time.Minute
reconnectionTimeout = 10 * time.Second
)
func main() {
flag.Parse()
cli, err := client.NewClientWithOpts()
if err != nil {
panic(err)
}
pingCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
log.Println("Pinging Docker...")
_, err = cli.Ping(pingCtx)
if err != nil {
panic(err)
}
log.Println("Docker daemon is available!")
deathNote := sync.Map{}
connectionAccepted := make(chan net.Addr)
connectionLost := make(chan net.Addr)
go processRequests(&deathNote, connectionAccepted, connectionLost)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
waitForPruneCondition(ctx, connectionAccepted, connectionLost)
dc, dn, dv, di := prune(cli, &deathNote)
log.Printf("Removed %d container(s), %d network(s), %d volume(s) %d image(s)", dc, dn, dv, di)
}
func processRequests(deathNote *sync.Map, connectionAccepted chan<- net.Addr, connectionLost chan<- net.Addr) {
log.Printf("Starting on port %d...", *port)
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
panic(err)
}
log.Println("Started!")
for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}
connectionAccepted <- conn.RemoteAddr()
go func(conn net.Conn) {
defer conn.Close()
defer func() { connectionLost <- conn.RemoteAddr() }()
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
message = strings.TrimSpace(message)
if len(message) > 0 {
query, err := url.ParseQuery(message)
if err != nil {
log.Println(err)
continue
}
args := filters.NewArgs()
for filterType, values := range query {
for _, value := range values {
args.Add(filterType, value)
}
}
paramBytes, err := args.MarshalJSON()
if err != nil {
log.Println(err)
continue
}
param := string(paramBytes)
log.Printf("Adding %s", param)
deathNote.Store(param, true)
_, _ = conn.Write([]byte("ACK\n"))
}
if err != nil {
log.Println(err)
break
}
}
}(conn)
}
}
func waitForPruneCondition(ctx context.Context, connectionAccepted <-chan net.Addr, connectionLost <-chan net.Addr) {
connectionCount := 0
never := make(chan time.Time, 1)
defer close(never)
handleConnectionAccepted := func(addr net.Addr) {
log.Printf("New client connected: %s", addr)
connectionCount++
}
select {
case <-time.After(initialConnectTimeout):
panic("Timed out waiting for the first connection")
case addr := <-connectionAccepted:
handleConnectionAccepted(addr)
case <-ctx.Done():
log.Println("Signal received")
return
}
for {
var noConnectionTimeout <-chan time.Time
if connectionCount == 0 {
noConnectionTimeout = time.After(reconnectionTimeout)
} else {
noConnectionTimeout = never
}
select {
case addr := <-connectionAccepted:
handleConnectionAccepted(addr)
break
case addr := <-connectionLost:
log.Printf("Client disconnected: %s", addr.String())
connectionCount--
break
case <-ctx.Done():
log.Println("Signal received")
return
case <-noConnectionTimeout:
log.Println("Timed out waiting for re-connection")
return
}
}
}
func prune(cli *client.Client, deathNote *sync.Map) (deletedContainers int, deletedNetworks int, deletedVolumes int, deletedImages int) {
deletedContainersMap := make(map[string]bool)
deletedNetworksMap := make(map[string]bool)
deletedVolumesMap := make(map[string]bool)
deletedImagesMap := make(map[string]bool)
deathNote.Range(func(note, _ interface{}) bool {
param := fmt.Sprint(note)
log.Printf("Deleting %s\n", param)
args, err := filters.FromJSON(param)
if err != nil {
log.Println(err)
return true
}
if containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: args}); err != nil {
log.Println(err)
} else {
for _, container := range containers {
_ = cli.ContainerRemove(context.Background(), container.ID, types.ContainerRemoveOptions{RemoveVolumes: true, Force: true})
deletedContainersMap[container.ID] = true
}
}
_ = try.Do(func(attempt int) (bool, error) {
networksPruneReport, err := cli.NetworksPrune(context.Background(), args)
for _, networkID := range networksPruneReport.NetworksDeleted {
deletedNetworksMap[networkID] = true
}
shouldRetry := attempt < 10
if err != nil && shouldRetry {
log.Printf("Network pruning has failed, retrying(%d/%d). The error was: %v", attempt, 10, err)
time.Sleep(1 * time.Second)
}
return shouldRetry, err
})
_ = try.Do(func(attempt int) (bool, error) {
volumesPruneReport, err := cli.VolumesPrune(context.Background(), args)
for _, volumeName := range volumesPruneReport.VolumesDeleted {
deletedVolumesMap[volumeName] = true
}
shouldRetry := attempt < 10
if err != nil && shouldRetry {
log.Printf("Volumes pruning has failed, retrying(%d/%d). The error was: %v", attempt, 10, err)
time.Sleep(1 * time.Second)
}
return shouldRetry, err
})
_ = try.Do(func(attempt int) (bool, error) {
args.Add("dangling", "false")
imagesPruneReport, err := cli.ImagesPrune(context.Background(), args)
for _, image := range imagesPruneReport.ImagesDeleted {
if image.Untagged != "" {
deletedImagesMap[image.Untagged] = true
}
}
shouldRetry := attempt < 10
if err != nil && shouldRetry {
log.Printf("Images pruning has failed, retrying(%d/%d). The error was: %v", attempt, 10, err)
time.Sleep(1 * time.Second)
}
return shouldRetry, err
})
return true
})
deletedContainers = len(deletedContainersMap)
deletedNetworks = len(deletedNetworksMap)
deletedVolumes = len(deletedVolumesMap)
deletedImages = len(deletedImagesMap)
return
}