forked from aws/aws-cdk
/
bundling.ts
232 lines (204 loc) · 7.37 KB
/
bundling.ts
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
import * as os from 'os';
import * as path from 'path';
import { Architecture, AssetCode, Code, Runtime } from '@aws-cdk/aws-lambda';
import * as cdk from '@aws-cdk/core';
import { BundlingOptions } from './types';
import { exec, findUp, getGoBuildVersion } from './util';
/**
* Options for bundling
*/
export interface BundlingProps extends BundlingOptions {
/**
* Directory containing your go.mod file
*
* This will accept either a directory path containing a `go.mod` file
* or a filepath to your `go.mod` file (i.e. `path/to/go.mod`).
*
* This will be used as the source of the volume mounted in the Docker
* container and will be the directory where it will run `go build` from.
*
* @default - the path is found by walking up parent directories searching for
* a `go.mod` file from the location of `entry`
*/
readonly moduleDir: string;
/**
* The path to the folder or file that contains the main application entry point files for the project.
*
* This accepts either a path to a directory or file.
*
* If a directory path is provided then it will assume there is a Go entry file (i.e. `main.go`) and
* will construct the build command using the directory path.
*
* For example, if you provide the entry as:
*
* entry: 'my-lambda-app/cmd/api'
*
* Then the `go build` command would be:
*
* `go build ./cmd/api`
*
* If a path to a file is provided then it will use the filepath in the build command.
*
* For example, if you provide the entry as:
*
* entry: 'my-lambda-app/cmd/api/main.go'
*
* Then the `go build` command would be:
*
* `go build ./cmd/api/main.go`
*/
readonly entry: string;
/**
* The runtime of the lambda function
*/
readonly runtime: Runtime;
/**
* The system architecture of the lambda function
*/
readonly architecture: Architecture;
}
/**
* Bundling
*/
export class Bundling implements cdk.BundlingOptions {
public static bundle(options: BundlingProps): AssetCode {
const bundling = new Bundling(options);
return Code.fromAsset(path.dirname(options.moduleDir), {
assetHashType: options.assetHashType ?? cdk.AssetHashType.OUTPUT,
assetHash: options.assetHash,
bundling: {
image: bundling.image,
command: bundling.command,
environment: bundling.environment,
local: bundling.local,
entrypoint: bundling.entrypoint,
volumes: bundling.volumes,
volumesFrom: bundling.volumesFrom,
workingDirectory: bundling.workingDirectory,
user: bundling.user,
securityOpt: bundling.securityOpt,
network: bundling.network,
},
});
}
public static clearRunsLocallyCache(): void { // for tests
this.runsLocally = undefined;
}
private static runsLocally?: boolean;
// Core bundling options
public readonly image: cdk.DockerImage;
public readonly command: string[];
public readonly environment?: { [key: string]: string };
public readonly local?: cdk.ILocalBundling;
public readonly entrypoint?: string[]
public readonly volumes?: cdk.DockerVolume[];
public readonly volumesFrom?: string[];
public readonly workingDirectory?: string;
public readonly user?: string;
public readonly securityOpt?: string;
public readonly network?: string;
private readonly relativeEntryPath: string;
constructor(private readonly props: BundlingProps) {
Bundling.runsLocally = Bundling.runsLocally
?? getGoBuildVersion()
?? false;
const projectRoot = path.dirname(props.moduleDir);
this.relativeEntryPath = `./${path.relative(projectRoot, path.resolve(props.entry))}`;
const cgoEnabled = props.cgoEnabled ? '1' : '0';
const environment: Record<string, string> = {
CGO_ENABLED: cgoEnabled,
GO111MODULE: 'on',
GOARCH: props.architecture.dockerPlatform.split('/')[1],
GOOS: 'linux',
...props.environment,
};
if (props.goProxies) {
environment.GOPROXY = props.goProxies.join(',');
}
// Docker bundling
const shouldBuildImage = props.forcedDockerBundling || !Bundling.runsLocally;
this.image = shouldBuildImage
? props.dockerImage ?? cdk.DockerImage.fromBuild(path.join(__dirname, '../lib'), {
buildArgs: {
...props.buildArgs ?? {},
IMAGE: Runtime.GO_1_X.bundlingImage.image, // always use the GO_1_X build image
},
platform: props.architecture.dockerPlatform,
})
: cdk.DockerImage.fromRegistry('dummy'); // Do not build if we don't need to
const bundlingCommand = this.createBundlingCommand(cdk.AssetStaging.BUNDLING_INPUT_DIR, cdk.AssetStaging.BUNDLING_OUTPUT_DIR);
this.command = props.command ?? ['bash', '-c', bundlingCommand];
this.environment = environment;
this.entrypoint = props.entrypoint;
this.volumes = props.volumes;
this.volumesFrom = props.volumesFrom;
this.workingDirectory = props.workingDirectory;
this.user = props.user;
this.securityOpt = props.securityOpt;
this.network = props.network;
// Local bundling
if (!props.forcedDockerBundling) { // only if Docker is not forced
const osPlatform = os.platform();
const createLocalCommand = (outputDir: string) => this.createBundlingCommand(projectRoot, outputDir, osPlatform);
this.local = {
tryBundle(outputDir: string) {
if (Bundling.runsLocally == false) {
process.stderr.write('go build cannot run locally. Switching to Docker bundling.\n');
return false;
}
const localCommand = createLocalCommand(outputDir);
exec(
osPlatform === 'win32' ? 'cmd' : 'bash',
[
osPlatform === 'win32' ? '/c' : '-c',
localCommand,
],
{
env: { ...process.env, ...environment ?? {} },
stdio: [ // show output
'ignore', // ignore stdio
process.stderr, // redirect stdout to stderr
'inherit', // inherit stderr
],
cwd: path.dirname(props.moduleDir),
windowsVerbatimArguments: osPlatform === 'win32',
},
);
return true;
},
};
}
}
public createBundlingCommand(inputDir: string, outputDir: string, osPlatform: NodeJS.Platform = 'linux'): string {
const pathJoin = osPathJoin(osPlatform);
const hasVendor = findUp('vendor', path.dirname(this.props.entry));
const goBuildCommand: string = [
'go', 'build',
hasVendor ? '-mod=vendor': '',
'-o', `${pathJoin(outputDir, 'bootstrap')}`,
`${this.props.goBuildFlags ? this.props.goBuildFlags.join(' ') : ''}`,
`${this.relativeEntryPath.replace(/\\/g, '/')}`,
].filter(c => !!c).join(' ');
return chain([
...this.props.commandHooks?.beforeBundling(inputDir, outputDir) ?? [],
goBuildCommand,
...this.props.commandHooks?.afterBundling(inputDir, outputDir) ?? [],
]);
}
}
/**
* Platform specific path join
*/
function osPathJoin(platform: NodeJS.Platform) {
return function(...paths: string[]): string {
const joined = path.join(...paths);
// If we are on win32 but need posix style paths
if (os.platform() === 'win32' && platform !== 'win32') {
return joined.replace(/\\/g, '/');
}
return joined;
};
}
function chain(commands: string[]): string {
return commands.filter(c => !!c).join(' && ');
}