This repository has been archived by the owner on Oct 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
almanac-distributed.js
181 lines (166 loc) · 6.44 KB
/
almanac-distributed.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
"use strict";
/*
Virtualization Layer | Distributed request module
by Alexandre Alapetite http://alexandre.alapetite.fr
from Alexandra Institute http://www.alexandra.dk
for the ALMANAC European project http://www.almanac-project.eu
*/
module.exports = function (almanac) {
var peerTimeout = 10 * 60 * 1000; //In milliseconds
var distributedInstances = {};
var extend = require('extend');
function servedistributedInstances(req, res) {
var me = {};
me[almanac.config.hosts.instanceName] = {
self: true,
date: Date.now(),
info: almanac.info(),
};
almanac.basicHttp.serveJson(req, res, extend(true, {}, distributedInstances, me));
}
function deleteExpiredPeers() {
var expireDate = Date.now() - peerTimeout;
var instanceNames = Object.keys(distributedInstances);
for (var i = instanceNames.length - 1; i >= 0; i--) {
var instanceName = instanceNames[i];
var instance = distributedInstances[instanceName];
if (instance.date < expireDate) {
almanac.log.info('VL', 'Distributed peer expired "' + instanceName + '": ' + JSON.stringify(distributedInstances[instanceName]));
delete distributedInstances[instanceName];
}
}
}
setInterval(deleteExpiredPeers, 60000);
almanac.updateInstance = function (info) {
if (info && info.instanceName) {
var wasKnown = distributedInstances[info.instanceName];
distributedInstances[info.instanceName] = {
date: Date.now(),
info: info,
};
if (!wasKnown) {
almanac.log.info('VL', 'Distributed peer discovered "' + info.instanceName + '": ' + JSON.stringify(distributedInstances[info.instanceName]));
}
}
};
var currentResponses = {};
var lastReqIds = {};
function endDistributedResponse(reqId) {
var currentResponse = currentResponses[reqId];
delete currentResponses[reqId];
if (currentResponse && currentResponse.res && currentResponse.res.end) {
if (currentResponse.mergeType === 'M') {
currentResponse.res.end("]}\n");
} else {
currentResponse.res.end("}}\n");
}
setTimeout(function() {
delete lastReqIds[reqId];
almanac.log.verbose('VL', 'lastReqIds size: ' + Object.keys(lastReqIds).length);
}, 60000);
}
}
function processDistributedRequest(req, res, mergeType) {
//TODO: Check that it comes from an authorised peer
if (req.method !== 'GET') {
almanac.basicHttp.serve405(req, res, 'GET');
} else if (!almanac.mqttClient || !almanac.mqttClient.connected || !almanac.mqttClient.broadcastDistributedRequest) {
almanac.basicHttp.serve503(req, res);
} else {
var reqId = Date.now() + '_' + Math.random();
currentResponses[reqId] = {
already: {},
mergeType: mergeType || 'S',
res: res,
};
try {
res.writeHead(200, {
'Content-Type': 'application/json; charset=UTF-8',
'Date': (new Date()).toUTCString(),
'Server': almanac.basicHttp.serverSignature,
});
if (mergeType === 'M') {
res.write('{"Thing":[');
} else {
res.write('{"instances":{');
}
almanac.mqttClient.broadcastDistributedRequest({
reqId: reqId,
//method: req.method, //Always GET
uri: req.url,
});
setTimeout(function() {
almanac.log.verbose('VL', 'processDistributedRequest: timeout without all ' + (1 + Object.keys(distributedInstances).length) + ' responses');
endDistributedResponse(reqId);
}, 30000);
} catch (ex) {
almanac.log.warn('VL', 'Error while processing distributed request: ' + ex);
}
}
}
almanac.processDistributedResponse = function (json) {
if (!(json && json.payload && json.payload.reqId && json.payload.body && json.info && json.info.instanceName)) {
return;
}
try {
var currentResponse = currentResponses[json.payload.reqId];
if (currentResponse && currentResponse.res && currentResponse.res.write) {
if (currentResponse.already[json.info.instanceName]) {
//Check to avoid processing two times the same response
almanac.log.verbose('VL', 'Distributed response already received for: ' + json.info.instanceName);
return;
}
currentResponse.already[json.info.instanceName] = true;
var alreadyNb = Object.keys(currentResponse.already).length;
if (currentResponse.mergeType === 'M') {
currentResponse.res.write(
(alreadyNb > 1 ? ',' : '' ) +
JSON.stringify(json.payload.body.Thing).slice(1, -1));
} else {
currentResponse.res.write(
(alreadyNb > 1 ? ',' : '' ) +
'"' + json.info.instanceName + '":' + JSON.stringify(json.payload));
}
if (alreadyNb >= 1 + Object.keys(distributedInstances).length) {
almanac.log.verbose('VL', 'processDistributedResponse: received all responses');
endDistributedResponse(json.payload.reqId);
}
} else {
almanac.log.warn('VL', 'No current response with ID: ' + json.payload.reqId);
}
} catch (ex) {
almanac.log.warn('VL', 'Error while processing distributed response: ' + ex);
}
};
almanac.replyToDistributedRequest = function (json) {
if (!(almanac.mqttClient && almanac.mqttClient.connected && almanac.mqttClient.broadcastDistributedResponse && json.payload && json.payload.reqId)) {
return;
}
if (lastReqIds[json.payload.reqId]) {
//Do not respond 2 times to the same request
almanac.log.verbose('VL', 'Distributed request already answered: ' + json.payload.reqId);
return;
}
lastReqIds[json.payload.reqId] = true;
almanac.defaultRequest.get({
url: almanac.config.hosts.virtualizationLayer.scheme + '://' + almanac.config.hosts.virtualizationLayer.host + ':' + almanac.config.hosts.virtualizationLayer.port + '/' + json.payload.uri,
json: true,
timeout: 10000,
}, function (error, response, body) {
if (error || response.statusCode != 200 || !(body)) {
almanac.log.warn('VL', 'Error ' + (response ? response.statusCode : 'undefined') + ' performing local request for distributed query! ' + json.payload.uri);
}
//TODO: Send the response only to the original requester instead of broadcast
almanac.mqttClient.broadcastDistributedResponse({
reqId: json.payload.reqId,
statusCode: response.statusCode,
error: error,
body: body,
});
});
};
almanac.routes['distributed/'] = function (req, res) { processDistributedRequest(req, res, 'S'); };
almanac.routes['distributed-split/'] = function (req, res) { processDistributedRequest(req, res, 'S'); };
almanac.routes['distributed-merge/'] = function (req, res) { processDistributedRequest(req, res, 'M'); };
almanac.routes['distributedInstances'] = servedistributedInstances;
};