]>
git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/request.js
b36b4f61339178d31ae52009200299e8ca3b3d96
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)) {
100 'Error sending secure request to %s pod.',
103 error: err
|| new Error('Status code not 20x'),
104 statusCode: res
.statusCode
108 return callback(false)
111 return callback(true)
115 // Make all the requests of the scheduler
116 function makeRequests () {
119 listWithLimit
.call(self
, constants
.REQUESTS_LIMIT
, function (err
, requests
) {
121 logger
.error('Cannot get the list of requests.', { err: err
})
125 // If there are no requests, abort
126 if (requests
.length
=== 0) {
127 logger
.info('No requests to make.')
131 logger
.info('Making requests to friends.')
133 // Requests by pods id
134 const requestsToMake
= {}
136 requests
.forEach(function (poolRequest
) {
137 poolRequest
.to
.forEach(function (toPodId
) {
138 if (!requestsToMake
[toPodId
]) {
139 requestsToMake
[toPodId
] = {
145 requestsToMake
[toPodId
].ids
.push(poolRequest
._id
)
146 requestsToMake
[toPodId
].datas
.push(poolRequest
.request
)
153 eachLimit(Object
.keys(requestsToMake
), constants
.REQUESTS_IN_PARALLEL
, function (toPodId
, callbackEach
) {
154 const requestToMake
= requestsToMake
[toPodId
]
156 // FIXME: mongodb request inside a loop :/
157 Pod
.load(toPodId
, function (err
, toPod
) {
159 logger
.error('Error finding pod by id.', { err: err
})
160 return callbackEach()
163 // Maybe the pod is not our friend anymore so simply remove them
165 removePodOf
.call(self
, requestToMake
.ids
, toPodId
)
166 return callbackEach()
169 makeRequest(toPod
, requestToMake
.datas
, function (success
) {
170 if (success
=== true) {
171 logger
.debug('Removing requests for %s pod.', toPodId
, { requestsIds: requestToMake
.ids
})
173 // Remove the pod id of these request ids
174 removePodOf
.call(self
, requestToMake
.ids
, toPodId
)
175 goodPods
.push(toPodId
)
177 badPods
.push(toPodId
)
184 // All the requests were made, we update the pods score
185 updatePodsScore(goodPods
, badPods
)
186 // Flush requests with no pod
187 removeWithEmptyTo
.call(self
)
192 // Remove pods with a score of 0 (too many requests where they were unreachable)
193 function removeBadPods () {
195 function findBadPods (callback
) {
196 Pod
.listBadPods(function (err
, pods
) {
198 logger
.error('Cannot find bad pods.', { error: err
})
202 return callback(null, pods
)
206 function listVideosOfTheseBadPods (pods
, callback
) {
207 if (pods
.length
=== 0) return callback(null)
209 const urls
= map(pods
, 'url')
211 Video
.listByUrls(urls
, function (err
, videosList
) {
213 logger
.error('Cannot list videos urls.', { error: err
, urls: urls
})
214 return callback(null, pods
, [])
217 return callback(null, pods
, videosList
)
221 function removeVideosOfTheseBadPods (pods
, videosList
, callback
) {
222 // We don't have to remove pods, skip
223 if (typeof pods
=== 'function') {
225 return callback(null)
228 each(videosList
, function (video
, callbackEach
) {
229 video
.remove(callbackEach
)
232 // Don't stop the process
233 logger
.error('Error while removing videos of bad pods.', { error: err
})
237 return callback(null, pods
)
241 function removeBadPodsFromDB (pods
, callback
) {
242 // We don't have to remove pods, skip
243 if (typeof pods
=== 'function') {
245 return callback(null)
248 each(pods
, function (pod
, callbackEach
) {
249 pod
.remove(callbackEach
)
251 if (err
) return callback(err
)
253 return callback(null, pods
.length
)
256 ], function (err
, numberOfPodsRemoved
) {
258 logger
.error('Cannot remove bad pods.', { error: err
})
259 } else if (numberOfPodsRemoved
) {
260 logger
.info('Removed %d pods.', numberOfPodsRemoved
)
262 logger
.info('No need to remove bad pods.')
267 function updatePodsScore (goodPods
, badPods
) {
268 logger
.info('Updating %d good pods and %d bad pods scores.', goodPods
.length
, badPods
.length
)
270 Pod
.incrementScores(goodPods
, constants
.PODS_SCORE
.BONUS
, function (err
) {
271 if (err
) logger
.error('Cannot increment scores of good pods.')
274 Pod
.incrementScores(badPods
, constants
.PODS_SCORE
.MALUS
, function (err
) {
275 if (err
) logger
.error('Cannot decrement scores of bad pods.')
280 function listWithLimit (limit
, callback
) {
281 this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit
).exec(callback
)
284 function removeAll (callback
) {
285 this.remove({ }, callback
)
288 function removePodOf (requestsIds
, podId
, callback
) {
289 if (!callback
) callback = function () {}
291 this.update({ _id: { $in: requestsIds
} }, { $pull: { to: podId
} }, { multi: true }, callback
)
294 function removeWithEmptyTo (callback
) {
295 if (!callback
) callback = function () {}
297 this.remove({ to: { $size: 0 } }, callback
)