diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..54815a1 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,23 @@ +version: 2 + +jobs: + release: + docker: + - image: circleci/node:6 + working_directory: ~/project + steps: + - checkout + - setup_remote_docker + - run: | + echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc + npm install + ./bin/release.sh + +workflows: + version: 2 + build_release: + jobs: + - release: + filters: + branches: + only: master 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/.gitignore b/.gitignore new file mode 100644 index 0000000..661372d --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +node_modules +build/ +dist/ +test-reports +tmp +.tmp +config/authorized_keys +config/cloudformation.yml +cache-invalidation/config/runtime_config.json +.env +cumulus-message-adapter +task +.tmp-work 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/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 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..a7261d8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM node:6.10.3 + +USER root +RUN apt-get update +RUN apt-get install -y unzip + +COPY . /home/service + +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 + +WORKDIR /home/service + +RUN npm install + +ENTRYPOINT [ "node", "--harmony", "bin/service.js" ] 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 787f84f..db11c9d 100644 --- a/README.md +++ b/README.md @@ -1 +1,206 @@ -# 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/). + +## About + +cumulus-ecs-task is a Docker image that can run Lambda functions as ECS services. + +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. + +## Compatibility + +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 + +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: + +``` +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: + +``` +npm start -- --activityArn --lambdaArn +``` + +To build the docker image: + +``` +npm run build +``` + +To run in Docker locally: + +``` +docker run -e AWS_ACCESS_KEY_ID='' \ + -e AWS_SECRET_ACCESS_KEY='' \ + cumuluss/cumulus-ecs-task \ + --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 + +``` +npm version +``` + +Create the build + +``` +npm run build +``` + +Release to Docker Hub + +``` +npm run release +``` + +## 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..49d0640 --- /dev/null +++ b/bin/release.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +IMAGE=cumuluss/cumulus-ecs-task +VERSION=$(cat package.json | node_modules/.bin/jsonfilter version | sed -e 's/^"//' -e 's/"$//') +PREVIOUS_VERSION=$(npm view @cumulus/cumulus-ecs-task 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/bin/service.js b/bin/service.js new file mode 100755 index 0000000..31c837b --- /dev/null +++ b/bin/service.js @@ -0,0 +1,60 @@ +#!/usr/bin/env node + +const fs = require('fs'); +const path = require('path'); + +const minimist = require('minimist'); +const createCliOptions = require('cliclopts'); +const rimraf = require('rimraf'); + +const runService = require('../index'); + +const taskDir = path.join(process.cwd(), 'task'); +const workDir = path.join(process.cwd(), '.tmp-work'); + +const cliOptions = createCliOptions([ + { + name: 'directory', + abbr: 'd', + alias: ['taskDirectory'], + default: taskDir, + help: 'path to task directory' + }, + { + name: 'work-directory', + abbr: 'w', + alias: ['workDirectory'], + default: workDir, + help: 'path to temporary working directory' + }, + { + name: 'lambda-arn', + abbr: 'l', + alias: ['lambdaArn'], + help: 'the arn of the lambda function that will run on ecs' + }, + { + name: 'activity-arn', + 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' + } +]); + +const argv = minimist(process.argv.slice(2), cliOptions.options()); + +rimraf.sync(argv.taskDirectory); +rimraf.sync(argv.workDirectory); + +fs.mkdirSync(argv.taskDirectory); +fs.mkdirSync(argv.workDirectory); + +runService(argv); + +process.on('exit', () => rimraf.sync(argv.workDirectory)); diff --git a/index.js b/index.js new file mode 100644 index 0000000..6862978 --- /dev/null +++ b/index.js @@ -0,0 +1,256 @@ +'use strict'; +/* eslint-disable no-console, max-len */ +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 region = process.env.AWS_DEFAULT_REGION || 'us-east-1'; +AWS.config.update({ region: region }); + +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 {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) { + const lambda = new AWS.Lambda({ apiVersion: '2015-03-31' }); + + lambda.getFunction({ FunctionName: arn }, (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(workDir, 'fn.zip'); + const file = fs.createWriteStream(filepath); + + file.on('error', callback); + file.on('finish', () => file.close()); + file.on('close', () => callback(null, filepath, moduleFileName, moduleFunctionName)); + + return https.get(codeUrl, (res) => res.pipe(file)); + }); +} + +/** +* Downloads and extracts the code of a lambda function from its zip file +* +* @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(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]); + }); +} + +/** +* Starts heartbeat to indicate worker is working on the task +* +* @param {string} taskToken - the task token +* @returns {intervalId} - interval id used by `clearInterval` +**/ +function startHeartbeat(taskToken) { + return setInterval(() => { + sf.sendTaskHeartbeat({ taskToken }, (err) => { + if (err) { + console.log('error sending heartbeat', err); + } + }, 60000); + }); +} + +/** +* 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); + } + }); +} + +/** +* Tells workflow that the task has succeeded and provides message for next task +* +* @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 +**/ +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) { + this.emit('error', err); + } + 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 {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) { + 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; + + // 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/`; + + downloadLambdaHandler(lambdaArn, workDir, taskDir, (downloadError, handler) => { + if (downloadError) { + // if lambda isn't downloaded, throw the error, as nothing else will work + throw downloadError; + } + + const poll = new TaskPoll(activityArn, heartbeatInterval); + + 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(); + }); +} + +module.exports = runService; diff --git a/package.json b/package.json new file mode 100644 index 0000000..7884f87 --- /dev/null +++ b/package.json @@ -0,0 +1,43 @@ +{ + "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", + "respawn": "^2.5.0", + "rimraf": "^2.6.2" + }, + "scripts": { + "start": "./bin/service.js", + "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" + }, + "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" + } +}