Skip to content

Commit e219b4a

Browse files
npalmgertjanmaas
andauthored
sync GitHub action distribution to S3 (#5)
* WIP lambda to sync s3 dist * Add update check * Add syncer * Refactor * Refactor to functions * Fix terraform validate * Fix error * Add linter, clenup * Add modules to root modules * Update modules/action-runner-binary-cache/variables.tf Co-authored-by: Gertjan Maas <[email protected]> * Fix review comments * Update jabascript libs * Add aws tags * Update default example Co-authored-by: Gertjan Maas <[email protected]>
1 parent d3d580e commit e219b4a

File tree

25 files changed

+5072
-8
lines changed

25 files changed

+5072
-8
lines changed

.github/workflows/lambda-syncer.yml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
name: Lambda Runner Distribution Syncer
2+
on:
3+
push:
4+
branches:
5+
- master
6+
pull_request:
7+
paths:
8+
- .github/workflows/lambda-agent-webhook.yml
9+
- "modules/action-runner-binary-cache/lambdas/syncer/**"
10+
11+
jobs:
12+
build:
13+
runs-on: ubuntu-latest
14+
container: node:12
15+
defaults:
16+
run:
17+
working-directory: modules/action-runner-binary-cache/lambdas/syncer
18+
19+
steps:
20+
- uses: actions/checkout@v2
21+
- name: Install dependencies
22+
run: yarn install
23+
- name: Run linter
24+
run: yarn lint
25+
- name: Build distribution
26+
run: yarn build

.github/workflows/terraform.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ jobs:
1818
steps:
1919
- name: "Checkout"
2020
uses: actions/checkout@v2
21+
- name: "Fake zip files" # Validate will fail if it cannot find the zip files
22+
run: |
23+
touch modules/action-runner-binary-cache/lambdas/syncer/syncer.zip
24+
touch modules/agent/lambdas/webhook/webhook.zip
2125
- name: "Terraform Format"
2226
uses: hashicorp/terraform-github-actions@master
2327
with:

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,6 @@
1313
*.out
1414
example/*.secrets*.tfvars
1515
.envrc
16+
*.zip
17+
*.gz
18+
*.tgz

examples/default/main.tf

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
locals {
2-
environment = "default-action-runners"
2+
environment = "default"
33
aws_region = "eu-west-1"
44
}
55

6+
7+
resource "random_password" "random" {
8+
length = 32
9+
}
10+
11+
612
module "runners" {
713
source = "../../"
814

@@ -14,5 +20,8 @@ module "runners" {
1420
Project = "ProjectX"
1521
}
1622

23+
github_app_webhook_secret = random_password.random.result
24+
1725
}
1826

27+

examples/default/outputs.tf

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,13 @@ output "action_runners" {
33
runners = module.runners.runners
44
}
55
}
6+
7+
8+
output "lambda_syncer_function_name" {
9+
value = module.runners.lambda_s3_action_runner_dist_syncer.id
10+
}
11+
12+
13+
output "github_app_webhook_secret" {
14+
value = random_password.random.result
15+
}

main.tf

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
locals {
2+
tags = merge(var.tags, {
3+
Environment = var.environment
4+
})
5+
6+
}
17
resource "random_string" "random" {
28
length = 24
39
special = false
@@ -9,7 +15,7 @@ module "dsitrubtion_cache" {
915

1016
aws_region = var.aws_region
1117
environment = var.environment
12-
tags = var.tags
18+
tags = local.tags
1319

1420
distribution_bucket_name = "${var.environment}-dist-${random_string.random.result}"
1521
}
@@ -20,12 +26,23 @@ module "runners" {
2026
aws_region = var.aws_region
2127
vpc_id = var.vpc_id
2228
environment = var.environment
23-
tags = var.tags
29+
tags = local.tags
2430

2531
s3_location_runner_distribution = module.dsitrubtion_cache.s3_location_runner_distribution
2632
}
2733

2834

35+
module "agent" {
36+
source = "./modules/agent"
37+
38+
aws_region = var.aws_region
39+
environment = var.environment
40+
tags = local.tags
41+
42+
github_app_webhook_secret = var.github_app_webhook_secret
43+
}
44+
45+
2946
resource "aws_iam_policy" "dist_bucket" {
3047
name = "${var.environment}-gh-distribution-bucket"
3148
path = "/"
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
module.exports = {
2+
root: true,
3+
parser: '@typescript-eslint/parser',
4+
plugins: ['@typescript-eslint'],
5+
extends: [
6+
'eslint:recommended',
7+
'plugin:@typescript-eslint/eslint-recommended',
8+
'plugin:@typescript-eslint/recommended',
9+
],
10+
};
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# dependencies
2+
node_modules/
3+
4+
# production
5+
dist/
6+
build/
7+
8+
# misc
9+
.DS_Store
10+
.env*
11+
*.zip
12+
13+
npm-debug.log*
14+
yarn-debug.log*
15+
yarn-error.log*
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
v12.16.1
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"printWidth": 120,
3+
"singleQuote": true,
4+
"trailingComma": "all"
5+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module.exports = {
2+
preset: 'ts-jest',
3+
testEnvironment: 'node',
4+
};
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
{
2+
"name": "github-runner-lambda-syncer",
3+
"version": "1.0.0",
4+
"main": "lambda.ts",
5+
"license": "MIT",
6+
"scripts": {
7+
"start": "ts-node-dev src/local.ts",
8+
"test": "NODE_ENV=test jest",
9+
"test:watch": "NODE_ENV=test jest --watch",
10+
"lint": "yarn eslint --ext ts,tsx src",
11+
"watch": "ts-node-dev --respawn --exit-child src/local.ts",
12+
"build": "ncc build src/lambda.ts -o dist",
13+
"dist": "yarn build && cd dist && zip ../syncer.zip index.js"
14+
},
15+
"devDependencies": {
16+
"@octokit/rest": "^17.6.0",
17+
"@types/jest": "^25.2.1",
18+
"@types/node": "^13.13.4",
19+
"@types/request": "^2.48.4",
20+
"@typescript-eslint/eslint-plugin": "^2.30.0",
21+
"@typescript-eslint/parser": "^2.30.0",
22+
"@zeit/ncc": "^0.22.1",
23+
"aws-sdk": "^2.645.0",
24+
"eslint": "^6.8.0",
25+
"jest": "^25.4.0",
26+
"ts-jest": "^25.4.0",
27+
"ts-node-dev": "^1.0.0-pre.44",
28+
"typescript": "^3.8.3"
29+
}
30+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { handle } from './syncer/handler';
2+
3+
module.exports.handler = async (event: any, context: any, callback: any): Promise<any> => {
4+
await handle();
5+
return callback();
6+
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { handle } from './syncer/handler';
2+
3+
handle()
4+
.then()
5+
.catch((e) => {
6+
console.log(e);
7+
});
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import { Octokit } from '@octokit/rest';
2+
import { PassThrough } from 'stream';
3+
import request from 'request';
4+
import { S3 } from 'aws-sdk';
5+
import AWS from 'aws-sdk';
6+
7+
AWS.config.update({
8+
region: process.env.AWS_REGION,
9+
});
10+
const s3 = new S3();
11+
12+
const versionKey = 'name';
13+
const bucketName = process.env.S3_BUCKET_NAME as string;
14+
const bucketObjectKey = process.env.S3_OBJECT_KEY as string;
15+
if (!bucketName || !bucketObjectKey) {
16+
throw new Error('Please check all mandatory variables are set.');
17+
}
18+
19+
async function getCachedVersion(): Promise<string | undefined> {
20+
try {
21+
const objectTagging = await s3
22+
.getObjectTagging({
23+
Bucket: bucketName,
24+
Key: bucketObjectKey,
25+
})
26+
.promise();
27+
const versions = objectTagging.TagSet?.filter((t: S3.Tag) => t.Key === versionKey);
28+
return versions.length === 1 ? versions[0].Value : undefined;
29+
} catch (e) {
30+
console.debug('No tags found');
31+
return undefined;
32+
}
33+
}
34+
35+
interface ReleaseAsset {
36+
name: string;
37+
downloadUrl: string;
38+
}
39+
40+
async function getLinuxReleaseAsset(): Promise<ReleaseAsset | undefined> {
41+
const githubClient = new Octokit();
42+
const linuxAssets = (
43+
await githubClient.repos.getLatestRelease({
44+
owner: 'actions',
45+
repo: 'runner',
46+
})
47+
).data.assets.filter((a) => a.name?.includes('actions-runner-linux-x64-'));
48+
return linuxAssets?.length === 1
49+
? { name: linuxAssets[0].name, downloadUrl: linuxAssets[0].browser_download_url }
50+
: undefined;
51+
}
52+
53+
async function uploadToS3(actionRunnerReleaseAsset: ReleaseAsset): Promise<void> {
54+
const writeStream = new PassThrough();
55+
s3.upload({
56+
Bucket: bucketName,
57+
Key: bucketObjectKey,
58+
Tagging: versionKey + '=' + actionRunnerReleaseAsset.name,
59+
Body: writeStream,
60+
}).promise();
61+
62+
await new Promise((resolve, reject) => {
63+
console.debug('Start downloading %s and uploading to S3.', actionRunnerReleaseAsset.name);
64+
request
65+
.get(actionRunnerReleaseAsset.downloadUrl)
66+
.pipe(writeStream)
67+
.on('finish', () => {
68+
console.info(`The new distribution is uploaded to S3.`);
69+
resolve();
70+
})
71+
.on('error', (error) => {
72+
reject(error);
73+
});
74+
}).catch((error) => {
75+
console.error(`Exception: ${error}`);
76+
});
77+
}
78+
79+
export const handle = async (): Promise<void> => {
80+
const actionRunnerReleaseAsset = await getLinuxReleaseAsset();
81+
if (actionRunnerReleaseAsset === undefined) {
82+
throw Error('Cannot find github release asset.');
83+
}
84+
85+
const currentVersion = await getCachedVersion();
86+
console.log('latest: ' + currentVersion);
87+
if (currentVersion === undefined || currentVersion != actionRunnerReleaseAsset.name) {
88+
uploadToS3(actionRunnerReleaseAsset);
89+
} else {
90+
console.debug('Distribution is up-to-date, no action.');
91+
}
92+
};
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
{
2+
"compilerOptions": {
3+
/* Basic Options */
4+
"target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
5+
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
6+
"outDir": "build",
7+
"lib": ["es2020", "DOM"] /* Specify library files to be included in the compilation. */,
8+
"allowJs": true /* Allow javascript files to be compiled. */,
9+
// "checkJs": true, /* Report errors in .js files. */
10+
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
11+
// "declaration": true, /* Generates corresponding '.d.ts' file. */
12+
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
13+
// "sourceMap": true, /* Generates corresponding '.map' file. */
14+
// "outFile": "./", /* Concatenate and emit output to single file. */
15+
// "outDir": "./", /* Redirect output structure to the directory. */
16+
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
17+
// "composite": true, /* Enable project compilation */
18+
// "incremental": true, /* Enable incremental compilation */
19+
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
20+
// "removeComments": true, /* Do not emit comments to output. */
21+
// "noEmit": true, /* Do not emit outputs. */
22+
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
23+
"downlevelIteration": true /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */,
24+
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
25+
/* Strict Type-Checking Options */
26+
"strict": true /* Enable all strict type-checking options. */,
27+
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
28+
// "strictNullChecks": true, /* Enable strict null checks. */
29+
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
30+
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
31+
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
32+
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
33+
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
34+
/* Additional Checks */
35+
// "noUnusedLocals": true, /* Report errors on unused locals. */
36+
// "noUnusedParameters": true, /* Report errors on unused parameters. */
37+
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
38+
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
39+
/* Module Resolution Options */
40+
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
41+
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
42+
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
43+
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
44+
// "typeRoots": [] /* List of folders to include type definitions from. */,
45+
// "types": [] /* Type declaration files to be included in compilation. */,
46+
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
47+
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
48+
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
49+
/* Source Map Options */
50+
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
51+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
52+
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
53+
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
54+
/* Experimental Options */
55+
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
56+
"emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,
57+
"resolveJsonModule": true
58+
},
59+
"include": ["src/**/*"]
60+
}

0 commit comments

Comments
 (0)