]>
Commit | Line | Data |
---|---|---|
9f10b292 C |
1 | 'use strict' |
2 | ||
1a42c9e2 C |
3 | const each = require('async/each') |
4 | const eachLimit = require('async/eachLimit') | |
1a42c9e2 | 5 | const waterfall = require('async/waterfall') |
67bf9b96 | 6 | const values = require('lodash/values') |
9f10b292 | 7 | |
f0f5567b C |
8 | const constants = require('../initializers/constants') |
9 | const logger = require('../helpers/logger') | |
f0f5567b | 10 | const requests = require('../helpers/requests') |
aaf61f38 | 11 | |
f0f5567b | 12 | let timer = null |
5abeec31 | 13 | let lastRequestTimestamp = 0 |
9f10b292 | 14 | |
00057e85 | 15 | // --------------------------------------------------------------------------- |
9f10b292 | 16 | |
feb4bdfd C |
17 | module.exports = function (sequelize, DataTypes) { |
18 | const Request = sequelize.define('Request', | |
19 | { | |
20 | request: { | |
67bf9b96 C |
21 | type: DataTypes.JSON, |
22 | allowNull: false | |
feb4bdfd C |
23 | }, |
24 | endpoint: { | |
67bf9b96 C |
25 | type: DataTypes.ENUM(values(constants.REQUEST_ENDPOINTS)), |
26 | allowNull: false | |
feb4bdfd C |
27 | } |
28 | }, | |
4b08096b | 29 | { |
feb4bdfd C |
30 | classMethods: { |
31 | associate, | |
32 | ||
33 | activate, | |
34 | countTotalRequests, | |
35 | deactivate, | |
36 | flush, | |
37 | forceSend, | |
38 | remainingMilliSeconds | |
39 | } | |
4b08096b | 40 | } |
feb4bdfd | 41 | ) |
528a9efa | 42 | |
feb4bdfd C |
43 | return Request |
44 | } | |
00057e85 C |
45 | |
46 | // ------------------------------ STATICS ------------------------------ | |
47 | ||
feb4bdfd C |
48 | function associate (models) { |
49 | this.belongsToMany(models.Pod, { | |
50 | foreignKey: { | |
51 | name: 'requestId', | |
52 | allowNull: false | |
53 | }, | |
54 | through: models.RequestToPod, | |
55 | onDelete: 'CASCADE' | |
56 | }) | |
57 | } | |
58 | ||
00057e85 C |
59 | function activate () { |
60 | logger.info('Requests scheduler activated.') | |
5abeec31 C |
61 | lastRequestTimestamp = Date.now() |
62 | ||
63 | const self = this | |
64 | timer = setInterval(function () { | |
65 | lastRequestTimestamp = Date.now() | |
66 | makeRequests.call(self) | |
67 | }, constants.REQUESTS_INTERVAL) | |
9f10b292 | 68 | } |
1fe5076f | 69 | |
feb4bdfd C |
70 | function countTotalRequests (callback) { |
71 | const query = { | |
72 | include: [ this.sequelize.models.Pod ] | |
73 | } | |
74 | ||
75 | return this.count(query).asCallback(callback) | |
76 | } | |
77 | ||
9f10b292 | 78 | function deactivate () { |
e3647ae2 | 79 | logger.info('Requests scheduler deactivated.') |
9f10b292 | 80 | clearInterval(timer) |
5abeec31 | 81 | timer = null |
9f10b292 | 82 | } |
1fe5076f | 83 | |
7920c273 | 84 | function flush (callback) { |
00057e85 C |
85 | removeAll.call(this, function (err) { |
86 | if (err) logger.error('Cannot flush the requests.', { error: err }) | |
7920c273 C |
87 | |
88 | return callback(err) | |
528a9efa C |
89 | }) |
90 | } | |
91 | ||
9f10b292 | 92 | function forceSend () { |
e3647ae2 | 93 | logger.info('Force requests scheduler sending.') |
00057e85 | 94 | makeRequests.call(this) |
9f10b292 | 95 | } |
c45f7f84 | 96 | |
5abeec31 C |
97 | function remainingMilliSeconds () { |
98 | if (timer === null) return -1 | |
99 | ||
100 | return constants.REQUESTS_INTERVAL - (Date.now() - lastRequestTimestamp) | |
101 | } | |
102 | ||
9f10b292 | 103 | // --------------------------------------------------------------------------- |
c45f7f84 | 104 | |
8c255eb5 | 105 | // Make a requests to friends of a certain type |
4b08096b | 106 | function makeRequest (toPod, requestEndpoint, requestsToMake, callback) { |
9f10b292 | 107 | if (!callback) callback = function () {} |
c45f7f84 | 108 | |
528a9efa C |
109 | const params = { |
110 | toPod: toPod, | |
38d78e5b | 111 | sign: true, // Prove our identity |
528a9efa | 112 | method: 'POST', |
4b08096b | 113 | path: '/api/' + constants.API_VERSION + '/remote/' + requestEndpoint, |
528a9efa C |
114 | data: requestsToMake // Requests we need to make |
115 | } | |
116 | ||
117 | // Make multiple retry requests to all of pods | |
118 | // The function fire some useful callbacks | |
119 | requests.makeSecureRequest(params, function (err, res) { | |
120 | if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) { | |
1e4b0080 C |
121 | err = err ? err.message : 'Status code not 20x : ' + res.statusCode |
122 | logger.error('Error sending secure request to %s pod.', toPod.host, { error: err }) | |
528a9efa C |
123 | |
124 | return callback(false) | |
9f10b292 | 125 | } |
c45f7f84 | 126 | |
528a9efa | 127 | return callback(true) |
9f10b292 C |
128 | }) |
129 | } | |
130 | ||
8c255eb5 | 131 | // Make all the requests of the scheduler |
e3647ae2 | 132 | function makeRequests () { |
00057e85 | 133 | const self = this |
feb4bdfd | 134 | const RequestToPod = this.sequelize.models.RequestToPod |
00057e85 | 135 | |
bd14d16a | 136 | // We limit the size of the requests |
43666d61 | 137 | // We don't want to stuck with the same failing requests so we get a random list |
bd14d16a | 138 | listWithLimitAndRandom.call(self, constants.REQUESTS_LIMIT_PODS, constants.REQUESTS_LIMIT_PER_POD, function (err, requests) { |
9f10b292 | 139 | if (err) { |
e3647ae2 | 140 | logger.error('Cannot get the list of requests.', { err: err }) |
9f10b292 C |
141 | return // Abort |
142 | } | |
143 | ||
8c255eb5 C |
144 | // If there are no requests, abort |
145 | if (requests.length === 0) { | |
146 | logger.info('No requests to make.') | |
147 | return | |
148 | } | |
9f10b292 | 149 | |
4b08096b | 150 | // We want to group requests by destinations pod and endpoint |
1e4b0080 | 151 | const requestsToMakeGrouped = buildRequestObjects(requests) |
8d6ae227 | 152 | |
edc5e860 | 153 | logger.info('Making requests to friends.') |
d8cc063e | 154 | |
528a9efa C |
155 | const goodPods = [] |
156 | const badPods = [] | |
157 | ||
4b08096b C |
158 | eachLimit(Object.keys(requestsToMakeGrouped), constants.REQUESTS_IN_PARALLEL, function (hashKey, callbackEach) { |
159 | const requestToMake = requestsToMakeGrouped[hashKey] | |
bd14d16a | 160 | const toPod = requestToMake.toPod |
528a9efa | 161 | |
bd14d16a C |
162 | // Maybe the pod is not our friend anymore so simply remove it |
163 | if (!toPod) { | |
164 | const requestIdsToDelete = requestToMake.ids | |
4b08096b | 165 | |
bd14d16a | 166 | logger.info('Removing %d requests of unexisting pod %s.', requestIdsToDelete.length, requestToMake.toPod.id) |
1e4b0080 | 167 | return RequestToPod.removePodOf(requestIdsToDelete, requestToMake.toPod.id, callbackEach) |
bd14d16a | 168 | } |
528a9efa | 169 | |
bd14d16a | 170 | makeRequest(toPod, requestToMake.endpoint, requestToMake.datas, function (success) { |
1e4b0080 | 171 | if (success === false) { |
bd14d16a | 172 | badPods.push(requestToMake.toPod.id) |
1e4b0080 | 173 | return callbackEach() |
bd14d16a | 174 | } |
1e4b0080 C |
175 | |
176 | logger.debug('Removing requests for pod %s.', requestToMake.toPod.id, { requestsIds: requestToMake.ids }) | |
177 | goodPods.push(requestToMake.toPod.id) | |
178 | ||
179 | // Remove the pod id of these request ids | |
180 | RequestToPod.removePodOf(requestToMake.ids, requestToMake.toPod.id, callbackEach) | |
528a9efa C |
181 | }) |
182 | }, function () { | |
183 | // All the requests were made, we update the pods score | |
feb4bdfd | 184 | updatePodsScore.call(self, goodPods, badPods) |
528a9efa | 185 | // Flush requests with no pod |
feb4bdfd C |
186 | removeWithEmptyTo.call(self, function (err) { |
187 | if (err) logger.error('Error when removing requests with no pods.', { error: err }) | |
188 | }) | |
528a9efa | 189 | }) |
9f10b292 C |
190 | }) |
191 | } | |
0b697522 | 192 | |
1e4b0080 C |
193 | function buildRequestObjects (requests) { |
194 | const requestsToMakeGrouped = {} | |
195 | ||
196 | Object.keys(requests).forEach(function (toPodId) { | |
197 | requests[toPodId].forEach(function (data) { | |
198 | const request = data.request | |
199 | const pod = data.pod | |
200 | const hashKey = toPodId + request.endpoint | |
201 | ||
202 | if (!requestsToMakeGrouped[hashKey]) { | |
203 | requestsToMakeGrouped[hashKey] = { | |
204 | toPod: pod, | |
205 | endpoint: request.endpoint, | |
206 | ids: [], // request ids, to delete them from the DB in the future | |
207 | datas: [] // requests data, | |
208 | } | |
209 | } | |
210 | ||
211 | requestsToMakeGrouped[hashKey].ids.push(request.id) | |
212 | requestsToMakeGrouped[hashKey].datas.push(request.request) | |
213 | }) | |
214 | }) | |
215 | ||
216 | return requestsToMakeGrouped | |
217 | } | |
218 | ||
8c255eb5 | 219 | // Remove pods with a score of 0 (too many requests where they were unreachable) |
9f10b292 | 220 | function removeBadPods () { |
feb4bdfd C |
221 | const self = this |
222 | ||
1a42c9e2 | 223 | waterfall([ |
e856e334 | 224 | function findBadPods (callback) { |
feb4bdfd | 225 | self.sequelize.models.Pod.listBadPods(function (err, pods) { |
e856e334 C |
226 | if (err) { |
227 | logger.error('Cannot find bad pods.', { error: err }) | |
228 | return callback(err) | |
229 | } | |
8d6ae227 | 230 | |
e856e334 C |
231 | return callback(null, pods) |
232 | }) | |
233 | }, | |
8d6ae227 | 234 | |
80a6c9e7 | 235 | function removeTheseBadPods (pods, callback) { |
1a42c9e2 | 236 | each(pods, function (pod, callbackEach) { |
feb4bdfd | 237 | pod.destroy().asCallback(callbackEach) |
a3ee6fa2 | 238 | }, function (err) { |
80a6c9e7 | 239 | return callback(err, pods.length) |
a3ee6fa2 | 240 | }) |
e856e334 | 241 | } |
a3ee6fa2 | 242 | ], function (err, numberOfPodsRemoved) { |
e856e334 C |
243 | if (err) { |
244 | logger.error('Cannot remove bad pods.', { error: err }) | |
a3ee6fa2 C |
245 | } else if (numberOfPodsRemoved) { |
246 | logger.info('Removed %d pods.', numberOfPodsRemoved) | |
e856e334 C |
247 | } else { |
248 | logger.info('No need to remove bad pods.') | |
249 | } | |
9f10b292 C |
250 | }) |
251 | } | |
0b697522 | 252 | |
bc503c2a | 253 | function updatePodsScore (goodPods, badPods) { |
feb4bdfd C |
254 | const self = this |
255 | const Pod = this.sequelize.models.Pod | |
256 | ||
bc503c2a | 257 | logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length) |
0b697522 | 258 | |
feb4bdfd C |
259 | if (goodPods.length !== 0) { |
260 | Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) { | |
67bf9b96 | 261 | if (err) logger.error('Cannot increment scores of good pods.', { error: err }) |
feb4bdfd C |
262 | }) |
263 | } | |
8425cb89 | 264 | |
feb4bdfd C |
265 | if (badPods.length !== 0) { |
266 | Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) { | |
67bf9b96 | 267 | if (err) logger.error('Cannot decrement scores of bad pods.', { error: err }) |
feb4bdfd C |
268 | removeBadPods.call(self) |
269 | }) | |
270 | } | |
9f10b292 | 271 | } |
00057e85 | 272 | |
bd14d16a | 273 | function listWithLimitAndRandom (limitPods, limitRequestsPerPod, callback) { |
43666d61 | 274 | const self = this |
bd14d16a | 275 | const Pod = this.sequelize.models.Pod |
43666d61 | 276 | |
bd14d16a | 277 | Pod.listRandomPodIdsWithRequest(limitPods, function (err, podIds) { |
43666d61 C |
278 | if (err) return callback(err) |
279 | ||
bd14d16a C |
280 | // We don't have friends that have requests |
281 | if (podIds.length === 0) return callback(null, []) | |
43666d61 | 282 | |
bd14d16a C |
283 | // The the first x requests of these pods |
284 | // It is very important to sort by id ASC to keep the requests order! | |
feb4bdfd C |
285 | const query = { |
286 | order: [ | |
287 | [ 'id', 'ASC' ] | |
288 | ], | |
bd14d16a C |
289 | include: [ |
290 | { | |
291 | model: self.sequelize.models.Pod, | |
292 | where: { | |
293 | id: { | |
294 | $in: podIds | |
295 | } | |
296 | } | |
297 | } | |
298 | ] | |
feb4bdfd C |
299 | } |
300 | ||
bd14d16a C |
301 | self.findAll(query).asCallback(function (err, requests) { |
302 | if (err) return callback(err) | |
303 | ||
304 | const requestsGrouped = groupAndTruncateRequests(requests, limitRequestsPerPod) | |
305 | return callback(err, requestsGrouped) | |
306 | }) | |
307 | }) | |
308 | } | |
309 | ||
310 | function groupAndTruncateRequests (requests, limitRequestsPerPod) { | |
311 | const requestsGrouped = {} | |
312 | ||
313 | requests.forEach(function (request) { | |
314 | request.Pods.forEach(function (pod) { | |
315 | if (!requestsGrouped[pod.id]) requestsGrouped[pod.id] = [] | |
316 | ||
317 | if (requestsGrouped[pod.id].length < limitRequestsPerPod) { | |
318 | requestsGrouped[pod.id].push({ | |
319 | request, | |
320 | pod | |
321 | }) | |
322 | } | |
323 | }) | |
43666d61 | 324 | }) |
bd14d16a C |
325 | |
326 | return requestsGrouped | |
00057e85 C |
327 | } |
328 | ||
329 | function removeAll (callback) { | |
feb4bdfd | 330 | // Delete all requests |
7920c273 | 331 | this.truncate({ cascade: true }).asCallback(callback) |
00057e85 C |
332 | } |
333 | ||
334 | function removeWithEmptyTo (callback) { | |
335 | if (!callback) callback = function () {} | |
336 | ||
feb4bdfd C |
337 | const query = { |
338 | where: { | |
339 | id: { | |
340 | $notIn: [ | |
341 | this.sequelize.literal('SELECT "requestId" FROM "RequestToPods"') | |
342 | ] | |
343 | } | |
344 | } | |
345 | } | |
346 | ||
347 | this.destroy(query).asCallback(callback) | |
00057e85 | 348 | } |