]>
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)) { | |
b9135905 C |
121 | logger.error( |
122 | 'Error sending secure request to %s pod.', | |
49abbbbe | 123 | toPod.host, |
b9135905 | 124 | { |
7c34bc64 | 125 | error: err || new Error('Status code not 20x : ' + res.statusCode) |
b9135905 C |
126 | } |
127 | ) | |
528a9efa C |
128 | |
129 | return callback(false) | |
9f10b292 | 130 | } |
c45f7f84 | 131 | |
528a9efa | 132 | return callback(true) |
9f10b292 C |
133 | }) |
134 | } | |
135 | ||
8c255eb5 | 136 | // Make all the requests of the scheduler |
e3647ae2 | 137 | function makeRequests () { |
00057e85 | 138 | const self = this |
feb4bdfd | 139 | const RequestToPod = this.sequelize.models.RequestToPod |
00057e85 | 140 | |
43666d61 C |
141 | // We limit the size of the requests (REQUESTS_LIMIT) |
142 | // We don't want to stuck with the same failing requests so we get a random list | |
143 | listWithLimitAndRandom.call(self, constants.REQUESTS_LIMIT, function (err, requests) { | |
9f10b292 | 144 | if (err) { |
e3647ae2 | 145 | logger.error('Cannot get the list of requests.', { err: err }) |
9f10b292 C |
146 | return // Abort |
147 | } | |
148 | ||
8c255eb5 C |
149 | // If there are no requests, abort |
150 | if (requests.length === 0) { | |
151 | logger.info('No requests to make.') | |
152 | return | |
153 | } | |
9f10b292 | 154 | |
8c255eb5 C |
155 | logger.info('Making requests to friends.') |
156 | ||
4b08096b C |
157 | // We want to group requests by destinations pod and endpoint |
158 | const requestsToMakeGrouped = {} | |
9f10b292 | 159 | |
feb4bdfd C |
160 | requests.forEach(function (request) { |
161 | request.Pods.forEach(function (toPod) { | |
162 | const hashKey = toPod.id + request.endpoint | |
4b08096b C |
163 | if (!requestsToMakeGrouped[hashKey]) { |
164 | requestsToMakeGrouped[hashKey] = { | |
feb4bdfd C |
165 | toPodId: toPod.id, |
166 | endpoint: request.endpoint, | |
167 | ids: [], // request ids, to delete them from the DB in the future | |
4b08096b | 168 | datas: [] // requests data, |
528a9efa C |
169 | } |
170 | } | |
171 | ||
feb4bdfd C |
172 | requestsToMakeGrouped[hashKey].ids.push(request.id) |
173 | requestsToMakeGrouped[hashKey].datas.push(request.request) | |
528a9efa | 174 | }) |
3c8ee69f | 175 | }) |
8d6ae227 | 176 | |
528a9efa C |
177 | const goodPods = [] |
178 | const badPods = [] | |
179 | ||
4b08096b C |
180 | eachLimit(Object.keys(requestsToMakeGrouped), constants.REQUESTS_IN_PARALLEL, function (hashKey, callbackEach) { |
181 | const requestToMake = requestsToMakeGrouped[hashKey] | |
528a9efa | 182 | |
feb4bdfd C |
183 | // FIXME: SQL request inside a loop :/ |
184 | self.sequelize.models.Pod.load(requestToMake.toPodId, function (err, toPod) { | |
00057e85 C |
185 | if (err) { |
186 | logger.error('Error finding pod by id.', { err: err }) | |
187 | return callbackEach() | |
188 | } | |
528a9efa | 189 | |
5abeec31 | 190 | // Maybe the pod is not our friend anymore so simply remove it |
528a9efa | 191 | if (!toPod) { |
4b08096b C |
192 | const requestIdsToDelete = requestToMake.ids |
193 | ||
194 | logger.info('Removing %d requests of unexisting pod %s.', requestIdsToDelete.length, requestToMake.toPodId) | |
feb4bdfd | 195 | RequestToPod.removePodOf.call(self, requestIdsToDelete, requestToMake.toPodId) |
528a9efa C |
196 | return callbackEach() |
197 | } | |
198 | ||
4b08096b | 199 | makeRequest(toPod, requestToMake.endpoint, requestToMake.datas, function (success) { |
528a9efa | 200 | if (success === true) { |
67bf9b96 | 201 | logger.debug('Removing requests for pod %s.', requestToMake.toPodId, { requestsIds: requestToMake.ids }) |
3c8ee69f | 202 | |
4b08096b | 203 | goodPods.push(requestToMake.toPodId) |
c2ee5ce8 C |
204 | |
205 | // Remove the pod id of these request ids | |
feb4bdfd | 206 | RequestToPod.removePodOf(requestToMake.ids, requestToMake.toPodId, callbackEach) |
528a9efa | 207 | } else { |
4b08096b | 208 | badPods.push(requestToMake.toPodId) |
c2ee5ce8 | 209 | callbackEach() |
528a9efa | 210 | } |
3c8ee69f | 211 | }) |
528a9efa C |
212 | }) |
213 | }, function () { | |
214 | // All the requests were made, we update the pods score | |
feb4bdfd | 215 | updatePodsScore.call(self, goodPods, badPods) |
528a9efa | 216 | // Flush requests with no pod |
feb4bdfd C |
217 | removeWithEmptyTo.call(self, function (err) { |
218 | if (err) logger.error('Error when removing requests with no pods.', { error: err }) | |
219 | }) | |
528a9efa | 220 | }) |
9f10b292 C |
221 | }) |
222 | } | |
0b697522 | 223 | |
8c255eb5 | 224 | // Remove pods with a score of 0 (too many requests where they were unreachable) |
9f10b292 | 225 | function removeBadPods () { |
feb4bdfd C |
226 | const self = this |
227 | ||
1a42c9e2 | 228 | waterfall([ |
e856e334 | 229 | function findBadPods (callback) { |
feb4bdfd | 230 | self.sequelize.models.Pod.listBadPods(function (err, pods) { |
e856e334 C |
231 | if (err) { |
232 | logger.error('Cannot find bad pods.', { error: err }) | |
233 | return callback(err) | |
234 | } | |
8d6ae227 | 235 | |
e856e334 C |
236 | return callback(null, pods) |
237 | }) | |
238 | }, | |
8d6ae227 | 239 | |
80a6c9e7 | 240 | function removeTheseBadPods (pods, callback) { |
1a42c9e2 | 241 | each(pods, function (pod, callbackEach) { |
feb4bdfd | 242 | pod.destroy().asCallback(callbackEach) |
a3ee6fa2 | 243 | }, function (err) { |
80a6c9e7 | 244 | return callback(err, pods.length) |
a3ee6fa2 | 245 | }) |
e856e334 | 246 | } |
a3ee6fa2 | 247 | ], function (err, numberOfPodsRemoved) { |
e856e334 C |
248 | if (err) { |
249 | logger.error('Cannot remove bad pods.', { error: err }) | |
a3ee6fa2 C |
250 | } else if (numberOfPodsRemoved) { |
251 | logger.info('Removed %d pods.', numberOfPodsRemoved) | |
e856e334 C |
252 | } else { |
253 | logger.info('No need to remove bad pods.') | |
254 | } | |
9f10b292 C |
255 | }) |
256 | } | |
0b697522 | 257 | |
bc503c2a | 258 | function updatePodsScore (goodPods, badPods) { |
feb4bdfd C |
259 | const self = this |
260 | const Pod = this.sequelize.models.Pod | |
261 | ||
bc503c2a | 262 | logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length) |
0b697522 | 263 | |
feb4bdfd C |
264 | if (goodPods.length !== 0) { |
265 | Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) { | |
67bf9b96 | 266 | if (err) logger.error('Cannot increment scores of good pods.', { error: err }) |
feb4bdfd C |
267 | }) |
268 | } | |
8425cb89 | 269 | |
feb4bdfd C |
270 | if (badPods.length !== 0) { |
271 | Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) { | |
67bf9b96 | 272 | if (err) logger.error('Cannot decrement scores of bad pods.', { error: err }) |
feb4bdfd C |
273 | removeBadPods.call(self) |
274 | }) | |
275 | } | |
9f10b292 | 276 | } |
00057e85 | 277 | |
43666d61 C |
278 | function listWithLimitAndRandom (limit, callback) { |
279 | const self = this | |
280 | ||
feb4bdfd | 281 | self.count().asCallback(function (err, count) { |
43666d61 C |
282 | if (err) return callback(err) |
283 | ||
feb4bdfd C |
284 | // Optimization... |
285 | if (count === 0) return callback(null, []) | |
286 | ||
43666d61 C |
287 | let start = Math.floor(Math.random() * count) - limit |
288 | if (start < 0) start = 0 | |
289 | ||
feb4bdfd C |
290 | const query = { |
291 | order: [ | |
292 | [ 'id', 'ASC' ] | |
293 | ], | |
294 | offset: start, | |
295 | limit: limit, | |
296 | include: [ this.sequelize.models.Pod ] | |
297 | } | |
298 | ||
299 | self.findAll(query).asCallback(callback) | |
43666d61 | 300 | }) |
00057e85 C |
301 | } |
302 | ||
303 | function removeAll (callback) { | |
feb4bdfd | 304 | // Delete all requests |
7920c273 | 305 | this.truncate({ cascade: true }).asCallback(callback) |
00057e85 C |
306 | } |
307 | ||
308 | function removeWithEmptyTo (callback) { | |
309 | if (!callback) callback = function () {} | |
310 | ||
feb4bdfd C |
311 | const query = { |
312 | where: { | |
313 | id: { | |
314 | $notIn: [ | |
315 | this.sequelize.literal('SELECT "requestId" FROM "RequestToPods"') | |
316 | ] | |
317 | } | |
318 | } | |
319 | } | |
320 | ||
321 | this.destroy(query).asCallback(callback) | |
00057e85 | 322 | } |