cloudfoundry-community / node-cfenv

easy access to your Cloud Foundry application environment for node
Apache License 2.0
74 stars 20 forks source link

cfenv function calls are competing to handle the same temporary file #40

Closed AkihiroKitada closed 5 years ago

AkihiroKitada commented 5 years ago

Please suppose that there are multiple cfenv function calls in the same host at the same time - in the specific cases, for examples, Concourse CI kicks multiple cfenv function calls in the same virtual machine.

Sometimes one of the cfenv function calls fails with the following error.

ENOENT: no such file or directory, rename '/root/.ports.json.tmp' -> '/root/.ports.json'

16 | const service = appEnv.getService(name);
17 | return service && service.credentials;
> 18 | };
| ^
19 | 

at write_json (node_modules/ports/index.js:54:6)
at Object.getPort (node_modules/ports/index.js:40:3)
at getPort (node_modules/cfenv/lib/cfenv.js:224:32)
at new AppEnv (node_modules/cfenv/lib/cfenv.js:45:19)
at Object.<anonymous>.cfenv.getAppEnv (node_modules/cfenv/lib/cfenv.js:23:12)
at Object.<anonymous> (../common/env.ts:18:3)

It seems that one cfenv function call has deleted the temporary json file while another tries to rename the same temporary json file.

Please consider to fix this race condition.

pmuellr commented 5 years ago

I believe this is an issue with the ports package - https://github.com/hoodiehq-archive/node-ports/issues/4

As a work-around, I think we can just try/catch around the getPort() call, in a loop (but not infinite) that calls it until it doesn't error. Per the note the PR, I think there may still be a race condition that multiple calls with different "names" could return the same port number, but shouldn't. This would be a problem if the ports were actually be used in real http servers. Is that the case for you? Do you use cfenv to get the port number, and then use that port to start an http server?

One immediate work-around for you would be to set the port number in one of the following env vars when running your app.

https://github.com/cloudfoundry-community/node-cfenv/blob/a5dbcebd3007b6502554f149a193dc4290abe96e/lib-src/cfenv.coffee#L169-L172

pmuellr commented 5 years ago

Thanks for the bug report! I've added a simple fix to prevent the error from ports from propagating up, hopefully this is good enough for your environment. If not, open a new issue.