]>
git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/request.js
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 removePodOf
.call(self
, requestToMake
.ids
, toPodId
)
180 return callbackEach()
183 makeRequest(toPod
, requestToMake
.datas
, function (success
) {
184 if (success
=== true) {
185 logger
.debug('Removing requests for %s pod.', toPodId
, { requestsIds: requestToMake
.ids
})
187 // Remove the pod id of these request ids
188 removePodOf
.call(self
, requestToMake
.ids
, toPodId
)
189 goodPods
.push(toPodId
)
191 badPods
.push(toPodId
)
198 // All the requests were made, we update the pods score
199 updatePodsScore(goodPods
, badPods
)
200 // Flush requests with no pod
201 removeWithEmptyTo
.call(self
)
206 // Remove pods with a score of 0 (too many requests where they were unreachable)
207 function removeBadPods () {
209 function findBadPods (callback
) {
210 Pod
.listBadPods(function (err
, pods
) {
212 logger
.error('Cannot find bad pods.', { error: err
})
216 return callback(null, pods
)
220 function listVideosOfTheseBadPods (pods
, callback
) {
221 if (pods
.length
=== 0) return callback(null)
223 const urls
= map(pods
, 'url')
225 Video
.listByUrls(urls
, function (err
, videosList
) {
227 logger
.error('Cannot list videos urls.', { error: err
, urls: urls
})
228 return callback(null, pods
, [])
231 return callback(null, pods
, videosList
)
235 function removeVideosOfTheseBadPods (pods
, videosList
, callback
) {
236 // We don't have to remove pods, skip
237 if (typeof pods
=== 'function') {
239 return callback(null)
242 each(videosList
, function (video
, callbackEach
) {
243 video
.remove(callbackEach
)
246 // Don't stop the process
247 logger
.error('Error while removing videos of bad pods.', { error: err
})
251 return callback(null, pods
)
255 function removeBadPodsFromDB (pods
, callback
) {
256 // We don't have to remove pods, skip
257 if (typeof pods
=== 'function') {
259 return callback(null)
262 each(pods
, function (pod
, callbackEach
) {
263 pod
.remove(callbackEach
)
265 if (err
) return callback(err
)
267 return callback(null, pods
.length
)
270 ], function (err
, numberOfPodsRemoved
) {
272 logger
.error('Cannot remove bad pods.', { error: err
})
273 } else if (numberOfPodsRemoved
) {
274 logger
.info('Removed %d pods.', numberOfPodsRemoved
)
276 logger
.info('No need to remove bad pods.')
281 function updatePodsScore (goodPods
, badPods
) {
282 logger
.info('Updating %d good pods and %d bad pods scores.', goodPods
.length
, badPods
.length
)
284 Pod
.incrementScores(goodPods
, constants
.PODS_SCORE
.BONUS
, function (err
) {
285 if (err
) logger
.error('Cannot increment scores of good pods.')
288 Pod
.incrementScores(badPods
, constants
.PODS_SCORE
.MALUS
, function (err
) {
289 if (err
) logger
.error('Cannot decrement scores of bad pods.')
294 function listWithLimit (limit
, callback
) {
295 this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit
).exec(callback
)
298 function removeAll (callback
) {
299 this.remove({ }, callback
)
302 function removePodOf (requestsIds
, podId
, callback
) {
303 if (!callback
) callback = function () {}
305 this.update({ _id: { $in: requestsIds
} }, { $pull: { to: podId
} }, { multi: true }, callback
)
308 function removeWithEmptyTo (callback
) {
309 if (!callback
) callback = function () {}
311 this.remove({ to: { $size: 0 } }, callback
)