Skip to content

Faster deployment by skipping unchanged lambda layers - #7680

Merged
medikoo merged 17 commits into
serverless:masterfrom
exoego:skip-layers
May 19, 2020
Merged

medikoo merged 17 commits into
serverless:masterfrom
exoego:skip-layers

Conversation

@exoego

@exoego exoego commented May 6, 2020 •

Copy link
Copy Markdown
Contributor

What did you implement

Closes #7516

This PR allows serverless framework to skip uploading unmodified layers, then use the previously-deployed existing layers.

Deployment time will be reduced, thanks to avoid unnecessary upload and creating new layer version.
This chart shows my experiment of deployment time reduction.
image

Skipping is based on the SHA1 hash value of the layer zip.
The hash value and S3 key of the previously-uploaded layer zip will be exposed in CloudFormation stack output, like below example:

Output key Output value
HelloLambdaLayerHash d312c754874c70b70a3c2da72657f249e8553dd5
HelloLambdaLayerS3Key serverless/test-7516/dev/1588905888489-2020-05-08T02:44:48.489Z/hello.zip

Since hash and S3Key of previous deployment is exposed and shared, all team members gains deployment time boost: if one developer in a team deployed the layer, then another developer can skip uploading when the layer is not changed.

How can we verify it

  1. npm install -g exoego/serverless#skip-layers
  2. Prepare a service with a large layer. Example serverless.yaml and layer-dir/nodejs/package.json is below
service: test-7516
provider:
  name: aws
  runtime: nodejs12.x
functions:
  hello:
    handler: handler.hello
    layers:
      - { Ref: "HelloLambdaLayer" }
    events:
      - http:
          path: hello
          method: get
          cors: true
layers:
  hello:
    path: layer-dir
    compatibleRuntimes:
      - nodejs12.x

and

{
  "dependencies": {
    "aws-sdk": "^2.672.0",
    "elasticsearch": "^16.7.1",
    "node-fetch": "2.6.0",
    "sharp": "^0.25.2"
  }
}
  1. time sls deploy
  2. Update handler.js a bit (if no update, sls skip the entire deployment`).
  3. time sls deploy
  4. You may notie the deployment time get reduced, thanks to skipping the unchanged layer.

Todos

Useful Scripts
  • npm run test:ci --> Run all validation checks on proposed changes
  • npm run lint:updated --> Lint all the updated files
  • npm run lint:fix --> Automatically fix lint problems (if possible)
  • npm run prettier-check:updated --> Check if updated files adhere to Prettier config
  • npm run prettify:updated --> Prettify all the updated files
  • Write and run all tests
  • Write documentation: N/A since this is internal change
  • Enable "Allow edits from maintainers" for this PR
  • Update the messages below

Is this ready for review?: YES
Is it a breaking change?: NO

@exoego exoego changed the title Do not create new version of layers if layers are not modified Skip creating new layer version if layers are not modified May 6, 2020
@exoego

exoego commented May 7, 2020 •

Copy link
Copy Markdown
Contributor Author

EDIT: I finally figured out how to stub correctly in 981c8c4

Hmm, some test cases, those creates two layers in single case (Promise.all([awsCompileLayers.compileLayers(), secondAwsCompileLayers.compileLayers()])), are failing due to lack of AWS credentials.
I wonder it is due to lack of stubbing aws provider request, so I tried to stub more, but could not figure out how to stub them correctly. 🤔
Any help ?

https://travis-ci.org/github/serverless/serverless/jobs/684073352#L3651

  1) AwsCompileLayers
       #compileLayers()
         should create a layer resource with a retention policy, has the same logical id when not modify:
     AssertionError: expected promise to be fulfilled but it was rejected with 'ServerlessError: Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1'

  2) AwsCompileLayers
       #compileLayers()
         should create a layer resource with a retention policy, has different logical id when modify:
     AssertionError: expected promise to be fulfilled but it was rejected with 'ServerlessError: Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1'

@exoego
exoego marked this pull request as ready for review May 8, 2020 02:57
@exoego

exoego commented May 8, 2020 •

Copy link
Copy Markdown
Contributor Author

@medikoo
I think the PR is ready to get reviewed.

I added enhancement and cat/dx label instead of refactoring, since this will redyce deployment time and therefore enhance developer experimences with Lambda layer.
Feel free to change labels if my suggestion does not fit to labeling policy.

@medikoo medikoo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@exoego that looks great! I've proposed just few minor, mostly stylistic changes, after that I believe we'll be ready to go

I added enhancement and cat/dx label instead of refactoring, since this will redyce deployment time and therefore enhance developer experimences with Lambda layer.
Feel free to change labels if my suggestion does not fit to labeling policy.

Yes, I'm still coining right meaning for them. In general idea was thatenhancement should be about some new small feature, config option etc. and anything that doesn't change anything on that level should be considered refactor.

Still I agree, that in this case, there's a visible impact for user, as performance is visibly improved, so it deserves to be counted as enhancement (while refactor is usually swept away under carpet, as something minor and not having direct effect for user).

I propose to mark it with perf (just introduced) label, which also will be pushed with perf commit message scope and mentioned in version changelog.

I believe all this label organization rules should be common effort, so let me know what you think.

const layerNames = this.serverless.service.getAllLayers();
artifactFilePaths = artifactFilePaths.concat(
_.map(layerNames, name => {
_.flatMap(layerNames, name => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's minimize lodash dependency (resort only when there's no convenient native counterpart). I think this case can be addresed by .map().filter(Boolean)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it was done in 3032678

Comment thread lib/plugins/aws/lib/naming.js Outdated
'Wild'
)}LambdaLayerPermission`;
},
getLambdaLayerArtifactPath(packagePath, layerName) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think util this doesn't fit well naming.js, which is more about name generation for resource and other entities.

Probably best location for it is lib/plugins/aws/utils

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in b3e3d1a

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, forgot to add new file. Fixed in bb0e5d3

this.packagePath,
layerName
);
const layerArtifactBinary = fs.readFileSync(layerArtifactPath);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not use sync counterparts of async functions, they block process (we already have some perf issues cause of that)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in adda468

return this.provider
.request('CloudFormation', 'describeStacks', { StackName: stackName })
.then(data => {
const lastHash = _.find(data.Stacks[0].Outputs, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use native .find

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean native Array#find method ?
Outputs is object, which does not have find method, I think.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh, you are right !!
I was seeing Outputs in CloudFormation template, which is plain object.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in e60da14

const lastHash = _.find(data.Stacks[0].Outputs, {
OutputKey: layerHashOutputLogicalId,
});
const compiledCloudFormationTemplate = this.serverless.service.provider

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style nit: We can exit here if lastHash is not found

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b5b0ec0

const layerS3keyOutputLogicalId = this.provider.naming.getLambdaLayerS3KeyOutputLogicalId(
layerName
);
const lastS3Key = _.find(data.Stacks[0].Outputs, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use native find

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in e60da14

this.serverless.cli.log(`Layer ${layerName} is already uploaded.`);
}
})
.catch(e => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's put it as second callback to previous then, otherwise we're catching here also error eventually coming from first then callback and that is unwanted

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 98c6177

})
.catch(e => {
if (e.message.indexOf('does not exist') > -1) {
return BbPromise.resolve();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's do just return (it's equivalent and noise free)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ef9d7ca

compileLayers() {
const allLayers = this.serverless.service.getAllLayers();
return BbPromise.each(allLayers, layerName => this.compileLayer(layerName));
return BbPromise.each(allLayers, layerName => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not rely on BbPromise functions that do not have native counterparts (we plan dropping bluebird dependency, as soon as we drop support for Node.js v6, with v2)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1aa3f01

@medikoo medikoo added perf and removed enhancement labels May 8, 2020
@exoego exoego changed the title Skip creating new layer version if layers are not modified Faster deployment by skipping unchanged lambda layers May 8, 2020
@medikoo

medikoo commented May 19, 2020

Copy link
Copy Markdown
Contributor

@exoego is this ready to take? If so, please re-request review. Thank you!

@exoego

exoego commented May 19, 2020

Copy link
Copy Markdown
Contributor Author

Yes, ready to re-review.

@exoego
exoego requested a review from medikoo May 19, 2020 08:48

@medikoo medikoo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @exoego looks great! I just proposed few last style/cleanup suggestions

return layerObject.package.artifact;
if (layerObject.artifactAlreadyUploaded) {
this.serverless.cli.log(`Skip uploading ${name}`);
return '';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we don't want to return anything, but ESLint complains let's return null

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b8b9d45

this.provider.serverless.service,
this.provider.naming
);
}).filter(name => name !== '')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

filter(Boolean)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b8b9d45

this.serverless.cli.log(`Layer ${layerName} is already uploaded.`);
},
e => {
if (e.message.indexOf('does not exist') > -1) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's rely on str.includes instead

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a44ced8

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

Merging #7680 into master will increase coverage by 0.01%.
The diff coverage is 90.27%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #7680      +/-   ##
==========================================
+ Coverage   87.99%   88.00%   +0.01%     
==========================================
  Files         244      245       +1     
  Lines        9209     9254      +45     
==========================================
+ Hits         8103     8144      +41     
- Misses       1106     1110       +4     
Impacted Files Coverage Δ
lib/plugins/aws/deploy/lib/uploadArtifacts.js 89.23% <20.00%> (-1.25%) ⬇️
lib/plugins/aws/package/compile/layers/index.js 95.60% <94.64%> (-2.61%) ⬇️
lib/plugins/aws/lib/naming.js 98.10% <100.00%> (+0.02%) ⬆️
...ib/plugins/aws/utils/getLambdaLayerArtifactPath.js 100.00% <100.00%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 8bb5517...b8b9d45. Read the comment docs.

@exoego
exoego requested a review from medikoo May 19, 2020 12:30
@exoego

exoego commented May 19, 2020

Copy link
Copy Markdown
Contributor Author

@medikoo Ready to re-review.

@medikoo medikoo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @exoego !

@medikoo
medikoo merged commit 2b9f63e into serverless:master May 19, 2020
@exoego
exoego deleted the skip-layers branch May 19, 2020 13:14
@exoego exoego mentioned this pull request May 19, 2020
51 of 54 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AWS s3 sync for lambda layers

3 participants