containerization-framework 0.6.0

Rust bindings for Apple's Containerization framework: Linux containers in lightweight VMs, in-process and without a daemon.
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
//===----------------------------------------------------------------------===//
// `Vminitd`, from Containerization: the client of the agent running in the
// guest, which `VZVirtualMachineInstance.dialAgent()` returns.
//===----------------------------------------------------------------------===//

import Containerization
import ContainerizationExtras
import ContainerizationOCI
import ContainerizationOS
import Foundation

final class CzVminitd: Sendable {
  let agent: Vminitd

  init(_ agent: Vminitd) {
    self.agent = agent
  }

  func standardSetup() -> CzOutcome {
    let agent = agent

    return CzOutcome { try blocking { try await agent.standardSetup() } }
  }

  func close() -> CzOutcome {
    let agent = agent

    return CzOutcome { try blocking { try await agent.close() } }
  }

  func filesystemOperation(operation: FilesystemOperationKind, path: RustStr, containerID: RustString?) -> CzOutcome {
    let agent = agent
    let path = path.toString()
    let containerID = containerID?.toString()
    let operation: FilesystemOperation =
      switch operation {
      case .Freeze: .freeze
      case .Thaw: .thaw
      case .Trim: .trim
      }

    return CzOutcome {
      try blocking { try await agent.filesystemOperation(operation: operation, path: path, containerID: containerID) }
    }
  }

  func getenv(key: RustStr) -> CzOutcome {
    let agent = agent
    let key = key.toString()

    return CzOutcome { try blocking { try await agent.getenv(key: key) } }
  }

  func setenv(key: RustStr, value: RustStr) -> CzOutcome {
    let agent = agent
    let key = key.toString()
    let value = value.toString()

    return CzOutcome { try blocking { try await agent.setenv(key: key, value: value) } }
  }

  func mount(mount: RustOciMount) -> CzOutcome {
    let agent = agent
    let mount = ContainerizationOCI.Mount(mount)

    return CzOutcome { try blocking { try await agent.mount(mount) } }
  }

  func umount(path: RustStr, flags: Int32) -> CzOutcome {
    let agent = agent
    let path = path.toString()

    return CzOutcome { try blocking { try await agent.umount(path: path, flags: flags) } }
  }

  func mkdir(path: RustStr, all: Bool, perms: UInt32) -> CzOutcome {
    let agent = agent
    let path = path.toString()

    return CzOutcome { try blocking { try await agent.mkdir(path: path, all: all, perms: perms) } }
  }

  func kill(pid: Int32, signal: Int32) -> CzOutcome {
    let agent = agent

    return CzOutcome { try blocking { try await agent.kill(pid: pid, signal: signal) } }
  }

  func sync() -> CzOutcome {
    let agent = agent

    return CzOutcome { try blocking { try await agent.sync() } }
  }

  /// `options` stands for `nil` when `hasOptions` is false.
  func createProcess(
    id: RustStr,
    containerID: RustString?,
    stdinPort: UInt32?,
    stdoutPort: UInt32?,
    stderrPort: UInt32?,
    ociRuntimePath: RustString?,
    configuration: RustSpec,
    hasOptions: Bool,
    options: RustVec<UInt8>
  ) -> CzOutcome {
    let agent = agent
    let id = id.toString()
    let containerID = containerID?.toString()
    let ociRuntimePath = ociRuntimePath?.toString()
    let configuration = ContainerizationOCI.Spec(configuration)
    let options = hasOptions ? Data(options) : nil

    return CzOutcome {
      try blocking {
        try await agent.createProcess(
          id: id,
          containerID: containerID,
          stdinPort: stdinPort,
          stdoutPort: stdoutPort,
          stderrPort: stderrPort,
          ociRuntimePath: ociRuntimePath,
          configuration: configuration,
          options: options
        )
      }
    }
  }

  func startProcess(id: RustStr, containerID: RustString?) -> CzOutcome {
    let agent = agent
    let id = id.toString()
    let containerID = containerID?.toString()

    return CzOutcome { try blocking { try await agent.startProcess(id: id, containerID: containerID) } }
  }

  func signalProcess(id: RustStr, containerID: RustString?, signal: Int32) -> CzOutcome {
    let agent = agent
    let id = id.toString()
    let containerID = containerID?.toString()

    return CzOutcome {
      try blocking { try await agent.signalProcess(id: id, containerID: containerID, signal: signal) }
    }
  }

  func resizeProcess(id: RustStr, containerID: RustString?, columns: UInt32, rows: UInt32) -> CzOutcome {
    let agent = agent
    let id = id.toString()
    let containerID = containerID?.toString()

    return CzOutcome {
      try blocking { try await agent.resizeProcess(id: id, containerID: containerID, columns: columns, rows: rows) }
    }
  }

  func waitProcess(id: RustStr, containerID: RustString?, timeoutInSeconds: Int64?) -> CzOutcome {
    let agent = agent
    let id = id.toString()
    let containerID = containerID?.toString()

    return CzOutcome {
      try blocking { try await agent.waitProcess(id: id, containerID: containerID, timeoutInSeconds: timeoutInSeconds) }
    }
  }

  func deleteProcess(id: RustStr, containerID: RustString?) -> CzOutcome {
    let agent = agent
    let id = id.toString()
    let containerID = containerID?.toString()

    return CzOutcome { try blocking { try await agent.deleteProcess(id: id, containerID: containerID) } }
  }

  func closeProcessStdin(id: RustStr, containerID: RustString?) -> CzOutcome {
    let agent = agent
    let id = id.toString()
    let containerID = containerID?.toString()

    return CzOutcome { try blocking { try await agent.closeProcessStdin(id: id, containerID: containerID) } }
  }

  func up(name: RustStr, mtu: UInt32?) -> CzOutcome {
    let agent = agent
    let name = name.toString()

    return CzOutcome { try blocking { try await agent.up(name: name, mtu: mtu) } }
  }

  func down(name: RustStr) -> CzOutcome {
    let agent = agent
    let name = name.toString()

    return CzOutcome { try blocking { try await agent.down(name: name) } }
  }

  func addressAdd(name: RustStr, address: RustInterfaceAddress) -> CzOutcome {
    let agent = agent
    let name = name.toString()

    return CzOutcome {
      let address = try InterfaceAddress(address)

      return try blocking { try await agent.addressAdd(name: name, address: address) }
    }
  }

  func routeAddLink(name: RustStr, route: RustLinkRoute) -> CzOutcome {
    let agent = agent
    let name = name.toString()
    let route = LinkRoute(route)

    return CzOutcome { try blocking { try await agent.routeAddLink(name: name, route: route) } }
  }

  func routeAddDefault(name: RustStr, route: RustDefaultRoute) -> CzOutcome {
    let agent = agent
    let name = name.toString()
    let route = DefaultRoute(route)

    return CzOutcome { try blocking { try await agent.routeAddDefault(name: name, route: route) } }
  }

  func configureDNS(config: RustDns, location: RustStr) -> CzOutcome {
    let agent = agent
    let config = DNS(config)
    let location = location.toString()

    return CzOutcome { try blocking { try await agent.configureDNS(config: config, location: location) } }
  }

  func configureHosts(config: RustHosts, location: RustStr) -> CzOutcome {
    let agent = agent
    let config = Hosts(config)
    let location = location.toString()

    return CzOutcome { try blocking { try await agent.configureHosts(config: config, location: location) } }
  }

  func containerStatistics(containerIDs: RustVec<RustString>, categories: Int64) -> CzOutcome {
    let agent = agent
    let containerIDs = strings(containerIDs)
    let categories = StatCategory(rawValue: Int(categories))

    return CzOutcome {
      try blocking { try await agent.containerStatistics(containerIDs: containerIDs, categories: categories) }
    }
  }

  func setupEmulator(binaryPath: RustStr, configuration: RustBinfmtEntry) -> CzOutcome {
    let agent = agent
    let binaryPath = binaryPath.toString()
    // `Binfmt.Entry` isn't `Sendable`, though it holds only `String`s.
    nonisolated(unsafe) let configuration = Binfmt.Entry(configuration)

    return CzOutcome {
      try blocking { try await agent.setupEmulator(binaryPath: binaryPath, configuration: configuration) }
    }
  }

  func setTime(sec: Int64, usec: Int32) -> CzOutcome {
    let agent = agent

    return CzOutcome { try blocking { try await agent.setTime(sec: sec, usec: usec) } }
  }

  /// The settings cross as their keys and their values in the same order.
  func sysctl(keys: RustVec<RustString>, values: RustVec<RustString>) -> CzOutcome {
    let agent = agent
    let settings = dictionary(keys, values)

    return CzOutcome { try blocking { try await agent.sysctl(settings: settings) } }
  }

  func stat(root: RustStr, path: RustStr) -> CzOutcome {
    let agent = agent
    let root = root.toString()
    let path = path.toString()

    return CzOutcome { try blocking { try await agent.stat(root: root, path: path) } }
  }

  func enableRosetta() -> CzOutcome {
    let agent = agent

    return CzOutcome { try blocking { try await agent.enableRosetta() } }
  }

  func relaySocket(port: UInt32, configuration: CzUnixSocketConfiguration) -> CzOutcome {
    let agent = agent
    let configuration = configuration.configuration

    return CzOutcome { try blocking { try await agent.relaySocket(port: port, configuration: configuration) } }
  }

  func stopSocketRelay(configuration: CzUnixSocketConfiguration) -> CzOutcome {
    let agent = agent
    let configuration = configuration.configuration

    return CzOutcome { try blocking { try await agent.stopSocketRelay(configuration: configuration) } }
  }
}

extension CzVirtualMachineInstance {
  func dialAgent() -> CzOutcome {
    let instance = instance

    return CzOutcome { CzVminitd(try blocking { try await instance.dialAgent() }) }
  }
}

// MARK: Rust to Swift

extension InterfaceAddress {
  init(_ address: RustInterfaceAddressRef) throws {
    self.init(
      ipv4Address: try CIDRv4(bridged: address.ipv4AddressValue(), prefix: address.ipv4AddressPrefix()),
      ipv6Address: address.hasIpv6Address()
        ? try CIDRv6(bridged: address.ipv6AddressAddress(), prefix: address.ipv6AddressPrefix())
        : nil
    )
  }
}

extension LinkRoute {
  init(_ route: RustLinkRouteRef) {
    self.init(
      ipv4Destination: route.ipv4Destination().map { IPv4Address($0) },
      ipv4Source: route.ipv4Source().map { IPv4Address($0) },
      ipv6Destination: route.hasIpv6Destination() ? IPv6Address(route.ipv6Destination()) : nil,
      ipv6Source: route.hasIpv6Source() ? IPv6Address(route.ipv6Source()) : nil
    )
  }
}

extension DefaultRoute {
  init(_ route: RustDefaultRouteRef) {
    self.init(
      ipv4Gateway: route.ipv4Gateway().map { IPv4Address($0) },
      ipv6Gateway: route.hasIpv6Gateway() ? IPv6Address(route.ipv6Gateway()) : nil
    )
  }
}

extension Binfmt.Entry {
  init(_ entry: RustBinfmtEntryRef) {
    self.init(
      name: entry.name().toString(),
      type: entry.entryType().toString(),
      offset: entry.offset().toString(),
      magic: entry.magic().toString(),
      mask: entry.mask().toString(),
      flags: entry.flags().toString()
    )
  }
}

// MARK: Swift to Rust

extension CzOutcome {
  func vminitd() -> CzVminitd { taken() }

  /// A `Stat`'s unsigned fields, in Swift's order.
  func statUnsigned() -> RustVec<UInt64> {
    let stat: ContainerizationOS.Stat = taken()
    let vec = RustVec<UInt64>()
    for value in [
      stat.dev, stat.ino, UInt64(stat.mode), stat.nlink, UInt64(stat.uid), UInt64(stat.gid), stat.rdev,
    ] {
      vec.push(value: value)
    }
    return vec
  }

  /// A `Stat`'s signed fields, in Swift's order, with each `TimeSpec` as its
  /// seconds and nanoseconds.
  func statSigned() -> RustVec<Int64> {
    let stat: ContainerizationOS.Stat = taken()
    let vec = RustVec<Int64>()
    for value in [
      stat.size, stat.blksize, stat.blocks,
      stat.atime.seconds, Int64(stat.atime.nanoseconds),
      stat.mtime.seconds, Int64(stat.mtime.nanoseconds),
      stat.ctime.seconds, Int64(stat.ctime.nanoseconds),
    ] {
      vec.push(value: value)
    }
    return vec
  }
}

/// For a unit test: `Binfmt.path`.
func binfmtPath() -> String {
  Binfmt.path
}

/// For a unit test: `Binfmt.Entry.amd64()`'s fields, in Swift's order.
func binfmtEntryAmd64() -> RustVec<RustString> {
  let entry = Binfmt.Entry.amd64()

  return rustStrings([entry.name, entry.type, entry.offset, entry.magic, entry.mask, entry.flags])
}