itns-sidechain/lib/workers/workerpool.js

697 lines
13 KiB
JavaScript
Raw Normal View History

/*!
2016-11-19 06:48:55 -08:00
* workerpool.js - worker processes for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
2017-02-03 22:47:26 -08:00
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
2016-06-09 16:18:50 -07:00
* https://github.com/bcoin-org/bcoin
*/
2017-07-31 00:34:42 -07:00
/* eslint no-nested-ternary: "off" */
2016-06-13 01:06:01 -07:00
'use strict';
2017-06-29 20:54:07 -07:00
const assert = require('assert');
const EventEmitter = require('events');
2017-06-29 20:54:07 -07:00
const os = require('os');
const Network = require('../protocol/network');
2018-01-02 20:24:56 -08:00
const consensus = require('../protocol/consensus');
2017-07-07 00:34:59 -07:00
const Child = require('./child');
2017-06-29 20:54:07 -07:00
const jobs = require('./jobs');
const Parser = require('./parser');
const Framer = require('./framer');
const packets = require('./packets');
/**
2017-11-16 20:26:28 -08:00
* Worker Pool
2017-02-03 22:47:26 -08:00
* @alias module:workers.WorkerPool
2017-11-16 20:26:28 -08:00
* @extends EventEmitter
2016-05-02 19:47:41 -07:00
* @property {Number} size
* @property {Number} timeout
2017-07-05 13:49:45 -07:00
* @property {Map} children
2017-07-07 08:15:10 -07:00
* @property {Number} uid
*/
2017-11-16 20:26:28 -08:00
class WorkerPool extends EventEmitter {
/**
* Create a worker pool.
* @constructor
* @param {Object} options
* @param {Number} [options.size=num-cores] - Max pool size.
* @param {Number} [options.timeout=120000] - Execution timeout.
*/
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
constructor(options) {
super();
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
this.enabled = false;
this.size = getCores();
this.timeout = 120000;
this.file = process.env.BCOIN_WORKER_FILE || 'worker.js';
2017-07-05 13:49:45 -07:00
2017-11-16 20:26:28 -08:00
this.children = new Map();
this.uid = 0;
2017-07-07 08:15:10 -07:00
2017-11-16 20:26:28 -08:00
this.set(options);
2017-01-14 14:41:55 -08:00
}
2017-11-16 20:26:28 -08:00
/**
* Set worker pool options.
* @param {Object} options
*/
2017-01-14 14:41:55 -08:00
2017-11-16 20:26:28 -08:00
set(options) {
if (!options)
return;
2017-11-16 20:26:28 -08:00
if (options.enabled != null) {
assert(typeof options.enabled === 'boolean');
this.enabled = options.enabled;
}
2017-01-14 14:41:55 -08:00
2017-11-16 20:26:28 -08:00
if (options.size != null) {
assert((options.size >>> 0) === options.size);
assert(options.size > 0);
this.size = options.size;
}
2017-07-05 13:49:45 -07:00
2017-11-16 20:26:28 -08:00
if (options.timeout != null) {
assert(Number.isSafeInteger(options.timeout));
assert(options.timeout >= -1);
this.timeout = options.timeout;
}
2017-07-05 13:49:45 -07:00
2017-11-16 20:26:28 -08:00
if (options.file != null) {
assert(typeof options.file === 'string');
this.file = options.file;
}
}
2017-07-05 13:49:45 -07:00
2017-11-16 20:26:28 -08:00
/**
* Open worker pool.
* @returns {Promise}
*/
2017-07-05 13:49:45 -07:00
2017-11-16 20:26:28 -08:00
async open() {
;
}
2017-11-16 20:26:28 -08:00
/**
* Close worker pool.
* @returns {Promise}
*/
2017-11-16 20:26:28 -08:00
async close() {
this.destroy();
}
2017-11-16 20:26:28 -08:00
/**
* Spawn a new worker.
* @param {Number} id - Worker ID.
* @returns {Worker}
*/
2017-11-16 20:26:28 -08:00
spawn(id) {
const child = new Worker(this.file);
2017-07-15 23:59:45 -07:00
2017-11-16 20:26:28 -08:00
child.id = id;
2017-11-16 20:26:28 -08:00
child.on('error', (err) => {
this.emit('error', err, child);
});
2017-11-16 20:26:28 -08:00
child.on('exit', (code) => {
this.emit('exit', code, child);
2017-07-05 13:49:45 -07:00
2017-11-16 20:26:28 -08:00
if (this.children.get(id) === child)
this.children.delete(id);
});
2016-05-22 18:13:54 -07:00
2017-11-16 20:26:28 -08:00
child.on('event', (items) => {
this.emit('event', items, child);
this.emit(...items);
});
2017-11-16 20:26:28 -08:00
child.on('log', (text) => {
this.emit('log', text, child);
});
2017-11-16 20:26:28 -08:00
this.emit('spawn', child);
2017-07-05 13:49:45 -07:00
2017-11-16 20:26:28 -08:00
return child;
}
2017-07-05 13:49:45 -07:00
2017-11-16 20:26:28 -08:00
/**
* Allocate a new worker, will not go above `size` option
* and will automatically load balance the workers.
* @returns {Worker}
*/
2017-11-16 20:26:28 -08:00
alloc() {
const id = this.uid++ % this.size;
2016-05-03 18:53:43 -07:00
2017-11-16 20:26:28 -08:00
if (!this.children.has(id))
this.children.set(id, this.spawn(id));
2016-05-03 18:53:43 -07:00
2017-11-16 20:26:28 -08:00
return this.children.get(id);
2016-05-03 18:53:43 -07:00
}
2017-11-16 20:26:28 -08:00
/**
* Emit an event on the worker side (all workers).
* @param {String} event
* @param {...Object} arg
* @returns {Boolean}
*/
2016-05-03 18:53:43 -07:00
2017-11-16 20:26:28 -08:00
sendEvent() {
let result = true;
2016-05-03 18:53:43 -07:00
2017-11-16 20:26:28 -08:00
for (const child of this.children.values()) {
if (!child.sendEvent.apply(child, arguments))
result = false;
}
2017-11-16 20:26:28 -08:00
return result;
}
2017-11-16 20:26:28 -08:00
/**
* Destroy all workers.
*/
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
destroy() {
for (const child of this.children.values())
child.destroy();
}
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
/**
* Call a method for a worker to execute.
* @param {Packet} packet
* @param {Number} timeout
* @returns {Promise}
*/
execute(packet, timeout) {
if (!this.enabled || !Child.hasSupport()) {
return new Promise((resolve, reject) => {
setImmediate(() => {
let result;
try {
result = jobs.handle(packet);
} catch (e) {
reject(e);
return;
}
resolve(result);
});
});
}
2017-11-16 20:26:28 -08:00
if (!timeout)
timeout = this.timeout;
2017-11-16 20:26:28 -08:00
const child = this.alloc();
2016-09-22 02:49:18 -07:00
2017-11-16 20:26:28 -08:00
return child.execute(packet, timeout);
}
2016-07-15 08:36:19 -07:00
2017-11-16 20:26:28 -08:00
/**
* Execute the tx check job (default timeout).
* @method
* @param {TX} tx
* @param {CoinView} view
* @param {VerifyFlags} flags
* @returns {Promise}
*/
2016-07-15 08:36:19 -07:00
2017-11-16 20:26:28 -08:00
async check(tx, view, flags) {
const packet = new packets.CheckPacket(tx, view, flags);
const result = await this.execute(packet, -1);
2016-07-15 08:36:19 -07:00
2017-11-16 20:26:28 -08:00
if (result.error)
throw result.error;
2016-07-15 08:36:19 -07:00
2017-11-16 20:26:28 -08:00
return null;
}
2016-07-15 08:36:19 -07:00
2017-11-16 20:26:28 -08:00
/**
* Execute the tx signing job (default timeout).
* @method
* @param {MTX} tx
* @param {KeyRing[]} ring
* @param {SighashType} type
* @returns {Promise}
*/
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
async sign(tx, ring, type) {
let rings = ring;
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
if (!Array.isArray(rings))
rings = [rings];
2017-11-16 20:26:28 -08:00
const packet = new packets.SignPacket(tx, rings, type);
const result = await this.execute(packet, -1);
2017-11-16 20:26:28 -08:00
result.inject(tx);
2016-07-15 08:36:19 -07:00
2017-11-16 20:26:28 -08:00
return result.total;
}
2016-09-22 02:49:18 -07:00
2017-11-16 20:26:28 -08:00
/**
* Execute the tx input check job (default timeout).
* @method
* @param {TX} tx
* @param {Number} index
* @param {Coin|Output} coin
* @param {VerifyFlags} flags
* @returns {Promise}
*/
2016-09-22 02:49:18 -07:00
2017-11-16 20:26:28 -08:00
async checkInput(tx, index, coin, flags) {
const packet = new packets.CheckInputPacket(tx, index, coin, flags);
const result = await this.execute(packet, -1);
2016-09-22 02:49:18 -07:00
2017-11-16 20:26:28 -08:00
if (result.error)
throw result.error;
2016-09-22 02:49:18 -07:00
2017-11-16 20:26:28 -08:00
return null;
}
2016-09-22 02:49:18 -07:00
2017-11-16 20:26:28 -08:00
/**
* Execute the tx input signing job (default timeout).
* @method
* @param {MTX} tx
* @param {Number} index
* @param {Coin|Output} coin
* @param {KeyRing} ring
* @param {SighashType} type
* @returns {Promise}
*/
async signInput(tx, index, coin, ring, type) {
const packet = new packets.SignInputPacket(tx, index, coin, ring, type);
const result = await this.execute(packet, -1);
result.inject(tx);
return result.value;
}
2016-09-22 02:49:18 -07:00
2017-11-16 20:26:28 -08:00
/**
* Execute the secp256k1 verify job (no timeout).
* @method
* @param {Buffer} msg
* @param {Buffer} sig - DER formatted.
* @param {Buffer} key
* @returns {Promise}
*/
async ecVerify(msg, sig, key) {
const packet = new packets.ECVerifyPacket(msg, sig, key);
const result = await this.execute(packet, -1);
return result.value;
}
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
/**
* Execute the secp256k1 signing job (no timeout).
* @method
* @param {Buffer} msg
* @param {Buffer} key
* @returns {Promise}
*/
async ecSign(msg, key) {
const packet = new packets.ECSignPacket(msg, key);
const result = await this.execute(packet, -1);
return result.sig;
}
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
/**
* Execute the mining job (no timeout).
* @method
2018-01-02 20:24:56 -08:00
* @param {Buffer} hdr
2017-11-16 20:26:28 -08:00
* @param {Buffer} target
2018-01-02 20:24:56 -08:00
* @param {Number} rounds
* @param {Object} params
2017-11-16 20:26:28 -08:00
* @returns {Promise} - Returns {Number}.
*/
2018-01-02 20:24:56 -08:00
async mine(hdr, target, rounds, params) {
const packet = new packets.MinePacket(hdr, target, rounds, params);
const {nonce, sol} = await this.execute(packet, -1);
nonce.copy(hdr, consensus.NONCE_POS);
return [nonce, sol];
2017-11-16 20:26:28 -08:00
}
2016-06-01 22:27:33 -07:00
2017-11-16 20:26:28 -08:00
/**
* Execute scrypt job (no timeout).
* @method
* @param {Buffer} passwd
* @param {Buffer} salt
* @param {Number} N
* @param {Number} r
* @param {Number} p
* @param {Number} len
* @returns {Promise}
*/
async scrypt(passwd, salt, N, r, p, len) {
const packet = new packets.ScryptPacket(passwd, salt, N, r, p, len);
const result = await this.execute(packet, -1);
return result.key;
}
}
2016-06-01 22:27:33 -07:00
2016-05-02 19:47:41 -07:00
/**
2017-11-16 20:26:28 -08:00
* Worker
2017-02-03 22:47:26 -08:00
* @alias module:workers.Worker
2017-11-16 20:26:28 -08:00
* @extends EventEmitter
2016-05-02 19:47:41 -07:00
*/
2017-11-16 20:26:28 -08:00
class Worker extends EventEmitter {
/**
* Create a worker.
* @constructor
* @param {String} file
*/
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
constructor(file) {
super();
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
this.id = -1;
this.framer = new Framer();
this.parser = new Parser();
this.pending = new Map();
2017-01-09 14:59:35 -08:00
2017-11-16 20:26:28 -08:00
this.child = new Child(file);
2016-07-27 17:17:17 -07:00
2017-11-16 20:26:28 -08:00
this.init();
}
2016-07-27 17:17:17 -07:00
2017-11-16 20:26:28 -08:00
/**
* Initialize worker. Bind to events.
* @private
*/
2016-12-02 18:14:17 -08:00
2017-11-16 20:26:28 -08:00
init() {
this.child.on('data', (data) => {
this.parser.feed(data);
});
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
this.child.on('exit', (code, signal) => {
this.emit('exit', code, signal);
});
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
this.child.on('error', (err) => {
this.emit('error', err);
});
2016-07-04 05:36:06 -07:00
2017-11-16 20:26:28 -08:00
this.parser.on('error', (err) => {
this.emit('error', err);
});
2016-12-02 18:14:17 -08:00
2017-11-16 20:26:28 -08:00
this.parser.on('packet', (packet) => {
this.emit('packet', packet);
});
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
this.listen();
}
2016-12-02 18:14:17 -08:00
2017-11-16 20:26:28 -08:00
/**
* Listen for packets.
* @private
*/
2016-12-02 18:14:17 -08:00
2017-11-16 20:26:28 -08:00
listen() {
this.on('exit', (code, signal) => {
this.killJobs();
});
2016-12-02 18:14:17 -08:00
2017-11-16 20:26:28 -08:00
this.on('error', (err) => {
this.killJobs();
});
2017-07-07 09:04:52 -07:00
2017-11-16 20:26:28 -08:00
this.on('packet', (packet) => {
try {
this.handlePacket(packet);
} catch (e) {
this.emit('error', e);
}
});
2016-07-04 05:36:06 -07:00
2017-11-16 20:26:28 -08:00
this.sendEnv({
BCOIN_WORKER_NETWORK: Network.type,
BCOIN_WORKER_ISTTY: process.stdout
? (process.stdout.isTTY ? '1' : '0')
: '0'
});
}
2016-07-04 05:36:06 -07:00
2017-11-16 20:26:28 -08:00
/**
* Handle packet.
* @private
* @param {Packet} packet
*/
handlePacket(packet) {
switch (packet.cmd) {
case packets.types.EVENT:
this.emit('event', packet.items);
this.emit(...packet.items);
break;
case packets.types.LOG:
this.emit('log', packet.text);
break;
case packets.types.ERROR:
this.emit('error', packet.error);
break;
case packets.types.ERRORRESULT:
this.rejectJob(packet.id, packet.error);
break;
default:
this.resolveJob(packet.id, packet);
break;
}
}
2016-07-04 05:36:06 -07:00
2017-11-16 20:26:28 -08:00
/**
* Send data to worker.
* @param {Buffer} data
* @returns {Boolean}
*/
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
write(data) {
return this.child.write(data);
}
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
/**
* Frame and send a packet.
* @param {Packet} packet
* @returns {Boolean}
*/
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
send(packet) {
return this.write(this.framer.packet(packet));
}
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
/**
* Send environment.
* @param {Object} env
* @returns {Boolean}
*/
2017-07-07 09:04:52 -07:00
2017-11-16 20:26:28 -08:00
sendEnv(env) {
return this.send(new packets.EnvPacket(env));
}
2017-07-07 09:04:52 -07:00
2017-11-16 20:26:28 -08:00
/**
* Emit an event on the worker side.
* @param {String} event
* @param {...Object} arg
* @returns {Boolean}
*/
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
sendEvent(...items) {
return this.send(new packets.EventPacket(items));
}
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
/**
* Destroy the worker.
*/
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
destroy() {
return this.child.destroy();
}
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
/**
* Call a method for a worker to execute.
* @param {Packet} packet
* @param {Number} timeout
* @returns {Promise}
*/
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
execute(packet, timeout) {
return new Promise((resolve, reject) => {
this._execute(packet, timeout, resolve, reject);
});
}
2016-07-04 05:36:06 -07:00
2017-11-16 20:26:28 -08:00
/**
* Call a method for a worker to execute.
* @private
* @param {Packet} packet
* @param {Number} timeout
* @param {Function} resolve
* @param {Function} reject
* the worker method specifies.
*/
2016-05-02 19:47:41 -07:00
2017-11-16 20:26:28 -08:00
_execute(packet, timeout, resolve, reject) {
const job = new PendingJob(this, packet.id, resolve, reject);
2017-11-16 20:26:28 -08:00
assert(!this.pending.has(packet.id), 'ID overflow.');
2017-11-16 20:26:28 -08:00
this.pending.set(packet.id, job);
2016-05-03 18:53:43 -07:00
2017-11-16 20:26:28 -08:00
job.start(timeout);
2017-11-16 20:26:28 -08:00
this.send(packet);
}
2017-11-16 20:26:28 -08:00
/**
* Resolve a job.
* @param {Number} id
* @param {Packet} result
*/
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
resolveJob(id, result) {
const job = this.pending.get(id);
2016-12-02 18:34:29 -08:00
2017-11-16 20:26:28 -08:00
if (!job)
throw new Error(`Job ${id} is not in progress.`);
2016-12-02 18:34:29 -08:00
2017-11-16 20:26:28 -08:00
job.resolve(result);
}
2017-11-16 20:26:28 -08:00
/**
* Reject a job.
* @param {Number} id
* @param {Error} err
*/
2016-09-20 14:56:54 -07:00
2017-11-16 20:26:28 -08:00
rejectJob(id, err) {
const job = this.pending.get(id);
2016-12-02 18:34:29 -08:00
2017-11-16 20:26:28 -08:00
if (!job)
throw new Error(`Job ${id} is not in progress.`);
2016-12-02 18:34:29 -08:00
2017-11-16 20:26:28 -08:00
job.reject(err);
}
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
/**
* Kill all jobs associated with worker.
*/
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
killJobs() {
for (const job of this.pending.values())
job.destroy();
}
}
2016-12-02 11:06:01 -08:00
/**
2017-02-03 22:47:26 -08:00
* Pending Job
* @ignore
2016-12-02 11:06:01 -08:00
*/
2017-11-16 20:26:28 -08:00
class PendingJob {
/**
* Create a pending job.
* @constructor
* @param {Worker} worker
* @param {Number} id
* @param {Function} resolve
* @param {Function} reject
*/
constructor(worker, id, resolve, reject) {
this.worker = worker;
this.id = id;
this.job = { resolve, reject };
this.timer = null;
}
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
/**
* Start the timer.
* @param {Number} timeout
*/
2016-12-02 18:14:17 -08:00
2017-11-16 20:26:28 -08:00
start(timeout) {
if (!timeout || timeout <= 0)
return;
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
this.timer = setTimeout(() => {
this.reject(new Error('Worker timed out.'));
}, timeout);
}
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
/**
* Destroy the job with an error.
*/
2016-12-02 18:14:17 -08:00
2017-11-16 20:26:28 -08:00
destroy() {
this.reject(new Error('Job was destroyed.'));
}
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
/**
* Cleanup job state.
* @returns {Job}
*/
2016-12-02 18:14:17 -08:00
2017-11-16 20:26:28 -08:00
cleanup() {
const job = this.job;
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
assert(job, 'Already finished.');
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
this.job = null;
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
if (this.timer != null) {
clearTimeout(this.timer);
this.timer = null;
}
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
assert(this.worker.pending.has(this.id));
this.worker.pending.delete(this.id);
2016-12-02 11:06:01 -08:00
2017-11-16 20:26:28 -08:00
return job;
}
2017-01-05 04:30:29 -08:00
2017-11-16 20:26:28 -08:00
/**
* Complete job with result.
* @param {Object} result
*/
2017-01-05 04:30:29 -08:00
2017-11-16 20:26:28 -08:00
resolve(result) {
const job = this.cleanup();
job.resolve(result);
}
2017-01-05 04:30:29 -08:00
2017-11-16 20:26:28 -08:00
/**
* Complete job with error.
* @param {Error} err
*/
2017-01-05 04:30:29 -08:00
2017-11-16 20:26:28 -08:00
reject(err) {
const job = this.cleanup();
job.reject(err);
}
}
2016-05-02 19:47:41 -07:00
2016-07-04 05:36:06 -07:00
/*
* Helpers
2016-05-02 19:47:41 -07:00
*/
2016-05-02 19:47:41 -07:00
function getCores() {
2017-06-27 00:31:14 -07:00
return Math.max(2, os.cpus().length);
}
2016-05-15 18:07:06 -07:00
/*
* Expose
*/
2017-06-30 03:03:39 -07:00
module.exports = WorkerPool;