SAM CLI Template Switch -T causes class not found error (does not have permission information)
Description
SAM CLI Template Switch -T causes class not found error due to permissions errors
Steps to reproduce
WORKS: sam local start-api --debug FAILS: sam local start-api --template template.yaml --debug
Observed result
When the -T flag is specified, "does not have permission information" is repeated per file in the jar in the console.
uecompressing test-sam/sam-app/HelloWorldFunction/target/HelloWorld-1.0.jar File META-INF/ in zipfile does not have permission information File META-INF/MANIFEST.MF in zipfile does not have permission information File helloworld/ in zipfile does not have permission information File helloworld/GatewayResponse.class in zipfile does not have permission information File helloworld/App.class in zipfile does not have permission information File META-INF/maven/ in zipfile does not have permission information File META-INF/maven/helloworld/ in zipfile does not have permission information File META-INF/maven/helloworld/HelloWorld/ in zipfile does not have permission information File META-INF/maven/helloworld/HelloWorld/pom.xml in zipfile does not have permission information File META-INF/maven/helloworld/HelloWorld/pom.properties in zipfile does not have permission information File com/ in zipfile does not have permission information etc
Expected result
Should work when specifying template path.
Additional environment details (Ex: Windows, Mac, Amazon Linux etc)
-
OS: NAME="Pop!_OS" VERSION="20.04 LTS" ID=pop ID_LIKE="ubuntu debian
-
sam --version: 0.53.0
I confirm that issue happens on OSX as well. Steps to re-produce;
1- Init a basic SAM java app (HelloWorld)
2- Run sam build
3- Run sam local start-api --template template.yaml --debug
4- curl or open browser to test the URL
It is going to error out;
❯ sam local start-api --template template.yaml --debug
Telemetry endpoint configured to be https://aws-serverless-tools-telemetry.us-west-2.amazonaws.com/metrics
local start-api command is called
No Parameters detected in the template
2 resources found in the template
Found Serverless function with name='HelloWorldFunction' and CodeUri='HelloWorldFunction'
No Parameters detected in the template
2 resources found in the template
Found '1' API Events in Serverless function with name 'HelloWorldFunction'
Detected Inline Swagger definition
Lambda function integration not found in Swagger document at path='/hello' method='get'
Found '0' APIs in resource 'ServerlessRestApi'
Removed duplicates from '0' Explicit APIs and '1' Implicit APIs to produce '1' APIs
1 APIs found in the template
Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template
Localhost server is starting up. Multi-threading = True
2020-07-17 17:30:15 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
Constructed String representation of Event to invoke Lambda. Event: {"httpMethod": "GET", "body": null, "resource": "/hello", "requestContext": {"resourceId": "123456", "apiId": "1234567890", "resourcePath": "/hello", "httpMethod": "GET", "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", "accountId": "123456789012", "stage": "Prod", "identity": {"apiKey": null, "userArn": null, "cognitoAuthenticationType": null, "caller": null, "userAgent": "Custom User Agent String", "user": null, "cognitoIdentityPoolId": null, "cognitoAuthenticationProvider": null, "sourceIp": "127.0.0.1", "accountId": null}, "extendedRequestId": null, "path": "/hello"}, "queryStringParameters": null, "multiValueQueryStringParameters": null, "headers": {"Host": "127.0.0.1:3000", "Connection": "keep-alive", "Cache-Control": "max-age=0", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Sec-Fetch-Site": "none", "Sec-Fetch-Mode": "navigate", "Sec-Fetch-User": "?1", "Sec-Fetch-Dest": "document", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.9,tr;q=0.8", "X-Forwarded-Proto": "http", "X-Forwarded-Port": "3000"}, "multiValueHeaders": {"Host": ["127.0.0.1:3000"], "Connection": ["keep-alive"], "Cache-Control": ["max-age=0"], "Upgrade-Insecure-Requests": ["1"], "User-Agent": ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"], "Accept": ["text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"], "Sec-Fetch-Site": ["none"], "Sec-Fetch-Mode": ["navigate"], "Sec-Fetch-User": ["?1"], "Sec-Fetch-Dest": ["document"], "Accept-Encoding": ["gzip, deflate, br"], "Accept-Language": ["en-US,en;q=0.9,tr;q=0.8"], "X-Forwarded-Proto": ["http"], "X-Forwarded-Port": ["3000"]}, "pathParameters": null, "stageVariables": null, "path": "/hello/", "isBase64Encoded": false}
Found one Lambda function with name 'HelloWorldFunction'
Invoking helloworld.App::handleRequest (java8)
No environment variables found for function 'HelloWorldFunction'
Environment variables overrides data is standard format
Loading AWS credentials from session with profile 'None'
Resolving code path. Cwd=/Volumes/unix/workplace/other/sam-app, CodeUri=HelloWorldFunction
Resolved absolute path to code is /Volumes/unix/workplace/other/sam-app/HelloWorldFunction
Code /Volumes/unix/workplace/other/sam-app/HelloWorldFunction is not a zip/jar file
Failed to download image with name amazon/aws-sam-cli-emulation-image-java8:rapid-1.0.0rc2
Failed to download a new amazon/aws-sam-cli-emulation-image-java8:rapid-1.0.0rc2 image. Invoking with the already downloaded image.
Mounting /Volumes/unix/workplace/other/sam-app/HelloWorldFunction as /var/task:ro,delegated inside runtime container
Starting a timer for 20 seconds for function 'HelloWorldFunction'
18 Jul 2020 00:30:20,530 [INFO] (lambdainternal.AWSLambda.startRuntime(AWSLambda.java:287)) JVM runtime reported running (invokeId: dummy)
18 Jul 2020 00:30:20,591 [INFO] (lambdainternal.AWSLambda.findUserMethods(AWSLambda.java:101)) Unable to locate class [classNotFound] (Exception: java.lang.ClassNotFoundException )
START RequestId: a9fbe346-ca68-14ce-ff25-a36dd123ca2a Version: $LATEST
Class not found: helloworld.App: java.lang.ClassNotFoundException
java.lang.ClassNotFoundException: helloworld.App
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
18 Jul 2020 00:30:20,602 [INFO] (lambdainternal.AWSLambda.startRuntime(AWSLambda.java:345)) Invoke failed with UserFault (Exception: java.lang.Throwable, Fatal: false )
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007ff4e18f16b1, pid=14, tid=0x00007ff4e25ae700
#
# JRE version: OpenJDK Runtime Environment (8.0_201-b09) (build 1.8.0_201-b09)
# Java VM: OpenJDK 64-Bit Server VM (25.201-b09 mixed mode, sharing linux-amd64 compressed oops)
# Problematic frame:
# C [libc.so.6+0x16f6b1] __strlen_sse2_pminub+0x11
#
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# An error report file with more information is saved as:
# //hs_err_pid14.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
Function 'HelloWorldFunction' timed out after 20 seconds
<class 'samcli.local.apigw.local_apigw_service.LambdaResponseParseException'>
2020-07-17 17:30:40 127.0.0.1 - - [17/Jul/2020 17:30:40] "GET /hello/ HTTP/1.1" 502 -
2020-07-17 17:30:40 127.0.0.1 - - [17/Jul/2020 17:30:40] "GET /favicon.ico HTTP/1.1" 403 -
^CSending Telemetry: {'metrics': [{'commandRun': {'awsProfileProvided': False, 'debugFlagProvided': True, 'region': '', 'commandName': 'sam local start-api', 'duration': 28178, 'exitReason': 'success', 'exitCode': 0, 'requestId': '0aac21a7-0d5a-40b0-9c7b-98024b2e9f51', 'installationId': '60c94637-8776-4efb-9dbb-4f828cf2eb13', 'sessionId': 'b1235b6f-0d00-4330-b219-6ae5c8aa76cd', 'executionEnvironment': 'CLI', 'pyversion': '3.7.8', 'samcliVersion': '1.0.0rc2'}}]}
Telemetry response: 200
Running with sam local start-api --debug succeeds without any error.
In the example template.yaml file, CodeUri field is using relative path:
CodeUri: HelloWorldFunction
Here the directory "HelloWorldFunction" is relative to template file directory instead of build directory with JAR files.
After running sam build, the directory structure of sam cli is like below:
.
├── .aws-sam
│ └── build
│ ├── HelloWorldFunction
│ │ ├── helloworld
│ │ │ └── App.class
│ │ └── lib
│ │ ├── aws-lambda-java-core-1.2.0.jar
│ │ ├── aws-lambda-java-events-3.1.0.jar
│ │ └── joda-time-2.6.jar
│ └── template.yaml
├── HelloWorldFunction
│ ├── pom.xml
│ └── src
│ ├── main
│ │ └── java
│ │ └── helloworld
│ │ └── App.java
│ └── test
│ └── java
│ └── helloworld
│ └── AppTest.java
├── README.md
├── events
│ └── event.json
└── template.yaml
The template file is copied to the build folder under ./.aws-sam/build in sam build. If we run sam local start-api --debug without specify --template, the default template file is the one copied to ./.aws-sam/build. This template file can find the jar files under ./.aws-sam/build/HelloworldFunction.
On the other hand, if we use the template file ./template.yaml, the absolute path of CodeUri is actually ./HelloWorldFunction instead of ./.aws-sam/build/HelloworldFunction. Therefore, we got ClassNotFoundException.
To resolve this issue, we can use absolute path in CodeUri field if we want to use our own template file. For example:
CodeUri: /user/path/sam-app/.aws-sam/build/HelloWorldFunction
Ref about CodeUri path: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-start-api.html
@wchengru thanks.
The full URI path was always specified in the template file so it's not a relative path issue. I've upgraded to SAM CLI 1.0.0 and the problem is still here. It's got something to with the target being a JAR file. I've specified a path in the template to the target/classes folder (no JAR) and it works.
The same code works on WSL2 Ubuntu 20.04 on Windows 10 with template specified. The same permissions missing messages were shown but didn't impact the code running successfully.
@lukepopp Thanks for the updates.
A similar issue is #909. When SAM CLI sees a zip/jar file, we unzip it into a temporary directory. Looks like you don't have permission to access to this directory.
Could you please check if you can access the temporary directory, and the directory is the same with and without --template option?
@wchengru, it is a problem with /tmp and SAM not being able to write. However, my permissions on /tmp look correct .
drwxrwxrwt 10 root root 4096 Aug 13 09:34 tmp
My logged in user can create new files in /tmp. Here's the stack dump. Please note the the referenced path, /tmp/tmp2h9y1w89 is not in the /tmp directory after the program bombs out.
Mounting /tmp/tmp2h9y1w89 as /var/task:ro,delegated inside runtime container
2020-08-13 09:41:47 Exception on /hello [GET]
Traceback (most recent call last):
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/docker/api/client.py", line 261, in _raise_for_status
response.raise_for_status()
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/requests/models.py", line 941, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 500 Server Error: Internal Server Error for url: http+docker://localhost/v1.35/containers/4cdf48cac2772524598ce96fd94bfe3548f0dc218dfdb2537ad2c30846e71b3e/start
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/flask/app.py", line 2317, in wsgi_app
response = self.full_dispatch_request()
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/flask/app.py", line 1840, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/flask/app.py", line 1743, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/flask/app.py", line 1838, in full_dispatch_request
rv = self.dispatch_request()
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/flask/app.py", line 1824, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/samcli/local/apigw/local_apigw_service.py", line 203, in _request_handler
self.lambda_runner.invoke(route.function_name, event, stdout=stdout_stream_writer, stderr=self.stderr)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/samcli/commands/local/lib/local_lambda.py", line 100, in invoke
self.local_runtime.invoke(config, event, debug_context=self.debug_context, stdout=stdout, stderr=stderr)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/samcli/local/lambdafn/runtime.py", line 83, in invoke
self._container_manager.run(container)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/samcli/local/docker/manager.py", line 95, in run
container.start(input_data=input_data)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/samcli/local/docker/container.py", line 188, in start
real_container.start()
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/docker/models/containers.py", line 400, in start
return self.client.api.start(self.id, **kwargs)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/docker/utils/decorators.py", line 19, in wrapped
return f(self, resource_id, *args, **kwargs)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/docker/api/container.py", line 1095, in start
self._raise_for_status(res)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/docker/api/client.py", line 263, in _raise_for_status
raise create_api_error_from_http_exception(e)
File "/home/linuxbrew/.linuxbrew/Cellar/aws-sam-cli/1.0.0/libexec/lib/python3.7/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 500 Server Error: Internal Server Error ("error while creating mount source path '/tmp/tmp2h9y1w89': mkdir /tmp/tmp2h9y1w89: no such file or directory")
Hi @lukepopp
Looks like it is a Docker issue from your logs. Docker cannot create that folder tmp2h9y1w89 under /tmp at first, then creation subdirectory is failed. Unfortunately I cannot reproduce your issue on my side. Could you please provide your template file, the jar file you are using, and the full logs if possible?
Same issues happens when deploying to an aws account as well.
If you use -t option to point a template which holds java function, when the function is deployed and invoked via api gateway, it results on ClassNotFoundException.
Same deployment works fine if you rename your template to default name and then deploym without using -t option.
@pankajagrawal16 have you built the SAM application? if you did build it, you need to point -t to the built template. within .aws-sam/build/template.yaml
@pankajagrawal16 have you built the SAM application? if you did build it, you need to point -t to the built template. within
.aws-sam/build/template.yaml
Hi @sriram-mv , No I didn't tried using sam path before. I tried it now and it worked. Is that a expected thing to do? Is it documented somewhere as well ? If no, Probably we should
sam deploy does not build and only deploys whatever the template it is pointing to.
Without -t, it defaults to the template inside of .aws-sam/build.
https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-deploy.html
By default when you use this command, the AWS SAM CLI assumes that your current working directory is your project's root directory. The AWS SAM CLI first tries to locate a template file built using the sam build command, located in the .aws-sam subfolder, and named template.yaml. Next, the AWS SAM CLI tries to locate a template file named template.yaml or template.yml in the current working directory. If you specify the --template option, AWS SAM CLI's default behavior is overridden, and will deploy just that AWS SAM template and the local resources it points to.
⚠️COMMENT VISIBILITY WARNING⚠️
Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.