From 10a2e8f8bb3d067b58409ccc2c38a9ca72b74a63 Mon Sep 17 00:00:00 2001 From: sethvincent Date: Mon, 5 Mar 2018 00:00:25 -0500 Subject: [PATCH 01/14] wip implementation --- .circleci/config.yml | 13 +++++ .gitignore | 10 ++++ .nvmrc | 1 + CONTRIBUTING.md | 44 +++++++++++++++ Dockerfile | 27 +++++++++ README.md | 52 ++++++++++++++++- bin/service.js | 47 ++++++++++++++++ index.js | 131 +++++++++++++++++++++++++++++++++++++++++++ package.json | 33 +++++++++++ 9 files changed, 357 insertions(+), 1 deletion(-) create mode 100644 .circleci/config.yml create mode 100644 .gitignore create mode 100644 .nvmrc create mode 100644 CONTRIBUTING.md create mode 100644 Dockerfile create mode 100644 bin/service.js create mode 100644 index.js create mode 100644 package.json diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..84a73ae --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,13 @@ +version: 2 +jobs: + build: + docker: + - image: docker:17.12.1-ce + working_directory: ~/ecs-lambda-runner + steps: + - checkout + - setup_remote_docker + - run: | + docker build -t developmentseed/cumulus:lambda-runner . + docker login -u scisco -p $DOCKER_PASSWORD + docker push developmentseed/cumulus:lambda-runner diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..64418ba --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +node_modules +build/ +dist/ +test-reports +tmp +.tmp +config/authorized_keys +config/cloudformation.yml +cache-invalidation/config/runtime_config.json +.env diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..3c02432 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +6.10.3 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a880603 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,44 @@ +# Contributing + +Thanks for considering contributing and making our planet easier to explore! + +We're excited you would like to contribute to Cumulus! Whether you're finding bugs, adding new features, fixing anything broken, or improving documentation, get started by submitting an issue or pull request! + +## Submitting an Issue + +If you have any questions or ideas, or notice any problems or bugs, first [search open issues](https://github.com/cumulus-nasa/cumulus-ecs-task/issues) to see if the issue has already been submitted. We may already be working on the issue. If you think your issue is new, you're welcome to [create a new issue](https://github.com/cumulus-nasa/cumulus-ecs-task/issues/new). + +## Pull Requests + +If you want to submit your own contributions, follow these steps: + +* Fork the Cumulus repo +* Create a new branch from the branch you'd like to contribute to +* If an issue does't already exist, submit one (see above) +* [Create a pull request](https://help.github.com/articles/creating-a-pull-request/) from your fork into the target branch of the cumulus-nasa/cumulus repo +* Be sure to [mention the corresponding issue number](https://help.github.com/articles/closing-issues-using-keywords/) in the PR description, i.e. "Fixes Issue #10" +* Upon submission of a pull request, the Cumulus development team will review the code +* The request will then either be merged, declined, or an adjustment to the code will be requested + +## Guidelines + +We ask that you follow these guidelines with your contributions: + +### Tests + +All of the automated tests for this project need to pass before your submission will be accepted. You can run `npm test` in the command line after making changes to verify that the tests pass. If you add new functionality, please consider adding tests for that functionality as well. + +### Commits + +* Make small commits that show the individual changes you are making +* Write descriptive commit messages that explain your changes + +Example of a good commit message; + +``` +Improve contributing guidelines. Fixes #10 + +Improve contributing docs and consolidate them in the standard location https://help.github.com/articles/setting-guidelines-for-repository-contributors/ +``` + +### For more information on Cumulus governance, see the [Cumulus Code Contribution Guidelines](https://docs.google.com/document/d/14J_DS6nyQ32BpeVjdR-YKfzHAzFB299tKghPGshXUTU/edit) and [the Cumulus Wiki](https://wiki.earthdata.nasa.gov/display/CUMULUS/Cumulus). \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6c37122 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,27 @@ +FROM centos:6 + +USER root +RUN yum install -y unzip + +COPY . /home/runner + +RUN groupadd -r runner -g 433 \ + && useradd -u 431 -r -g runner -d /home/runner -s /sbin/nologin -c "Docker image user" runner \ + && chown -R runner:runner /home/runner + +USER runner + +RUN curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash +ENV NODE_VERSION 6.10.3 +RUN . $HOME/.nvm/nvm.sh && nvm install $NODE_VERSION +ENV NVM_PATH $HOME/.nvm/versions/node/v$NODE_VERSION/lib/node +ENV NVM_DIR $HOME/.nvm +ENV PATH /home/runner/.nvm/versions/node/v$NODE_VERSION/bin:$PATH +ENV NVM_BIN $HOME/.nvm/versions/node/v$NODE_VERSION/bin + + +WORKDIR /home/runner + +RUN npm install + +ENTRYPOINT [ "node", "--harmony", "bin/service.js" ] diff --git a/README.md b/README.md index 787f84f..76b5e35 100644 --- a/README.md +++ b/README.md @@ -1 +1,51 @@ -# cumulus-ecs-task \ No newline at end of file +# cumulus-ecs-task + +Use this Docker image to run a Node.js Lambda function in AWS [ECS](https://aws.amazon.com/ecs/). + +## Environment variables expected + +`AWS_DEFAULT_REGION` – defaults to `us-east-1` + +## Useful Commands + +To build: + +``` +npm run docker:build +``` + +To run locally: + +``` +./bin/service.js --activityArn --lambdaArn +``` + +To run in Docker locally: + +``` +docker run -e AWS_ACCESS_KEY_ID='' \ + -e AWS_SECRET_ACCESS_KEY='' \ + cumuluss/cumulus-ecs-task \ + --activityArn \ + --lambdaArn \ +``` + +To deploy to the AWS repo: + +``` +export AWS_ACCOUNT_ID= +docker tag cumulus-ecs-task:latest $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/cumulus-ecs-task:latest +docker push $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/cumulus-ecs-task:latest + +``` + +To clean up local deployments after repeated builds: + +``` +npm run docker:clean +``` + +## Contributing + +## License +[Apache-2.0](LICENSE) diff --git a/bin/service.js b/bin/service.js new file mode 100644 index 0000000..4fc95eb --- /dev/null +++ b/bin/service.js @@ -0,0 +1,47 @@ +const fs = require('fs'); + +const minimist = require('minimist'); +const createCliOptions = require('cliclopts'); +const rimraf = require('rimraf'); + +const runService = require('../index'); + +const dir = path.join(process.cwd(), 'tmp'); + +var cliOptions = createCliOptions([ + { + name: 'directory', + abbr: 'd', + default: dir, + help: 'path to temporary directory' + }, + { + name: 'event', + abbr: 'e', + help: 'JSON string of an AWS Lambda event' + }, + { + name: 'context', + abbr: 'c', + help: 'JSON string of an AWS Lambda context' + }, + { + name: 'lambdaArn', + abbr: 'l', + help: 'the arn of the lambda function that will run on ecs' + }, + { + name: 'activityArn', + abbr: 'a', + help: 'the arn of the step function activity for this task' + } +]); + +var argv = minimist(process.argv.slice(2), cliOptions.options()); + +rimraf.sync(dir); +fs.mkdirSync(dir); + +// get args +// runService(dir, args) +process.on('exit', () => rimraf.sync(dir)); diff --git a/index.js b/index.js new file mode 100644 index 0000000..77e7563 --- /dev/null +++ b/index.js @@ -0,0 +1,131 @@ +"use strict"; +/* eslint-disable no-console */ +const https = require('https'); +const path = require('path'); +const execSync = require('child_process').execSync; +const assert = require('assert'); +const EventEmitter = require('events').EventEmitter; + +const AWS = require('aws-sdk'); +const fs = require('fs'); +const rimraf = require('rimraf'); + +const region = process.env.AWS_DEFAULT_REGION || 'us-east-1'; +AWS.config.update({ region: region }); + +const sqs = new AWS.SQS({ apiVersion: '2012-11-05' }); +const sf = new AWS.StepFunctions({ apiVersion: '2016-11-23' }); + +/** +* Download the zip file of a lambda function from AWS +* +* @param {string} arn - the arn of the lambda function +* @param {strind} dir – the dir to download the lambda function to +* @param {function} callback - callback function with `err`, `filepath`, `moduleFileName`, +* and `moduleFunctionName` arguments. +* The `filepath` is the path to the zip file of the lambda function. +* The `moduleFileName` is the filename of the node module. +* The `moduleFunctionName` is the name of the exported function to call in the module. +**/ +function getLambdaZip (arn, dir, callback) { + const lambda = new AWS.Lambda({ apiVersion: '2015-03-31' }); + + lambda.getFunction({ FunctionName: arn }, function (err, data) { + if (err) return callback(err); + + const codeUrl = data.Code.Location; + const handlerId = data.Configuration.Handler; + const moduleFn = handlerId.split('.'); + const moduleFileName = moduleFn[0]; + const moduleFunctionName = moduleFn[1]; + + const filepath = path.join(dir, 'fn.zip'); + const file = fs.createWriteStream(filepath); + + file.on('error' callback); + file.on('finish', () => file.close()); + file.on('close', () => callback(null, filepath, moduleFileName, moduleFunctionName)); + + https.get(codeUrl, (res) => res.pipe(file)); + }); +} + +/** +* Downloads and extracts the code of a lambda function from its zip file +* +* @param {string} arn - the arn of the lambda function +* @param {strind} dir – the dir to download the lambda function to +* @param {function} callback - callback function with `err`, `handler` arguments +* the `handler` is the javascript function that will run in the ECS service +**/ +function downloadLambdaHandler (arn, dir, callback) { + return getLambdaZip(arn, dir, function (err, filepath, moduleFileName, moduleFunctionName) { + if (err) return callback(err); + + // TODO: consider making the target dir configurable + execSync('unzip -o ' + filepath + ' -d ./'); + const task = require(`./${moduleFileName}`); //eslint-disable-line global-require + callback(null, task[moduleFunctionName]); + }) +} + +/** +* +**/ +function pollForWork (activityArn) { + const emitter = new EventEmitter(); + + const interval = setInterval(function () { + sf.getActivityTask({ activityArn: activityArn }, function (err, data) { + if (err) return emitter.emit('error', err); + emitter.emit('data', data); + }); + }, 500); + + return emitter +} + +/** +* +**/ +function runService (options, callback) { + assert(options && typeof options === 'object', 'options.lambdaArn string is required'); + assert(options.lambdaArn && typeof options.lambdaArn === 'string', 'options.lambdaArn string is required'); + assert(options.activityArn && typeof options.activityArn === 'string', 'options.activityArn string is required'); + assert(options.directory && typeof options.directory === 'string', 'options.directory string is required'); + + const lambdaArn = options.lambdaArn; + const activityArn = options.activityArn; + const dir = options.directory; + + downloadLambdaHandler(arn, dir, function (err, handler) { + if (err) return callback(err) + + const work = pollForWork(activityArn); + work.on('error', callback); + + work.on('data', function (data) { + console.log('data', data) + const token = data.token; + const input = JSON.parse(data.input); + const event = input.event; + const context = input.context; + + handler(event, context, function (err, output) { + if (err) { + return sf.sendTaskFailure({ + taskToken: token, + error: err.toString() + }) + } + + sf.sendTaskSuccess({ + taskToken: token, + output: output + }); + }); + }); + }); +} + +module.exports = runService; diff --git a/package.json b/package.json new file mode 100644 index 0000000..51e8e0d --- /dev/null +++ b/package.json @@ -0,0 +1,33 @@ +{ + "name": "@cumulus/cumulus-ecs-task", + "version": "1.0.0", + "description": "Run lambda functions in ECS", + "main": "index.js", + "bin": { + "cumulus-ecs-task": "index.js" + }, + "keywords": [ + "CUMULUS", + "GIBS", + "NASA" + ], + "repository": { + "type": "git", + "url": "git@github.com:cumulus-nasa/cumulus-ecs-task.git" + }, + "license": "Apache-2.0", + "dependencies": { + "aws-sdk": "^2.203.0", + "cliclopts": "^1.1.1", + "lodash": "^4.17.5", + "minimist": "^1.2.0", + "rimraf": "^2.6.2" + }, + "scripts": { + "docker:build": "docker build -t cumulus-ecs-task .", + "docker:push": "docker push cumuluss/cumulus-ecs-task", + "docker:deploy": "npm run docker:build && npm run docker:push", + "docker:clean": "docker rm -v $(docker ps -a -q -f status=exited); docker rmi $(docker images -f \"dangling=true\" -q); true" + }, + "devDependencies": {} +} From 330a8a8c2a8211ad5d182f0baebd0ada99d9e319 Mon Sep 17 00:00:00 2001 From: sethvincent Date: Mon, 5 Mar 2018 11:31:23 -0500 Subject: [PATCH 02/14] add jsdoc comments --- index.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/index.js b/index.js index 77e7563..2ddd7c0 100644 --- a/index.js +++ b/index.js @@ -70,7 +70,10 @@ function downloadLambdaHandler (arn, dir, callback) { } /** +* Polls for work for the given activity arn * +* @param {string} activityArn - the lambda activity arn +* @return {object} - eventEmitter emits `data` and `error` events **/ function pollForWork (activityArn) { const emitter = new EventEmitter(); @@ -86,7 +89,12 @@ function pollForWork (activityArn) { } /** +* Start the Lambda handler as a service * +* @param {object} options - options object +* @param {string} options.lambdaArn - the arn of the lambda handler +* @param {string} options.activityArn - the arn of the activity +* @param {string} options.directory - the directory to put the lambda zip file in **/ function runService (options, callback) { assert(options && typeof options === 'object', 'options.lambdaArn string is required'); From 6698feb886f093f6853ffc20ddcecc3c7d54abd0 Mon Sep 17 00:00:00 2001 From: sethvincent Date: Mon, 5 Mar 2018 13:00:02 -0500 Subject: [PATCH 03/14] update circleci --- .circleci/config.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 84a73ae..7c66daf 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,11 +3,11 @@ jobs: build: docker: - image: docker:17.12.1-ce - working_directory: ~/ecs-lambda-runner + working_directory: ~/cumulus-ecs-task steps: - checkout - setup_remote_docker - run: | - docker build -t developmentseed/cumulus:lambda-runner . - docker login -u scisco -p $DOCKER_PASSWORD - docker push developmentseed/cumulus:lambda-runner + docker build -t cumuluss/cumulus-ecs-task . + docker login -u cumulususer -p $DOCKER_PASSWORD + docker push cumuluss/cumulus-ecs-task From 73fa4d21d0cfcc025041e838efc62a049297b2e7 Mon Sep 17 00:00:00 2001 From: sethvincent Date: Mon, 5 Mar 2018 22:13:10 -0500 Subject: [PATCH 04/14] improve release process, fix code errors --- .circleci/config.yml | 2 +- .gitignore | 2 ++ README.md | 17 ++++++------ bin/release.sh | 8 ++++++ bin/service.js | 49 ++++++++++++++++++++------------ index.js | 66 ++++++++++++++++++++++++-------------------- package.json | 3 +- 7 files changed, 89 insertions(+), 58 deletions(-) create mode 100755 bin/release.sh mode change 100644 => 100755 bin/service.js diff --git a/.circleci/config.yml b/.circleci/config.yml index 7c66daf..b2433d6 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -10,4 +10,4 @@ jobs: - run: | docker build -t cumuluss/cumulus-ecs-task . docker login -u cumulususer -p $DOCKER_PASSWORD - docker push cumuluss/cumulus-ecs-task + ./bin/release.sh diff --git a/.gitignore b/.gitignore index 64418ba..ba9be3a 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ config/authorized_keys config/cloudformation.yml cache-invalidation/config/runtime_config.json .env +cumulus-message-adapter +task diff --git a/README.md b/README.md index 76b5e35..b846bbb 100644 --- a/README.md +++ b/README.md @@ -27,25 +27,26 @@ docker run -e AWS_ACCESS_KEY_ID='' \ -e AWS_SECRET_ACCESS_KEY='' \ cumuluss/cumulus-ecs-task \ --activityArn \ - --lambdaArn \ + --lambdaArn ``` -To deploy to the AWS repo: +## Create a release -``` -export AWS_ACCOUNT_ID= -docker tag cumulus-ecs-task:latest $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/cumulus-ecs-task:latest -docker push $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/cumulus-ecs-task:latest +Bump the version +``` +npm version ``` -To clean up local deployments after repeated builds: +Create the build ``` -npm run docker:clean +./bin/build.sh ``` ## Contributing +See the [CONTRIBUTING.md](CONTRIBUTING.md) file. + ## License [Apache-2.0](LICENSE) diff --git a/bin/release.sh b/bin/release.sh new file mode 100755 index 0000000..c9f1809 --- /dev/null +++ b/bin/release.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +IMAGE=cumuluss/cumulus-ecs-task +VERSION=$(cat package.json | node_modules/.bin/jsonfilter version | sed -e 's/^"//' -e 's/"$//') +echo $VERSION + +docker tag $IMAGE:latest $IMAGE:$VERSION +docker push $IMAGE:$VERSION diff --git a/bin/service.js b/bin/service.js old mode 100644 new mode 100755 index 4fc95eb..a065d77 --- a/bin/service.js +++ b/bin/service.js @@ -1,4 +1,7 @@ +#!/usr/bin/env node + const fs = require('fs'); +const path = require('path'); const minimist = require('minimist'); const createCliOptions = require('cliclopts'); @@ -6,42 +9,52 @@ const rimraf = require('rimraf'); const runService = require('../index'); -const dir = path.join(process.cwd(), 'tmp'); +const taskDir = path.join(process.cwd(), 'task'); +const workDir = path.join(process.cwd(), '.tmp-work'); var cliOptions = createCliOptions([ { name: 'directory', abbr: 'd', - default: dir, - help: 'path to temporary directory' - }, - { - name: 'event', - abbr: 'e', - help: 'JSON string of an AWS Lambda event' + alias: ['taskDirectory'], + default: taskDir, + help: 'path to task directory' }, { - name: 'context', - abbr: 'c', - help: 'JSON string of an AWS Lambda context' + name: 'work-directory', + abbr: 'w', + alias: ['workDirectory'], + default: workDir, + help: 'path to temporary working directory' }, { - name: 'lambdaArn', + name: 'lambda-arn', abbr: 'l', + alias: ['lambdaArn'], help: 'the arn of the lambda function that will run on ecs' }, { - name: 'activityArn', + name: 'activity-arn', abbr: 'a', + alias: ['activityArn'], help: 'the arn of the step function activity for this task' } ]); var argv = minimist(process.argv.slice(2), cliOptions.options()); +console.log('argv', argv); -rimraf.sync(dir); -fs.mkdirSync(dir); +rimraf.sync(argv.taskDirectory); +rimraf.sync(argv.workDirectory); + +fs.mkdirSync(argv.taskDirectory); +fs.mkdirSync(argv.workDirectory); + +runService(argv, function (err) { + if (err) { + console.log(err); + process.exit(1); + } +}); -// get args -// runService(dir, args) -process.on('exit', () => rimraf.sync(dir)); +process.on('exit', () => rimraf.sync(argv.workDirectory)); diff --git a/index.js b/index.js index 2ddd7c0..4cc4ada 100644 --- a/index.js +++ b/index.js @@ -20,14 +20,14 @@ const sf = new AWS.StepFunctions({ apiVersion: '2016-11-23' }); * Download the zip file of a lambda function from AWS * * @param {string} arn - the arn of the lambda function -* @param {strind} dir – the dir to download the lambda function to +* @param {strind} workDir – the dir to download the lambda function to * @param {function} callback - callback function with `err`, `filepath`, `moduleFileName`, * and `moduleFunctionName` arguments. * The `filepath` is the path to the zip file of the lambda function. * The `moduleFileName` is the filename of the node module. * The `moduleFunctionName` is the name of the exported function to call in the module. **/ -function getLambdaZip (arn, dir, callback) { +function getLambdaZip (arn, workDir, callback) { const lambda = new AWS.Lambda({ apiVersion: '2015-03-31' }); lambda.getFunction({ FunctionName: arn }, function (err, data) { @@ -39,10 +39,10 @@ function getLambdaZip (arn, dir, callback) { const moduleFileName = moduleFn[0]; const moduleFunctionName = moduleFn[1]; - const filepath = path.join(dir, 'fn.zip'); + const filepath = path.join(workDir, 'fn.zip'); const file = fs.createWriteStream(filepath); - file.on('error' callback); + file.on('error', callback); file.on('finish', () => file.close()); file.on('close', () => callback(null, filepath, moduleFileName, moduleFunctionName)); @@ -58,13 +58,13 @@ function getLambdaZip (arn, dir, callback) { * @param {function} callback - callback function with `err`, `handler` arguments * the `handler` is the javascript function that will run in the ECS service **/ -function downloadLambdaHandler (arn, dir, callback) { - return getLambdaZip(arn, dir, function (err, filepath, moduleFileName, moduleFunctionName) { +function downloadLambdaHandler (arn, workDir, taskDir, callback) { + return getLambdaZip(arn, workDir, function (err, filepath, moduleFileName, moduleFunctionName) { if (err) return callback(err); - // TODO: consider making the target dir configurable - execSync('unzip -o ' + filepath + ' -d ./'); - const task = require(`./${moduleFileName}`); //eslint-disable-line global-require + // TODO: consider making the target dir of `task` configurable + execSync(`unzip -o ${filepath} -d ${taskDir}`); + const task = require(`${taskDir}/${moduleFileName}`); //eslint-disable-line global-require callback(null, task[moduleFunctionName]); }) } @@ -94,19 +94,22 @@ function pollForWork (activityArn) { * @param {object} options - options object * @param {string} options.lambdaArn - the arn of the lambda handler * @param {string} options.activityArn - the arn of the activity -* @param {string} options.directory - the directory to put the lambda zip file in +* @param {string} options.taskDirectory - the directory to put the unzipped lambda zip +* @param {string} options.workDirectory - the directory to use for downloading the lambda zip file **/ function runService (options, callback) { assert(options && typeof options === 'object', 'options.lambdaArn string is required'); assert(options.lambdaArn && typeof options.lambdaArn === 'string', 'options.lambdaArn string is required'); assert(options.activityArn && typeof options.activityArn === 'string', 'options.activityArn string is required'); - assert(options.directory && typeof options.directory === 'string', 'options.directory string is required'); + assert(options.taskDirectory && typeof options.taskDirectory === 'string', 'options.taskDirectory string is required'); + assert(options.workDirectory && typeof options.workDirectory === 'string', 'options.workDirectory string is required'); const lambdaArn = options.lambdaArn; const activityArn = options.activityArn; - const dir = options.directory; - - downloadLambdaHandler(arn, dir, function (err, handler) { + const taskDir = options.taskDirectory; + const workDir = options.workDirectory; + + downloadLambdaHandler(lambdaArn, workDir, taskDir, function (err, handler) { if (err) return callback(err) const work = pollForWork(activityArn); @@ -114,24 +117,27 @@ function runService (options, callback) { work.on('data', function (data) { console.log('data', data) - const token = data.token; - const input = JSON.parse(data.input); - const event = input.event; - const context = input.context; - - handler(event, context, function (err, output) { - if (err) { - return sf.sendTaskFailure({ - taskToken: token, - error: err.toString() - }) - } - sf.sendTaskSuccess({ - taskToken: token, - output: output + if (data.token && data.input) { + const token = data.token; + const input = JSON.parse(data.input); + const event = input.event; + const context = input.context; + + handler(event, context, function (err, output) { + if (err) { + return sf.sendTaskFailure({ + taskToken: token, + error: err.toString() + }) + } + + sf.sendTaskSuccess({ + taskToken: token, + output: output + }); }); - }); + } }); }); } diff --git a/package.json b/package.json index 51e8e0d..a353c9e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@cumulus/cumulus-ecs-task", - "version": "1.0.0", + "version": "0.0.1", "description": "Run lambda functions in ECS", "main": "index.js", "bin": { @@ -19,6 +19,7 @@ "dependencies": { "aws-sdk": "^2.203.0", "cliclopts": "^1.1.1", + "jsonfilter": "^1.1.2", "lodash": "^4.17.5", "minimist": "^1.2.0", "rimraf": "^2.6.2" From 9049d8101c33e5bc22403e9beef56222e1f1385e Mon Sep 17 00:00:00 2001 From: sethvincent Date: Tue, 6 Mar 2018 20:53:37 -0500 Subject: [PATCH 05/14] bug fixes --- bin/service.js | 1 - index.js | 41 ++++++++++++++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/bin/service.js b/bin/service.js index a065d77..3ffa344 100755 --- a/bin/service.js +++ b/bin/service.js @@ -42,7 +42,6 @@ var cliOptions = createCliOptions([ ]); var argv = minimist(process.argv.slice(2), cliOptions.options()); -console.log('argv', argv); rimraf.sync(argv.taskDirectory); rimraf.sync(argv.workDirectory); diff --git a/index.js b/index.js index 4cc4ada..b6b09ef 100644 --- a/index.js +++ b/index.js @@ -61,8 +61,7 @@ function getLambdaZip (arn, workDir, callback) { function downloadLambdaHandler (arn, workDir, taskDir, callback) { return getLambdaZip(arn, workDir, function (err, filepath, moduleFileName, moduleFunctionName) { if (err) return callback(err); - - // TODO: consider making the target dir of `task` configurable + execSync(`unzip -o ${filepath} -d ${taskDir}`); const task = require(`${taskDir}/${moduleFileName}`); //eslint-disable-line global-require callback(null, task[moduleFunctionName]); @@ -80,6 +79,7 @@ function pollForWork (activityArn) { const interval = setInterval(function () { sf.getActivityTask({ activityArn: activityArn }, function (err, data) { + console.log('getActivityTask response', err, data) if (err) return emitter.emit('error', err); emitter.emit('data', data); }); @@ -88,6 +88,21 @@ function pollForWork (activityArn) { return emitter } +/** +* Starts heartbeat to indicate worker is working on the task +* +* @param {string} token - the task token +**/ +function startHeartbeat (token) { + return setInterval(function () { + sf.sendTaskHeartbeat({ taskToken: token }, function (err, data) { + if (err) { + console.log('error sending heartbeat', err); + } + }, 60000); + }); +} + /** * Start the Lambda handler as a service * @@ -108,6 +123,8 @@ function runService (options, callback) { const activityArn = options.activityArn; const taskDir = options.taskDirectory; const workDir = options.workDirectory; + + process.env.CUMULUS_MESSAGE_ADAPTER_DIR=`${taskDir}/cumulus-message-adapter/` downloadLambdaHandler(lambdaArn, workDir, taskDir, function (err, handler) { if (err) return callback(err) @@ -116,25 +133,31 @@ function runService (options, callback) { work.on('error', callback); work.on('data', function (data) { - console.log('data', data) - if (data.token && data.input) { - const token = data.token; - const input = JSON.parse(data.input); - const event = input.event; - const context = input.context; + if (data.taskToken && data.input) { + const token = data.taskToken; + const event = JSON.parse(data.input); + const context = { via: 'ECS' }; + + const heartbeat = startHeartbeat(token); handler(event, context, function (err, output) { + clearInterval(heartbeat); + if (err) { return sf.sendTaskFailure({ taskToken: token, error: err.toString() + }, function(err, data) { + console.log('sendTaskFailure response', err.stack, data) }) } sf.sendTaskSuccess({ taskToken: token, - output: output + output: JSON.stringify(output) + }, function(err, data) { + console.log('sendTaskSuccess response', err.stack, data) }); }); } From 32a11df6390581a1663b6a5ace25eab2dcabe0ad Mon Sep 17 00:00:00 2001 From: sethvincent Date: Wed, 7 Mar 2018 19:59:28 -0500 Subject: [PATCH 06/14] improve implementation, lint fixes, eslintrc file, license file, update readme --- .eslintrc.json | 97 ++++++++++++++++++++ LICENSE | 60 +++++++++++++ README.md | 174 +++++++++++++++++++++++++++++++++-- bin/service.js | 17 ++-- index.js | 239 +++++++++++++++++++++++++++++++++---------------- package.json | 19 ++-- 6 files changed, 509 insertions(+), 97 deletions(-) create mode 100644 .eslintrc.json create mode 100644 LICENSE diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..c8ae692 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,97 @@ +{ + "root": true, + "extends": "airbnb", + "plugins": ["eslint-plugin-jsdoc"], + "parser": "babel-eslint", + "env": { + "node": true, + "mocha": true + }, + "rules": { + "require-jsdoc": ["error", { + "require": { + "FunctionDeclaration": true, + "MethodDefinition": true, + "ClassDeclaration": true, + "ArrowFunctionExpression": true + } + }], + "valid-jsdoc": [ "error", { + "prefer": { + "arg": "param", + "return": "returns" + }, + "preferType": { + "Boolean": "boolean", + "Number": "number", + "String": "string", + "object": "Object", + "array": "Array", + "date": "Date", + "regexp": "RegExp", + "Regexp": "RegExp", + "promise": "Promise" + }, + "requireReturn": true + }], + "jsdoc/check-param-names": "error", + "jsdoc/check-tag-names": "error", + "jsdoc/check-types": "off", + "jsdoc/newline-after-description": "error", + "jsdoc/require-description-complete-sentence": "off", + "jsdoc/require-example": "off", + "jsdoc/require-hyphen-before-param-description": "error", + "jsdoc/require-param": "error", + "jsdoc/require-param-description": "error", + "jsdoc/require-param-name": "error", + "jsdoc/require-param-type": "error", + "jsdoc/require-returns-description": "error", + "jsdoc/require-returns-type": "error", + "generator-star-spacing": "off", + "import/no-extraneous-dependencies": "off", + "import/newline-after-import": "off", + "no-warning-comments": [ + 2, + { + "terms": [ + "TODO", + "fixme" + ], + "location": "anywhere" + } + ], + "no-unused-vars": [ + "error", + { "argsIgnorePattern": "^_" } + ], + "no-useless-escape": "off", + "no-console": "warn", + "spaced-comment": "off", + "require-yield": "off", + "prefer-template": "warn", + "no-underscore-dangle": "off", + "comma-dangle": [ + "warn", + "never" + ], + "strict": "off", + "guard-for-in": "off", + "object-shorthand": "off", + "space-before-function-paren": [ + "warn", + "never" + ], + "brace-style": [ + 2, + "stroustrup" + ], + "max-len": [ + 2, + { + "code": 100, + "ignorePattern": "(https?:|JSON\\.parse|[Uu]rl =)" + } + ], + "arrow-parens": ["error", "always"] + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..251c5b9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,60 @@ +Copyright © 2017 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICE NSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +--- + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + You must give any other recipients of the Work or Derivative Works a copy of this License; and + You must cause any modified files to carry prominent notices stating that You changed the files; and + You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.md b/README.md index b846bbb..06ea966 100644 --- a/README.md +++ b/README.md @@ -2,22 +2,140 @@ Use this Docker image to run a Node.js Lambda function in AWS [ECS](https://aws.amazon.com/ecs/). -## Environment variables expected +## About -`AWS_DEFAULT_REGION` – defaults to `us-east-1` +cumulus-ecs-task is a Docker image that can run Lambda functions as ECS services. -## Useful Commands +When included in a Cumulus workflow and deployed to AWS, it will download a specified Lambda function, and act as an activity in a Step Functions workflow. -To build: +## Compatibility + +TODO: update when new cumulus release goes out with cumulus-message-adapter-js version bump + +This only works with Node.js Lmabda functions. + +## Usage + +Like other Cumulus libraries, cumulus-ecs-task is designed to be deployed to AWS using [kes](https://github.com/developmentseed/kes) to manage Cloudformation config. This documentation assumes you're working with a Cumulus deployment and that you have files and directory stucture similar to what's found in the [cumulus template repository](https://github.com/cumulus-nasa/template-deploy). + +Most importantly, we'll need to edit these files: + +- lambdas.yml +- workflows.yml +- app/config.yml +- iam/cloudformation.template.yml + +### Options + +This library has two options: + +- `activityArn` **required** + - The arn of the activity in a step functions workflow. Used to receive messages for that activity and send success/failure responses. +- `lambdaArn` **required** + - The arn of the lambda function you want to run in ECS. + +### lambdas.yml config + +There's no config in lambdas.yml that is special to ecs-cumulus-task, just make sure to add the lambda that will be run in ECS. We won't use that lambda directly in workflows.yml, but we will reference the arn of the lambda in workflows.yml. + +### workflows.yml config + +An example state of a workflow in workflows.yml: ``` -npm run docker:build +EcsTaskHelloWorld: + CumulusConfig: + buckets: '{$.meta.buckets}' + provider: '{$.meta.provider}' + collection: '{$.meta.collection}' + Type: Task + Resource: ${EcsTaskHelloWorldActivity} + Next: < ... next state in the workflow ... > ``` +The important line is `Resource: ${EcsTaskHelloWorldActivity}`. + +We'll define that activity in the app/config.yml file. + +### ECS config + +This library requires additional configuration to be added to the app/config.yml file under the `ecs` block, as well as a list of activity names under `activities`. + +Here's an example: + +```yml +yourdeployment: + ecs: + instanceType: t2.small + desiredInstances: 1 + availabilityZone: us-east-1a + imageId: ami-a7a242da + publicIp: true + docker: + username: cumulususer + services: + EcsTaskHelloWorld: + image: cumuluss/cumulus-ecs-task:0.0.1 + cpu: 800 + memory: 1500 + count: 0 + envs: + AWS_DEFAULT_REGION: + function: Fn::Sub + value: '${AWS::Region}' + commands: + - cumulus-ecs-task + - '--activityArn' + - function: Ref + value: EcsTaskHelloWorldActivity + - '--lambdaArn' + - function: Ref + value: EcsTaskHelloWorldLambdaFunction + + activities: + - name: EcsTaskHelloWorld +``` + +Under `activities` we define the activity name `EcsTaskHelloWorld`, which can then be referenced to in the `ecs` section and in workflows.yml as `EcsTaskHelloWorldActivity`. + +We can give our service the same name as the activity. Be sure to double-check the options like `cpu`, `memory`, and others to be sure they'll work with your use case. + +Note that under the the `commands` section we're referencing the `EcsTaskHelloWorldActivity` as the `activityArn` and the `EcsTaskHelloWorldLambdaFunction` as the `lambdaArn`. + + +### IAM permissions + +The `EcsRole` will need to include permissions to send requests to the step functions API. + +The following should be included in the `Statement` of the `EcsRole` policy: + +```yml +# Allow state machine interactions +- Effect: Allow + Action: + - states:SendTaskFailure + - states:SendTaskSuccess + - states:SendTaskHeartbeat + - states:GetActivityTask + Resource: arn:aws:states:*:*:* +``` + +## Environment variables + +- `AWS_DEFAULT_REGION` – defaults to `us-east-1` + +## Development + To run locally: ``` -./bin/service.js --activityArn --lambdaArn +npm start -- --activityArn --lambdaArn +``` + +To build the docker image: + +``` +npm run build ``` To run in Docker locally: @@ -26,10 +144,42 @@ To run in Docker locally: docker run -e AWS_ACCESS_KEY_ID='' \ -e AWS_SECRET_ACCESS_KEY='' \ cumuluss/cumulus-ecs-task \ - --activityArn \ - --lambdaArn + --activityArn \ + --lambdaArn +``` + +### To test a workflow while developing locally + +You can execute workflows on AWS that test the version of cumulus-ecs-task that you're developing on locally. + +First, make sure that the ECS cluster for your deployment has zero tasks running that might respond to a workflow's requests. + +That way only your local version will respond to your workflow. + +Next, start ecs-cumulus-task locally. + +Either with node: + +``` +npm start -- --activityArn --lambdaArn +``` + +Or with docker: + +``` +# build the image +npm run build + +# run the image +docker run -e AWS_ACCESS_KEY_ID='' \ + -e AWS_SECRET_ACCESS_KEY='' \ + cumuluss/cumulus-ecs-task \ + --activityArn \ + --lambdaArn ``` +Finally, trigger a workflow. You can do this from the Cumulus dashboard, the Cumulus API, or with the AWS Console by supplying a + ## Create a release Bump the version @@ -41,7 +191,13 @@ npm version Create the build ``` -./bin/build.sh +npm run build +``` + +Release to Docker Hub + +``` +npm run release ``` ## Contributing diff --git a/bin/service.js b/bin/service.js index 3ffa344..31c837b 100755 --- a/bin/service.js +++ b/bin/service.js @@ -12,7 +12,7 @@ const runService = require('../index'); const taskDir = path.join(process.cwd(), 'task'); const workDir = path.join(process.cwd(), '.tmp-work'); -var cliOptions = createCliOptions([ +const cliOptions = createCliOptions([ { name: 'directory', abbr: 'd', @@ -38,10 +38,16 @@ var cliOptions = createCliOptions([ abbr: 'a', alias: ['activityArn'], help: 'the arn of the step function activity for this task' + }, + { + name: 'heartbeat', + abbr: 'h', + help: 'interval in milliseconds between sending heartbeat messages to the state machine. ' + + 'default is null, which disables the heartbeat' } ]); -var argv = minimist(process.argv.slice(2), cliOptions.options()); +const argv = minimist(process.argv.slice(2), cliOptions.options()); rimraf.sync(argv.taskDirectory); rimraf.sync(argv.workDirectory); @@ -49,11 +55,6 @@ rimraf.sync(argv.workDirectory); fs.mkdirSync(argv.taskDirectory); fs.mkdirSync(argv.workDirectory); -runService(argv, function (err) { - if (err) { - console.log(err); - process.exit(1); - } -}); +runService(argv); process.on('exit', () => rimraf.sync(argv.workDirectory)); diff --git a/index.js b/index.js index b6b09ef..b46f8fa 100644 --- a/index.js +++ b/index.js @@ -1,5 +1,5 @@ -"use strict"; -/* eslint-disable no-console */ +'use strict'; +/* eslint-disable no-console, max-len */ const https = require('https'); const path = require('path'); const execSync = require('child_process').execSync; @@ -8,29 +8,28 @@ const EventEmitter = require('events').EventEmitter; const AWS = require('aws-sdk'); const fs = require('fs'); -const rimraf = require('rimraf'); const region = process.env.AWS_DEFAULT_REGION || 'us-east-1'; AWS.config.update({ region: region }); -const sqs = new AWS.SQS({ apiVersion: '2012-11-05' }); const sf = new AWS.StepFunctions({ apiVersion: '2016-11-23' }); /** * Download the zip file of a lambda function from AWS * * @param {string} arn - the arn of the lambda function -* @param {strind} workDir – the dir to download the lambda function to +* @param {strind} workDir - the dir to download the lambda function to * @param {function} callback - callback function with `err`, `filepath`, `moduleFileName`, * and `moduleFunctionName` arguments. * The `filepath` is the path to the zip file of the lambda function. * The `moduleFileName` is the filename of the node module. * The `moduleFunctionName` is the name of the exported function to call in the module. +* @returns {undefined} - callback is used instead of return value **/ -function getLambdaZip (arn, workDir, callback) { +function getLambdaZip(arn, workDir, callback) { const lambda = new AWS.Lambda({ apiVersion: '2015-03-31' }); - lambda.getFunction({ FunctionName: arn }, function (err, data) { + lambda.getFunction({ FunctionName: arn }, (err, data) => { if (err) return callback(err); const codeUrl = data.Code.Location; @@ -46,122 +45,212 @@ function getLambdaZip (arn, workDir, callback) { file.on('finish', () => file.close()); file.on('close', () => callback(null, filepath, moduleFileName, moduleFunctionName)); - https.get(codeUrl, (res) => res.pipe(file)); + return https.get(codeUrl, (res) => res.pipe(file)); }); } /** * Downloads and extracts the code of a lambda function from its zip file * -* @param {string} arn - the arn of the lambda function -* @param {strind} dir – the dir to download the lambda function to +* @param {string} lambdaArn - the arn of the lambda function +* @param {string} workDir - the temporary dir used to download the lambda zip file +* @param {string} taskDir - the dir where the lambda function will be located * @param {function} callback - callback function with `err`, `handler` arguments * the `handler` is the javascript function that will run in the ECS service +* @returns {undefined} - callback is used instead of return value **/ -function downloadLambdaHandler (arn, workDir, taskDir, callback) { - return getLambdaZip(arn, workDir, function (err, filepath, moduleFileName, moduleFunctionName) { - if (err) return callback(err); - - execSync(`unzip -o ${filepath} -d ${taskDir}`); - const task = require(`${taskDir}/${moduleFileName}`); //eslint-disable-line global-require - callback(null, task[moduleFunctionName]); - }) +function downloadLambdaHandler(lambdaArn, workDir, taskDir, callback) { + // return getLambdaZip(lambdaArn, workDir, (err, filepath, moduleFileName, moduleFunctionName) => { + // if (err) return callback(err); + // + // execSync(`unzip -o ${filepath} -d ${taskDir}`); + // const task = require(`${taskDir}/${moduleFileName}`); //eslint-disable-line global-require + // return callback(null, task[moduleFunctionName]); + // }); + return callback(null, require('./task/index').handler); } /** -* Polls for work for the given activity arn +* Starts heartbeat to indicate worker is working on the task * -* @param {string} activityArn - the lambda activity arn -* @return {object} - eventEmitter emits `data` and `error` events +* @param {string} taskToken - the task token +* @returns {intervalId} - interval id used by `clearInterval` **/ -function pollForWork (activityArn) { - const emitter = new EventEmitter(); - - const interval = setInterval(function () { - sf.getActivityTask({ activityArn: activityArn }, function (err, data) { - console.log('getActivityTask response', err, data) - if (err) return emitter.emit('error', err); - emitter.emit('data', data); - }); - }, 500); +function startHeartbeat(taskToken) { + return setInterval(() => { + sf.sendTaskHeartbeat({ taskToken }, (err) => { + if (err) { + console.log('error sending heartbeat', err); + } + }, 60000); + }); +} - return emitter +/** +* Tells workflow that the task has failed +* +* @param {string} taskToken - the task token +* @param {Object} taskError - the error +* @returns {undefined} - no return value +**/ +function sendTaskFailure(taskToken, taskError) { + sf.sendTaskFailure({ + taskToken: taskToken, + error: taskError.toString() + }, (err) => { + if (err) { + console.log('sendTaskFailure err', err); + } + }); } /** -* Starts heartbeat to indicate worker is working on the task +* Tells workflow that the task has succeeded and provides message for next task * -* @param {string} token - the task token +* @param {string} taskToken - the task token +* @param {Object} output - output message for next task +* @returns {undefined} - no return value +**/ +function sendTaskSuccess(taskToken, output) { + sf.sendTaskSuccess({ + taskToken: taskToken, + output: output + }, (err) => { + if (err) { + console.log('sendTasksuccess error', err); + } + }); +} + +/** +* Simple class for polling the state machine for work **/ -function startHeartbeat (token) { - return setInterval(function () { - sf.sendTaskHeartbeat({ taskToken: token }, function (err, data) { +class TaskPoll extends EventEmitter { + /** + * initialize Poll class + * + * @param {string} activityArn - the lambda activity arn + * @returns {undefined} - no return value + **/ + constructor(activityArn) { + super(); + this.activityArn = activityArn; + } + + /** + * start polling + * + * @returns {undefined} - no return value + **/ + start() { + // kick off sf.getActivityTask + this.getTask(); + // repeat every 60 seconds (the timeout of sf.getActivityTask) + this.intervalId = setInterval(() => this.getTask(), 60000); + } + + /** + * repeatedly checks for work using sf.getActivityTask + * + * @returns {undefined} - no return value + **/ + getTask() { + sf.getActivityTask({ activityArn: this.activityArn }, (err, data) => { if (err) { - console.log('error sending heartbeat', err); + this.emit('error', err); } - }, 60000); + else if (data && data.taskToken && data.taskToken.length && data.input) { + const token = data.taskToken; + const event = JSON.parse(data.input); + clearInterval(this.intervalId); + this.emit('data', event, token); + this.start(); + } + }); + } +} + +/** +* Handle the data event from poll.getTask() +* +* @param {Object} event - the event to pass to the lambda function +* @param {string} taskToken - the task token +* @param {function} handler - the lambda function to execute +* @param {integer} heartbeatInterval - number of milliseconds between heartbeat messages. +* defaults to null, which deactivates heartbeats +* @returns {undefined} - no return value +**/ +function handlePollResponse(event, taskToken, handler, heartbeatInterval) { + const context = { via: 'ECS' }; + let heartbeat; + + if (heartbeatInterval) { + heartbeat = startHeartbeat(taskToken); + } + + handler(event, context, (err, output) => { + if (heartbeatInterval) { + clearInterval(heartbeat); + } + + if (err) { + sendTaskFailure(taskToken, err); + } + else { + sendTaskSuccess(taskToken, JSON.stringify(output)); + } }); } /** * Start the Lambda handler as a service * -* @param {object} options - options object +* @param {Object} options - options object * @param {string} options.lambdaArn - the arn of the lambda handler * @param {string} options.activityArn - the arn of the activity +* @param {integer} options.heartbeat - number of milliseconds between heartbeat messages. +* defaults to null, which deactivates heartbeats * @param {string} options.taskDirectory - the directory to put the unzipped lambda zip * @param {string} options.workDirectory - the directory to use for downloading the lambda zip file +* @returns {undefined} - callback is used instead of return value **/ -function runService (options, callback) { +function runService(options) { assert(options && typeof options === 'object', 'options.lambdaArn string is required'); assert(options.lambdaArn && typeof options.lambdaArn === 'string', 'options.lambdaArn string is required'); assert(options.activityArn && typeof options.activityArn === 'string', 'options.activityArn string is required'); assert(options.taskDirectory && typeof options.taskDirectory === 'string', 'options.taskDirectory string is required'); assert(options.workDirectory && typeof options.workDirectory === 'string', 'options.workDirectory string is required'); + if (options.heartbeat) { + assert(Number.isInteger(options.heartbeat), 'options.heartbeat must be an integer'); + } const lambdaArn = options.lambdaArn; const activityArn = options.activityArn; const taskDir = options.taskDirectory; const workDir = options.workDirectory; + const heartbeatInterval = options.heartbeat; - process.env.CUMULUS_MESSAGE_ADAPTER_DIR=`${taskDir}/cumulus-message-adapter/` - - downloadLambdaHandler(lambdaArn, workDir, taskDir, function (err, handler) { - if (err) return callback(err) + // the cumulus-message-adapter dir is in an unexpected place, + // so tell the adapter where to find it + process.env.CUMULUS_MESSAGE_ADAPTER_DIR = `${taskDir}/cumulus-message-adapter/`; - const work = pollForWork(activityArn); - work.on('error', callback); + downloadLambdaHandler(lambdaArn, workDir, taskDir, (downloadError, handler) => { + if (downloadError) { + // if lambda isn't downloaded, throw the error, as nothing else will work + throw downloadError; + } - work.on('data', function (data) { + const poll = new TaskPoll(activityArn, heartbeatInterval); - if (data.taskToken && data.input) { - const token = data.taskToken; - const event = JSON.parse(data.input); - const context = { via: 'ECS' }; - - const heartbeat = startHeartbeat(token); - - handler(event, context, function (err, output) { - clearInterval(heartbeat); - - if (err) { - return sf.sendTaskFailure({ - taskToken: token, - error: err.toString() - }, function(err, data) { - console.log('sendTaskFailure response', err.stack, data) - }) - } - - sf.sendTaskSuccess({ - taskToken: token, - output: JSON.stringify(output) - }, function(err, data) { - console.log('sendTaskSuccess response', err.stack, data) - }); - }); - } + poll.on('error', (err) => { + console.log('error polling for work with sf.getActivityTask', err); }); + + poll.on('data', (event, taskToken) => { + handlePollResponse(event, taskToken, handler, heartbeatInterval); + }); + + poll.start(); }); } diff --git a/package.json b/package.json index a353c9e..d4b1edb 100644 --- a/package.json +++ b/package.json @@ -19,16 +19,25 @@ "dependencies": { "aws-sdk": "^2.203.0", "cliclopts": "^1.1.1", - "jsonfilter": "^1.1.2", "lodash": "^4.17.5", "minimist": "^1.2.0", + "respawn": "^2.5.0", "rimraf": "^2.6.2" }, "scripts": { - "docker:build": "docker build -t cumulus-ecs-task .", - "docker:push": "docker push cumuluss/cumulus-ecs-task", - "docker:deploy": "npm run docker:build && npm run docker:push", + "start": "./bin/service.js", + "build": "docker build -t cumulus-ecs-task .", + "release": "./bin/release.sh", "docker:clean": "docker rm -v $(docker ps -a -q -f status=exited); docker rmi $(docker images -f \"dangling=true\" -q); true" }, - "devDependencies": {} + "devDependencies": { + "babel-eslint": "^6.1.2", + "eslint": "^3.2.2", + "eslint-config-airbnb": "^10.0.0", + "eslint-plugin-import": "^1.13.0", + "eslint-plugin-jsdoc": "^3.3.1", + "eslint-plugin-jsx-a11y": "^2.1.0", + "eslint-plugin-react": "^6.0.0", + "jsonfilter": "^1.1.2" + } } From 3ed5e241b8c79b11da0464a3c3c79dcee5da378c Mon Sep 17 00:00:00 2001 From: sethvincent Date: Wed, 7 Mar 2018 20:10:50 -0500 Subject: [PATCH 07/14] revise circleci --- .circleci/config.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index b2433d6..52345d0 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,4 +1,5 @@ version: 2 + jobs: build: docker: @@ -11,3 +12,12 @@ jobs: docker build -t cumuluss/cumulus-ecs-task . docker login -u cumulususer -p $DOCKER_PASSWORD ./bin/release.sh + +workflows: + version: 2 + build_release: + jobs: + - build + # filters: + # branches: + # only: master From db025a65871403226aaf186013a2cb976ea3caca Mon Sep 17 00:00:00 2001 From: sethvincent Date: Wed, 7 Mar 2018 20:17:18 -0500 Subject: [PATCH 08/14] improve circleci, dockerfile, and release.sh, fix typo, bump version --- .circleci/config.yml | 12 ++++++------ .gitignore | 1 + Dockerfile | 26 ++++++++------------------ bin/release.sh | 18 +++++++++++++++--- index.js | 15 +++++++-------- package.json | 4 ++-- 6 files changed, 39 insertions(+), 37 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 52345d0..2103dd6 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,23 +1,23 @@ version: 2 jobs: - build: + release: docker: - - image: docker:17.12.1-ce - working_directory: ~/cumulus-ecs-task + - image: circleci/node:6 + working_directory: ~/project steps: - checkout - setup_remote_docker - run: | - docker build -t cumuluss/cumulus-ecs-task . - docker login -u cumulususer -p $DOCKER_PASSWORD + echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc + npm install ./bin/release.sh workflows: version: 2 build_release: jobs: - - build + - release # filters: # branches: # only: master diff --git a/.gitignore b/.gitignore index ba9be3a..661372d 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ cache-invalidation/config/runtime_config.json .env cumulus-message-adapter task +.tmp-work diff --git a/Dockerfile b/Dockerfile index 6c37122..a7261d8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,26 +1,16 @@ -FROM centos:6 +FROM node:6.10.3 USER root -RUN yum install -y unzip +RUN apt-get update +RUN apt-get install -y unzip -COPY . /home/runner +COPY . /home/service -RUN groupadd -r runner -g 433 \ - && useradd -u 431 -r -g runner -d /home/runner -s /sbin/nologin -c "Docker image user" runner \ - && chown -R runner:runner /home/runner +RUN groupadd -r service -g 433 +RUN useradd -u 431 -r -g service -d /home/service -s /sbin/nologin -c "Docker image user" service +RUN chown -R service:service /home/service -USER runner - -RUN curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash -ENV NODE_VERSION 6.10.3 -RUN . $HOME/.nvm/nvm.sh && nvm install $NODE_VERSION -ENV NVM_PATH $HOME/.nvm/versions/node/v$NODE_VERSION/lib/node -ENV NVM_DIR $HOME/.nvm -ENV PATH /home/runner/.nvm/versions/node/v$NODE_VERSION/bin:$PATH -ENV NVM_BIN $HOME/.nvm/versions/node/v$NODE_VERSION/bin - - -WORKDIR /home/runner +WORKDIR /home/service RUN npm install diff --git a/bin/release.sh b/bin/release.sh index c9f1809..49d0640 100755 --- a/bin/release.sh +++ b/bin/release.sh @@ -2,7 +2,19 @@ IMAGE=cumuluss/cumulus-ecs-task VERSION=$(cat package.json | node_modules/.bin/jsonfilter version | sed -e 's/^"//' -e 's/"$//') -echo $VERSION +PREVIOUS_VERSION=$(npm view @cumulus/cumulus-ecs-task version) -docker tag $IMAGE:latest $IMAGE:$VERSION -docker push $IMAGE:$VERSION +set -o pipefail + +if [ "$VERSION" = "$PREVIOUS_VERSION" ]; then + echo "$VERSION already released" + exit 0 +fi + +if [ "$VERSION" != "$PREVIOUS_VERSION" ]; then + npm publish --access public + docker build -t cumuluss/cumulus-ecs-task . + docker login -u cumulususer -p $DOCKER_PASSWORD + docker tag $IMAGE:latest $IMAGE:$VERSION + docker push $IMAGE:$VERSION +fi diff --git a/index.js b/index.js index b46f8fa..6862978 100644 --- a/index.js +++ b/index.js @@ -60,14 +60,13 @@ function getLambdaZip(arn, workDir, callback) { * @returns {undefined} - callback is used instead of return value **/ function downloadLambdaHandler(lambdaArn, workDir, taskDir, callback) { - // return getLambdaZip(lambdaArn, workDir, (err, filepath, moduleFileName, moduleFunctionName) => { - // if (err) return callback(err); - // - // execSync(`unzip -o ${filepath} -d ${taskDir}`); - // const task = require(`${taskDir}/${moduleFileName}`); //eslint-disable-line global-require - // return callback(null, task[moduleFunctionName]); - // }); - return callback(null, require('./task/index').handler); + return getLambdaZip(lambdaArn, workDir, (err, filepath, moduleFileName, moduleFunctionName) => { + if (err) return callback(err); + + execSync(`unzip -o ${filepath} -d ${taskDir}`); + const task = require(`${taskDir}/${moduleFileName}`); //eslint-disable-line global-require + return callback(null, task[moduleFunctionName]); + }); } /** diff --git a/package.json b/package.json index d4b1edb..0d999e4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@cumulus/cumulus-ecs-task", - "version": "0.0.1", + "version": "1.0.0-alpha1", "description": "Run lambda functions in ECS", "main": "index.js", "bin": { @@ -26,7 +26,7 @@ }, "scripts": { "start": "./bin/service.js", - "build": "docker build -t cumulus-ecs-task .", + "build": "docker build -t cumuluss/cumulus-ecs-task .", "release": "./bin/release.sh", "docker:clean": "docker rm -v $(docker ps -a -q -f status=exited); docker rmi $(docker images -f \"dangling=true\" -q); true" }, From dc36f784b5f4a947525218cbc90404954b2514fd Mon Sep 17 00:00:00 2001 From: sethvincent Date: Thu, 8 Mar 2018 14:09:25 -0500 Subject: [PATCH 09/14] update compatibility section of readme --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 06ea966..db11c9d 100644 --- a/README.md +++ b/README.md @@ -10,9 +10,7 @@ When included in a Cumulus workflow and deployed to AWS, it will download a spec ## Compatibility -TODO: update when new cumulus release goes out with cumulus-message-adapter-js version bump - -This only works with Node.js Lmabda functions. +This only works with Node.js Lmabda functions, and requires that the Lambda function it is running has a dependency of at least v1.0.1 of [cumulus-message-adapter-js](https://github.com/cumulus-nasa/cumulus-message-adapter-js). ## Usage From cd5ffe4b3ac321561dd29870b73cf979f532adba Mon Sep 17 00:00:00 2001 From: sethvincent Date: Thu, 8 Mar 2018 14:57:55 -0500 Subject: [PATCH 10/14] add changelog --- CHANGELOG.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..0811e00 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,16 @@ +# cumulus-ecs-task change log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] +- + +## [v1.0.0] - 2018-03-08 + +### Added +- Initial release + +[Unreleased]: https://github.com/cumulus-nasa/cumulus-cumulus-ecs-task/compare/v1.0.0...HEAD +[v1.0.0]: https://github.com/cumulus-nasa/cumulus-ecs-task/tree/v1.0.0 From 83b7ae1a379c5641404744fabf471d9911ccdfa0 Mon Sep 17 00:00:00 2001 From: sethvincent Date: Thu, 8 Mar 2018 14:58:11 -0500 Subject: [PATCH 11/14] 1.0.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 0d999e4..7884f87 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@cumulus/cumulus-ecs-task", - "version": "1.0.0-alpha1", + "version": "1.0.0", "description": "Run lambda functions in ECS", "main": "index.js", "bin": { From 7f89bd592ae7602f308e3649fd9b68b2bd6a133a Mon Sep 17 00:00:00 2001 From: sethvincent Date: Thu, 8 Mar 2018 14:59:30 -0500 Subject: [PATCH 12/14] restore circleci branch filtering --- .circleci/config.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 2103dd6..5618060 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -18,6 +18,6 @@ workflows: build_release: jobs: - release - # filters: - # branches: - # only: master + filters: + branches: + only: master From b30163dc82f7d0c398de032517ef94a08f1dc5e0 Mon Sep 17 00:00:00 2001 From: sethvincent Date: Thu, 8 Mar 2018 15:00:10 -0500 Subject: [PATCH 13/14] fix typo --- .circleci/config.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 5618060..b604722 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -18,6 +18,6 @@ workflows: build_release: jobs: - release - filters: - branches: - only: master + filters: + branches: + only: master From 037ef8385454f397f0cdf43d131a14e805d836f9 Mon Sep 17 00:00:00 2001 From: sethvincent Date: Thu, 8 Mar 2018 15:01:11 -0500 Subject: [PATCH 14/14] fix typo --- .circleci/config.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b604722..54815a1 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -17,7 +17,7 @@ workflows: version: 2 build_release: jobs: - - release - filters: - branches: - only: master + - release: + filters: + branches: + only: master