Skip to content

Commit f9961dc

Browse files
committed
network prune client side approach
1 parent b124a86 commit f9961dc

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

Sources/ContainerCommands/Network/NetworkPrune.swift

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,36 @@ extension Application.NetworkCommand {
3030
var global: Flags.Global
3131

3232
public func run() async throws {
33-
let networkNames = try await ClientNetwork.prune()
33+
let allContainers = try await ClientContainer.list()
34+
let allNetworks = try await ClientNetwork.list()
3435

35-
for name in networkNames {
36+
var networksInUse = Set<String>()
37+
for container in allContainers {
38+
for network in container.configuration.networks {
39+
networksInUse.insert(network.network)
40+
}
41+
}
42+
43+
let networksToPrune = allNetworks.filter { network in
44+
network.id != ClientNetwork.defaultNetworkName && !networksInUse.contains(network.id)
45+
}
46+
47+
var prunedNetworks = [String]()
48+
49+
for network in networksToPrune {
50+
do {
51+
try await ClientNetwork.delete(id: network.id)
52+
prunedNetworks.append(network.id)
53+
log.info("Pruned network", metadata: ["name": "\(network.id)"])
54+
} catch {
55+
// Note: This failure may occur due to a race condition between the network/
56+
// container collection above and a container run command that attaches to a
57+
// network listed in the networksToPrune collection.
58+
log.error("Failed to prune network \(network.id): \(error)")
59+
}
60+
}
61+
62+
for name in prunedNetworks {
3663
print(name)
3764
}
3865
}

0 commit comments

Comments
 (0)