Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions lib/addNewMask.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
/* eslint-disable promise/catch-or-return */

// ↓ Should be imported first
const { terminate } = require('@codefresh-io/cf-telemetry/init');
require('@codefresh-io/cf-telemetry/init');
// ↓ Keep one blank line below to prevent automatic import reordering

const { Logger } = require('@codefresh-io/cf-telemetry/logs');
const { getServerAddress, registerExitHandlers } = require('./helpers');
const { getServerAddress, registerExitHandlers, shutdownGracefully } = require('./helpers');

const logger = new Logger('codefresh:containerLogger:addNewMask');

Expand Down Expand Up @@ -45,14 +45,14 @@ async function updateMasks(secret) {
if (response.statusCode === 201) {
logger.log(`successfully updated masks with secret: ${secret.key}`);
exitWithError = false;
terminate().finally(() => process.exit(exitCodes.success));
await shutdownGracefully(exitCodes.success);
} else {
logger.error(`could not create mask for secret: ${secret.key}. Server responded with: ${response.statusCode}\n\n${response.body}`);
terminate().finally(() => process.exit(exitCodes.error));
await shutdownGracefully(exitCodes.error);
}
} catch (error) {
logger.error(`could not create mask for secret: ${secret.key}. Error: ${error}`);
terminate().finally(() => process.exit(exitCodes.error));
await shutdownGracefully(exitCodes.error);
}
}

Expand All @@ -62,11 +62,12 @@ if (require.main === module) {
// first argument is the secret key second argument is the secret value
if (process.argv.length < 4) {
logger.log('not enough arguments, need secret key and secret value');
terminate().finally(() => process.exit(exitCodes.missingArguments));
shutdownGracefully(exitCodes.missingArguments);
} else {
const key = process.argv[2];
const value = process.argv[3];
updateMasks({ key, value });
}
const key = process.argv[2];
const value = process.argv[3];
updateMasks({ key, value });
} else {
module.exports = { updateMasks, exitHandler };
}
20 changes: 16 additions & 4 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,21 +60,33 @@ const getServerAddress = async () => {
}
};

const shutdownGracefully = async (code) => {
try {
await terminate();
} catch (error) {
// supress any error during terminating telemetry
logger.error(`Error occurred while terminating telemetry.`, error);
}

process.exit(code);
};

/**
* As `@codefresh-io/cf-telemetry/init` changes the original node.js behavior of how SIGTERM and SIGINT
* signals are handled, we revert this change back to the original node.js behavior.
*/
const registerExitHandlers = () => {
process.on('SIGTERM', () => {
terminate().finally(() => process.exit(143)); // default exit code for SIGTERM
process.on('SIGTERM', async () => {
await shutdownGracefully(143); // default exit code for SIGTERM
});

process.on('SIGINT', () => {
terminate().finally(() => process.exit(130)); // default exit code for SIGINT
process.on('SIGINT', async () => {
await shutdownGracefully(130); // default exit code for SIGINT
});
};

module.exports = {
shutdownGracefully,
watchForBuildFinishedSignal,
saveServerAddress,
getServerAddress,
Expand Down
5 changes: 3 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ const logger = new Logger({
showProgress: process.env.SHOW_PROGRESS === 'true',
});

logger.validate();
logger.start();
// eslint-disable-next-line promise/catch-or-return
logger.validate()
.then(() => logger.start());

process.on('beforeExit', (code) => {
logs.log(`beforeExit: ${code}`);
Expand Down
22 changes: 14 additions & 8 deletions lib/isReady.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/* eslint-disable promise/catch-or-return */

// ↓ Should be imported first
const { terminate } = require('@codefresh-io/cf-telemetry/init');
require('@codefresh-io/cf-telemetry/init');
// ↓ Keep one blank line below to prevent automatic import reordering

const { readFileSync } = require('fs');
const _ = require('lodash');
const { Logger } = require('@codefresh-io/cf-telemetry/logs');
const { ContainerHandlingStatus } = require('./enums');
const { registerExitHandlers } = require('./helpers');
const { registerExitHandlers, shutdownGracefully } = require('./helpers');

registerExitHandlers();

Expand All @@ -33,15 +33,21 @@ function isContainerLoggerReady(state) {
return isReady;
}

(() => {
const isReady = async () => {
const containerId = process.argv[2];
const state = JSON.parse(readFileSync('./lib/state.json').toString('utf-8'));
let isReady = false;
let ready = false;
if (containerId) {
isReady = isContainerReady(state, containerId);
ready = isContainerReady(state, containerId);
} else {
isReady = isContainerLoggerReady(state);
ready = isContainerLoggerReady(state);
}

terminate().finally(() => process.exit(isReady ? 0 : 1));
})();
await shutdownGracefully(ready ? 0 : 1);
};

if (require.main === module) {
isReady();
} else {
module.exports = { isReady };
}
18 changes: 9 additions & 9 deletions lib/logger.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable promise/catch-or-return */

// ↓ Should be imported first
const { terminate } = require('@codefresh-io/cf-telemetry/init');
require('@codefresh-io/cf-telemetry/init');
// ↓ Keep one blank line below to prevent automatic import reordering

const fs = require('fs');
Expand All @@ -19,6 +19,7 @@ const ContainerLogger = require('./ContainerLogger');

// eslint-disable-next-line import/no-unresolved,import/extensions
const { HttpServer } = require('./http-server');
const { shutdownGracefully } = require('./helpers');

const logger = new Logs('codefresh:containerLogger');

Expand Down Expand Up @@ -70,12 +71,12 @@ class Logger {
* validates the passed params of the constructor
* @returns {*}
*/
validate() {
async validate() {
if (!this.taskLoggerConfig) {
return this._error(new CFError('taskLogger configuration is missing'));
return await this._error(new CFError('taskLogger configuration is missing'));
}
if (!this.loggerId) {
return this._error(new CFError('logger id is missing'));
return await this._error(new CFError('logger id is missing'));
}
return undefined;
}
Expand Down Expand Up @@ -126,12 +127,11 @@ class Logger {
this._listenForExistingContainers();
}
})
.catch((err) => {
this._error(new CFError({
.catch(async (err) => {
await this._error(new CFError({
cause: err,
message: `Failed to create taskLogger`
}));

});

await this._listenForEngineRequests();
Expand All @@ -155,9 +155,9 @@ class Logger {
* will print the error and exit the process
* @param err
*/
_error(err) {
async _error(err) {
logger.error(err.toString());
terminate().finally(() => process.exit(1));
await shutdownGracefully(1);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion service.yaml
Original file line number Diff line number Diff line change
@@ -1 +1 @@
version: 1.13.0
version: 1.13.1
36 changes: 14 additions & 22 deletions test/addNewMask.unit.spec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
const {shutdownGracefully} = require("../lib/helpers");
const proxyquire = require('proxyquire').noCallThru();

const expect = chai.expect;
Expand Down Expand Up @@ -57,12 +58,10 @@ describe('addNewMask', () => {
stubGot.post.resolves({ statusCode: 201 });

const { updateMasks, exitHandler } = proxyquire('../lib/addNewMask', {
'@codefresh-io/cf-telemetry/init': {
terminate: () => ({
finally: callback => callback(),
})
'./helpers': {
getServerAddress: stubGetServerAddress,
shutdownGracefully,
},
'./helpers': { getServerAddress: stubGetServerAddress },
});
process.listeners('exit').forEach((listener) => {
if (listener === exitHandler) {
Expand All @@ -82,16 +81,12 @@ describe('addNewMask', () => {
it('should fail if the server address is not available', async () => {
stubGetServerAddress.rejects('could not get server address');
const { updateMasks, exitHandler } = proxyquire('../lib/addNewMask', {
'@codefresh-io/cf-telemetry/init': {
terminate: () => ({
finally: callback => callback(),
})
},
'@codefresh-io/cf-telemetry/logs': {
Logger: function() { return stubLogger },
},
'./helpers': {
getServerAddress: stubGetServerAddress,
shutdownGracefully,
},
});
process.listeners('exit').forEach((listener) => {
Expand All @@ -107,16 +102,12 @@ describe('addNewMask', () => {
it('should fail if the server address is not valid URL', async () => {
stubGetServerAddress.resolves('foo');
const { updateMasks, exitHandler } = proxyquire('../lib/addNewMask', {
'@codefresh-io/cf-telemetry/init': {
terminate: () => ({
finally: callback => callback(),
})
},
'@codefresh-io/cf-telemetry/logs': {
Logger: function() { return stubLogger },
},
'./helpers': {
getServerAddress: stubGetServerAddress,
shutdownGracefully,
},
});
process.listeners('exit').forEach((listener) => {
Expand All @@ -137,15 +128,13 @@ describe('addNewMask', () => {
body: 'Internal Server Error',
});
const { updateMasks, exitHandler } = proxyquire('../lib/addNewMask', {
'@codefresh-io/cf-telemetry/init': {
terminate: () => ({
finally: callback => callback(),
})
},
'@codefresh-io/cf-telemetry/logs': {
Logger: function() { return stubLogger },
},
'./helpers': { getServerAddress: stubGetServerAddress },
'./helpers': {
getServerAddress: stubGetServerAddress,
shutdownGracefully,
},
});
process.listeners('exit').forEach((listener) => {
if (listener === exitHandler) {
Expand Down Expand Up @@ -202,7 +191,10 @@ describe('addNewMask', () => {
stubGetServerAddress.resolves(serverAddress);
stubGot.post.resolves({ statusCode: 201 });
const { updateMasks, exitHandler } = proxyquire('../lib/addNewMask', {
'./helpers': { getServerAddress: stubGetServerAddress },
'./helpers': {
getServerAddress: stubGetServerAddress,
shutdownGracefully,
},
});
process.listeners('exit').forEach((listener) => {
if (listener === exitHandler) {
Expand Down
Loading