aws-sam-cli icon indicating copy to clipboard operation
aws-sam-cli copied to clipboard

JavaMavenWorkflow is packaging layers with lambdas

Open gustahrodrigues opened this issue 6 years ago • 16 comments

Description

JavaMavenWorkflow is packaging layer's jar as part of lambda's deployment package.

In java lambda project, we should use <scope>provided</scope> to let runtime (layer in this case) provides the dependency for us, ie, exclude it from built artifact (reference). But, JavaMavenWorkflow is explicitly including it by running mvn dependency:copy-dependencies -DincludeScope=compile (reference).

It breaks one of Layer's goal:

Layers let you keep your deployment package small, which makes development easier. Reference: AWS Lambda layers

Steps to reproduce

  1. Clone this sample repo, branch packaging-layers that I've created to reproduce it easily
  2. Replace HelloWorldFunction layers for a valid layer's ARN
  3. Run sam build
  4. Check that on ..aws-sam\build\HelloWorldFunction\lib layer's jar would be there
  5. Deploy your lambda using sam deploy and download deployment package (on the functions page of the Lambda console, choose your function, then Actions, and then Export function. In the Export your function dialog box, choose Download deployment package) and check on lib/ that layer's jar would be there too

OR

  1. Create a java8 project (it can be HelloWorldFunction template)
  2. Add hello-world-layer to your template.yaml
....
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: HelloWorldFunction
      Handler: helloworld.App::handleRequest
      Runtime: java8
      MemorySize: 512
      Layers:
        - arn:aws:lambda:us-east-1:*:layer:hello-world-layer:1 # Account id removed
      ....
....
  1. In order to use it, declare sample-layer as a dependency on HelloWorldFunction/pom.xml
    <dependencies>
       ....
        <dependency>
            <groupId>helloworld</groupId>
            <artifactId>sample-layer</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
  1. Build it using sam build
  2. Check that on ..aws-sam\build\HelloWorldFunction\lib layer's jar would be there
  3. Deploy your lambda using sam deploy and download deployment package (on the functions page of the Lambda console, choose your function, then Actions, and then Export function. In the Export your function dialog box, choose Download deployment package) and check on lib/ that layer's jar would be there too

Observed result

SAM is packaging layers's jar with lambda's deployment package.

image

Expected result

Dependencies set as provided should not be packaged by SAM, since it would be provided by runtime (layer).

Fix

  1. Replace mvn dependency:copy-dependencies -DincludeScope=compile by mvn dependency:copy-dependencies -DexcludeScope=provided

Workaround

  1. Create a custom build method to fix maven dependency copy command
build-MyFunction:
	@ mvn clean install
	@ mvn dependency:copy-dependencies -DexcludeScope=provided
	@ cp -rf ./target/classes/* $(ARTIFACTS_DIR)/
	@ mkdir -p $(ARTIFACTS_DIR)/lib
	@ cp -rf ./target/dependency/* $(ARTIFACTS_DIR)/lib
	@ rm -rf ./target

Additional environment details (Ex: Windows, Mac, Amazon Linux etc)

  1. OS: Windows 10
  2. sam --version: SAM CLI, version 0.52.0

Add --debug flag to command you are running

gustahrodrigues avatar Jun 16 '20 14:06 gustahrodrigues

@gustahrodrigues The layer is showing up in your function code because you have defined it to be a dependency. We don't do any special logic to extract or remove dependencies based on the template. sam build basically wraps the language tooling (maven and gradle for java). Why do you need this layer to be a dependency on the function? It will be available in the classpath on lambda and layers are meant to be a separate resource, so combining them like this seems strange (at first glance).

jfuss avatar Jun 17 '20 14:06 jfuss

@jfuss I'm trying to use layers to share common code between multiple lambdas. In order to actually be able to call such common code in my lambdas, I have to add it as a dependency.

I don't know a way to call a external code without explicitly declare it as dependency on compiled languages like Java (I don't think it would be a problem on python or nodejs).

Do you have an example about how to achieve it on Java?

I thought that the Layers would be hosted and available in the Lambda "ecosystem" and referenced, but not deployed with the function as a JAR. This comment would seem to indicate that the Layer dependencies have to be loaded in the Classloader just like the rest of the rest of the JAR dependencies.

You can configure your Lambda function to pull in additional code and content in the form of layers. A layer is a ZIP archive that contains libraries, a custom runtime, or other dependencies. AWS Lambda Layers.

I was also thinking to use layers to share dependencies (multiple jars) as suggested above to let my deployment package small. However, with this SAM behaviour, I won't be able to.

I think I was also under some misconceptions about how layers worked and what they could do for me. Perhaps I misread some of the enthusiasm I saw in various articles about it

gustahrodrigues avatar Jun 17 '20 15:06 gustahrodrigues

This is admittedly a use case that sam build has a difficult time with for many dependency managers (I can say for example Ruby has the same dilemma - bundler has no way to be told "please just trust me, the dependency will be there, don't rebuild it or its dependencies").

If you did not use sam build and were manually running Maven, can you get around this problem? If so, you can define a Makefile and use that instead of the standard build process. That process is documented here.

awood45 avatar Jun 26 '20 17:06 awood45

@jfuss using -DincludeScope=compile has other bad ramifications - it does not include runtime only dependencies and java library projects are often split into separate jars, some that provide just the interfaces and are needed at compile time and others that are implementations of these interfaces (some times multiple alternative implementations) which are needed at runtime

Please take a look at the maven dependency plugin documentation here: https://maven.apache.org/plugins/maven-dependency-plugin/copy-dependencies-mojo.html

As it explains for includeScope:

  • runtime scope gives runtime and compile dependencies,
  • compile scope gives compile, provided, and system dependencies,
  • provided scope just gives provided dependencies,

I would suggest changing scope to -DincludeScope=runtime

This should fix both:

  • my problem where my "runtime" dependencies are not included
  • @gustahrodrigues problem where his "provided" dependencies which he needs only during compile time and will provide them later as a layer are included

ikrustev avatar Jul 26 '20 12:07 ikrustev

We are on the same boat as @gustahrodrigues , our layers are also declared as dependencies for multiple functions. any updates on this? and sam build will not honor the exclusions.

RobertoC27 avatar Nov 11 '20 23:11 RobertoC27

Any update on this issue really appreciated. sam build not working as expected with Java when coupled with Lambda Layers

vilunet avatar Feb 09 '21 01:02 vilunet

The following setup works very well for me:

I start my container like this- sam local start-lambda --warm-containers EAGER --template template.yaml --debug

template.yaml looks like this

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Foo 
Resources:
  Foo:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: java11
      CodeUri: target/classes
      Handler: foo.RequestHandler
      Layers:
        - !Ref FooLayer

  FooLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: foo-dependencies
      ContentUri: ./target
      CompatibleRuntimes:
        - java11

Before I start the container, I run these commands-

mkdir -p target/java/lib ; cp target/dependency/*.jar ./target/java/lib

and that's about it. If I need to make a change in my source code, I simply make the change and run the command mvn compile which updates the target/classes directory. If I add or remove dependencies, I re-run the above series to commands to update the layer directory.

I do not like shade plugin so I have this in my pom.xml :

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.1.2</version>
        <configuration>
          <includeScope>runtime</includeScope>
        </configuration>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
          </execution>
        </executions>
 </plugin>

This semi-auto setup works pretty well and I am sure that mvn compile can be made to be invoked when some src/main file changes

gauravphoenix avatar Mar 30 '21 17:03 gauravphoenix

Any objection to changing aws-lambda-builders -> maven.py so that it uses includeScope=runtime? That would I believe fix this issue. @awood45 @jfuss

maven.py

    def copy_dependency(self, scratch_dir):
        args = ["dependency:copy-dependencies", "-DincludeScope=runtime", "-Dmdep.prependGroupId=true"]

Currently this is set to compile. When a dependency is in maven is set to scope provided the expectation is that a packaging plugin won't include it in the final artifact but it will be added to the classpath of the compile plugin. SAM cli is playing the role of a maven packaging plugin in this scenario.

@jfuss your question about why @gustahrodrigues is including a dependency in his functions maven project which is already in his function's AWS Lambda Layer was not directly answered. The reason is his maven Java project requires that dependency for compilation. In this particular example in runtime the dependency will of course use the jars in the AWS Lambda Layer. This is why the maven dependency scope provided exists to let downstream packaging components know not to included it but let the maven compiler plugin know it is needed for compilation.

One typical example would be use WAR plugin to build a web application the maven project would need the Java Servlet dependency for compilation but the WAR plugin shouldn't include that dependency jar in the WAR archive as the Servlet container would provide those classes. The provided scope is how maven communicates that fact to the compile and war plugins.

It's a similar case here with AWS Lambda Layers used to package his common library code. His maven project will need the his common library dependency jar for compilation but this jar shouldn't be packaged with his SAM function deployment package as it will be provided by the AWS Lambda Layer which contains his common library code.

I agree with @ikrustev the includeScope used by the dependency plugin should be runtime instead of compile. @ikrustev has documented reasons why above which we'd want the compile and runtime scope dependencies to be included.

Can somebody make the above change? Would there be any objections to that change? I don't do much programming at all in python or I'd just submit the PR.

Gradle would have similar scenario its scope for this was compileOnly. Somebody should check me on that scope name... gradle has changed the names of it's scopes over the years. I don't know if that is the correct scope name for current version.

prower-turnitin avatar Aug 11 '21 22:08 prower-turnitin

@awood45 Is there some process I need to follow to get contributors with write access to review my PRs? I'm not sure what I should be doing to get feedback on PRs and hopefully get this issue resolved. Thanks.

prower-turnitin avatar Aug 30 '21 17:08 prower-turnitin

@awood45 @jfuss Can somebody who has write permission please review my PRs which fix this issue? https://github.com/aws/aws-lambda-builders/pull/267 https://github.com/aws/aws-sam-cli/pull/3209

prower-turnitin avatar Sep 13 '21 15:09 prower-turnitin

i'd like that using compile scope also prevents you from doing local debug of the lambda, because it doesn't copy transitive depdencies , will this be fixed?

emaayan avatar Nov 21 '21 15:11 emaayan

Thanks everyone for all the feedback in this issue.

We will be moving forward with the approach that I explained in the PR that @prower-turnitin has raised earlier. You can see my comment here; https://github.com/aws/aws-lambda-builders/pull/267#issuecomment-985239364

mndeveci avatar Dec 03 '21 06:12 mndeveci

Thanks @mndeveci

Wanted to check if the solution is already in place for a particular aws-sam-cli version or it is an upcoming solution. Was not clear from the comment here; https://github.com/aws/aws-lambda-builders/pull/267#issuecomment-985239364

RajasGujarathi avatar Dec 17 '21 16:12 RajasGujarathi

@RajasGujarathi it is not out yet. We've raised following PRs for the changes (you can see them below). Once they are merged and a new version of SAM CLI is out, you will be able to use this by running SAM_CLI_BETA_MAVEN_SCOPE_AND_LAYER=1 sam build. We will make this behavior default in the near future.

https://github.com/aws/aws-lambda-builders/pull/318 https://github.com/aws/aws-sam-cli/pull/3602

mndeveci avatar Jan 26 '22 18:01 mndeveci

Hi everyone,

With SAM CLI v1.38.0, we have added these build changes behind a feature flag. Please go ahead and try it by running SAM_CLI_BETA_MAVEN_SCOPE_AND_LAYER=1 sam build.

As mentioned earlier, this will be behind a feature flag until we got your feedback. We are planning to make this default by 1st of April, 2022.

If you encounter any problems or have recommendation, please leave a comment under https://github.com/aws/aws-sam-cli/issues/3639

Thanks everyone for all the feedback under this issue. And special thanks to @prower-turnitin for providing the implementation.

mndeveci avatar Feb 17 '22 02:02 mndeveci

Hi,

You're welcome. I just noticed it got into the base. Terrible about reading email and noticed your message about the switch after upgrading SAM. Works great with the switch. I'm glad you decided to make it the default soon. Maven users should be happier with this change giving them a more expected experience.

Thanks for getting this change into the baseline Mehmet.

On Wed, Feb 16, 2022 at 7:00 PM Mehmet Nuri Deveci @.***> wrote:

Hi everyone,

With SAM CLI v1.38.0, we have added these build changes behind a feature flag. Please go ahead and try it by running SAM_CLI_BETA_MAVEN_SCOPE_AND_LAYER=1 sam build.

As mentioned earlier, this will be behind a feature flag until we got your feedback. We are planning to make this default by 1st of April, 2022.

If you encounter any problems or have recommendation, please leave a comment under #3639 https://github.com/aws/aws-sam-cli/issues/3639

Thanks everyone for all the feedback under this issue. And special thanks to @prower-turnitin https://github.com/prower-turnitin for providing the implementation.

— Reply to this email directly, view it on GitHub https://github.com/aws/aws-sam-cli/issues/2047#issuecomment-1042491915, or unsubscribe https://github.com/notifications/unsubscribe-auth/ATFQ5J3D7ZYXIUYJB5LSGVLU3RJFPANCNFSM4N7WH4BA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you were mentioned.Message ID: @.***>

prower-turnitin avatar Feb 23 '22 17:02 prower-turnitin