]>
Commit | Line | Data |
---|---|---|
9f10b292 C |
1 | 'use strict' |
2 | ||
1a42c9e2 C |
3 | const each = require('async/each') |
4 | const eachLimit = require('async/eachLimit') | |
4b08096b | 5 | const values = require('lodash/values') |
aaf61f38 | 6 | const mongoose = require('mongoose') |
1a42c9e2 | 7 | const waterfall = require('async/waterfall') |
9f10b292 | 8 | |
f0f5567b C |
9 | const constants = require('../initializers/constants') |
10 | const logger = require('../helpers/logger') | |
f0f5567b | 11 | const requests = require('../helpers/requests') |
aaf61f38 | 12 | |
a3ee6fa2 | 13 | const Pod = mongoose.model('Pod') |
9f10b292 | 14 | |
f0f5567b | 15 | let timer = null |
5abeec31 | 16 | let lastRequestTimestamp = 0 |
9f10b292 | 17 | |
00057e85 | 18 | // --------------------------------------------------------------------------- |
9f10b292 | 19 | |
00057e85 C |
20 | const RequestSchema = mongoose.Schema({ |
21 | request: mongoose.Schema.Types.Mixed, | |
4b08096b C |
22 | endpoint: { |
23 | type: String, | |
24 | enum: [ values(constants.REQUEST_ENDPOINTS) ] | |
25 | }, | |
26 | to: [ | |
27 | { | |
28 | type: mongoose.Schema.Types.ObjectId, | |
29 | ref: 'Pod' | |
30 | } | |
31 | ] | |
00057e85 | 32 | }) |
9f10b292 | 33 | |
00057e85 C |
34 | RequestSchema.statics = { |
35 | activate, | |
36 | deactivate, | |
37 | flush, | |
d3cd34be | 38 | forceSend, |
5abeec31 C |
39 | list, |
40 | remainingMilliSeconds | |
00057e85 | 41 | } |
9f10b292 | 42 | |
00057e85 C |
43 | RequestSchema.pre('save', function (next) { |
44 | const self = this | |
528a9efa | 45 | |
00057e85 | 46 | if (self.to.length === 0) { |
a3ee6fa2 | 47 | Pod.listAllIds(function (err, podIds) { |
00057e85 | 48 | if (err) return next(err) |
9f10b292 | 49 | |
00057e85 C |
50 | // No friends |
51 | if (podIds.length === 0) return | |
528a9efa | 52 | |
00057e85 C |
53 | self.to = podIds |
54 | return next() | |
528a9efa | 55 | }) |
00057e85 C |
56 | } else { |
57 | return next() | |
528a9efa | 58 | } |
00057e85 | 59 | }) |
528a9efa | 60 | |
00057e85 C |
61 | mongoose.model('Request', RequestSchema) |
62 | ||
63 | // ------------------------------ STATICS ------------------------------ | |
64 | ||
65 | function activate () { | |
66 | logger.info('Requests scheduler activated.') | |
5abeec31 C |
67 | lastRequestTimestamp = Date.now() |
68 | ||
69 | const self = this | |
70 | timer = setInterval(function () { | |
71 | lastRequestTimestamp = Date.now() | |
72 | makeRequests.call(self) | |
73 | }, constants.REQUESTS_INTERVAL) | |
9f10b292 | 74 | } |
1fe5076f | 75 | |
9f10b292 | 76 | function deactivate () { |
e3647ae2 | 77 | logger.info('Requests scheduler deactivated.') |
9f10b292 | 78 | clearInterval(timer) |
5abeec31 | 79 | timer = null |
9f10b292 | 80 | } |
1fe5076f | 81 | |
528a9efa | 82 | function flush () { |
00057e85 C |
83 | removeAll.call(this, function (err) { |
84 | if (err) logger.error('Cannot flush the requests.', { error: err }) | |
528a9efa C |
85 | }) |
86 | } | |
87 | ||
9f10b292 | 88 | function forceSend () { |
e3647ae2 | 89 | logger.info('Force requests scheduler sending.') |
00057e85 | 90 | makeRequests.call(this) |
9f10b292 | 91 | } |
c45f7f84 | 92 | |
d3cd34be C |
93 | function list (callback) { |
94 | this.find({ }, callback) | |
95 | } | |
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, | |
111 | encrypt: true, // Security | |
112 | sign: true, // To prove our identity | |
113 | method: 'POST', | |
4b08096b | 114 | path: '/api/' + constants.API_VERSION + '/remote/' + requestEndpoint, |
528a9efa C |
115 | data: requestsToMake // Requests we need to make |
116 | } | |
117 | ||
118 | // Make multiple retry requests to all of pods | |
119 | // The function fire some useful callbacks | |
120 | requests.makeSecureRequest(params, function (err, res) { | |
121 | if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) { | |
b9135905 C |
122 | logger.error( |
123 | 'Error sending secure request to %s pod.', | |
49abbbbe | 124 | toPod.host, |
b9135905 | 125 | { |
7c34bc64 | 126 | error: err || new Error('Status code not 20x : ' + res.statusCode) |
b9135905 C |
127 | } |
128 | ) | |
528a9efa C |
129 | |
130 | return callback(false) | |
9f10b292 | 131 | } |
c45f7f84 | 132 | |
528a9efa | 133 | return callback(true) |
9f10b292 C |
134 | }) |
135 | } | |
136 | ||
8c255eb5 | 137 | // Make all the requests of the scheduler |
e3647ae2 | 138 | function makeRequests () { |
00057e85 C |
139 | const self = this |
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 | |
3c8ee69f | 160 | requests.forEach(function (poolRequest) { |
528a9efa | 161 | poolRequest.to.forEach(function (toPodId) { |
4b08096b C |
162 | const hashKey = toPodId + poolRequest.endpoint |
163 | if (!requestsToMakeGrouped[hashKey]) { | |
164 | requestsToMakeGrouped[hashKey] = { | |
165 | toPodId, | |
166 | endpoint: poolRequest.endpoint, | |
167 | ids: [], // pool request ids, to delete them from the DB in the future | |
168 | datas: [] // requests data, | |
528a9efa C |
169 | } |
170 | } | |
171 | ||
4b08096b C |
172 | requestsToMakeGrouped[hashKey].ids.push(poolRequest._id) |
173 | requestsToMakeGrouped[hashKey].datas.push(poolRequest.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 C |
182 | |
183 | // FIXME: mongodb request inside a loop :/ | |
4b08096b | 184 | 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) | |
195 | 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) { |
4b08096b | 201 | logger.debug('Removing requests for %s pod.', 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 | |
4b08096b | 206 | removePodOf.call(self, 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 | |
215 | updatePodsScore(goodPods, badPods) | |
216 | // Flush requests with no pod | |
00057e85 | 217 | removeWithEmptyTo.call(self) |
528a9efa | 218 | }) |
9f10b292 C |
219 | }) |
220 | } | |
0b697522 | 221 | |
8c255eb5 | 222 | // Remove pods with a score of 0 (too many requests where they were unreachable) |
9f10b292 | 223 | function removeBadPods () { |
1a42c9e2 | 224 | waterfall([ |
e856e334 | 225 | function findBadPods (callback) { |
a3ee6fa2 | 226 | Pod.listBadPods(function (err, pods) { |
e856e334 C |
227 | if (err) { |
228 | logger.error('Cannot find bad pods.', { error: err }) | |
229 | return callback(err) | |
230 | } | |
8d6ae227 | 231 | |
e856e334 C |
232 | return callback(null, pods) |
233 | }) | |
234 | }, | |
8d6ae227 | 235 | |
80a6c9e7 C |
236 | function removeTheseBadPods (pods, callback) { |
237 | if (pods.length === 0) return callback(null, 0) | |
a3ee6fa2 | 238 | |
1a42c9e2 | 239 | each(pods, function (pod, callbackEach) { |
a3ee6fa2 C |
240 | pod.remove(callbackEach) |
241 | }, function (err) { | |
80a6c9e7 | 242 | return callback(err, pods.length) |
a3ee6fa2 | 243 | }) |
e856e334 | 244 | } |
a3ee6fa2 | 245 | ], function (err, numberOfPodsRemoved) { |
e856e334 C |
246 | if (err) { |
247 | logger.error('Cannot remove bad pods.', { error: err }) | |
a3ee6fa2 C |
248 | } else if (numberOfPodsRemoved) { |
249 | logger.info('Removed %d pods.', numberOfPodsRemoved) | |
e856e334 C |
250 | } else { |
251 | logger.info('No need to remove bad pods.') | |
252 | } | |
9f10b292 C |
253 | }) |
254 | } | |
0b697522 | 255 | |
bc503c2a C |
256 | function updatePodsScore (goodPods, badPods) { |
257 | logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length) | |
0b697522 | 258 | |
a3ee6fa2 | 259 | Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) { |
9f10b292 C |
260 | if (err) logger.error('Cannot increment scores of good pods.') |
261 | }) | |
8425cb89 | 262 | |
a3ee6fa2 | 263 | Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) { |
8c255eb5 | 264 | if (err) logger.error('Cannot decrement scores of bad pods.') |
9f10b292 C |
265 | removeBadPods() |
266 | }) | |
267 | } | |
00057e85 | 268 | |
43666d61 C |
269 | function listWithLimitAndRandom (limit, callback) { |
270 | const self = this | |
271 | ||
272 | self.count(function (err, count) { | |
273 | if (err) return callback(err) | |
274 | ||
275 | let start = Math.floor(Math.random() * count) - limit | |
276 | if (start < 0) start = 0 | |
277 | ||
4b08096b | 278 | self.find().sort({ _id: 1 }).skip(start).limit(limit).exec(callback) |
43666d61 | 279 | }) |
00057e85 C |
280 | } |
281 | ||
282 | function removeAll (callback) { | |
283 | this.remove({ }, callback) | |
284 | } | |
285 | ||
286 | function removePodOf (requestsIds, podId, callback) { | |
287 | if (!callback) callback = function () {} | |
288 | ||
289 | this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback) | |
290 | } | |
291 | ||
292 | function removeWithEmptyTo (callback) { | |
293 | if (!callback) callback = function () {} | |
294 | ||
295 | this.remove({ to: { $size: 0 } }, callback) | |
296 | } |