dcp-worker 3.2.30-2 → 3.2.30-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,187 @@
1
+ /**
2
+ * @file default-event.js
3
+ * Default worker/sandbox events, providing default logging behaviours (event handlers)
4
+ * for the dcp-worker.
5
+ *
6
+ * - All event handlers use the *current* global console object to emit messages;
7
+ * enhanced logging subsystems should intercept this object to achieve their desired
8
+ * behaviours.
9
+ *
10
+ * - All event handlers invoke functions which are properties of the eventHandlers return
11
+ * value from the hook function. This means that alternate user interfaces can either
12
+ * hook or intercept the properties of that object to modify the event handlers'
13
+ * behaviour without actually removing/replacing the event handler on the instance of
14
+ * Worker.
15
+ *
16
+ * NOTE: This is just a convenience module. There is no requirement to use this module to
17
+ * hook worker events, this module mainly exists to make it easy for the
18
+ * dashboard-tui to replace event handlers with better ones, but it also makes it
19
+ * easier to sandbox events since we only need to register one event handler here
20
+ * to handle every sandbox.
21
+ *
22
+ * @author Ryan Rossiter, ryan@kingsds.network
23
+ * @date April 2020
24
+ * @author Wes Garland, wes@distributive.network
25
+ * @date June 2023
26
+ */
27
+ 'use strict';
28
+
29
+ const sandboxEventHandlers = {};
30
+ const workerEventHandlers = {};
31
+
32
+ /**
33
+ * Sandbox 1: Slice Started: slice 1, 0x5b5214D48F0428669c4E: Simple Job
34
+ * Sandbox 1: Slice Completed: slice 1, 0x5b5214D48F0428669c4E: Simple Job: dt 114ms
35
+ */
36
+
37
+ /**
38
+ * @param worker The instance of Worker to hook
39
+ * @param options cliArgs from worker
40
+ */
41
+ exports.hook = function hookWorkerEvents$$hook(worker, options)
42
+ {
43
+ const sliceMap = {}; // jobAddress --> ( sliceNumber, t0 )
44
+ const truncationLength = 22; // Extra 2 for '0x'
45
+
46
+ delete exports.hook;
47
+
48
+ function makeSliceId (sandbox, sliceNumber)
49
+ {
50
+ if (!sandbox.jobAddress)
51
+ return '<no job>';
52
+
53
+ const address = sandbox.jobAddress ? sandbox.jobAddress.slice(0, truncationLength) : 'null';
54
+ const baseInfo = sandbox.public?.name ? `${address}: ${sandbox.public.name}` : `${address}:`;
55
+
56
+ if (!sliceNumber)
57
+ sliceNumber = sandbox.slice ? sandbox.slice.sliceNumber : 0;
58
+ return sliceNumber ? `slice ${sliceNumber}, ${baseInfo}` : baseInfo;
59
+ }
60
+
61
+ sandboxEventHandlers.ready = function sandboxReadyHandler(sandbox, sandboxData, ev) {
62
+ console.log(` . Sandbox ${sandboxData.shortId}: Initialized`);
63
+ };
64
+
65
+ sandboxEventHandlers.terminated = function sandboxTerminatedHandler(sandbox, sandboxData, ev) {
66
+ const sliceInfo = sliceMap[sandbox.id];
67
+ console.log(` * Sandbox ${sandboxData.shortId}: Terminated: ${makeSliceId(sandbox, sliceInfo?.slice)}`);
68
+ delete sliceMap[sandbox.id];
69
+ };
70
+
71
+ sandboxEventHandlers.start = function sliceStartHandler(sandbox, sandboxData, ev) {
72
+ const sliceNumber = sandbox.slice ? sandbox.slice.sliceNumber : 0;
73
+ sliceMap[sandbox.id] = { slice: sliceNumber, t0: Date.now() };
74
+ console.log(` . Sandbox ${sandboxData.shortId}: Slice Started: ${makeSliceId(sandbox)}`);
75
+ };
76
+
77
+ sandboxEventHandlers.sliceProgress = function sliceProgressHandler(sandbox, sandbodData, ev) {
78
+ // NOP
79
+ };
80
+
81
+ sandboxEventHandlers.sliceFinish = function sliceFinishHandler(sandbox, sandboxData, ev) {
82
+ const sliceInfo = sliceMap[sandbox.id];
83
+ if (sliceInfo)
84
+ console.log(` * Sandbox ${sandboxData.shortId}: Slice Completed: ${makeSliceId(sandbox, sliceInfo.slice)}: dt ${Date.now() - sliceInfo.t0}ms`);
85
+ else
86
+ console.log(` * Sandbox ${sandboxData.shortId}: Slice Completed: ${makeSliceId(sandbox)}`);
87
+ };
88
+
89
+ workerEventHandlers.payment = function paymentHandler(ev) {
90
+ const payment = parseFloat(ev.payment);
91
+
92
+ if (isNaN(payment))
93
+ console.error(' ! Failed to parse payment:', payment);
94
+ else
95
+ console.log(` . Payment: ${payment.toFixed(3)} ⊇`);
96
+ };
97
+
98
+ workerEventHandlers.fetchStart = function fetchStartHandler() {
99
+ options.verbose && console.log(' * Fetching slices...');
100
+ };
101
+
102
+ workerEventHandlers.fetch = function fetchHandler(ev) {
103
+ var slicesFetched;
104
+
105
+ if (ev instanceof Error)
106
+ {
107
+ console.error(' ! Failed to fetch slices:', ev);
108
+ return;
109
+ }
110
+
111
+ if (typeof ev === 'number' || typeof ev === 'string') /* <= June 2023 Worker events: remove ~ Sep 2023 /wg */
112
+ slicesFetched = ev;
113
+ else
114
+ {
115
+ const task = ev;
116
+ slicesFetched = task.slices.length;
117
+ }
118
+
119
+ options.verbose && console.log(' . Fetched', slicesFetched, 'slices');
120
+ };
121
+
122
+ workerEventHandlers.fetchError = function fetchErrorHandler(ev) {
123
+ console.log(' ! Failed to fetch slices:', ev);
124
+ };
125
+
126
+ workerEventHandlers.submitStart = function submitStartHandler() {
127
+ options.verbose >= 2 && console.log(' * Submitting results...');
128
+ };
129
+
130
+ workerEventHandlers.submit = function submitHandler() {
131
+ options.verbose >= 2 && console.log(' . Submitted');
132
+ };
133
+
134
+ workerEventHandlers.submitError = function submitErrorHandler(ev) {
135
+ console.log(' ! Failed to submit results:', ev);
136
+ };
137
+
138
+ /* Register the appropriate event handlers on the worker and on each sandbox. The handlers are
139
+ * registered in such a way that mutating the exports object to supply different handlers after
140
+ * registration will work.
141
+ *
142
+ * The handlers registered on each sandbox receive two extra arguments before the usual event
143
+ * arguments; these are the sandbox handle emitted by the Worker<sandbox> event and an object
144
+ * called `sandboxData` which is just arbitrary storage for the eventHandlers' use, eg for memos.
145
+ */
146
+ for (let eventName in workerEventHandlers)
147
+ worker.addEventListener(eventName, workerEventHandlers[eventName]);
148
+
149
+ worker.on('sandbox', function newSandboxHandler(sandbox) {
150
+ const sandboxData = {
151
+ shortId: sandbox.id.toString(10).padStart(3)
152
+ };
153
+ for (let eventName in sandboxEventHandlers)
154
+ sandbox.addEventListener(eventName, (...args) => sandboxEventHandlers[eventName](sandbox, sandboxData, ...args));
155
+ });
156
+
157
+ exports.sandboxEventHandlers = sandboxEventHandlers;
158
+ exports. workerEventHandlers = workerEventHandlers;
159
+ };
160
+
161
+ /**
162
+ * Function to replace a worker event handler.
163
+ *
164
+ * @param {string} eventName name of the event to replace
165
+ * @param {function} eventHandler new event handler
166
+ */
167
+ exports.replaceWorkerEvent = function hookWorkerEvents$$replace(eventName, eventHandler)
168
+ {
169
+ if (!workerEventHandlers.hasOwnProperty(eventName))
170
+ throw new Error('unknown worker event: ' + eventName + `(${Object.keys(workerEventHandlers).join(', ')})`);
171
+
172
+ workerEventHandlers[eventName] = eventHandler;
173
+ }
174
+
175
+ /**
176
+ * Function to replace a sandbox event handler.
177
+ *
178
+ * @param {string} eventName name of the event to replace
179
+ * @param {function} eventHandler new event handler
180
+ */
181
+ exports.replaceSandboxEvent = function hookSandboxEvents$$replace(eventName, eventHandler)
182
+ {
183
+ if (!sandboxEventHandlers.hasOwnProperty(eventName))
184
+ throw new Error('unknown sandbox event: ' + eventName + `(${Object.keys(sandboxEventHandlers).join(', ')})`);
185
+
186
+ sandboxEventHandlers[eventName] = eventHandler;
187
+ }
package/lib/pidfile.js CHANGED
@@ -21,7 +21,7 @@ const path = require('path');
21
21
  *
22
22
  * @param {string} filename the location of the pid file
23
23
  */
24
- exports.write = async function pidfile$$write(filename)
24
+ exports.write = function pidfile$$write(filename)
25
25
  {
26
26
  var fd;
27
27
 
@@ -47,7 +47,7 @@ function daemonEval()
47
47
 
48
48
  function callbackTelnet(port, client, registry) {
49
49
  client.unref();
50
- debugging() && console.debug(' ! telnetd - listening on port', port);
50
+ debugging() && console.notice(' ! telnetd - listening on port', port);
51
51
  }
52
52
 
53
53
  /**
@@ -76,8 +76,16 @@ exports.init = function remoteConsole$$init(...commands)
76
76
 
77
77
  console.warn('*** Enabling telnet daemon on port', port, '(security risk) ***');
78
78
 
79
+ if (port !== 0)
80
+ exports.port = port;
81
+ else
82
+ {
83
+ /* telnet-console library does not properly support port 0 so we mostly work-around here */
84
+ exports.port = Math.floor(1023 + (Math.random() * (63 * 1024)));
85
+ }
86
+
79
87
  ci = require('telnet-console').start({
80
- port,
88
+ port: exports.port,
81
89
  callbackTelnet,
82
90
  eval: daemonEval,
83
91
  histfile: edcFilename + '.history',
@@ -1,97 +1,127 @@
1
1
  /**
2
2
  * @file startWorkerLogger.js
3
+ * Start the DCP Worker logging subsystem. Sets console.log (etc) redirection, determine
4
+ * the correct log target (screen, TUI, syslog, windows event log, file) and redirect the
5
+ * output there.
3
6
  * @author Ryan Rossiter, ryan@kingsds.network
4
7
  * @date April 2020
8
+ * @author Wes Garland, wes@distributive.network
5
9
  */
10
+ 'use strict';
6
11
 
7
12
  const process = require('process');
8
13
  const os = require('os');
9
- require('./worker-loggers/common-types');
14
+ const util = require('util');
10
15
 
11
16
  /**
12
17
  * Detects and returns the appropriate logger for the environment
18
+ * @param {object} options - cliArgs from worker
13
19
  * @returns {WorkerLogger}
14
20
  */
15
- function getLogger({ outputMode='detect' }) {
16
- if (outputMode === 'detect') {
17
- if (process.stdout.isTTY && os.platform() !== 'win32' &&
18
- process.env.LANG && process.env.LANG.match(/utf-?8/i)) {
19
- outputMode = 'dashboard';
20
- } else {
21
- outputMode = 'console';
22
- }
21
+ function getLogger(options)
22
+ {
23
+ if (options.outputMode === 'detect')
24
+ {
25
+ options.outputMode = 'console';
26
+ /* have TTY - use dashboard when charset supports line drawing */
27
+ if ((process.env.LANG && process.env.LANG.match(/utf-|latin-|iso-8859-/i)) || os.platform() === 'win32')
28
+ options.outputMode = 'dashboard';
23
29
  }
24
30
 
25
31
  try
26
32
  {
27
- const om = require('path').basename(outputMode);
33
+ const om = require('path').basename(options.outputMode);
28
34
  return require('./worker-loggers/' + om);
29
35
  }
30
36
  catch (error)
31
37
  {
32
- console.error(`032: Failed to load worker logger "${outputMode}":`, error);
33
-
34
38
  if (error.code === 'MODULE_NOT_FOUND')
35
- throw new Error(`Unknown outputMode "${outputMode}"`);
39
+ throw new Error(`Unknown outputMode "${options.outputMode}"`);
36
40
  throw error;
37
41
  }
38
42
  }
39
43
 
40
- const workerEvents = {
41
- fetchStart: 'onFetchingSlices',
42
- fetchEnd: 'onFetchedSlices',
43
- fetchError: 'onFetchSlicesFailed',
44
- submit: 'onSubmit',
45
- submitError: 'onSubmitError',
46
- payment: 'onPayment',
47
- }
48
- const supervisorEvents = {
49
- submittingResult: 'onSubmitStart',
50
- }
51
- const sandboxEvents = {
52
- start: 'sandbox$onSliceStart',
53
- sliceProgress: 'sandbox$onSliceProgress',
54
- sliceFinish: 'sandbox$onSliceFinish',
55
- terminated: 'sandbox$onWorkerStop',
56
- }
44
+ /**
45
+ * Start intercepting console.* methods so that log output from the worker goes to the appropriate log
46
+ * target; eg syslog, file, windows event log, etc. Unlike the telnet console log interceptor which is
47
+ * merely a passthrough shim, this is a "dead end" interceptor - we do not pass the log message through
48
+ * to the original console method. This implies, for example, that sending console messages to syslogd
49
+ * quiesces the tty output.
50
+ *
51
+ * @param {object} options - cliArgs from worker
52
+ */
53
+ exports.init = function startWorkerLogger$$init(options)
54
+ {
55
+ const logger = getLogger(options);
56
+
57
+ logger.init(options);
57
58
 
58
- Object.assign(exports, {
59
- /**
60
- * This method will attach event listeners from the provided
61
- * worker to a worker logger. The logger to use is
62
- * determined by getLogger based on the environment.
63
- *
64
- * @param {Worker} worker
65
- * @param {object} options
66
- * @param {number} options.verbose
67
- * @param {boolean} options.outputMode - which logger to use (default='detect')
59
+ /* The logger module's exports are its API. The following functions are supported, in this order
60
+ * of severity:
61
+ * . debug: debug-level message
62
+ * . info: informational message
63
+ * . log: normal, but significant, condition
64
+ * . warn: warning conditions
65
+ * . error: error conditions
66
+ *
67
+ * Additionally, generic functions may be used when one of the above is not defined:
68
+ * . at: write a log message at a specific log level; the level is the first argument
69
+ * . raw: same as at, but arguments are not formatted
70
+ * . any: write a log message without regard to log level
71
+ *
72
+ * All of these functions, with the exception of raw, receive only string arguments.
68
73
  */
69
- startWorkerLogger(worker, options={}) {
70
- const logger = getLogger(options);
71
- logger.init(worker, options);
72
74
 
73
- for (const [ev, handler] of Object.entries(workerEvents))
75
+ for (let level of ['debug', 'error', 'info', 'log', 'warn'])
76
+ {
77
+ if (logger[level])
78
+ console[level] = (...args) => logger[level]( ...format(...args));
79
+ else if (logger.at)
80
+ console[level] = (...args) => logger.at(level, ...format(...args));
81
+ else if (logger.raw)
82
+ console[level] = (...args) => logger.raw(level, ...args);
83
+ else if (logger.any)
84
+ console[level] = (...args) => logger.any(`${level}:`, format(...args));
85
+ else
86
+ {
87
+ require('./remote-console').reintercept();
88
+ throw new Error('logger module missing export for ' + level);
89
+ }
90
+ }
91
+
92
+ require('./remote-console').reintercept();
93
+ }
94
+
95
+ /**
96
+ * Format console.log arguments for use by a non-native logger, eg syslog. All non-string arguments are
97
+ * converted into the best human-readable strings we can muster.
98
+ */
99
+ function format(...argv)
100
+ {
101
+ for (let i in argv)
102
+ {
103
+ try
74
104
  {
75
- if (typeof logger[handler] === 'function')
76
- worker.on(ev, logger[handler].bind(logger));
105
+ if (typeof argv[i] === 'object' && argv[i] instanceof String)
106
+ argv[i] = String(argv[i]);
107
+ if (typeof argv[i] === 'object')
108
+ argv[i] = util.inspect(argv[i], exports.inspectOptions);
109
+ if (typeof argv[i] !== 'string')
110
+ argv[i] = String(argv[i]);
77
111
  }
78
- for (const [ev, handler] of Object.entries(supervisorEvents))
112
+ catch(e)
79
113
  {
80
- if (typeof logger[handler] === 'function')
81
- worker.addSupervisorEventListener(ev, logger[handler].bind(logger));
114
+ if (e instanceof TypeError)
115
+ argv[i] = '[encoding error: ' + e.message + ']';
82
116
  }
83
-
84
- worker.on('sandbox', (sandbox) => {
85
- /**
86
- * logger.onSandboxStart can return a data object that will be provided to
87
- * the other sandbox event handlers
88
- */
89
- const data = logger.onSandboxReady(sandbox) || {};
90
- for (const [ev, handler] of Object.entries(sandboxEvents))
91
- {
92
- if (typeof logger[handler] === 'function')
93
- sandbox.on(ev, logger[handler].bind(logger, sandbox, data));
94
- }
95
- });
96
117
  }
97
- });
118
+
119
+ return argv;
120
+ }
121
+
122
+ /**
123
+ * Options for util.inspect. Loggers which cannot deal with colours should force this false.
124
+ */
125
+ exports.inspectOptions = {
126
+ colors: process.stdout.hasColors() || process.env.FORCE_COLOR,
127
+ };
@@ -1,114 +1,30 @@
1
1
  /**
2
- * @file worker-loggers/console.js
3
- * @author Ryan Rossiter, ryan@kingsds.network
4
- * @date April 2020
5
- *
6
- * This worker logger uses console.log to produce
7
- * simple log output.
2
+ * @file worker-loggers/console.js
3
+ * Logger interface which just logs to the node console on stdout/stderr.
4
+ * @author Wes Garland, wes@distributive.network
5
+ * @date June 2023
8
6
  */
7
+ 'use strict';
9
8
 
10
- require('./common-types');
9
+ const process = require('process');
11
10
 
12
- /**
13
- * When this.enhancedDisplay is true
14
- * Sandbox 1: Slice Started: slice 1, 0x5b5214D48F0428669c4E: Simple Job
15
- * Sandbox 1: Slice Completed: slice 1, 0x5b5214D48F0428669c4E: Simple Job: dt 114ms
16
- * When this.enhancedDisplay is false
17
- * Sandbox 1: Slice Started: 0x5b5214D48F0428669c4E68779896D29D77c42903 Simple Job
18
- * Sandbox 1: Slice Completed: 0x5b5214D48F0428669c4E68779896D29D77c42903 Simple Job
19
- * @type {WorkerLogger}
20
- */
21
- const consoleLogger = {
22
- init(worker, options) {
23
- this.worker = worker;
24
- this.options = Object.assign({}, options);
25
- this.sliceMap = {}; // jobAddress --> ( sliceNumber, t0 )
26
- this.enhancedDisplay = true; // When false, no timing, no sliceNumber, full jobAddress
27
- this.truncationLength = 22; // Extra 2 for '0x'
28
- },
29
-
30
- id (sandbox, sliceNumber) {
31
- if (!this.enhancedDisplay)
32
- return sandbox.public ? `${sandbox.jobAddress} ${sandbox.public.name}` : `${sandbox.jobAddress}`;
33
-
34
- const address = sandbox.jobAddress ? sandbox.jobAddress.slice(0, this.truncationLength) : 'null';
35
- const baseInfo = sandbox.public ? `${address}: ${sandbox.public.name}` : `${address}:`;
36
-
37
- if (!sliceNumber)
38
- sliceNumber = sandbox.slice ? sandbox.slice.sliceNumber : 0;
39
- return sliceNumber ? `slice ${sliceNumber}, ${baseInfo}` : baseInfo;
40
- },
41
-
42
- onSandboxReady(sandbox) {
43
- const shortId = sandbox.id.toString(10).padStart(3);
11
+ exports.init = function console$$init(options)
12
+ {
13
+ const myConsole = new (require('console').Console)(process);
44
14
 
45
- const sandboxData = {
46
- shortId,
15
+ delete exports.init; // singleton
16
+ if (process.env.RAW_CONSOLE)
17
+ {
18
+ /* raw mode is used to debug node-inspect problems by dumping raw types directly to console.log */
19
+ exports.raw = function console$$raw(level, ...args) {
20
+ myConsole[level](...args);
47
21
  };
48
-
49
- console.log(` * Sandbox ${sandboxData.shortId}: Initialized`);
50
-
51
- return sandboxData;
52
- },
53
-
54
- sandbox$onSliceStart(sandbox, sandboxData, ev) {
55
- const sliceNumber = sandbox.slice ? sandbox.slice.sliceNumber : 0;
56
- this.sliceMap[sandbox.id] = { slice: sliceNumber, t0: Date.now() };
57
- console.log(` * Sandbox ${sandboxData.shortId}: Slice Started: ${this.id(sandbox)}`);
58
- },
59
-
60
- sandbox$onSliceProgress(sandbox, sandboxData, ev) {
61
- // something
62
- },
63
-
64
- sandbox$onSliceFinish(sandbox, sandboxData, ev) {
65
- const sliceInfo = this.sliceMap[sandbox.id];
66
- if (sliceInfo && this.enhancedDisplay)
67
- console.log(` * Sandbox ${sandboxData.shortId}: Slice Completed: ${this.id(sandbox, sliceInfo.slice)}: dt ${Date.now() - sliceInfo.t0}ms`);
68
- else
69
- console.log(` * Sandbox ${sandboxData.shortId}: Slice Completed: ${this.id(sandbox)}`);
70
- },
71
-
72
- sandbox$onWorkerStop(sandbox, sandboxData, ev) {
73
- const sliceInfo = this.sliceMap[sandbox.id];
74
- delete this.sliceMap[sandbox.id];
75
- console.log(` * Sandbox ${sandboxData.shortId}: Terminated: ${this.id(sandbox, sliceInfo?.slice)}`);
76
- },
77
-
78
- onPayment({ payment }) {
79
- try {
80
- payment = parseFloat(payment);
81
- } catch (e) {
82
- console.error(" ! Failed to parse payment:", payment);
83
- return;
84
- }
85
-
86
- if (payment > 0) console.log(` * DCC Credit: ${payment.toFixed(3)}`);
87
- },
88
-
89
- onFetchingSlices() {
90
- this.options.verbose && console.log(" * Fetching slices...");
91
- },
92
-
93
- onFetchedSlices(ev) {
94
- this.options.verbose && console.log(" * Fetched", ev);
95
- },
96
-
97
- onFetchSlicesFailed(ev) {
98
- console.log(" ! Failed to fetch slices:", ev);
99
- },
100
-
101
- onSubmitStart() {
102
- this.options.verbose >= 2 && console.log(" * Submitting results...");
103
- },
104
-
105
- onSubmit() {
106
- this.options.verbose >= 2 && console.log(" * Submitted");
107
- },
108
-
109
- onSubmitError(ev) {
110
- console.log(" ! Failed to submit results:", ev);
111
- },
112
- };
113
-
114
- Object.assign(exports, consoleLogger);
22
+ }
23
+ else
24
+ {
25
+ /* Log a single string to the console; conceptually very similar to other loggers */
26
+ exports.at = function console$$at(level, ...args) {
27
+ myConsole[level](args.join(' '));
28
+ };
29
+ }
30
+ }