Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(aws-lambda-nodejs): Uploaded file must be a non-empty zip #18459

Closed
apoorvmote opened this issue Jan 16, 2022 · 55 comments · Fixed by #22393
Closed

(aws-lambda-nodejs): Uploaded file must be a non-empty zip #18459

apoorvmote opened this issue Jan 16, 2022 · 55 comments · Fixed by #22393
Labels
@aws-cdk/aws-lambda-nodejs bug This issue is a bug. management/tracking Issues that track a subject or multiple issues p1

Comments

@apoorvmote
Copy link

apoorvmote commented Jan 16, 2022

What is the problem?

I updated lambda function dependancies and deploying the lambda function but it fails with following error.

error

I also have another api under the same project and I updated its lambda function dependancies and it was deployed successfully.

Both api's and its lambda functions are almost identical to each other. However only one gets deployed and another one doesn't.

I deleted the cdk.out folder and tried to deploy again and it fails with same error each time.

Reproduction Steps

I have simple lambda function that I am trying to deploy as follows

import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Architecture, Code, Function, Runtime } from 'aws-cdk-lib/aws-lambda';

const authFn = new NodejsFunction(this, 'authNodeJs', {
      runtime: Runtime.NODEJS_14_X,
      entry: `${__dirname}/../auth/index.ts`,
      handler: 'auth',
      architecture: Architecture.ARM_64,
      memorySize: 1024,
      environment: {
        CLIENT_ID: appClientID
      }
    })

const auth1Fn = new Function(this, 'authGolang', {
      runtime: Runtime.GO_1_X,
      code: Code.fromAsset(`${__dirname}/../auth-1/`, {
        bundling: {
          image: Runtime.GO_1_X.bundlingImage,
          user: 'root',
          command: [
            'bash', '-c', [
              'cd /asset-input',
              'go build -o main main.go',
              'mv /asset-input/main /asset-output/'
            ].join(' && ')
          ]
        }
      }),
      handler: 'main',
      memorySize: 512,
      environment: {
        CLIENT_ID: appClientID
      }
    })

What did you expect to happen?

I expected it to deploy all of my lambda functions.

What actually happened?

It failed with error Uploaded file must be a non-empty zip

CDK CLI Version

2.8.0

Framework Version

No response

Node.js Version

v16.13.2

OS

Ubuntu 20.04 on WSL 2

Language

Typescript

Language Version

~3.9.7

Other information

No response

@apoorvmote apoorvmote added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Jan 16, 2022
@jogold
Copy link
Contributor

jogold commented Jan 17, 2022

Looks like for some (unknown) reason an empty zip file landed on S3 for this asset.

It should be fixed If you manually remove the asset file from the bootstrap bucket and then retry.

rix0rrr added a commit that referenced this issue Jan 18, 2022
Due to something we haven't completely figured out yet, our asset
packaging sometimes produces empty zip files, leading to an error
like this uploading code Lambda:

```
Uploaded file must be a non-empty zip
```

Do the following to address this:

* If any empty zip files already ended up in S3, do not regard this as a
  cache hit. Rebuild the asset and upload it again. We do this by
  checking the item's size: this may be overly pessimistic, but if it is
  we're probably not wasting a lot of time rebuilding and
  uploading a tiny file.
* If a fresh asset build is producing an empty zip file, loudly complain
  and ask the user to come to our bug tracker, so we can figure out
  where these spurious issues are coming from.

Relates to #18459.
mergify bot pushed a commit that referenced this issue Jan 18, 2022
Due to something we haven't completely figured out yet, our asset
packaging sometimes produces empty zip files, leading to an error
like this uploading code Lambda:

```
Uploaded file must be a non-empty zip
```

Do the following to address this:

* If any empty zip files already ended up in S3, do not regard this as a
  cache hit. Rebuild the asset and upload it again. We do this by
  checking the item's size: this may be overly pessimistic, but if it is
  we're probably not wasting a lot of time rebuilding and
  uploading a tiny file.
* If a fresh asset build is producing an empty zip file, loudly complain
  and ask the user to come to our bug tracker, so we can figure out
  where these spurious issues are coming from.

Relates to #18459.


----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
@peterwoodworth peterwoodworth added management/tracking Issues that track a subject or multiple issues p1 and removed needs-triage This issue or PR still needs to be triaged. labels Jan 18, 2022
@apoorvmote
Copy link
Author

The real issue is docker build with golang is not working. For my usecase golang lambda is still experimental. I am just keeping an eye on it for future use. I am heavily into NodeJS lambdas and they are working fine. So I just deleted single golang function and everything got deployed.

Again the issue is not resolved. But golang lambda is not priority for me so I am closing this thread.

@github-actions
Copy link

⚠️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.

TikiTDO pushed a commit to TikiTDO/aws-cdk that referenced this issue Feb 21, 2022
Due to something we haven't completely figured out yet, our asset
packaging sometimes produces empty zip files, leading to an error
like this uploading code Lambda:

```
Uploaded file must be a non-empty zip
```

Do the following to address this:

* If any empty zip files already ended up in S3, do not regard this as a
  cache hit. Rebuild the asset and upload it again. We do this by
  checking the item's size: this may be overly pessimistic, but if it is
  we're probably not wasting a lot of time rebuilding and
  uploading a tiny file.
* If a fresh asset build is producing an empty zip file, loudly complain
  and ask the user to come to our bug tracker, so we can figure out
  where these spurious issues are coming from.

Relates to aws#18459.


----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
@maciejtoporowicz
Copy link

In my case it was a human error. I had a CDK project with TypeScript where I had a lambda written in JavaScript. In .gitignore I had an entry that simply excluded javascript files. Once I checked out the repository on another computer the JavaScript file with the lambda was obviously not there. Took me at least two hours to realise that.

This is my typescript code:

  const senderLambda = new lambda.Function(params.scope, params.functionName, {
    runtime: lambda.Runtime.NODEJS_14_X,
    handler: 'sender.handler',
    code: lambda.Code.fromAsset(path.join(__dirname, 'email-sender-lambda')),
    functionName: params.functionName,
    environment: {
      EMAIL_FROM: params.emailFrom,
      EMAIL_TO: params.emailTo,
      EMAIL_BCC: params.emailBcc
    }
  });

The lambda was meant to be in email-sender-lambda/sender.js.

Guess it would be good to have a different error/warning message there or simply fail the deployment as soon as the file cannot be found during compilation.

@AndrewGuenther
Copy link

I'm seeing this issue when trying to upgrade to CDK v2.

assets.json file:

{
  "version": "16.0.0",
  "files": {
    "4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659": {
      "source": {
        "path": "asset.4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659",
        "packaging": "zip"
      },
      "destinations": {
        "<redacted>-us-west-2": {
          "bucketName": "cdk-hnb659fds-assets-<redacted>-us-west-2",
          "objectKey": "4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659.zip",
          "region": "us-west-2",
          "assumeRoleArn": "arn:${AWS::Partition}:iam::<redacted>:role/cdk-hnb659fds-file-publishing-role-<redacted>-us-west-2"
        }
      }
    },
    "0af5e7a7e0c998e4fa0c980dc1158a921cc5b19392ddc8dc5d92a0a5a62155fc": {
      "source": {
        "path": "ses-validation-stack.template.json",
        "packaging": "file"
      },
      "destinations": {
        "<redacted>-us-west-2": {
          "bucketName": "cdk-hnb659fds-assets-<redacted>-us-west-2",
          "objectKey": "0af5e7a7e0c998e4fa0c980dc1158a921cc5b19392ddc8dc5d92a0a5a62155fc.json",
          "region": "us-west-2",
          "assumeRoleArn": "arn:${AWS::Partition}:iam::<redacted>:role/cdk-hnb659fds-file-publishing-role-<redacted>-us-west-2"
        }
      }
    }
  },
  "dockerImages": {}
}

My cdk.out directory:

cdk.out/tree.json
cdk.out/ses-validation-stack.template.json
cdk.out/asset.4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659/
cdk.out/asset.4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659/aws-sdk-patch/
cdk.out/asset.4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659/aws-sdk-patch/opensearch-2021-01-01.service.json
cdk.out/asset.4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659/aws-sdk-patch/opensearch-2021-01-01.paginators.json
cdk.out/asset.4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659/index.d.ts
cdk.out/asset.4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659/index.js.map
cdk.out/asset.4a575666d1c2c6412590d2a56f328e040a81ad1ef59aecee31ae9b393d05f659/index.js
cdk.out/manifest.json
cdk.out/cdk.out
cdk.out/ses-validation-stack.assets.json

So the asset files are certainly in the cdk.out directory and where they are supposed to be according the the asset.json. I'll try to dig some more into how this differs between CDK v1 and v2...

@AndrewGuenther
Copy link

Assets and directory structure are identical (excluding hashes) with CDK v1. Seems to have been an issue introduced in v2? The error output would imply to me that there's something wrong with how the zip path is being given somewhere, but the verbose output didn't give much additional insight on that.

@AndrewGuenther
Copy link

his does appear to be the result of some pathing assumptions. In our setup, we bundle cdk.out and deploy it separately from where it was synthesized. I get this error when doing that, but not if I deploy from the same place I ran synth.

@peterwoodworth
Copy link
Contributor

Reopening issue for visibility and tracking

@AndrewGuenther
Copy link

So I originally thought this issue was exclusive to CDK v2, but it turns out that this is not the case. We hadn't seen it prior to the migration because assets were being cached. This issue is blocking us from doing any deployments to new environments.

@AndrewGuenther
Copy link

Based on my testing, the issue was introduced between v1.133.0 and v1.139.0

@AndrewGuenther
Copy link

Is there a way to disable all asset caching? Is the easiest way to handle this to delete the CDK bootstrap stack as well and recreate it? If I deploy with a good version, destroy my stack, then deploy a bad version, it will still succeed. I can only reproduce the issue with a newly bootstrapped account which is a pain in the ass to debug...

@AndrewGuenther
Copy link

This appears to be a result of the --no-staging flag. I can successfully deploy zip assets when staging is enabled, but not when it is disabled. This is inconsistent with the behavior of other asset types. For example, docker image tarballs upload just fine when staging is disabled. We have staging disabled so that we don't copy our docker image tarballs unnecessarily to the cdk.out directory since they can be quite large. The zip packaging type seems to want to work with --no-staging, but it doesn't.

So I guess the question is: is this a bug or is this intended behavior with poor error messaging?

@AndrewGuenther
Copy link

For reference, when --no-staging is passed asset sources inside of assets.json refer to a non-existent tmp directory like this one: /tmp/jsii-kernel-GqHEA2

@AndrewGuenther
Copy link

This will probably be my last update here. The asset code is abstracted down so many levels it's head spinning to try and understand what it is actually doing and there's little to no documentation on its internals.

Here's what I've gathered: the --no-staging flag makes it so that assets are not copied to cdk.out. The aws-lambda-nodejs package will perform a build on Code assets and put the build output in a folder inside of /tmp, aws-lambda-nodejs expects that these files will be copied into cdk.out and will delete the directory when it is finished, but when --no-staging is passed, the assets.json will still point to this non-existent folder in /tmp and fail to zip it.

Without any comments from the maintainers, it's hard to say if this behavior is expected or not, whether it should be fixed, or whether to add clearer messaging on the effects. I'd be happy to make any one of these changes, but I need to know that this is something the CDK team is interested in seeing fixed before I dedicate more time to this.

@junerd
Copy link

junerd commented Mar 20, 2022

I think I know why this is happening for my specific case. I found this occurring (as in the error showing but then the deploy succeeding) when I was using the code

    new s3deploy.BucketDeployment(this, `DeployWithInvalidation1`, {
      sources: [s3deploy.Source.asset('../out', { exclude: ['!*\\.*'] })],
      destinationBucket: rootSiteBucket,
      distribution,
      distributionPaths: ['/*'],
      prune: false,
    });

My explanation for why it's occurring is the \\. escape characters needed to do globbing on files that don't have . character because . is already a special character. It may have something to do with cdk script running without checking for escape characters vs escape characters working correctly during deployment?

I am not using zip files just plain old directory reference to out dir.

@chrichts
Copy link

chrichts commented Mar 31, 2022

Got the fail: 🚨 WARNING: EMPTY ZIP FILE 🚨 message so heading over here to provide details. This has started out of the blue in the last few days. We build the first time, get this warning, build again and everything works fine. See below the details (worth noting we've experienced this with 3 diff developers all who have very different setups (OS etc))

OS: Linux (WSL2) 5.10.102.1-microsoft-standard-WSL2 x86_64 - Ubuntu 20.04.4 LTS
Node: v16.13.0
CDK: 2.18.0 (build 75c90fa)
Package Manager: NPM 8.5.5

We're using the @aws-cdk/aws-lambda-go-alpha construct. With the following bundling options:

this.lambda = new goLambda.GoFunction(this, id, {
      entry: props.entry,
      environment: props.environmentVariables,
      architecture: lambda.Architecture.ARM_64,
      vpc: props.vpc,
      timeout: Duration.seconds(300),
      logRetention: props.environment === 'prod' ? logs.RetentionDays.FIVE_YEARS : logs.RetentionDays.ONE_DAY,
      insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_119_0,
      tracing: lambda.Tracing.ACTIVE,
      layers: props.layers,
      bundling: {
        cgoEnabled: true,
        goBuildFlags: ['-ldflags "-s -w"','-trimpath'],
        environment: {
          "GOOS": "linux",
          "GOARCH": "arm64",
          ...(process.platform == "linux") && { "CC": "aarch64-linux-gnu-gcc" },
          ...(process.platform == "darwin") && { "CC": "aarch64-unknown-linux-gnu-gcc" }
        }
      }
    })

Expecting the built bootstrap binary in the zip. I've already deleted contents of cdk.out so not sure what the actual contents was.

Finally, I don't think this is reproducible, as I said it's a hit and miss when it happens. Let me know if I can provide any other info or help with troubleshooting.

@tirthrami
Copy link

tirthrami commented Aug 10, 2022

I get this error (🚨 WARNING: EMPTY ZIP FILE 🚨) when trying to bootstrap a Golang package and upload lambda assets to s3. Is the golang issue mentioned in the beginning of this thread still not resolved? What are some workarounds?

MacOS Monterey 12.3.1
NodeJS v12.22.12
CDK: 2.33.0
Typescript: 4.2.4

I even tried by removing build/cdk.out directory

@thomasklinger1234
Copy link

Same here

MacOS Monterey 12.3.1
NodeJS v16.13.1
CDK: 2.38.0
Typescript: 4.2.4

My Python Code does not get bundled even thogh I have a requirements.txt and valid code

@TheRealAmazonKendra
Copy link
Contributor

Interesting. I just got this running our ecs integration tests. ec2/integ.environment-file-integ.environment-file

@abury
Copy link

abury commented Aug 28, 2022

I'm not sure if it's due to some sort of restructure, but this issue has become far more prevalent in the last week or so, around the same time as we updated cdk to v2.39.0.

It's gone from happening ~2 times a week to 3 times a day, (deploying 10-30 times a day).

There is no rhyme or reason as to why this is occurring, and a re-deploy always resolves the issue, not need to delete any cache files.

@quaeler
Copy link

quaeler commented Sep 5, 2022

This occurred for me using an internal build system (@quaeler) in which my CDK package built a lambda supplied by another package; both packages were in my local workspace, however the lambda package had been built clean and not built since.

Despite the Makefile in cdk.out having the correct formula (i.e cd in the lambda package, build, bats, ...), it did not perform this build. Building release in the lambda package and then attempting the ... cdk deploy ... again succeeded.

@Wytrykus
Copy link

Wytrykus commented Sep 13, 2022

Also encountered the error (🚨 WARNING: EMPTY ZIP FILE 🚨) now while performing cdk deploy.
It had never happened before.
Now it occured once after I had aborted cdk deploy in the middle of the process the last time before.
After I deployed the exact same code state to another AWS account and then again to the affected account, it did not occur again.

OS: MacOS Catalina 10.15.7
Runtime: NodeJS 16.15.1
Packager: yarn 1.22.19 + esbuild 0.14.42
AWS CLI: aws-cli/2.7.7 Python/3.9.13 Darwin/19.6.0
CDK: 2.26.0 (build a409d63)

@Rooster212
Copy link

Just got it again on my machine. Removing cdk.out and retrying with no other code changes fixed it for me (as it did before as I believe I've posted in this thread before).

Mac OS 12.5.1
NodeJS 18.7.0
CDK 2.41.0
esbuild 0.14.54

@jk2l
Copy link

jk2l commented Sep 19, 2022

I have issues today. my docker service (On windows) frozen and non responsive, the lambda packaging produce a empty zip file.

i have to clean the cdk.out and reboot my pc to get everything work again

@abury
Copy link

abury commented Sep 22, 2022

Ok, I've narrowed down what's causing this for me.

Whenever I cancel a deployment for a stack (ctrl-c), the next time I deploy and it gets to that step, ~15% of the time I'll get this error. Redoing the deployment always resolves the issue. I've noticed this to be the case every time I've see it happen over the last two weeks.

@christopher-taylor
Copy link

christopher-taylor commented Sep 23, 2022

Happened for the first time, then immediately again. CDK out was very full (like 4gb).

Windows 11, latest update.
Node v16.14.2
CDK 2.41.0 (build 6ad48a3)
NPM 8.18.0

After first instance I cleared out the cdk folder per the instructions (worth noting it hung at 99% for two minutes despite the folder being empty) , resynthed and deployed and it failed again. It failed again, I let it run that time, and it did in fact fail. Issue persisted after a restart. Fully deleting the cdk.out folder, and not merely it's contents (in case an invisible folder hung around), and recreating did not solve it. Just running the deploy again without any of the inbetween steps did nothing also. The issue occurred about six times in a row before I just gave up for the night since I'm like 4 hours over the work day anyway.

cdk.out.zip

@Wytrykus
Copy link

Wytrykus commented Oct 4, 2022

@abury Was the same in my case. So far the issue has only occurred after I have canceled a deployment before.

rix0rrr added a commit that referenced this issue Oct 6, 2022
Here's a possible scenario that can lead to "Uploaded file must be a
non-empty zip":

- Bundling starts
- A partial zip file is written
- The process is interrupted (`^C` or similar) while writing.
- On next run, the destination file already exists, is taken to be
  complete, and uploaded.

In this fix, we'll write the zip to a temporary file and atomically
rename it into place once finished, thereby avoiding this possible
scenario.

Attempts to fix #18459.
@mergify mergify bot closed this as completed in #22393 Oct 6, 2022
mergify bot pushed a commit that referenced this issue Oct 6, 2022
#22393)

Here's a possible scenario that can lead to "Uploaded file must be a non-empty zip":

- Bundling starts
- A partial zip file is written
- The process is interrupted (`^C` or similar) while writing.
- On next run, the destination file already exists, is taken to be complete, and uploaded.

In this fix, we'll write the zip to a temporary file and atomically rename it into place once finished, thereby avoiding this possible scenario.

Attempts to fix #18459.

I don't have tests for this, I don't know how to write them properly. To my mind, if the code looks good and we pass integration tests, that should be sufficient. Add a global asset salting mechanism so that we know all asset hashes are always unique.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
@github-actions
Copy link

github-actions bot commented Oct 6, 2022

⚠️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.

arewa pushed a commit to arewa/aws-cdk that referenced this issue Oct 8, 2022
aws#22393)

Here's a possible scenario that can lead to "Uploaded file must be a non-empty zip":

- Bundling starts
- A partial zip file is written
- The process is interrupted (`^C` or similar) while writing.
- On next run, the destination file already exists, is taken to be complete, and uploaded.

In this fix, we'll write the zip to a temporary file and atomically rename it into place once finished, thereby avoiding this possible scenario.

Attempts to fix aws#18459.

I don't have tests for this, I don't know how to write them properly. To my mind, if the code looks good and we pass integration tests, that should be sufficient. Add a global asset salting mechanism so that we know all asset hashes are always unique.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
@theUltimateZoltan
Copy link

theUltimateZoltan commented Oct 8, 2022

Ubuntu 20.04
on WSL
Node v18.6.0
CDK 2.44.0 (build bf32cb1)
NPM 8.13.2

asset was supposed to contain a lambda function. i thaught I caused it because of a recently emptied sub directory.
creating files in all empty dirs has not solved it.
neither did deleting the cdk.out directory .

git diff has revealed that the change causing this to happen was : I was creating a dependencies layer (by installing with pip into a directory and adding it as a lambda layer) for a function with an empty dependencies file.

removing the empty requirements file and conditioning the layer on finding it in the lambda directory fixed the issue for me.

@alex-arzaghi
Copy link

alex-arzaghi commented Nov 1, 2022

Has this issue been really closed? I am getting the following error in the Assets step my of code pipeline. The same code works fine when I deploy locally via cdk deploy

error  : [0%] fail: 🚨 WARNING: EMPTY ZIP FILE 🚨
--
43 | error  : [0%] fail:
44 | error  : [0%] fail: Zipping this asset produced an empty zip file. We do not know the root cause for this yet, and we need your help tracking it down.

dockerEnabledForSynth: true is set for the pipeline

The build project runs on aws/codebuild/standard:5.0

@abury
Copy link

abury commented Nov 3, 2022

Has this issue been really closed? I am getting the following error in the Assets step my of code pipeline. The same code works fine when I deploy locally via cdk deploy

error  : [0%] fail: 🚨 WARNING: EMPTY ZIP FILE 🚨
--
43 | error  : [0%] fail:
44 | error  : [0%] fail: Zipping this asset produced an empty zip file. We do not know the root cause for this yet, and we need your help tracking it down.

dockerEnabledForSynth: true is set for the pipeline

The build project runs on aws/codebuild/standard:5.0

Yeah I'm definitely still seeing this issue in development. Totally get it's a really tough one to solve, but it might need to be re-opened sadly.

@alex-arzaghi
Copy link

alex-arzaghi commented Nov 3, 2022

Has this issue been really closed? I am getting the following error in the Assets step my of code pipeline. The same code works fine when I deploy locally via cdk deploy

error  : [0%] fail: 🚨 WARNING: EMPTY ZIP FILE 🚨
--
43 | error  : [0%] fail:
44 | error  : [0%] fail: Zipping this asset produced an empty zip file. We do not know the root cause for this yet, and we need your help tracking it down.

dockerEnabledForSynth: true is set for the pipeline
The build project runs on aws/codebuild/standard:5.0

Yeah I'm definitely still seeing this issue in development. Totally get it's a really tough one to solve, but it might need to be re-opened sadly.

@abury Just got mine fixed. I had to update the CDK CLI version to 2.46.0 (or newer).

@estrehle
Copy link

In my case it was human error, too. My handler function had a non-default name (i.e., not handler) and I had forgotten to specify the handler property in the NodejsFunctionProps accordingly.

A more precise error message in this case would be useful. For example: "No export 'handler' found in entry file".

homakk pushed a commit to homakk/aws-cdk that referenced this issue Dec 1, 2022
aws#22393)

Here's a possible scenario that can lead to "Uploaded file must be a non-empty zip":

- Bundling starts
- A partial zip file is written
- The process is interrupted (`^C` or similar) while writing.
- On next run, the destination file already exists, is taken to be complete, and uploaded.

In this fix, we'll write the zip to a temporary file and atomically rename it into place once finished, thereby avoiding this possible scenario.

Attempts to fix aws#18459.

I don't have tests for this, I don't know how to write them properly. To my mind, if the code looks good and we pass integration tests, that should be sufficient. Add a global asset salting mechanism so that we know all asset hashes are always unique.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
@Amin-Tajgardoon
Copy link

In my case it was a misplacement of the lambda//Handler class file. The error message should be more specific!

@Technickel-Dev
Copy link

Consistently running into this problem without even having cancelled a build as others have mentioned. Deleting cdk.out and the asset files in S3 doesn't help.

Windows 11
Running Ubuntu WSL2
Node v18.15.0
CDK 2.68.0 (build 25fda51)
NPM 9.5.0

I'm trying to use a basic Nodejs function construct and I've confirmed that the docker container does build the code correctly.

const crudLambda = new NodejsFunction(this, "crud-lambda", {
  runtime: lambda.Runtime.NODEJS_18_X
});

Narrowed the problem down to what I think is trouble zipping the asset output on specifically WSL, as it runs fine from Powershell. Running CDK in verbose mode doesn't lead to anything that sheds light on why it would fail.

So, TLDR for those still running into this:
Seems to be a problem with WSL and CDK, try using Powershell or another environment

@EhudGrand
Copy link

In my case, the CodeUri of the function pointed to the wrong directory.

@korcek-juraj
Copy link

I was getting the same error and I managed to solve it for my particular case.

Stack:
Windows 10
wsl2
Docker Desktop

Events (possibly) leading to my issue:

  • for another project I added other wsl distribution and set it as default
  • docker switched itself to "Resource saving mode" which caused cdk synth to run extremely slowly
  • I cancelled cdk deploy (due to being slow) using Ctrl+C

Steps to fix my issue:

  1. revert wsl default distro to docker-desktop: wsl --set-default docker-desktop
  2. in Docker Desktop disable Resource Saver mode in Settings -> Resources
  3. restart Docker Desktop
  4. delete cdk.out
  5. run cdk synth

Note: Possibly, a subset of the five steps listed above might be sufficient to resolve the issue.

@adamelkhayyat
Copy link

adamelkhayyat commented Apr 23, 2024

After a successful deployment we ran into this error and noticed that the code wasn't being bundled, we simply removed cdk.out & re-deployed and things were working again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
@aws-cdk/aws-lambda-nodejs bug This issue is a bug. management/tracking Issues that track a subject or multiple issues p1
Projects
None yet
Development

Successfully merging a pull request may close this issue.