forked from apple/container
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNetworksService.swift
More file actions
346 lines (305 loc) · 13.4 KB
/
Copy pathNetworksService.swift
File metadata and controls
346 lines (305 loc) · 13.4 KB
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
//===----------------------------------------------------------------------===//
// Copyright © 2026 Apple Inc. and the container project authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//
import ContainerAPIClient
import ContainerNetworkServiceClient
import ContainerPersistence
import ContainerPlugin
import ContainerResource
import Containerization
import ContainerizationError
import ContainerizationExtras
import ContainerizationOS
import Foundation
import Logging
public actor NetworksService {
private let pluginLoader: PluginLoader
private let resourceRoot: URL
private let containersService: ContainersService
private let log: Logger
private let store: FilesystemEntityStore<NetworkConfiguration>
private let networkPlugin: Plugin
private var networkStates = [String: NetworkState]()
private var busyNetworks = Set<String>()
public init(
pluginLoader: PluginLoader,
resourceRoot: URL,
containersService: ContainersService,
log: Logger
) async throws {
self.pluginLoader = pluginLoader
self.resourceRoot = resourceRoot
self.containersService = containersService
self.log = log
try FileManager.default.createDirectory(at: resourceRoot, withIntermediateDirectories: true)
self.store = try FilesystemEntityStore<NetworkConfiguration>(
path: resourceRoot,
type: "network",
log: log
)
let networkPlugin =
pluginLoader
.findPlugins()
.filter { $0.hasType(.network) }
.first
guard let networkPlugin else {
throw ContainerizationError(.internalError, message: "cannot find network plugin")
}
self.networkPlugin = networkPlugin
let configurations = try await store.list()
for var configuration in configurations {
// Ensure the network with id "default" is marked as builtin.
if configuration.id == ClientNetwork.defaultNetworkName {
let role = configuration.labels[ResourceLabelKeys.role]
if role == nil || role != ResourceRoleValues.builtin {
configuration.labels[ResourceLabelKeys.role] = ResourceRoleValues.builtin
try await store.update(configuration)
}
}
// Start up the network.
do {
try await registerService(configuration: configuration)
} catch {
log.error(
"failed to start network",
metadata: [
"id": "\(configuration.id)"
])
}
let client = NetworkClient(id: configuration.id)
let networkState = try await client.state()
// FIXME: Temporary workaround for persisted configuration being overwritten
// by what comes back from the network helper, which messes up creationDate.
switch networkState {
case .created(_):
networkStates[configuration.id] = NetworkState.created(configuration)
case .running(_, let status):
networkStates[configuration.id] = NetworkState.running(configuration, status)
}
guard case .running = networkState else {
log.error(
"network failed to start",
metadata: [
"id": "\(configuration.id)",
"state": "\(networkState.state)",
])
return
}
}
}
/// List all networks registered with the service.
public func list() async throws -> [NetworkState] {
log.info("network service: list")
return networkStates.reduce(into: [NetworkState]()) {
$0.append($1.value)
}
}
/// Create a new network from the provided configuration.
public func create(configuration: NetworkConfiguration) async throws -> NetworkState {
log.info(
"network service: create",
metadata: [
"id": "\(configuration.id)"
])
//Ensure that the network is not named "none"
if configuration.id == ClientNetwork.noNetworkName {
throw ContainerizationError(.unsupported, message: "network \(configuration.id) is not a valid name")
}
// Ensure nobody is manipulating the network already.
guard !busyNetworks.contains(configuration.id) else {
throw ContainerizationError(.exists, message: "network \(configuration.id) has a pending operation")
}
busyNetworks.insert(configuration.id)
defer { busyNetworks.remove(configuration.id) }
// Ensure the network doesn't already exist.
guard networkStates[configuration.id] == nil else {
throw ContainerizationError(.exists, message: "network \(configuration.id) already exists")
}
// Create and start the network.
try await registerService(configuration: configuration)
let client = NetworkClient(id: configuration.id)
// Ensure the network is running, and set up the persistent network state
// using our configuration data, as the one from the helper doesn't include
// metadata.
guard case .running(_, let status) = try await client.state() else {
throw ContainerizationError(.invalidState, message: "network \(configuration.id) failed to start")
}
let networkState: NetworkState = .running(configuration, status)
networkStates[configuration.id] = networkState
// Persist the configuration data.
do {
try await store.create(configuration)
return networkState
} catch {
networkStates.removeValue(forKey: configuration.id)
do {
try pluginLoader.deregisterWithLaunchd(plugin: networkPlugin, instanceId: configuration.id)
} catch {
log.error(
"failed to deregister network service after failed creation",
metadata: [
"id": "\(configuration.id)",
"error": "\(error.localizedDescription)",
])
}
throw error
}
}
/// Delete a network.
public func delete(id: String) async throws {
// check actor busy state
guard !busyNetworks.contains(id) else {
throw ContainerizationError(.exists, message: "network \(id) has a pending operation")
}
// make actor state busy for this network
busyNetworks.insert(id)
defer { busyNetworks.remove(id) }
log.info(
"network service: delete",
metadata: [
"id": "\(id)"
])
guard let networkState = networkStates[id] else {
throw ContainerizationError(.notFound, message: "no network for id \(id)")
}
// basic sanity checks on network itself
if networkState.isBuiltin {
throw ContainerizationError(.invalidArgument, message: "cannot delete builtin network: \(id)")
}
guard case .running = networkState else {
throw ContainerizationError(.invalidState, message: "cannot delete network \(id) in state \(networkState.state)")
}
// prevent container operations while we atomically check and delete
try await containersService.withContainerList { containers in
// find all containers that refer to the network
var referringContainers = Set<String>()
for container in containers {
for attachmentConfiguration in container.configuration.networks {
if attachmentConfiguration.network == id {
referringContainers.insert(container.configuration.id)
break
}
}
}
// bail if any referring containers
guard referringContainers.isEmpty else {
throw ContainerizationError(
.invalidState,
message: "cannot delete subnet \(id) with referring containers: \(referringContainers.joined(separator: ", "))"
)
}
// disable the allocator so nothing else can attach
// TODO: remove this from the network helper later, not necesssary now that withContainerList is here
let client = NetworkClient(id: id)
guard try await client.disableAllocator() else {
throw ContainerizationError(.invalidState, message: "cannot delete subnet \(id) because the IP allocator cannot be disabled with active containers")
}
// start network deletion, this is the last place we'll want to throw
do {
try self.pluginLoader.deregisterWithLaunchd(plugin: self.networkPlugin, instanceId: id)
} catch {
self.log.error(
"failed to deregister network service",
metadata: [
"id": "\(id)",
"error": "\(error.localizedDescription)",
])
}
// deletion is underway, do not throw anything now
do {
try await self.store.delete(id)
} catch {
self.log.error(
"failed to delete network from configuration store",
metadata: [
"id": "\(id)",
"error": "\(error.localizedDescription)",
])
}
}
// having deleted successfully, remove the runtime state
self.networkStates.removeValue(forKey: id)
}
/// Perform a hostname lookup on all networks.
public func lookup(hostname: String) async throws -> Attachment? {
for id in networkStates.keys {
let client = NetworkClient(id: id)
guard let allocation = try await client.lookup(hostname: hostname) else {
continue
}
return allocation
}
return nil
}
private func registerService(configuration: NetworkConfiguration) async throws {
guard configuration.mode == .nat || configuration.mode == .hostOnly else {
throw ContainerizationError(.invalidArgument, message: "unsupported network mode \(configuration.mode.rawValue)")
}
guard let serviceIdentifier = networkPlugin.getMachService(instanceId: configuration.id, type: .network) else {
throw ContainerizationError(.invalidArgument, message: "unsupported network mode \(configuration.mode.rawValue)")
}
var args = [
"start",
"--id",
configuration.id,
"--service-identifier",
serviceIdentifier,
"--mode",
configuration.mode.rawValue,
]
if let ipv4Subnet = configuration.ipv4Subnet {
var existingCidrs: [CIDRv4] = []
for networkState in networkStates.values {
if case .running(_, let status) = networkState {
existingCidrs.append(status.ipv4Subnet)
}
}
let overlap = existingCidrs.first {
$0.contains(ipv4Subnet.lower)
|| $0.contains(ipv4Subnet.upper)
|| ipv4Subnet.contains($0.lower)
|| ipv4Subnet.contains($0.upper)
}
if let overlap {
throw ContainerizationError(.exists, message: "IPv4 subnet \(ipv4Subnet) overlaps an existing network with subnet \(overlap)")
}
args += ["--subnet", ipv4Subnet.description]
}
if let ipv6Subnet = configuration.ipv6Subnet {
var existingCidrs: [CIDRv6] = []
for networkState in networkStates.values {
if case .running(_, let status) = networkState, let otherIPv6Subnet = status.ipv6Subnet {
existingCidrs.append(otherIPv6Subnet)
}
}
let overlap = existingCidrs.first {
$0.contains(ipv6Subnet.lower)
|| $0.contains(ipv6Subnet.upper)
|| ipv6Subnet.contains($0.lower)
|| ipv6Subnet.contains($0.upper)
}
if let overlap {
throw ContainerizationError(.exists, message: "IPv6 subnet \(ipv6Subnet) overlaps an existing network with subnet \(overlap)")
}
args += ["--subnet-v6", ipv6Subnet.description]
}
try await pluginLoader.registerWithLaunchd(
plugin: networkPlugin,
pluginStateRoot: store.entityUrl(configuration.id),
args: args,
instanceId: configuration.id
)
}
}