forked from swift-server/swift-aws-lambda-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlugin.swift
549 lines (486 loc) · 21.4 KB
/
Plugin.swift
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftAWSLambdaRuntime open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftAWSLambdaRuntime project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftAWSLambdaRuntime project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import Foundation
import PackagePlugin
import Synchronization
@available(macOS 15.0, *)
@main
struct AWSLambdaPackager: CommandPlugin {
func performCommand(context: PackagePlugin.PluginContext, arguments: [String]) async throws {
let configuration = try Configuration(context: context, arguments: arguments)
guard !configuration.products.isEmpty else {
throw Errors.unknownProduct("no appropriate products found to package")
}
if configuration.products.count > 1 && !configuration.explicitProducts {
let productNames = configuration.products.map(\.name)
print(
"No explicit products named, building all executable products: '\(productNames.joined(separator: "', '"))'"
)
}
let builtProducts: [LambdaProduct: Path]
if self.isAmazonLinux2() {
// build directly on the machine
builtProducts = try self.build(
packageIdentity: context.package.id,
products: configuration.products,
buildConfiguration: configuration.buildConfiguration,
verboseLogging: configuration.verboseLogging
)
} else {
// build with docker
builtProducts = try self.buildInDocker(
packageIdentity: context.package.id,
packageDirectory: context.package.directory,
products: configuration.products,
toolsProvider: { name in try context.tool(named: name).path },
outputDirectory: configuration.outputDirectory,
baseImage: configuration.baseDockerImage,
disableDockerImageUpdate: configuration.disableDockerImageUpdate,
buildConfiguration: configuration.buildConfiguration,
verboseLogging: configuration.verboseLogging
)
}
// create the archive
let archives = try self.package(
packageName: context.package.displayName,
products: builtProducts,
toolsProvider: { name in try context.tool(named: name).path },
outputDirectory: configuration.outputDirectory,
verboseLogging: configuration.verboseLogging
)
print(
"\(archives.count > 0 ? archives.count.description : "no") archive\(archives.count != 1 ? "s" : "") created"
)
for (product, archivePath) in archives {
print(" * \(product.name) at \(archivePath.string)")
}
}
private func buildInDocker(
packageIdentity: Package.ID,
packageDirectory: Path,
products: [Product],
toolsProvider: (String) throws -> Path,
outputDirectory: Path,
baseImage: String,
disableDockerImageUpdate: Bool,
buildConfiguration: PackageManager.BuildConfiguration,
verboseLogging: Bool
) throws -> [LambdaProduct: Path] {
let dockerToolPath = try toolsProvider("docker")
print("-------------------------------------------------------------------------")
print("building \"\(packageIdentity)\" in docker")
print("-------------------------------------------------------------------------")
if !disableDockerImageUpdate {
// update the underlying docker image, if necessary
print("updating \"\(baseImage)\" docker image")
try self.execute(
executable: dockerToolPath,
arguments: ["pull", baseImage],
logLevel: .output
)
}
// get the build output path
let buildOutputPathCommand = "swift build -c \(buildConfiguration.rawValue) --show-bin-path"
let dockerBuildOutputPath = try self.execute(
executable: dockerToolPath,
arguments: [
"run", "--rm", "-v", "\(packageDirectory.string):/workspace", "-w", "/workspace", baseImage, "bash",
"-cl", buildOutputPathCommand,
],
logLevel: verboseLogging ? .debug : .silent
)
guard let buildPathOutput = dockerBuildOutputPath.split(separator: "\n").last else {
throw Errors.failedParsingDockerOutput(dockerBuildOutputPath)
}
let buildOutputPath = Path(
buildPathOutput.replacingOccurrences(of: "/workspace", with: packageDirectory.string)
)
// build the products
var builtProducts = [LambdaProduct: Path]()
for product in products {
print("building \"\(product.name)\"")
let buildCommand =
"swift build -c \(buildConfiguration.rawValue) --product \(product.name) --static-swift-stdlib"
if ProcessInfo.processInfo.environment["LAMBDA_USE_LOCAL_DEPS"] != nil {
// when developing locally, we must have the full swift-aws-lambda-runtime project in the container
// because Examples' Package.swift have a dependency on ../..
// just like Package.swift's examples assume ../.., we assume we are two levels below the root project
let lastComponent = packageDirectory.lastComponent
let beforeLastComponent = packageDirectory.removingLastComponent().lastComponent
try self.execute(
executable: dockerToolPath,
arguments: [
"run", "--rm", "--env", "LAMBDA_USE_LOCAL_DEPS=true", "-v",
"\(packageDirectory.string)/../..:/workspace", "-w",
"/workspace/\(beforeLastComponent)/\(lastComponent)", baseImage, "bash", "-cl", buildCommand,
],
logLevel: verboseLogging ? .debug : .output
)
} else {
try self.execute(
executable: dockerToolPath,
arguments: [
"run", "--rm", "-v", "\(packageDirectory.string):/workspace", "-w", "/workspace", baseImage,
"bash", "-cl", buildCommand,
],
logLevel: verboseLogging ? .debug : .output
)
}
let productPath = buildOutputPath.appending(product.name)
guard FileManager.default.fileExists(atPath: productPath.string) else {
Diagnostics.error("expected '\(product.name)' binary at \"\(productPath.string)\"")
throw Errors.productExecutableNotFound(product.name)
}
builtProducts[.init(product)] = productPath
}
return builtProducts
}
private func build(
packageIdentity: Package.ID,
products: [Product],
buildConfiguration: PackageManager.BuildConfiguration,
verboseLogging: Bool
) throws -> [LambdaProduct: Path] {
print("-------------------------------------------------------------------------")
print("building \"\(packageIdentity)\"")
print("-------------------------------------------------------------------------")
var results = [LambdaProduct: Path]()
for product in products {
print("building \"\(product.name)\"")
var parameters = PackageManager.BuildParameters()
parameters.configuration = buildConfiguration
parameters.otherSwiftcFlags = ["-static-stdlib"]
parameters.logging = verboseLogging ? .verbose : .concise
let result = try packageManager.build(
.product(product.name),
parameters: parameters
)
guard let artifact = result.executableArtifact(for: product) else {
throw Errors.productExecutableNotFound(product.name)
}
results[.init(product)] = artifact.path
}
return results
}
// TODO: explore using ziplib or similar instead of shelling out
private func package(
packageName: String,
products: [LambdaProduct: Path],
toolsProvider: (String) throws -> Path,
outputDirectory: Path,
verboseLogging: Bool
) throws -> [LambdaProduct: Path] {
let zipToolPath = try toolsProvider("zip")
var archives = [LambdaProduct: Path]()
for (product, artifactPath) in products {
print("-------------------------------------------------------------------------")
print("archiving \"\(product.name)\"")
print("-------------------------------------------------------------------------")
// prep zipfile location
let workingDirectory = outputDirectory.appending(product.name)
let zipfilePath = workingDirectory.appending("\(product.name).zip")
if FileManager.default.fileExists(atPath: workingDirectory.string) {
try FileManager.default.removeItem(atPath: workingDirectory.string)
}
try FileManager.default.createDirectory(atPath: workingDirectory.string, withIntermediateDirectories: true)
// rename artifact to "bootstrap"
let relocatedArtifactPath = workingDirectory.appending(artifactPath.lastComponent)
let symbolicLinkPath = workingDirectory.appending("bootstrap")
try FileManager.default.copyItem(atPath: artifactPath.string, toPath: relocatedArtifactPath.string)
try FileManager.default.createSymbolicLink(
atPath: symbolicLinkPath.string,
withDestinationPath: relocatedArtifactPath.lastComponent
)
var arguments: [String] = []
#if os(macOS) || os(Linux)
arguments = [
"--recurse-paths",
"--symlinks",
zipfilePath.lastComponent,
relocatedArtifactPath.lastComponent,
symbolicLinkPath.lastComponent,
]
#else
throw Errors.unsupportedPlatform("can't or don't know how to create a zip file on this platform")
#endif
// add resources
let artifactDirectory = artifactPath.removingLastComponent()
let resourcesDirectoryName = "\(packageName)_\(product.name).resources"
let resourcesDirectory = artifactDirectory.appending(resourcesDirectoryName)
let relocatedResourcesDirectory = workingDirectory.appending(resourcesDirectoryName)
if FileManager.default.fileExists(atPath: resourcesDirectory.string) {
try FileManager.default.copyItem(
atPath: resourcesDirectory.string,
toPath: relocatedResourcesDirectory.string
)
arguments.append(resourcesDirectoryName)
}
// run the zip tool
try self.execute(
executable: zipToolPath,
arguments: arguments,
customWorkingDirectory: workingDirectory,
logLevel: verboseLogging ? .debug : .silent
)
archives[product] = zipfilePath
}
return archives
}
@discardableResult
private func execute(
executable: Path,
arguments: [String],
customWorkingDirectory: Path? = .none,
logLevel: ProcessLogLevel
) throws -> String {
if logLevel >= .debug {
print("\(executable.string) \(arguments.joined(separator: " "))")
}
let fd = dup(1)
let stdout = fdopen(fd, "rw")
defer { fclose(stdout) }
// We need to use an unsafe transfer here to get the fd into our Sendable closure.
// This transfer is fine, because we guarantee that the code in the outputHandler
// is run before we continue the functions execution, where the fd is used again.
// See `process.waitUntilExit()` and the following `outputSync.wait()`
struct UnsafeTransfer<Value>: @unchecked Sendable {
let value: Value
}
let outputMutex = Mutex("")
let outputSync = DispatchGroup()
let outputQueue = DispatchQueue(label: "AWSLambdaPackager.output")
let unsafeTransfer = UnsafeTransfer(value: stdout)
let outputHandler = { @Sendable (data: Data?) in
dispatchPrecondition(condition: .onQueue(outputQueue))
outputSync.enter()
defer { outputSync.leave() }
guard
let _output = data.flatMap({
String(data: $0, encoding: .utf8)?.trimmingCharacters(in: CharacterSet(["\n"]))
}), !_output.isEmpty
else {
return
}
outputMutex.withLock { output in
output += _output + "\n"
}
switch logLevel {
case .silent:
break
case .debug(let outputIndent), .output(let outputIndent):
print(String(repeating: " ", count: outputIndent), terminator: "")
print(_output)
fflush(unsafeTransfer.value)
}
}
let pipe = Pipe()
pipe.fileHandleForReading.readabilityHandler = { fileHandle in
outputQueue.async { outputHandler(fileHandle.availableData) }
}
let process = Process()
process.standardOutput = pipe
process.standardError = pipe
process.executableURL = URL(fileURLWithPath: executable.string)
process.arguments = arguments
if let workingDirectory = customWorkingDirectory {
process.currentDirectoryURL = URL(fileURLWithPath: workingDirectory.string)
}
process.terminationHandler = { _ in
outputQueue.async {
outputHandler(try? pipe.fileHandleForReading.readToEnd())
}
}
try process.run()
process.waitUntilExit()
// wait for output to be full processed
outputSync.wait()
let output = outputMutex.withLock { $0 }
if process.terminationStatus != 0 {
// print output on failure and if not already printed
if logLevel < .output {
print(output)
fflush(stdout)
}
throw Errors.processFailed([executable.string] + arguments, process.terminationStatus)
}
return output
}
private func isAmazonLinux2() -> Bool {
if let data = FileManager.default.contents(atPath: "/etc/system-release"),
let release = String(data: data, encoding: .utf8)
{
return release.hasPrefix("Amazon Linux release 2")
} else {
return false
}
}
}
@available(macOS 15.0, *)
private struct Configuration: CustomStringConvertible {
public let outputDirectory: Path
public let products: [Product]
public let explicitProducts: Bool
public let buildConfiguration: PackageManager.BuildConfiguration
public let verboseLogging: Bool
public let baseDockerImage: String
public let disableDockerImageUpdate: Bool
public init(
context: PluginContext,
arguments: [String]
) throws {
var argumentExtractor = ArgumentExtractor(arguments)
let verboseArgument = argumentExtractor.extractFlag(named: "verbose") > 0
let outputPathArgument = argumentExtractor.extractOption(named: "output-path")
let productsArgument = argumentExtractor.extractOption(named: "products")
let configurationArgument = argumentExtractor.extractOption(named: "configuration")
let swiftVersionArgument = argumentExtractor.extractOption(named: "swift-version")
let baseDockerImageArgument = argumentExtractor.extractOption(named: "base-docker-image")
let disableDockerImageUpdateArgument = argumentExtractor.extractFlag(named: "disable-docker-image-update") > 0
self.verboseLogging = verboseArgument
if let outputPath = outputPathArgument.first {
var isDirectory: ObjCBool = false
guard FileManager.default.fileExists(atPath: outputPath, isDirectory: &isDirectory), isDirectory.boolValue
else {
throw Errors.invalidArgument("invalid output directory '\(outputPath)'")
}
self.outputDirectory = Path(outputPath)
} else {
self.outputDirectory = context.pluginWorkDirectory.appending(subpath: "\(AWSLambdaPackager.self)")
}
self.explicitProducts = !productsArgument.isEmpty
if self.explicitProducts {
let products = try context.package.products(named: productsArgument)
for product in products {
guard product is ExecutableProduct else {
throw Errors.invalidArgument("product named '\(product.name)' is not an executable product")
}
}
self.products = products
} else {
self.products = context.package.products.filter { $0 is ExecutableProduct }
}
if let buildConfigurationName = configurationArgument.first {
guard let buildConfiguration = PackageManager.BuildConfiguration(rawValue: buildConfigurationName) else {
throw Errors.invalidArgument("invalid build configuration named '\(buildConfigurationName)'")
}
self.buildConfiguration = buildConfiguration
} else {
self.buildConfiguration = .release
}
guard !(!swiftVersionArgument.isEmpty && !baseDockerImageArgument.isEmpty) else {
throw Errors.invalidArgument("--swift-version and --base-docker-image are mutually exclusive")
}
let swiftVersion = swiftVersionArgument.first ?? .none // undefined version will yield the latest docker image
self.baseDockerImage =
baseDockerImageArgument.first ?? "swift:\(swiftVersion.map { $0 + "-" } ?? "")amazonlinux2"
self.disableDockerImageUpdate = disableDockerImageUpdateArgument
if self.verboseLogging {
print("-------------------------------------------------------------------------")
print("configuration")
print("-------------------------------------------------------------------------")
print(self)
}
}
var description: String {
"""
{
outputDirectory: \(self.outputDirectory)
products: \(self.products.map(\.name))
buildConfiguration: \(self.buildConfiguration)
baseDockerImage: \(self.baseDockerImage)
disableDockerImageUpdate: \(self.disableDockerImageUpdate)
}
"""
}
}
private enum ProcessLogLevel: Comparable {
case silent
case output(outputIndent: Int)
case debug(outputIndent: Int)
var naturalOrder: Int {
switch self {
case .silent:
return 0
case .output:
return 1
case .debug:
return 2
}
}
static var output: Self {
.output(outputIndent: 2)
}
static var debug: Self {
.debug(outputIndent: 2)
}
static func < (lhs: ProcessLogLevel, rhs: ProcessLogLevel) -> Bool {
lhs.naturalOrder < rhs.naturalOrder
}
}
private enum Errors: Error, CustomStringConvertible {
case invalidArgument(String)
case unsupportedPlatform(String)
case unknownProduct(String)
case productExecutableNotFound(String)
case failedWritingDockerfile
case failedParsingDockerOutput(String)
case processFailed([String], Int32)
var description: String {
switch self {
case .invalidArgument(let description):
return description
case .unsupportedPlatform(let description):
return description
case .unknownProduct(let description):
return description
case .productExecutableNotFound(let product):
return "product executable not found '\(product)'"
case .failedWritingDockerfile:
return "failed writing dockerfile"
case .failedParsingDockerOutput(let output):
return "failed parsing docker output: '\(output)'"
case .processFailed(let arguments, let code):
return "\(arguments.joined(separator: " ")) failed with code \(code)"
}
}
}
private struct LambdaProduct: Hashable {
let underlying: Product
init(_ underlying: Product) {
self.underlying = underlying
}
var name: String {
self.underlying.name
}
func hash(into hasher: inout Hasher) {
self.underlying.id.hash(into: &hasher)
}
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.underlying.id == rhs.underlying.id
}
}
extension PackageManager.BuildResult {
// find the executable produced by the build
func executableArtifact(for product: Product) -> PackageManager.BuildResult.BuiltArtifact? {
let executables = self.builtArtifacts.filter { $0.kind == .executable && $0.path.lastComponent == product.name }
guard !executables.isEmpty else {
return nil
}
guard executables.count == 1, let executable = executables.first else {
return nil
}
return executable
}
}