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

Worker refactor #661

Merged
merged 3 commits into from
Feb 14, 2018
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
67 changes: 27 additions & 40 deletions integration-tests/spec/wait.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use strict';

var _ = require('lodash');
var Promise = require('bluebird');
var misc = require('./misc')();
const _ = require('lodash');
const Promise = require('bluebird');
const misc = require('./misc')();

module.exports = function wait() {
/*
Expand All @@ -11,12 +11,8 @@ module.exports = function wait() {
*/
function forLength(func, value, iterations) {
return forValue(
function() {
return func()
.then(function(result) {
return result.length
})
},
() => func()
.then(result => result.length),
value, iterations);
}

Expand All @@ -26,44 +22,37 @@ module.exports = function wait() {
* time for the value to match before the returned promise will
* reject.
*/
function forValue(func, value, iterations) {
if (! iterations) iterations = 100;
var counter = 0;
function forValue(func, value, _iterations) {
const iterations = _iterations || 100;
let counter = 0;

return new Promise(function(resolve, reject) {
return new Promise(((resolve, reject) => {
function checkValue() {
func()
.then(function(result) {
counter++;

.then((result) => {
counter += 1;
if (result === value) {
return resolve(result);
}

if (counter > iterations) {
reject(`forValue didn't find target value after ${iterations} iterations.`);
}
else {
} else {
setTimeout(checkValue, 500);
}
})
});
}

checkValue();
});
}));
}

/*
* Wait for 'node_count' nodes to be available.
*/
function forNodes(node_count) {
return forLength(function() {
return misc.teraslice().cluster
.state()
.then(function(state) {
return _.keys(state)
});
}, node_count);
function forNodes(nodeCount) {
return forLength(() => misc.teraslice().cluster
.state()
.then(state => _.keys(state)), nodeCount);
}

/*
Expand All @@ -74,17 +63,15 @@ module.exports = function wait() {
* 'joined'
*/
function forWorkersJoined(jobId, workerCount, iterations) {
return forValue(() => {
return misc.teraslice().cluster
.slicers()
.then((slicers) => {
const slicer = _.find(slicers, s => s.job_id === jobId);
if (slicer !== undefined) {
return slicer.workers_joined;
}
return 0;
});
}, workerCount, iterations)
return forValue(() => misc.teraslice().cluster
.slicers()
.then((slicers) => {
const slicer = _.find(slicers, s => s.job_id === jobId);
if (slicer !== undefined) {
return slicer.workers_joined;
}
return 0;
}), workerCount, iterations)
.catch((e) => {
throw (new Error(`(forWorkersJoined) ${e}`));
});
Expand Down
2 changes: 1 addition & 1 deletion lib/cluster/cluster_master.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ module.exports = function (context) {
}
require('./services/execution.js')(context)
.then((clusterService) => {
messaging.initialize({ server });
messaging.listen({ server });
logger.trace('cluster_service has instantiated');
context.services.execution = clusterService;
return require('./services/jobs')(context);
Expand Down
33 changes: 8 additions & 25 deletions lib/cluster/execution_controller/engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,6 @@ module.exports = function module(context, messaging, exStore, stateStore, execut
}
});

// events can be fired from anything that instantiates a client, such as stores and slicers
// needs to be setup before executionRunner
messaging.register({ event: 'worker:shutdown', callback: _executionShutdown });

messaging.register({
event: 'assets:loaded',
callback: ipcMessage => events.emit('execution:assets_loaded', ipcMessage)
Expand Down Expand Up @@ -278,13 +274,12 @@ module.exports = function module(context, messaging, exStore, stateStore, execut
// send message that execution is in running state
logger.info(`execution: ${exId} has initialized and is listening on port ${executionConfig.slicer_port}`);
exStore.setStatus(exId, 'running');

if (!executionAnalytics) executionAnalytics = require('./execution_analytics')(context, messaging);
if (!slicerAnalytics) slicerAnalytics = require('./slice_analytics')(context, executionContext);
_setQueueLength(executionContext);
if (!recovery) recovery = require('./recovery')(context, messaging, executionAnalytics, exStore, stateStore, executionContext);

messaging.initialize({ port: executionContext.config.slicer_port });
messaging.listen({ port: executionContext.config.slicer_port });

// start the engine
if (engineCanRun) {
Expand Down Expand Up @@ -385,11 +380,6 @@ module.exports = function module(context, messaging, exStore, stateStore, execut
engine = setInterval(engineFn, 1);
}

function _shutdown() {
engineCanRun = false;
clearInterval(engine);
}

function _adjustSlicerQueueLength() {
if (dynamicQueueLength && messaging.getClientCounts() > queueLength) {
queueLength = messaging.getClientCounts();
Expand Down Expand Up @@ -430,7 +420,7 @@ module.exports = function module(context, messaging, exStore, stateStore, execut
slicerAnalytics.analyzeStats();
}

logger.info(`execution ${executionConfig.name} has finished in ${time} seconds`);
logger.info(`execution ${exId} has finished in ${time} seconds`);
}

function _allSlicesProcessed() {
Expand Down Expand Up @@ -489,25 +479,19 @@ module.exports = function module(context, messaging, exStore, stateStore, execut
_watchDog(checkFn, timeout, errMsg, logMsg);
}

function _executionShutdown() {
function shutdown() {
logger.info(`slicer for execution: ${exId} has received a shutdown notice`);
isShuttingDown = true;
engineCanRun = false;
clearInterval(engine);
events.emit('execution:stop');

function stateStoreShutdown() {
if (stateStore) {
return stateStore.shutdown();
}
return true;
}

Promise.all([_shutdown(), executionAnalytics.shutdown(), stateStoreShutdown()])
return Promise.resolve()
.then(executionAnalytics.shutdown)
.then(() => logger.flush())
.then(() => events.emit('execution:shutdown'))
.catch((err) => {
const errMsg = parseError(err);
logger.error(errMsg);
events.emit('execution:shutdown');
});
}

Expand Down Expand Up @@ -573,8 +557,6 @@ module.exports = function module(context, messaging, exStore, stateStore, execut
_adjustSlicerQueueLength,
_pause,
_resume,
_shutdown,
_executionShutdown,
_engineSetup,
_executionRecovery,
_terminalError,
Expand All @@ -587,6 +569,7 @@ module.exports = function module(context, messaging, exStore, stateStore, execut

return {
initialize,
shutdown,
__test_context: testContext
};
};
33 changes: 30 additions & 3 deletions lib/cluster/execution_controller/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ module.exports = function module(contextConfig) {
const events = context.apis.foundation.getSystemEvents();
const logger = context.apis.foundation.makeLogger({ module: 'execution_controller', ex_id: exId, job_id: jobId });
const messaging = messageModule(context, logger);
let exStore;
let stateStore;
let engine;

// to catch signal propagation, but cleanup through msg sent from master
messaging.register({ event: 'process:SIGTERM', callback: () => {} });
messaging.register({ event: 'process:SIGINT', callback: () => {} });
messaging.register({ event: 'worker:shutdown', callback: executionShutdown });


events.on('client:initialization:error', terminalShutdown);
// emitted after final cleanup of execution is complete
Expand All @@ -28,7 +33,10 @@ module.exports = function module(contextConfig) {
function initializeExecutionController() {
Promise.resolve(executionInit())
.catch(terminalShutdown)
.then(engine => engine.initialize())
.then((_engine) => {
engine = _engine;
engine.initialize();
})
.catch(terminalShutdown);
}

Expand All @@ -41,15 +49,18 @@ module.exports = function module(contextConfig) {
// assets store is loaded first so it can register apis before executionRunner is called
return Promise.resolve(require('../storage/assets')(context))
.then(() => Promise.all([executionRunner.initialize(events, logger), require('../storage/state')(context), require('../storage/execution')(context)]))
.spread((executionContext, stateStore, exStore) => {
.spread((executionContext, _stateStore, _exStore) => {
logger.trace('stateStore and jobStore for slicer has been initialized');
stateStore = _stateStore;
exStore = _exStore;
return require('./engine')(context, messaging, exStore, stateStore, executionContext);
});
}

function terminalShutdown(errObj) {
logger.error(`Terminal error: shutting down execution ${exId}`);
const errMsg = errObj.error || parseError(errObj);
logger.error(`Terminal error: shutting down execution ${exId}, error: ${errMsg}`);

// exStore may not be initialized, must rely on CM
messaging.send({
to: 'cluster_master',
Expand All @@ -58,4 +69,20 @@ module.exports = function module(contextConfig) {
ex_id: exId
});
}

function executionShutdown() {
const shutdownSequence = [];
if (stateStore) shutdownSequence.push(stateStore.shutdown());
if (exStore) shutdownSequence.push(exStore.shutdown());
if (engine) shutdownSequence.push(engine.shutdown());

Promise.all(shutdownSequence)
.then(logger.flush)
.catch((err) => {
const errMsg = parseError(err);
logger.error(`Error while attempting to shutdown execution_controller ex_id: ${exId}, error: ${errMsg}`);
return logger.flush();
})
.finally(process.exit);
}
};
2 changes: 1 addition & 1 deletion lib/cluster/node_master.js
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ module.exports = function module(context) {
return state;
}

messaging.initialize();
messaging.listen();

if (context.sysconfig.teraslice.master) {
const assetsPort = systemPorts.getPort(true);
Expand Down
4 changes: 2 additions & 2 deletions lib/cluster/services/messaging.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ module.exports = function messaging(context, logger, childHookFn) {
return destinationType;
}

function initialize(obj) {
function listen(obj) {
let port;
let server;

Expand Down Expand Up @@ -502,7 +502,7 @@ module.exports = function messaging(context, logger, childHookFn) {

return {
register,
initialize,
listen,
getHostUrl,
getClientCounts,
send,
Expand Down
Loading