forked from LiskArchive/lisk-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workers_controller.js
240 lines (220 loc) Β· 7.07 KB
/
workers_controller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*
* Copyright Β© 2018 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
'use strict';
var SCWorker = require('socketcluster/scworker');
var async = require('async');
var SlaveWAMPServer = require('wamp-socket-cluster/SlaveWAMPServer');
var Peer = require('./logic/peer');
var System = require('./modules/system');
var Handshake = require('./api/ws/workers/middlewares/handshake').middleware
.Handshake;
var extractHeaders = require('./api/ws/workers/middlewares/handshake')
.extractHeaders;
var emitMiddleware = require('./api/ws/workers/middlewares/emit');
var PeersUpdateRules = require('./api/ws/workers/peers_update_rules');
var Rules = require('./api/ws/workers/rules');
var failureCodes = require('./api/ws/rpc/failure_codes');
var Logger = require('./logger');
var config = require('./config.json');
/**
* Instantiate the SocketCluster SCWorker instance with custom logic
* inside the run function. The run function is invoked when the worker process
* is ready to accept requests/connections.
*/
SCWorker.create({
run() {
var self = this;
var scServer = this.getSCServer();
async.auto(
{
logger(cb) {
cb(
null,
new Logger({
echo: config.consoleLogLevel,
errorLevel: config.fileLogLevel,
filename: config.logFileName,
})
);
},
slaveWAMPServer: [
'logger',
function(scope, cb) {
new SlaveWAMPServer(self, 20e3, cb);
},
],
config: [
'slaveWAMPServer',
function(scope, cb) {
cb(null, scope.slaveWAMPServer.config);
},
],
peersUpdateRules: [
'slaveWAMPServer',
function(scope, cb) {
cb(null, new PeersUpdateRules(scope.slaveWAMPServer));
},
],
registerRPCSlaveEndpoints: [
'peersUpdateRules',
function(scope, cb) {
scope.slaveWAMPServer.reassignRPCSlaveEndpoints({
updateMyself: scope.peersUpdateRules.external.update,
});
cb();
},
],
system: [
'config',
function(scope, cb) {
new System(cb, { config: scope.config });
},
],
handshake: [
'system',
function(scope, cb) {
return cb(null, Handshake(scope.system, scope.config));
},
],
},
(err, scope) => {
scServer.addMiddleware(
scServer.MIDDLEWARE_HANDSHAKE_WS,
(req, next) => {
scope.handshake(extractHeaders(req), (err, peer) => {
if (err) {
// Set a custom property on the HTTP request object; we will check this property and handle
// this issue later.
// Because of WebSocket protocol handshake restrictions, we can't call next(err) here because the
// error will not be passed to the client. So we can attach the error to the request and disconnect later during the SC 'handshake' event.
req.failedHeadersValidationError = err;
// When ip is blacklisted, error is thrown as soon as possible.
if (err.code === failureCodes.BLACKLISTED_PEER) {
return next(err);
}
} else {
req.peerObject = peer.object();
}
// Pass through the WebSocket MIDDLEWARE_HANDSHAKE_WS successfully, but
// we will handle the req.failedQueryValidation error later inside scServer.on('handshake', handler);
next();
});
}
);
scServer.addMiddleware(scServer.MIDDLEWARE_EMIT, emitMiddleware);
scServer.on('handshake', socket => {
socket.on('message', message => {
scope.logger.trace(
`[Inbound socket :: message] Received message from ${
socket.request.remoteAddress
} - ${message}`
);
});
// We can access the HTTP request (which instantiated the WebSocket connection) using socket.request
// so we can access our custom socket.request.failedQueryValidation property here.
// If the property exists then we disconnect the connection.
if (socket.request.failedHeadersValidationError) {
var handshakeFailedCode =
socket.request.failedHeadersValidationError.code;
var handshakeFailedDesc =
socket.request.failedHeadersValidationError.description;
scope.logger.debug(
`[Inbound socket :: handshake] WebSocket handshake from ${
socket.request.remoteAddress
} failed with code ${handshakeFailedCode} - ${handshakeFailedDesc}`
);
return socket.disconnect(handshakeFailedCode, handshakeFailedDesc);
}
if (!socket.request.peerObject) {
var handshakeErrorCode = failureCodes.ON_MASTER.UPDATE.INVALID_PEER;
var handshakeErrorDesc =
'Could not find the peerObject property on the handshake request';
scope.logger.error(
`[Inbound socket :: handshake] WebSocket handshake from ${
socket.request.remoteAddress
} failed with code ${handshakeErrorCode} - ${handshakeErrorDesc}`
);
return socket.disconnect(handshakeErrorCode, handshakeErrorDesc);
}
scope.logger.trace(
`[Inbound socket :: handshake] WebSocket handshake from ${
socket.request.remoteAddress
} succeeded`
);
updatePeerConnection(
Rules.UPDATES.INSERT,
socket,
socket.request.peerObject,
onUpdateError => {
if (onUpdateError) {
socket.disconnect(
onUpdateError.code,
onUpdateError.description
);
}
}
);
});
scServer.on('connection', socket => {
scope.slaveWAMPServer.upgradeToWAMP(socket);
socket.on('disconnect', removePeerConnection.bind(null, socket));
});
function removePeerConnection(socket, code) {
scope.logger.trace(
`[Inbound socket :: disconnect] Peer socket from ${
socket.request.remoteAddress
} disconnected`
);
if (failureCodes.errorMessages[code]) {
return;
}
var headers = extractHeaders(socket.request);
updatePeerConnection(
Rules.UPDATES.REMOVE,
socket,
new Peer(headers).object(),
() => {}
);
}
function updatePeerConnection(updateType, socket, peer, cb) {
scope.peersUpdateRules.internal.update(
updateType,
peer,
socket.id,
onUpdateError => {
var actionName = Object.keys(Rules.UPDATES)[updateType];
if (onUpdateError) {
scope.logger.warn(
`Peer ${actionName} error: code: ${
onUpdateError.code
}, message: ${
failureCodes.errorMessages[onUpdateError.code]
}, description: ${onUpdateError.description} on peer ${
peer.ip
}:${peer.wsPort}`
);
} else {
scope.logger.info(
`${actionName} peer - ${peer.ip}:${peer.wsPort} success`
);
}
return setImmediate(cb, onUpdateError);
}
);
}
scope.logger.debug(`Worker pid ${process.pid} started`);
}
);
},
});