Workers, threads and cluster
NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), F.worker, the cluster options, SHELL(), F.python(), F.pipinstall() and PYPELINE().
On this page
Methods, properties, start options and events for worker threads, forked processes, thread pools, the cluster, SHELL() and PYPELINE(). For an introduction with examples read the guide Workers, threads and cluster.
API
method
NEWTHREAD(name, [data])
Starts a worker thread from the workers/ folder.
NEWTHREAD(name, [data])| Parameter | Type | Description |
|---|---|---|
name |
String |
The file name in workers/ without .js, or ~ and an absolute path |
data? |
Object |
Data copied into the thread as F.worker.data |
Returns Worker The Node.js worker thread
Runs workers/{name}.js in a new Node.js worker thread. A name that starts with ~ is an absolute path to the script. data is copied into the thread and is available there as F.worker.data. The thread receives --worker in its process.argv.
The result is the Node.js Worker object: use postMessage() to send a message and on('message'), on('error') and on('exit') to listen. The framework adds kill() and exit(), which call terminate().
var thread = NEWTHREAD('calc', { user: 'Peter' });
thread.on('message', function(msg) {
console.log(msg.sum);
thread.kill();
});
thread.postMessage({ a: 1, b: 2 });
method
NEWTHREAD()
Inside a worker script: returns the worker object F.worker.
NEWTHREAD()Returns Object F.worker
Called without a name in a script that runs as a worker, NEWTHREAD() creates F.worker (or returns it when it exists), sets the application directory to the current working directory and starts passing the messages from the parent to F.worker.message. Load the framework with require('total5') before you call it.
require('total5');
var worker = NEWTHREAD();
worker.message = function(msg) {
worker.send({ sum: msg.a + msg.b });
};
property
F.worker
The worker object of a script that runs as a worker.
F.workerReturns Object
Created by NEWTHREAD() (or NEWFORK()) without a name. It holds the data from the parent and the methods to receive and send messages and to end the worker. In the main application it is undefined.
var worker = NEWTHREAD();
console.log(F.worker === worker); // true
console.log(worker.data);
property
F.worker.data
The data passed to NEWTHREAD(name, data).
F.worker.dataReturns Object
A copy of the second argument of NEWTHREAD() in the main thread. It is an empty object {} when no data were passed, in a fork and in the threads of a pool.
var worker = NEWTHREAD();
var user = worker.data.user;
property
F.worker.is
true when the script runs as a worker.
F.worker.isReturns Boolean
true in a thread from NEWTHREAD(), in a fork from NEWFORK() and in the workers of NEWTHREADPOOL(): they all get the argument --worker in process.argv.
var worker = NEWTHREAD();
if (!worker.is)
console.log('Started directly with node, not as a worker');
property
F.worker.isfork
true in a forked process, false in a worker thread.
F.worker.isforkReturns Boolean
true when the worker is a process from NEWFORK() (messages go through process.send()), false in a worker thread.
var worker = NEWTHREAD();
console.log(worker.isfork ? 'process ' + process.pid : 'thread');
delegate
F.worker.message = function(msg) {}
Receives the messages from the parent.
F.worker.message = function(msg) {}| Parameter | Type | Description |
|---|---|---|
msg |
Object |
The message from the parent |
Assign a function. It is called with every message the parent sends with postMessage(). The default does nothing.
var worker = NEWTHREAD();
worker.message = function(msg) {
if (msg.type === 'ping')
worker.send({ type: 'pong' });
};
method
F.worker.send(msg)
Sends a message to the parent.
F.worker.send(msg)| Parameter | Type | Description |
|---|---|---|
msg |
Object |
The message; it is copied, functions are not allowed |
Sends the message to the process or thread that started the worker. F.worker.postMessage() is the same method. The parent receives it in on('message').
worker.send({ id: msg.id, result: result });
method
F.worker.exit([code])
Ends the worker.
F.worker.exit([code])| Parameter | Type | Description |
|---|---|---|
code? |
Number |
The exit code Default: 0 |
Calls process.exit(code). Inside a thread it ends the thread; the parent gets the exit event with the code. F.worker.kill() and F.worker.close() are the same method.
worker.message = function(msg) {
work(msg);
worker.exit();
};
method
F.worker.setTimeout(timeout)
Ends the worker with code 1 after a timeout.
F.worker.setTimeout(timeout)| Parameter | Type | Description |
|---|---|---|
timeout |
Number |
Milliseconds |
Starts a countdown. When it runs out, the worker ends with exit code 1. A new call clears the previous countdown and starts a new one, so call it at the start of each job.
worker.message = function(msg) {
worker.setTimeout(10000);
job(msg, function(response) {
worker.send(response);
});
};
method
thread.kill()
Stops a thread started with NEWTHREAD().
thread.kill()Calls terminate() of the Node.js Worker. thread.exit() is the same method.
var thread = NEWTHREAD('calc');
setTimeout(() => thread.kill(), 5000);
method
NEWFORK(name)
since 0.0.16
Runs a script from the workers/ folder in a new Node.js process.
NEWFORK(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The file name in workers/ without .js, or ~ and an absolute path |
Returns ChildProcess The forked process
Starts workers/{name}.js with child_process.fork(). A name that starts with ~ is an absolute path. The result is the Node.js ChildProcess; the framework adds postMessage() (the same as send()) and terminate(). Messages are serialized as JSON.
The working directory of the fork is the folder of its script. The framework in the fork sends the string total:init to the parent after it starts, so skip string messages in the parent. Called without a name inside the fork, NEWFORK() returns F.worker, as NEWTHREAD() does in a thread; F.worker.data is then an empty object.
var fork = NEWFORK('report');
fork.on('message', function(msg) {
if (typeof(msg) === 'string')
return;
console.log(msg);
fork.terminate();
});
fork.postMessage({ id: 100 });
require('total5');
var worker = NEWFORK();
worker.message = function(msg) {
worker.send({ id: msg.id, done: true });
};
method
fork.terminate()
since 0.0.16
Kills a process started with NEWFORK().
fork.terminate()Sends SIGKILL to the process. The process ends at once, without running its exit handlers.
var fork = NEWFORK('report');
setTimeout(() => fork.terminate(), 60000);
method
fork.postMessage(msg)
since 0.0.16
Sends a message to a process started with NEWFORK().
fork.postMessage(msg)| Parameter | Type | Description |
|---|---|---|
msg |
Object |
The message; it is serialized as JSON |
The same method as fork.send() of Node.js, so the code for threads and forks can look the same. The fork receives the message in F.worker.message.
fork.postMessage({ id: 100, type: 'pdf' });
method
NEWTHREADPOOL(name, count, [isfork])
Starts a pool of worker threads or forks and lends them to jobs.
NEWTHREADPOOL(name, count, [isfork])| Parameter | Type | Description |
|---|---|---|
name |
String |
The file name in workers/ without .js |
count |
Number |
The number of workers |
isfork? |
Boolean |
Start the workers with NEWFORK() instead of threads Default: false |
Returns Object The pool
Starts count workers of workers/{name}.js at once and returns a pool: worker threads, or processes from NEWFORK() when isfork is true. Jobs get the workers through pool.exec(); a worker goes to the next job only after the current job calls release(). Jobs that arrive while all workers are busy wait in pool.pending. A worker that exits is replaced by a new one, which is given to the next waiting job. The workers get no data (F.worker.data is {}). The pool is also stored in F.workers[name].
var pool = NEWTHREADPOOL('calc', 4);
pool.exec(function(worker, release) {
worker.on('message', function(msg) {
console.log(msg.sum);
release();
});
worker.postMessage({ a: 5, b: 5 });
});
var pool = NEWTHREADPOOL('report', 2, true);
method
pool.exec([fn])
Runs a job on the next free worker of the pool.
pool.exec([fn])| Parameter | Type | Description |
|---|---|---|
fn? |
Function |
function(worker, release) |
Returns Promise Only without fn: resolves with the worker
Adds the job to the queue and starts it as soon as a worker is free. The function gets (worker, release); call release() when the job is done. Without a function the method returns a promise that resolves with the worker; release it with worker.release().
Before a worker starts a job, the pool removes all its message listeners, so each job attaches its own.
pool.exec(function(worker, release) {
worker.on('message', function(msg) {
release();
});
worker.postMessage({ a: 1, b: 2 });
});
var worker = await pool.exec();
worker.on('message', function(msg) {
worker.release();
});
worker.postMessage({ a: 1, b: 2 });
method
worker.release()
Returns a worker of a pool back to the pool.
worker.release()Every worker of a pool has this method. It marks the worker as free and gives it to the next waiting job. It is the same function as the release argument of pool.exec(fn).
var worker = await pool.exec();
worker.on('message', () => worker.release());
worker.postMessage({});
property
pool.workers
The workers of the pool.
pool.workersReturns Array
An array of the Worker objects that the pool started.
pool.workers.forEach(w => w.postMessage({ type: 'reload' }));
property
pool.pending
The jobs that wait for a free worker.
pool.pendingReturns Array
An array of the functions passed to pool.exec() that have not started yet. Its length tells how busy the pool is.
console.log('Waiting jobs:', pool.pending.length);
property
pool.count
The number of workers of the pool.
pool.countReturns Number
The count given to NEWTHREADPOOL(). The pool keeps this number of workers: a worker that exits is replaced.
var pool = NEWTHREADPOOL('calc', 4);
console.log(pool.count); // 4
property
F.workers
The thread pools of the application by name.
F.workersReturns Object
NEWTHREADPOOL(name, count) stores the pool here under its name.
var pool = F.workers.calc;
config
options.cluster = 4
Start option: runs the application in a cluster of processes.
options.cluster = 4A number of processes, or 'auto'. Set it in the options of Total.run(). The first process becomes the master: it starts the processes one after another, each of them loads the application and listens on the same port. A process that exits is started again after one second. The processes run in release mode with options.release = true or options.watcher = false; otherwise they run in debug mode and the master restarts them all when a source file changes.
With 'auto' the master starts one process, pings all processes every 5 seconds and adds one when the average answer takes longer than 70 ms (up to limit). When they answer fast again, it removes the last process if it has fewer than two pending requests.
require('total5');
const options = {};
options.port = 8000;
options.release = true;
options.cluster = 4;
Total.run(options);
config
options.limit = 10
Start option: the maximum number of processes of an 'auto' cluster.
options.limit = 10Used only with cluster: 'auto'. Without it the master can add processes without a limit.
require('total5');
Total.run({ release: true, port: 8000, cluster: 'auto', limit: 8 });
config
options.tz = 'utc'
Start option of a cluster: the time zone of the processes.
options.tz = 'utc'In cluster mode the framework sets process.env.TZ to this value before it starts the processes. The default is 'utc'.
require('total5');
Total.run({ release: true, cluster: 4, tz: 'Europe/Madrid' });
config
options.logs = 'isolated'
Start option of a cluster: always print the cluster header.
options.logs = 'isolated'The master prints the CLUSTER header (PID, versions, thread count, mode) when it runs on its own. When it runs under another Node.js process (with an IPC channel) the header is skipped, unless logs is 'isolated'.
require('total5');
Total.run({ release: true, cluster: 2, logs: 'isolated' });
delegate
options.callback = function(forks) {}
Start option of a cluster: called after all processes have started.
options.callback = function(forks) {}| Parameter | Type | Description |
|---|---|---|
forks |
Array |
The cluster workers |
Runs in the master once every process of the cluster has started. forks is the array of the cluster.Worker objects.
require('total5');
Total.run({
release: true,
cluster: 2,
callback: function(forks) {
console.log('Started', forks.length, 'processes');
}
});
property
F.isCluster
true in a process of a cluster.
F.isClusterReturns Boolean
The framework sets it when the master sends the start options to the process. In other cases it is undefined.
if (F.isCluster)
process.send({ type: 'clearcache' });
property
F.isWorker
true when the process is a worker of the Node.js cluster.
F.isWorkerReturns Boolean
The value of cluster.isWorker of Node.js, so it is true in the processes of a Total.js cluster. It is false when the environment variable PASSENGER_APP_ENV is set. Processes with F.isWorker send their statistics to the master.
console.log(F.isWorker);
property
F.clusterid
The identifier of the process in a cluster.
F.clusteridReturns String
A string such as '1' or '2', the same value as F.id. Outside a cluster it is an empty string. The framework adds it to the names of temporary files and to the statistics.
var filename = PATH.tmp('export' + F.clusterid + '.csv');
property
F.id
The identifier of the process in a cluster.
F.idReturns String
The same value as F.clusterid: a string with the number of the process, or an empty string outside a cluster.
console.log('Process', F.id);
event
ON('$message', function(msg, handle) {})
Every message the process receives through its IPC channel.
ON('$message', function(msg, handle) {})| Parameter | Type | Description |
|---|---|---|
msg |
Object |
The message |
handle |
Object |
The handle sent with the message, if any |
Emitted for each message from the parent process. In a cluster an object that one process sends with process.send() is passed by the master to all ready processes, the sender included, and each of them gets it here. Do not use the TYPE property and strings that start with total: in your messages: the framework uses them.
ON('$message', function(msg) {
if (msg && msg.type === 'clearcache')
MAIN.products = null;
});
// in any process
process.send({ type: 'clearcache' });
command
restart (file)
A file that restarts all processes of a cluster.
restart (file)The master of a cluster checks every 5 seconds whether a file named restart exists in the application directory. If it does, the master deletes it and restarts the processes one by one, two seconds apart. A second restart within 30 seconds is ignored.
$ touch restart
method
SHELL(cmd, [callback], [cwd])
Runs a shell command.
SHELL(cmd, [callback], [cwd])| Parameter | Type | Description |
|---|---|---|
cmd |
String |
The command |
callback? |
Function |
function(err, stdout); or the working directory as a string |
cwd? |
String |
The working directory Default: the application root |
Returns Promise Only without a callback: resolves with the standard output
Runs the command with child_process.exec() in the system shell. With a callback it calls callback(err, stdout); without one it returns a promise that resolves with the standard output or rejects with the error. A string as the second argument is the working directory. The default directory is the application root. The config key $shell sets the shell to use. The output can have up to 100 MB (maxBuffer); a larger output ends with an error.
SHELL('git rev-parse HEAD', function(err, stdout) {
console.log(stdout.trim());
});
var list = await SHELL('ls -1', PATH.public());
config
$shell : /bin/bash
The shell that SHELL() uses.
$shell : /bin/bashThe path of the shell for SHELL(). Not set by default, which uses the default shell of Node.js (/bin/sh, or cmd.exe on Windows).
$shell : /bin/bash
method
F.python(filename, [callback])
Runs a Python script and returns its output.
F.python(filename, [callback])| Parameter | Type | Description |
|---|---|---|
filename |
String |
The absolute path to the .py file. |
callback? |
Function |
function(err, stdout, stderr). |
Returns Promise Only without a callback: resolves with the standard output.
Runs $python <filename> with child_process.exec() in the folder of the script. With a callback it calls callback(err, stdout, stderr); without one it returns a promise that resolves with the standard output. A script that ends with an exit code other than 0 gives an error (err.code is the exit code) and the promise rejects. $python is the config key with the Python command (python3 by default).
var output = await F.python(PATH.root('scripts/report.py'));
F.python(PATH.root('scripts/report.py'), function(err, stdout, stderr) {
if (err)
console.log(stderr);
else
console.log(stdout);
});
method
PYPELINE(name, [options])
Starts a Python script and exchanges messages with it.
PYPELINE(name, [options])| Parameter | Type | Description |
|---|---|---|
name |
String |
The file name in pypelines/ without .py, ~ and an absolute path, or inline code |
options? |
Object |
{ autorestart, type, socket } |
Returns Pypeline An object with events and the methods below
Runs python3 with pypelines/{name}.py (or an absolute path that starts with ~) in the folder of the script. A name that contains a new line, ; or a quote is inline code, run with python3 -c in the application root.
The framework listens on a Unix socket in tmp/ and passes its path to the script as sys.argv[1]. Each message in both directions is a 4-byte big-endian length followed by the payload. The script's standard output and error go to the console of the application. When the application exits, all Python processes are killed.
The options are autorestart (default true: start the script again when it ends), type ('json' by default, 'text' for strings, or any other value for raw buffers) and socket (false runs the script without a socket, for scripts that only run).
var py = PYPELINE('upper');
py.on('data', function(msg) {
console.log(msg.text);
});
py.send({ text: 'hello' });
var py = PYPELINE('tokenizer', { type: 'text' });
method
F.pipinstall(name, [callback])
Installs a Python package with pip.
F.pipinstall(name, [callback])| Parameter | Type | Description |
|---|---|---|
name |
String |
The package, optionally with a version (requests==2.32.3). |
callback? |
Function |
function(err). |
Returns Promise Only without a callback.
Runs $python -m pip install <name> in the application directory. With a callback it calls callback(err); without one it returns a promise. When pip fails, the error is the error output of pip (a string), or the error of the process.
await F.pipinstall('requests');
var output = await F.python(PATH.root('scripts/download.py'));
method
pypeline.send(data)
Sends a message to the Python script.
pypeline.send(data)| Parameter | Type | Description |
|---|---|---|
data |
Object|Buffer|String |
The message |
Returns Pypeline The pipeline (only when the script is connected)
An object is sent as JSON, a Buffer as it is and other values as text, each with a 4-byte length in front. Messages sent before the script connects wait and are sent when it connects.
py.send({ text: 'hello' });
method
pypeline.close()
Stops the Python script for good.
pypeline.close()Returns Pypeline
Turns autorestart off, closes the socket server and kills the Python process.
py.close();
method
pypeline.restart()
Kills the Python process and starts it again.
pypeline.restart()Kills the current process and starts the script again. pypeline.run() is the same method.
py.restart();
event
pypeline.on('data', function(msg) {})
A message from the Python script.
pypeline.on('data', function(msg) {})| Parameter | Type | Description |
|---|---|---|
msg |
Object|String|Buffer |
The message |
Emitted for every complete message. With type: 'json' the message is parsed, with 'text' it is a string, otherwise a Buffer.
py.on('data', function(msg) {
console.log(msg);
});
event
pypeline.on('open', function() {})
The Python script connected to the socket.
pypeline.on('open', function() {})Emitted each time the script connects, after the waiting messages have been sent.
py.on('open', function() {
console.log('Python is ready');
});
event
pypeline.on('restart', function() {})
The Python script ended and was started again.
pypeline.on('restart', function() {})Emitted with autorestart: true after the framework has started the script again.
py.on('restart', function() {
console.log('Python restarted');
});
property
pypeline.name
The name of the pipeline.
pypeline.nameReturns String
The name passed to PYPELINE(), or Inline Python Code for inline code.
console.log(py.name);