]>
git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/request.js
c2cfe83cedcc0a3607b56961665a8159ce8f3581
3 const each
= require('async/each')
4 const eachLimit
= require('async/eachLimit')
5 const values
= require('lodash/values')
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')
16 let lastRequestTimestamp
= 0
18 // ---------------------------------------------------------------------------
20 const RequestSchema
= mongoose
.Schema({
21 request: mongoose
.Schema
.Types
.Mixed
,
24 enum: [ values(constants
.REQUEST_ENDPOINTS
) ]
28 type: mongoose
.Schema
.Types
.ObjectId
,
34 RequestSchema
.statics
= {
43 RequestSchema
.pre('save', function (next
) {
46 if (self
.to
.length
=== 0) {
47 Pod
.listAllIds(function (err
, podIds
) {
48 if (err
) return next(err
)
51 if (podIds
.length
=== 0) return
61 mongoose
.model('Request', RequestSchema
)
63 // ------------------------------ STATICS ------------------------------
65 function activate () {
66 logger
.info('Requests scheduler activated.')
67 lastRequestTimestamp
= Date
.now()
70 timer
= setInterval(function () {
71 lastRequestTimestamp
= Date
.now()
72 makeRequests
.call(self
)
73 }, constants
.REQUESTS_INTERVAL
)
76 function deactivate () {
77 logger
.info('Requests scheduler deactivated.')
83 removeAll
.call(this, function (err
) {
84 if (err
) logger
.error('Cannot flush the requests.', { error: err
})
88 function forceSend () {
89 logger
.info('Force requests scheduler sending.')
90 makeRequests
.call(this)
93 function list (callback
) {
94 this.find({ }, callback
)
97 function remainingMilliSeconds () {
98 if (timer
=== null) return -1
100 return constants
.REQUESTS_INTERVAL
- (Date
.now() - lastRequestTimestamp
)
103 // ---------------------------------------------------------------------------
105 // Make a requests to friends of a certain type
106 function makeRequest (toPod
, requestEndpoint
, requestsToMake
, callback
) {
107 if (!callback
) callback = function () {}
111 sign: true, // Prove our identity
113 path: '/api/' + constants
.API_VERSION
+ '/remote/' + requestEndpoint
,
114 data: requestsToMake
// Requests we need to make
117 // Make multiple retry requests to all of pods
118 // The function fire some useful callbacks
119 requests
.makeSecureRequest(params
, function (err
, res
) {
120 if (err
|| (res
.statusCode
!== 200 && res
.statusCode
!== 201 && res
.statusCode
!== 204)) {
122 'Error sending secure request to %s pod.',
125 error: err
|| new Error('Status code not 20x : ' + res
.statusCode
)
129 return callback(false)
132 return callback(true)
136 // Make all the requests of the scheduler
137 function makeRequests () {
140 // We limit the size of the requests (REQUESTS_LIMIT)
141 // We don't want to stuck with the same failing requests so we get a random list
142 listWithLimitAndRandom
.call(self
, constants
.REQUESTS_LIMIT
, function (err
, requests
) {
144 logger
.error('Cannot get the list of requests.', { err: err
})
148 // If there are no requests, abort
149 if (requests
.length
=== 0) {
150 logger
.info('No requests to make.')
154 logger
.info('Making requests to friends.')
156 // We want to group requests by destinations pod and endpoint
157 const requestsToMakeGrouped
= {}
159 requests
.forEach(function (poolRequest
) {
160 poolRequest
.to
.forEach(function (toPodId
) {
161 const hashKey
= toPodId
+ poolRequest
.endpoint
162 if (!requestsToMakeGrouped
[hashKey
]) {
163 requestsToMakeGrouped
[hashKey
] = {
165 endpoint: poolRequest
.endpoint
,
166 ids: [], // pool request ids, to delete them from the DB in the future
167 datas: [] // requests data,
171 requestsToMakeGrouped
[hashKey
].ids
.push(poolRequest
._id
)
172 requestsToMakeGrouped
[hashKey
].datas
.push(poolRequest
.request
)
179 eachLimit(Object
.keys(requestsToMakeGrouped
), constants
.REQUESTS_IN_PARALLEL
, function (hashKey
, callbackEach
) {
180 const requestToMake
= requestsToMakeGrouped
[hashKey
]
182 // FIXME: mongodb request inside a loop :/
183 Pod
.load(requestToMake
.toPodId
, function (err
, toPod
) {
185 logger
.error('Error finding pod by id.', { err: err
})
186 return callbackEach()
189 // Maybe the pod is not our friend anymore so simply remove it
191 const requestIdsToDelete
= requestToMake
.ids
193 logger
.info('Removing %d requests of unexisting pod %s.', requestIdsToDelete
.length
, requestToMake
.toPodId
)
194 removePodOf
.call(self
, requestIdsToDelete
, requestToMake
.toPodId
)
195 return callbackEach()
198 makeRequest(toPod
, requestToMake
.endpoint
, requestToMake
.datas
, function (success
) {
199 if (success
=== true) {
200 logger
.debug('Removing requests for %s pod.', requestToMake
.toPodId
, { requestsIds: requestToMake
.ids
})
202 goodPods
.push(requestToMake
.toPodId
)
204 // Remove the pod id of these request ids
205 removePodOf
.call(self
, requestToMake
.ids
, requestToMake
.toPodId
, callbackEach
)
207 badPods
.push(requestToMake
.toPodId
)
213 // All the requests were made, we update the pods score
214 updatePodsScore(goodPods
, badPods
)
215 // Flush requests with no pod
216 removeWithEmptyTo
.call(self
)
221 // Remove pods with a score of 0 (too many requests where they were unreachable)
222 function removeBadPods () {
224 function findBadPods (callback
) {
225 Pod
.listBadPods(function (err
, pods
) {
227 logger
.error('Cannot find bad pods.', { error: err
})
231 return callback(null, pods
)
235 function removeTheseBadPods (pods
, callback
) {
236 if (pods
.length
=== 0) return callback(null, 0)
238 each(pods
, function (pod
, callbackEach
) {
239 pod
.remove(callbackEach
)
241 return callback(err
, pods
.length
)
244 ], function (err
, numberOfPodsRemoved
) {
246 logger
.error('Cannot remove bad pods.', { error: err
})
247 } else if (numberOfPodsRemoved
) {
248 logger
.info('Removed %d pods.', numberOfPodsRemoved
)
250 logger
.info('No need to remove bad pods.')
255 function updatePodsScore (goodPods
, badPods
) {
256 logger
.info('Updating %d good pods and %d bad pods scores.', goodPods
.length
, badPods
.length
)
258 Pod
.incrementScores(goodPods
, constants
.PODS_SCORE
.BONUS
, function (err
) {
259 if (err
) logger
.error('Cannot increment scores of good pods.')
262 Pod
.incrementScores(badPods
, constants
.PODS_SCORE
.MALUS
, function (err
) {
263 if (err
) logger
.error('Cannot decrement scores of bad pods.')
268 function listWithLimitAndRandom (limit
, callback
) {
271 self
.count(function (err
, count
) {
272 if (err
) return callback(err
)
274 let start
= Math
.floor(Math
.random() * count
) - limit
275 if (start
< 0) start
= 0
277 self
.find().sort({ _id: 1 }).skip(start
).limit(limit
).exec(callback
)
281 function removeAll (callback
) {
282 this.remove({ }, callback
)
285 function removePodOf (requestsIds
, podId
, callback
) {
286 if (!callback
) callback = function () {}
288 this.update({ _id: { $in: requestsIds
} }, { $pull: { to: podId
} }, { multi: true }, callback
)
291 function removeWithEmptyTo (callback
) {
292 if (!callback
) callback = function () {}
294 this.remove({ to: { $size: 0 } }, callback
)