]>
Commit | Line | Data |
---|---|---|
1 | 'use strict' | |
2 | ||
3 | const each = require('async/each') | |
4 | const eachLimit = require('async/eachLimit') | |
5 | const map = require('lodash/map') | |
6 | const mongoose = require('mongoose') | |
7 | const waterfall = require('async/waterfall') | |
8 | ||
9 | const constants = require('../initializers/constants') | |
10 | const logger = require('../helpers/logger') | |
11 | const requests = require('../helpers/requests') | |
12 | ||
13 | const Pod = mongoose.model('Pod') | |
14 | const Video = mongoose.model('Video') | |
15 | ||
16 | let timer = null | |
17 | ||
18 | // --------------------------------------------------------------------------- | |
19 | ||
20 | const RequestSchema = mongoose.Schema({ | |
21 | request: mongoose.Schema.Types.Mixed, | |
22 | to: [ { type: mongoose.Schema.Types.ObjectId, ref: 'users' } ] | |
23 | }) | |
24 | ||
25 | RequestSchema.statics = { | |
26 | activate, | |
27 | deactivate, | |
28 | flush, | |
29 | forceSend | |
30 | } | |
31 | ||
32 | RequestSchema.pre('save', function (next) { | |
33 | const self = this | |
34 | ||
35 | if (self.to.length === 0) { | |
36 | Pod.listAllIds(function (err, podIds) { | |
37 | if (err) return next(err) | |
38 | ||
39 | // No friends | |
40 | if (podIds.length === 0) return | |
41 | ||
42 | self.to = podIds | |
43 | return next() | |
44 | }) | |
45 | } else { | |
46 | return next() | |
47 | } | |
48 | }) | |
49 | ||
50 | mongoose.model('Request', RequestSchema) | |
51 | ||
52 | // ------------------------------ STATICS ------------------------------ | |
53 | ||
54 | function activate () { | |
55 | logger.info('Requests scheduler activated.') | |
56 | timer = setInterval(makeRequests.bind(this), constants.INTERVAL) | |
57 | } | |
58 | ||
59 | function deactivate () { | |
60 | logger.info('Requests scheduler deactivated.') | |
61 | clearInterval(timer) | |
62 | } | |
63 | ||
64 | function flush () { | |
65 | removeAll.call(this, function (err) { | |
66 | if (err) logger.error('Cannot flush the requests.', { error: err }) | |
67 | }) | |
68 | } | |
69 | ||
70 | function forceSend () { | |
71 | logger.info('Force requests scheduler sending.') | |
72 | makeRequests.call(this) | |
73 | } | |
74 | ||
75 | // --------------------------------------------------------------------------- | |
76 | ||
77 | // Make a requests to friends of a certain type | |
78 | function makeRequest (toPod, requestsToMake, callback) { | |
79 | if (!callback) callback = function () {} | |
80 | ||
81 | const params = { | |
82 | toPod: toPod, | |
83 | encrypt: true, // Security | |
84 | sign: true, // To prove our identity | |
85 | method: 'POST', | |
86 | path: '/api/' + constants.API_VERSION + '/remote/videos', | |
87 | data: requestsToMake // Requests we need to make | |
88 | } | |
89 | ||
90 | // Make multiple retry requests to all of pods | |
91 | // The function fire some useful callbacks | |
92 | requests.makeSecureRequest(params, function (err, res) { | |
93 | if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) { | |
94 | logger.error('Error sending secure request to %s pod.', toPod.url, { error: err || new Error('Status code not 20x') }) | |
95 | ||
96 | return callback(false) | |
97 | } | |
98 | ||
99 | return callback(true) | |
100 | }) | |
101 | } | |
102 | ||
103 | // Make all the requests of the scheduler | |
104 | function makeRequests () { | |
105 | const self = this | |
106 | ||
107 | listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) { | |
108 | if (err) { | |
109 | logger.error('Cannot get the list of requests.', { err: err }) | |
110 | return // Abort | |
111 | } | |
112 | ||
113 | // If there are no requests, abort | |
114 | if (requests.length === 0) { | |
115 | logger.info('No requests to make.') | |
116 | return | |
117 | } | |
118 | ||
119 | logger.info('Making requests to friends.') | |
120 | ||
121 | // Requests by pods id | |
122 | const requestsToMake = {} | |
123 | ||
124 | requests.forEach(function (poolRequest) { | |
125 | poolRequest.to.forEach(function (toPodId) { | |
126 | if (!requestsToMake[toPodId]) { | |
127 | requestsToMake[toPodId] = { | |
128 | ids: [], | |
129 | datas: [] | |
130 | } | |
131 | } | |
132 | ||
133 | requestsToMake[toPodId].ids.push(poolRequest._id) | |
134 | requestsToMake[toPodId].datas.push(poolRequest.request) | |
135 | }) | |
136 | }) | |
137 | ||
138 | const goodPods = [] | |
139 | const badPods = [] | |
140 | ||
141 | eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) { | |
142 | const requestToMake = requestsToMake[toPodId] | |
143 | ||
144 | // FIXME: mongodb request inside a loop :/ | |
145 | Pod.load(toPodId, function (err, toPod) { | |
146 | if (err) { | |
147 | logger.error('Error finding pod by id.', { err: err }) | |
148 | return callbackEach() | |
149 | } | |
150 | ||
151 | // Maybe the pod is not our friend anymore so simply remove them | |
152 | if (!toPod) { | |
153 | removePodOf.call(self, requestToMake.ids, toPodId) | |
154 | return callbackEach() | |
155 | } | |
156 | ||
157 | makeRequest(toPod, requestToMake.datas, function (success) { | |
158 | if (err) { | |
159 | logger.error('Errors when sent request to %s.', toPod.url, { error: err }) | |
160 | // Do not stop the process just for one error | |
161 | return callbackEach() | |
162 | } | |
163 | ||
164 | if (success === true) { | |
165 | logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids }) | |
166 | ||
167 | // Remove the pod id of these request ids | |
168 | removePodOf.call(self, requestToMake.ids, toPodId) | |
169 | goodPods.push(toPodId) | |
170 | } else { | |
171 | badPods.push(toPodId) | |
172 | } | |
173 | ||
174 | callbackEach() | |
175 | }) | |
176 | }) | |
177 | }, function () { | |
178 | // All the requests were made, we update the pods score | |
179 | updatePodsScore(goodPods, badPods) | |
180 | // Flush requests with no pod | |
181 | removeWithEmptyTo.call(self) | |
182 | }) | |
183 | }) | |
184 | } | |
185 | ||
186 | // Remove pods with a score of 0 (too many requests where they were unreachable) | |
187 | function removeBadPods () { | |
188 | waterfall([ | |
189 | function findBadPods (callback) { | |
190 | Pod.listBadPods(function (err, pods) { | |
191 | if (err) { | |
192 | logger.error('Cannot find bad pods.', { error: err }) | |
193 | return callback(err) | |
194 | } | |
195 | ||
196 | return callback(null, pods) | |
197 | }) | |
198 | }, | |
199 | ||
200 | function listVideosOfTheseBadPods (pods, callback) { | |
201 | if (pods.length === 0) return callback(null) | |
202 | ||
203 | const urls = map(pods, 'url') | |
204 | ||
205 | Video.listByUrls(urls, function (err, videosList) { | |
206 | if (err) { | |
207 | logger.error('Cannot list videos urls.', { error: err, urls: urls }) | |
208 | return callback(null, pods, []) | |
209 | } | |
210 | ||
211 | return callback(null, pods, videosList) | |
212 | }) | |
213 | }, | |
214 | ||
215 | function removeVideosOfTheseBadPods (pods, videosList, callback) { | |
216 | // We don't have to remove pods, skip | |
217 | if (typeof pods === 'function') { | |
218 | callback = pods | |
219 | return callback(null) | |
220 | } | |
221 | ||
222 | each(videosList, function (video, callbackEach) { | |
223 | video.remove(callbackEach) | |
224 | }, function (err) { | |
225 | if (err) { | |
226 | // Don't stop the process | |
227 | logger.error('Error while removing videos of bad pods.', { error: err }) | |
228 | return | |
229 | } | |
230 | ||
231 | return callback(null, pods) | |
232 | }) | |
233 | }, | |
234 | ||
235 | function removeBadPodsFromDB (pods, callback) { | |
236 | // We don't have to remove pods, skip | |
237 | if (typeof pods === 'function') { | |
238 | callback = pods | |
239 | return callback(null) | |
240 | } | |
241 | ||
242 | each(pods, function (pod, callbackEach) { | |
243 | pod.remove(callbackEach) | |
244 | }, function (err) { | |
245 | if (err) return callback(err) | |
246 | ||
247 | return callback(null, pods.length) | |
248 | }) | |
249 | } | |
250 | ], function (err, numberOfPodsRemoved) { | |
251 | if (err) { | |
252 | logger.error('Cannot remove bad pods.', { error: err }) | |
253 | } else if (numberOfPodsRemoved) { | |
254 | logger.info('Removed %d pods.', numberOfPodsRemoved) | |
255 | } else { | |
256 | logger.info('No need to remove bad pods.') | |
257 | } | |
258 | }) | |
259 | } | |
260 | ||
261 | function updatePodsScore (goodPods, badPods) { | |
262 | logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length) | |
263 | ||
264 | Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) { | |
265 | if (err) logger.error('Cannot increment scores of good pods.') | |
266 | }) | |
267 | ||
268 | Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) { | |
269 | if (err) logger.error('Cannot decrement scores of bad pods.') | |
270 | removeBadPods() | |
271 | }) | |
272 | } | |
273 | ||
274 | function listWithLimit (limit, callback) { | |
275 | this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit).exec(callback) | |
276 | } | |
277 | ||
278 | function removeAll (callback) { | |
279 | this.remove({ }, callback) | |
280 | } | |
281 | ||
282 | function removePodOf (requestsIds, podId, callback) { | |
283 | if (!callback) callback = function () {} | |
284 | ||
285 | this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback) | |
286 | } | |
287 | ||
288 | function removeWithEmptyTo (callback) { | |
289 | if (!callback) callback = function () {} | |
290 | ||
291 | this.remove({ to: { $size: 0 } }, callback) | |
292 | } |