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')
9 const constants = require('../initializers/constants')
10 const logger = require('../helpers/logger')
11 const requests = require('../helpers/requests')
13 const Pod = mongoose.model('Pod')
14 const Video = mongoose.model('Video')
18 // ---------------------------------------------------------------------------
20 const RequestSchema = mongoose.Schema({
21 request: mongoose.Schema.Types.Mixed,
22 to: [ { type: mongoose.Schema.Types.ObjectId, ref: 'users' } ]
25 RequestSchema.statics = {
32 RequestSchema.pre('save', function (next) {
35 if (self.to.length === 0) {
36 Pod.listAllIds(function (err, podIds) {
37 if (err) return next(err)
40 if (podIds.length === 0) return
50 mongoose.model('Request', RequestSchema)
52 // ------------------------------ STATICS ------------------------------
54 function activate () {
55 logger.info('Requests scheduler activated.')
56 timer = setInterval(makeRequests.bind(this), constants.INTERVAL)
59 function deactivate () {
60 logger.info('Requests scheduler deactivated.')
65 removeAll.call(this, function (err) {
66 if (err) logger.error('Cannot flush the requests.', { error: err })
70 function forceSend () {
71 logger.info('Force requests scheduler sending.')
72 makeRequests.call(this)
75 // ---------------------------------------------------------------------------
77 // Make a requests to friends of a certain type
78 function makeRequest (toPod, requestsToMake, callback) {
79 if (!callback) callback = function () {}
83 encrypt: true, // Security
84 sign: true, // To prove our identity
86 path: '/api/' + constants.API_VERSION + '/remote/videos',
87 data: requestsToMake // Requests we need to make
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') })
96 return callback(false)
103 // Make all the requests of the scheduler
104 function makeRequests () {
107 listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
109 logger.error('Cannot get the list of requests.', { err: err })
113 // If there are no requests, abort
114 if (requests.length === 0) {
115 logger.info('No requests to make.')
119 logger.info('Making requests to friends.')
121 // Requests by pods id
122 const requestsToMake = {}
124 requests.forEach(function (poolRequest) {
125 poolRequest.to.forEach(function (toPodId) {
126 if (!requestsToMake[toPodId]) {
127 requestsToMake[toPodId] = {
133 requestsToMake[toPodId].ids.push(poolRequest._id)
134 requestsToMake[toPodId].datas.push(poolRequest.request)
141 eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
142 const requestToMake = requestsToMake[toPodId]
144 // FIXME: mongodb request inside a loop :/
145 Pod.load(toPodId, function (err, toPod) {
147 logger.error('Error finding pod by id.', { err: err })
148 return callbackEach()
151 // Maybe the pod is not our friend anymore so simply remove them
153 removePodOf.call(self, requestToMake.ids, toPodId)
154 return callbackEach()
157 makeRequest(toPod, requestToMake.datas, function (success) {
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()
164 if (success === true) {
165 logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids })
167 // Remove the pod id of these request ids
168 removePodOf.call(self, requestToMake.ids, toPodId)
169 goodPods.push(toPodId)
171 badPods.push(toPodId)
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)
186 // Remove pods with a score of 0 (too many requests where they were unreachable)
187 function removeBadPods () {
189 function findBadPods (callback) {
190 Pod.listBadPods(function (err, pods) {
192 logger.error('Cannot find bad pods.', { error: err })
196 return callback(null, pods)
200 function listVideosOfTheseBadPods (pods, callback) {
201 if (pods.length === 0) return callback(null)
203 const urls = map(pods, 'url')
205 Video.listByUrls(urls, function (err, videosList) {
207 logger.error('Cannot list videos urls.', { error: err, urls: urls })
208 return callback(null, pods, [])
211 return callback(null, pods, videosList)
215 function removeVideosOfTheseBadPods (pods, videosList, callback) {
216 // We don't have to remove pods, skip
217 if (typeof pods === 'function') {
219 return callback(null)
222 each(videosList, function (video, callbackEach) {
223 video.remove(callbackEach)
226 // Don't stop the process
227 logger.error('Error while removing videos of bad pods.', { error: err })
231 return callback(null, pods)
235 function removeBadPodsFromDB (pods, callback) {
236 // We don't have to remove pods, skip
237 if (typeof pods === 'function') {
239 return callback(null)
242 each(pods, function (pod, callbackEach) {
243 pod.remove(callbackEach)
245 if (err) return callback(err)
247 return callback(null, pods.length)
250 ], function (err, numberOfPodsRemoved) {
252 logger.error('Cannot remove bad pods.', { error: err })
253 } else if (numberOfPodsRemoved) {
254 logger.info('Removed %d pods.', numberOfPodsRemoved)
256 logger.info('No need to remove bad pods.')
261 function updatePodsScore (goodPods, badPods) {
262 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
264 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
265 if (err) logger.error('Cannot increment scores of good pods.')
268 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
269 if (err) logger.error('Cannot decrement scores of bad pods.')
274 function listWithLimit (limit, callback) {
275 this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit).exec(callback)
278 function removeAll (callback) {
279 this.remove({ }, callback)
282 function removePodOf (requestsIds, podId, callback) {
283 if (!callback) callback = function () {}
285 this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback)
288 function removeWithEmptyTo (callback) {
289 if (!callback) callback = function () {}
291 this.remove({ to: { $size: 0 } }, callback)