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: 'Pod' } ]
25 RequestSchema.statics = {
33 RequestSchema.pre('save', function (next) {
36 if (self.to.length === 0) {
37 Pod.listAllIds(function (err, podIds) {
38 if (err) return next(err)
41 if (podIds.length === 0) return
51 mongoose.model('Request', RequestSchema)
53 // ------------------------------ STATICS ------------------------------
55 function activate () {
56 logger.info('Requests scheduler activated.')
57 timer = setInterval(makeRequests.bind(this), constants.REQUESTS_INTERVAL)
60 function deactivate () {
61 logger.info('Requests scheduler deactivated.')
66 removeAll.call(this, function (err) {
67 if (err) logger.error('Cannot flush the requests.', { error: err })
71 function forceSend () {
72 logger.info('Force requests scheduler sending.')
73 makeRequests.call(this)
76 function list (callback) {
77 this.find({ }, callback)
80 // ---------------------------------------------------------------------------
82 // Make a requests to friends of a certain type
83 function makeRequest (toPod, requestsToMake, callback) {
84 if (!callback) callback = function () {}
88 encrypt: true, // Security
89 sign: true, // To prove our identity
91 path: '/api/' + constants.API_VERSION + '/remote/videos',
92 data: requestsToMake // Requests we need to make
95 // Make multiple retry requests to all of pods
96 // The function fire some useful callbacks
97 requests.makeSecureRequest(params, function (err, res) {
98 if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
99 logger.error('Error sending secure request to %s pod.', toPod.url, { error: err || new Error('Status code not 20x') })
101 return callback(false)
104 return callback(true)
108 // Make all the requests of the scheduler
109 function makeRequests () {
112 listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
114 logger.error('Cannot get the list of requests.', { err: err })
118 // If there are no requests, abort
119 if (requests.length === 0) {
120 logger.info('No requests to make.')
124 logger.info('Making requests to friends.')
126 // Requests by pods id
127 const requestsToMake = {}
129 requests.forEach(function (poolRequest) {
130 poolRequest.to.forEach(function (toPodId) {
131 if (!requestsToMake[toPodId]) {
132 requestsToMake[toPodId] = {
138 requestsToMake[toPodId].ids.push(poolRequest._id)
139 requestsToMake[toPodId].datas.push(poolRequest.request)
146 eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
147 const requestToMake = requestsToMake[toPodId]
149 // FIXME: mongodb request inside a loop :/
150 Pod.load(toPodId, function (err, toPod) {
152 logger.error('Error finding pod by id.', { err: err })
153 return callbackEach()
156 // Maybe the pod is not our friend anymore so simply remove them
158 removePodOf.call(self, requestToMake.ids, toPodId)
159 return callbackEach()
162 makeRequest(toPod, requestToMake.datas, function (success) {
164 logger.error('Errors when sent request to %s.', toPod.url, { error: err })
165 // Do not stop the process just for one error
166 return callbackEach()
169 if (success === true) {
170 logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids })
172 // Remove the pod id of these request ids
173 removePodOf.call(self, requestToMake.ids, toPodId)
174 goodPods.push(toPodId)
176 badPods.push(toPodId)
183 // All the requests were made, we update the pods score
184 updatePodsScore(goodPods, badPods)
185 // Flush requests with no pod
186 removeWithEmptyTo.call(self)
191 // Remove pods with a score of 0 (too many requests where they were unreachable)
192 function removeBadPods () {
194 function findBadPods (callback) {
195 Pod.listBadPods(function (err, pods) {
197 logger.error('Cannot find bad pods.', { error: err })
201 return callback(null, pods)
205 function listVideosOfTheseBadPods (pods, callback) {
206 if (pods.length === 0) return callback(null)
208 const urls = map(pods, 'url')
210 Video.listByUrls(urls, function (err, videosList) {
212 logger.error('Cannot list videos urls.', { error: err, urls: urls })
213 return callback(null, pods, [])
216 return callback(null, pods, videosList)
220 function removeVideosOfTheseBadPods (pods, videosList, callback) {
221 // We don't have to remove pods, skip
222 if (typeof pods === 'function') {
224 return callback(null)
227 each(videosList, function (video, callbackEach) {
228 video.remove(callbackEach)
231 // Don't stop the process
232 logger.error('Error while removing videos of bad pods.', { error: err })
236 return callback(null, pods)
240 function removeBadPodsFromDB (pods, callback) {
241 // We don't have to remove pods, skip
242 if (typeof pods === 'function') {
244 return callback(null)
247 each(pods, function (pod, callbackEach) {
248 pod.remove(callbackEach)
250 if (err) return callback(err)
252 return callback(null, pods.length)
255 ], function (err, numberOfPodsRemoved) {
257 logger.error('Cannot remove bad pods.', { error: err })
258 } else if (numberOfPodsRemoved) {
259 logger.info('Removed %d pods.', numberOfPodsRemoved)
261 logger.info('No need to remove bad pods.')
266 function updatePodsScore (goodPods, badPods) {
267 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
269 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
270 if (err) logger.error('Cannot increment scores of good pods.')
273 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
274 if (err) logger.error('Cannot decrement scores of bad pods.')
279 function listWithLimit (limit, callback) {
280 this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit).exec(callback)
283 function removeAll (callback) {
284 this.remove({ }, callback)
287 function removePodOf (requestsIds, podId, callback) {
288 if (!callback) callback = function () {}
290 this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback)
293 function removeWithEmptyTo (callback) {
294 if (!callback) callback = function () {}
296 this.remove({ to: { $size: 0 } }, callback)