-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
runner.ts
434 lines (394 loc) · 15 KB
/
runner.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
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
import * as cdk from 'aws-cdk-lib';
import {
aws_ec2 as ec2,
aws_iam as iam,
aws_lambda as lambda,
aws_stepfunctions as stepfunctions,
aws_stepfunctions_tasks as stepfunctions_tasks,
} from 'aws-cdk-lib';
import { FunctionUrlAuthType } from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';
import { CodeBuildRunner } from './providers/codebuild';
import { IRunnerProvider } from './providers/common';
import { FargateRunner } from './providers/fargate';
import { LambdaRunner } from './providers/lambda';
import { Secrets } from './secrets';
import { BundledNodejsFunction } from './utils';
import { GithubWebhookHandler } from './webhook';
/**
* Properties for GitHubRunners
*/
export interface GitHubRunnersProps {
/**
* List of runner providers to use. At least one provider is required. Provider will be selected when its label matches the labels requested by the workflow job.
*
* @default CodeBuild, Lambda and Fargate runners with all the defaults (no VPC or default account VPC)
*/
readonly providers?: IRunnerProvider[];
/**
* VPC used for all management functions. Use this with GitHub Enterprise Server hosted that's inaccessible from outside the VPC.
*/
readonly vpc?: ec2.IVpc;
/**
* VPC subnets used for all management functions. Use this with GitHub Enterprise Server hosted that's inaccessible from outside the VPC.
*/
readonly vpcSubnets?: ec2.SubnetSelection;
/**
* Allow management functions to run in public subnets. Lambda Functions in a public subnet can NOT access the internet.
*
* @default false
*/
readonly allowPublicSubnet?: boolean;
/**
* Security group attached to all management functions. Use this with to provide access to GitHub Enterprise Server hosted inside a VPC.
*/
readonly securityGroup?: ec2.ISecurityGroup;
/**
* Path to a directory containing a file named certs.pem containing any additional certificates required to trust GitHub Enterprise Server. Use this when GitHub Enterprise Server certificates are self-signed.
*
* You may also want to use custom images for your runner providers that contain the same certificates. See {@link CodeBuildImageBuilder.addCertificates}.
*
* ```typescript
* const imageBuilder = new CodeBuildImageBuilder(this, 'Image Builder with Certs', {
* dockerfilePath: CodeBuildRunner.LINUX_X64_DOCKERFILE_PATH,
* });
* imageBuilder.addExtraCertificates('path-to-my-extra-certs-folder');
*
* const provider = new CodeBuildRunner(this, 'CodeBuild', {
* imageBuilder: imageBuilder,
* });
*
* new GitHubRunners(
* this,
* 'runners',
* {
* providers: [provider],
* extraCertificates: 'path-to-my-extra-certs-folder',
* }
* );
* ```
*/
readonly extraCertificates?: string;
/**
* Time to wait before stopping a runner that remains idle. If the user cancelled the job, or if another runner stole it, this stops the runner to avoid wasting resources.
*
* @default 10 minutes
*/
readonly idleTimeout?: cdk.Duration;
}
/**
* Create all the required infrastructure to provide self-hosted GitHub runners. It creates a webhook, secrets, and a step function to orchestrate all runs. Secrets are not automatically filled. See README.md for instructions on how to setup GitHub integration.
*
* By default, this will create a runner provider of each available type with the defaults. This is good enough for the initial setup stage when you just want to get GitHub integration working.
*
* ```typescript
* new GitHubRunners(this, 'runners');
* ```
*
* Usually you'd want to configure the runner providers so the runners can run in a certain VPC or have certain permissions.
*
* ```typescript
* const vpc = ec2.Vpc.fromLookup(this, 'vpc', { vpcId: 'vpc-1234567' });
* const runnerSg = new ec2.SecurityGroup(this, 'runner security group', { vpc: vpc });
* const dbSg = ec2.SecurityGroup.fromSecurityGroupId(this, 'database security group', 'sg-1234567');
* const bucket = new s3.Bucket(this, 'runner bucket');
*
* // create a custom CodeBuild provider
* const myProvider = new CodeBuildRunner(
* this, 'codebuild runner',
* {
* label: 'my-codebuild',
* vpc: vpc,
* securityGroup: runnerSg,
* },
* );
* // grant some permissions to the provider
* bucket.grantReadWrite(myProvider);
* dbSg.connections.allowFrom(runnerSg, ec2.Port.tcp(3306), 'allow runners to connect to MySQL database');
*
* // create the runner infrastructure
* new GitHubRunners(
* this,
* 'runners',
* {
* providers: [myProvider],
* }
* );
* ```
*/
export class GitHubRunners extends Construct {
private readonly props: GitHubRunnersProps;
/**
* Configured runner providers.
*/
readonly providers: IRunnerProvider[];
/**
* Secrets for GitHub communication including webhook secret and runner authentication.
*/
readonly secrets: Secrets;
private readonly webhook: GithubWebhookHandler;
private readonly orchestrator: stepfunctions.StateMachine;
private readonly setupUrl: string;
private readonly extraLambdaEnv: {[p: string]: string} = {};
private readonly extraLambdaProps: lambda.FunctionOptions;
constructor(scope: Construct, id: string, props?: GitHubRunnersProps) {
super(scope, id);
this.props = props ?? {};
this.secrets = new Secrets(this, 'Secrets');
this.extraLambdaProps = {
vpc: this.props.vpc,
vpcSubnets: this.props.vpcSubnets,
allowPublicSubnet: this.props.allowPublicSubnet,
securityGroups: this.props.securityGroup ? [this.props.securityGroup] : undefined,
layers: this.props.extraCertificates ? [new lambda.LayerVersion(scope, 'Certificate Layer', {
description: 'Layer containing GitHub Enterprise Server certificate for cdk-github-runners',
code: lambda.Code.fromAsset(this.props.extraCertificates),
})] : undefined,
};
if (this.props.extraCertificates) {
this.extraLambdaEnv.NODE_EXTRA_CA_CERTS = '/opt/certs.pem';
}
if (this.props.providers) {
this.providers = this.props.providers;
} else {
this.providers = [
new CodeBuildRunner(this, 'CodeBuild', {}),
new LambdaRunner(this, 'Lambda', {}),
new FargateRunner(this, 'Fargate', {}),
];
}
this.orchestrator = this.stateMachine(props);
this.webhook = new GithubWebhookHandler(this, 'Webhook Handler', {
orchestrator: this.orchestrator,
secrets: this.secrets,
});
this.setupUrl = this.setupFunction();
this.statusFunction();
}
private stateMachine(props?: GitHubRunnersProps) {
const tokenRetrieverTask = new stepfunctions_tasks.LambdaInvoke(
this,
'Get Runner Token',
{
lambdaFunction: this.tokenRetriever(),
payloadResponseOnly: true,
resultPath: '$.runner',
},
);
let deleteRunnerFunction = this.deleteRunner();
const deleteRunnerTask = new stepfunctions_tasks.LambdaInvoke(
this,
'Delete Runner',
{
lambdaFunction: deleteRunnerFunction,
payloadResponseOnly: true,
resultPath: '$.delete',
payload: stepfunctions.TaskInput.fromObject({
runnerName: stepfunctions.JsonPath.stringAt('$$.Execution.Name'),
owner: stepfunctions.JsonPath.stringAt('$.owner'),
repo: stepfunctions.JsonPath.stringAt('$.repo'),
runId: stepfunctions.JsonPath.stringAt('$.runId'),
installationId: stepfunctions.JsonPath.stringAt('$.installationId'),
idleOnly: false,
}),
},
);
deleteRunnerTask.addRetry({
errors: [
'RunnerBusy',
],
interval: cdk.Duration.minutes(1),
backoffRate: 1,
maxAttempts: 60,
});
const waitForIdleRunner = new stepfunctions.Wait(this, 'Wait', {
time: stepfunctions.WaitTime.duration(props?.idleTimeout ?? cdk.Duration.minutes(10)),
});
const deleteIdleRunnerTask = new stepfunctions_tasks.LambdaInvoke(
this,
'Delete Idle Runner',
{
lambdaFunction: deleteRunnerFunction,
payloadResponseOnly: true,
resultPath: '$.delete',
payload: stepfunctions.TaskInput.fromObject({
runnerName: stepfunctions.JsonPath.stringAt('$$.Execution.Name'),
owner: stepfunctions.JsonPath.stringAt('$.owner'),
repo: stepfunctions.JsonPath.stringAt('$.repo'),
runId: stepfunctions.JsonPath.stringAt('$.runId'),
installationId: stepfunctions.JsonPath.stringAt('$.installationId'),
idleOnly: true,
}),
},
);
const providerChooser = new stepfunctions.Choice(this, 'Choose provider');
for (const provider of this.providers) {
const providerTask = provider.getStepFunctionTask(
{
runnerTokenPath: stepfunctions.JsonPath.stringAt('$.runner.token'),
runnerNamePath: stepfunctions.JsonPath.stringAt('$$.Execution.Name'),
githubDomainPath: stepfunctions.JsonPath.stringAt('$.runner.domain'),
ownerPath: stepfunctions.JsonPath.stringAt('$.owner'),
repoPath: stepfunctions.JsonPath.stringAt('$.repo'),
},
);
providerChooser.when(
stepfunctions.Condition.and(
...provider.labels.map(
label => stepfunctions.Condition.isPresent(`$.labels.${label}`),
),
),
providerTask,
);
}
providerChooser.otherwise(new stepfunctions.Succeed(this, 'Unknown label'));
const work = tokenRetrieverTask.next(
new stepfunctions.Parallel(this, 'Error Catcher', { resultPath: '$.result' })
.branch(providerChooser)
.branch(waitForIdleRunner.next(deleteIdleRunnerTask))
.addCatch(
deleteRunnerTask
.next(new stepfunctions.Fail(this, 'Runner Failed')),
{
resultPath: '$.error',
},
),
);
const check = new stepfunctions.Choice(this, 'Is self hosted?')
.when(stepfunctions.Condition.isNotPresent('$.labels.self-hosted'), new stepfunctions.Succeed(this, 'No'))
.otherwise(work);
return new stepfunctions.StateMachine(
this,
'Runner Orchestrator',
{
definition: check,
},
);
}
private tokenRetriever() {
const func = new BundledNodejsFunction(
this,
'token-retriever',
{
description: 'Get token from GitHub Actions used to start new self-hosted runner',
environment: {
GITHUB_SECRET_ARN: this.secrets.github.secretArn,
GITHUB_PRIVATE_KEY_SECRET_ARN: this.secrets.githubPrivateKey.secretArn,
...this.extraLambdaEnv,
},
timeout: cdk.Duration.seconds(30),
...this.extraLambdaProps,
},
);
this.secrets.github.grantRead(func);
this.secrets.githubPrivateKey.grantRead(func);
return func;
}
private deleteRunner() {
const func = new BundledNodejsFunction(
this,
'delete-runner',
{
description: 'Delete GitHub Actions runner on error',
environment: {
GITHUB_SECRET_ARN: this.secrets.github.secretArn,
GITHUB_PRIVATE_KEY_SECRET_ARN: this.secrets.githubPrivateKey.secretArn,
...this.extraLambdaEnv,
},
timeout: cdk.Duration.seconds(30),
...this.extraLambdaProps,
},
);
this.secrets.github.grantRead(func);
this.secrets.githubPrivateKey.grantRead(func);
return func;
}
private statusFunction() {
const statusFunction = new BundledNodejsFunction(
this,
'status',
{
description: 'Provide user with status about self-hosted GitHub Actions runners',
environment: {
WEBHOOK_SECRET_ARN: this.secrets.webhook.secretArn,
GITHUB_SECRET_ARN: this.secrets.github.secretArn,
GITHUB_PRIVATE_KEY_SECRET_ARN: this.secrets.githubPrivateKey.secretArn,
SETUP_SECRET_ARN: this.secrets.setup.secretArn,
WEBHOOK_URL: this.webhook.url,
WEBHOOK_HANDLER_ARN: this.webhook.handler.latestVersion.functionArn,
STEP_FUNCTION_ARN: this.orchestrator.stateMachineArn,
SETUP_FUNCTION_URL: this.setupUrl,
...this.extraLambdaEnv,
},
timeout: cdk.Duration.minutes(3),
...this.extraLambdaProps,
},
);
const providers = this.providers.map(provider => {
provider.image.imageRepository.grant(statusFunction, 'ecr:DescribeImages');
return {
type: provider.constructor.name,
labels: provider.labels,
vpcArn: provider.vpc?.vpcArn,
securityGroup: provider.securityGroup?.securityGroupId,
roleArn: (provider.grantPrincipal.grantPrincipal as iam.Role).roleArn,
image: {
imageRepository: provider.image.imageRepository.repositoryUri,
imageTag: provider.image.imageTag,
imageBuilderLogGroup: provider.image.logGroup?.logGroupName,
},
};
});
// expose providers as stack metadata as it's too big for Lambda environment variables
// specifically integration testing got an error because lambda update request was >5kb
const stack = cdk.Stack.of(this);
const f = (statusFunction.node.defaultChild as lambda.CfnFunction);
f.addPropertyOverride('Environment.Variables.LOGICAL_ID', f.logicalId);
f.addPropertyOverride('Environment.Variables.STACK_NAME', stack.stackName);
f.addMetadata('providers', providers);
statusFunction.addToRolePolicy(new iam.PolicyStatement({
actions: ['cloudformation:DescribeStackResource'],
resources: [stack.stackId],
}));
this.secrets.webhook.grantRead(statusFunction);
this.secrets.github.grantRead(statusFunction);
this.secrets.githubPrivateKey.grantRead(statusFunction);
this.secrets.setup.grantRead(statusFunction);
this.orchestrator.grantRead(statusFunction);
new cdk.CfnOutput(
this,
'status command',
{
value: `aws --region ${stack.region} lambda invoke --function-name ${statusFunction.functionName} status.json`,
},
);
}
private setupFunction(): string {
const setupFunction = new BundledNodejsFunction(
this,
'setup',
{
description: 'Setup GitHub Actions integration with self-hosted runners',
environment: {
SETUP_SECRET_ARN: this.secrets.setup.secretArn,
WEBHOOK_SECRET_ARN: this.secrets.webhook.secretArn,
GITHUB_SECRET_ARN: this.secrets.github.secretArn,
GITHUB_PRIVATE_KEY_SECRET_ARN: this.secrets.githubPrivateKey.secretArn,
WEBHOOK_URL: this.webhook.url,
...this.extraLambdaEnv,
},
timeout: cdk.Duration.minutes(3),
...this.extraLambdaProps,
},
);
// this.secrets.webhook.grantRead(setupFunction);
this.secrets.webhook.grantWrite(setupFunction);
this.secrets.github.grantRead(setupFunction);
this.secrets.github.grantWrite(setupFunction);
// this.secrets.githubPrivateKey.grantRead(setupFunction);
this.secrets.githubPrivateKey.grantWrite(setupFunction);
this.secrets.setup.grantRead(setupFunction);
this.secrets.setup.grantWrite(setupFunction);
return setupFunction.addFunctionUrl({ authType: FunctionUrlAuthType.NONE }).url;
}
}