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')
17 let lastRequestTimestamp = 0
19 // ---------------------------------------------------------------------------
21 const RequestSchema = mongoose.Schema({
22 request: mongoose.Schema.Types.Mixed,
23 to: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Pod' } ]
26 RequestSchema.statics = {
35 RequestSchema.pre('save', function (next) {
38 if (self.to.length === 0) {
39 Pod.listAllIds(function (err, podIds) {
40 if (err) return next(err)
43 if (podIds.length === 0) return
53 mongoose.model('Request', RequestSchema)
55 // ------------------------------ STATICS ------------------------------
57 function activate () {
58 logger.info('Requests scheduler activated.')
59 lastRequestTimestamp = Date.now()
62 timer = setInterval(function () {
63 lastRequestTimestamp = Date.now()
64 makeRequests.call(self)
65 }, constants.REQUESTS_INTERVAL)
68 function deactivate () {
69 logger.info('Requests scheduler deactivated.')
75 removeAll.call(this, function (err) {
76 if (err) logger.error('Cannot flush the requests.', { error: err })
80 function forceSend () {
81 logger.info('Force requests scheduler sending.')
82 makeRequests.call(this)
85 function list (callback) {
86 this.find({ }, callback)
89 function remainingMilliSeconds () {
90 if (timer === null) return -1
92 return constants.REQUESTS_INTERVAL - (Date.now() - lastRequestTimestamp)
95 // ---------------------------------------------------------------------------
97 // Make a requests to friends of a certain type
98 function makeRequest (toPod, requestsToMake, callback) {
99 if (!callback) callback = function () {}
103 encrypt: true, // Security
104 sign: true, // To prove our identity
106 path: '/api/' + constants.API_VERSION + '/remote/videos',
107 data: requestsToMake // Requests we need to make
110 // Make multiple retry requests to all of pods
111 // The function fire some useful callbacks
112 requests.makeSecureRequest(params, function (err, res) {
113 if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
115 'Error sending secure request to %s pod.',
118 error: err || new Error('Status code not 20x : ' + res.statusCode)
122 return callback(false)
125 return callback(true)
129 // Make all the requests of the scheduler
130 function makeRequests () {
133 listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
135 logger.error('Cannot get the list of requests.', { err: err })
139 // If there are no requests, abort
140 if (requests.length === 0) {
141 logger.info('No requests to make.')
145 logger.info('Making requests to friends.')
147 // Requests by pods id
148 const requestsToMake = {}
150 requests.forEach(function (poolRequest) {
151 poolRequest.to.forEach(function (toPodId) {
152 if (!requestsToMake[toPodId]) {
153 requestsToMake[toPodId] = {
159 requestsToMake[toPodId].ids.push(poolRequest._id)
160 requestsToMake[toPodId].datas.push(poolRequest.request)
167 eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
168 const requestToMake = requestsToMake[toPodId]
170 // FIXME: mongodb request inside a loop :/
171 Pod.load(toPodId, function (err, toPod) {
173 logger.error('Error finding pod by id.', { err: err })
174 return callbackEach()
177 // Maybe the pod is not our friend anymore so simply remove it
179 logger.info('Removing %d requests of unexisting pod %s.', requestToMake.ids.length, toPodId)
180 removePodOf.call(self, requestToMake.ids, toPodId)
181 return callbackEach()
184 makeRequest(toPod, requestToMake.datas, function (success) {
185 if (success === true) {
186 logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids })
188 // Remove the pod id of these request ids
189 removePodOf.call(self, requestToMake.ids, toPodId)
190 goodPods.push(toPodId)
192 badPods.push(toPodId)
199 // All the requests were made, we update the pods score
200 updatePodsScore(goodPods, badPods)
201 // Flush requests with no pod
202 removeWithEmptyTo.call(self)
207 // Remove pods with a score of 0 (too many requests where they were unreachable)
208 function removeBadPods () {
210 function findBadPods (callback) {
211 Pod.listBadPods(function (err, pods) {
213 logger.error('Cannot find bad pods.', { error: err })
217 return callback(null, pods)
221 function listVideosOfTheseBadPods (pods, callback) {
222 if (pods.length === 0) return callback(null)
224 const urls = map(pods, 'url')
226 Video.listByUrls(urls, function (err, videosList) {
228 logger.error('Cannot list videos urls.', { error: err, urls: urls })
229 return callback(null, pods, [])
232 return callback(null, pods, videosList)
236 function removeVideosOfTheseBadPods (pods, videosList, callback) {
237 // We don't have to remove pods, skip
238 if (typeof pods === 'function') {
240 return callback(null)
243 each(videosList, function (video, callbackEach) {
244 video.remove(callbackEach)
247 // Don't stop the process
248 logger.error('Error while removing videos of bad pods.', { error: err })
252 return callback(null, pods)
256 function removeBadPodsFromDB (pods, callback) {
257 // We don't have to remove pods, skip
258 if (typeof pods === 'function') {
260 return callback(null)
263 each(pods, function (pod, callbackEach) {
264 pod.remove(callbackEach)
266 if (err) return callback(err)
268 return callback(null, pods.length)
271 ], function (err, numberOfPodsRemoved) {
273 logger.error('Cannot remove bad pods.', { error: err })
274 } else if (numberOfPodsRemoved) {
275 logger.info('Removed %d pods.', numberOfPodsRemoved)
277 logger.info('No need to remove bad pods.')
282 function updatePodsScore (goodPods, badPods) {
283 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
285 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
286 if (err) logger.error('Cannot increment scores of good pods.')
289 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
290 if (err) logger.error('Cannot decrement scores of bad pods.')
295 function listWithLimit (limit, callback) {
296 this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit).exec(callback)
299 function removeAll (callback) {
300 this.remove({ }, callback)
303 function removePodOf (requestsIds, podId, callback) {
304 if (!callback) callback = function () {}
306 this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback)
309 function removeWithEmptyTo (callback) {
310 if (!callback) callback = function () {}
312 this.remove({ to: { $size: 0 } }, callback)