]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/request.js
Update README roadmap
[github/Chocobozzz/PeerTube.git] / server / models / request.js
CommitLineData
9f10b292
C
1'use strict'
2
1a42c9e2
C
3const each = require('async/each')
4const eachLimit = require('async/eachLimit')
35f1c54e 5const map = require('lodash/map')
aaf61f38 6const mongoose = require('mongoose')
1a42c9e2 7const waterfall = require('async/waterfall')
9f10b292 8
f0f5567b
C
9const constants = require('../initializers/constants')
10const logger = require('../helpers/logger')
f0f5567b 11const requests = require('../helpers/requests')
aaf61f38 12
a3ee6fa2 13const Pod = mongoose.model('Pod')
aaf61f38 14const Video = mongoose.model('Video')
9f10b292 15
f0f5567b 16let timer = null
9f10b292 17
00057e85 18// ---------------------------------------------------------------------------
9f10b292 19
00057e85
C
20const RequestSchema = mongoose.Schema({
21 request: mongoose.Schema.Types.Mixed,
d3cd34be 22 to: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Pod' } ]
00057e85 23})
9f10b292 24
00057e85
C
25RequestSchema.statics = {
26 activate,
27 deactivate,
28 flush,
d3cd34be
C
29 forceSend,
30 list
00057e85 31}
9f10b292 32
00057e85
C
33RequestSchema.pre('save', function (next) {
34 const self = this
528a9efa 35
00057e85 36 if (self.to.length === 0) {
a3ee6fa2 37 Pod.listAllIds(function (err, podIds) {
00057e85 38 if (err) return next(err)
9f10b292 39
00057e85
C
40 // No friends
41 if (podIds.length === 0) return
528a9efa 42
00057e85
C
43 self.to = podIds
44 return next()
528a9efa 45 })
00057e85
C
46 } else {
47 return next()
528a9efa 48 }
00057e85 49})
528a9efa 50
00057e85
C
51mongoose.model('Request', RequestSchema)
52
53// ------------------------------ STATICS ------------------------------
54
55function activate () {
56 logger.info('Requests scheduler activated.')
d3cd34be 57 timer = setInterval(makeRequests.bind(this), constants.REQUESTS_INTERVAL)
9f10b292 58}
1fe5076f 59
9f10b292 60function deactivate () {
e3647ae2 61 logger.info('Requests scheduler deactivated.')
9f10b292
C
62 clearInterval(timer)
63}
1fe5076f 64
528a9efa 65function flush () {
00057e85
C
66 removeAll.call(this, function (err) {
67 if (err) logger.error('Cannot flush the requests.', { error: err })
528a9efa
C
68 })
69}
70
9f10b292 71function forceSend () {
e3647ae2 72 logger.info('Force requests scheduler sending.')
00057e85 73 makeRequests.call(this)
9f10b292 74}
c45f7f84 75
d3cd34be
C
76function list (callback) {
77 this.find({ }, callback)
78}
79
9f10b292 80// ---------------------------------------------------------------------------
c45f7f84 81
8c255eb5 82// Make a requests to friends of a certain type
528a9efa 83function makeRequest (toPod, requestsToMake, callback) {
9f10b292 84 if (!callback) callback = function () {}
c45f7f84 85
528a9efa
C
86 const params = {
87 toPod: toPod,
88 encrypt: true, // Security
89 sign: true, // To prove our identity
90 method: 'POST',
91 path: '/api/' + constants.API_VERSION + '/remote/videos',
92 data: requestsToMake // Requests we need to make
93 }
94
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)) {
b9135905
C
99 logger.error(
100 'Error sending secure request to %s pod.',
101 toPod.url,
102 {
103 error: err || new Error('Status code not 20x'),
104 statusCode: res.statusCode
105 }
106 )
528a9efa
C
107
108 return callback(false)
9f10b292 109 }
c45f7f84 110
528a9efa 111 return callback(true)
9f10b292
C
112 })
113}
114
8c255eb5 115// Make all the requests of the scheduler
e3647ae2 116function makeRequests () {
00057e85
C
117 const self = this
118
b3595463 119 listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
9f10b292 120 if (err) {
e3647ae2 121 logger.error('Cannot get the list of requests.', { err: err })
9f10b292
C
122 return // Abort
123 }
124
8c255eb5
C
125 // If there are no requests, abort
126 if (requests.length === 0) {
127 logger.info('No requests to make.')
128 return
129 }
9f10b292 130
8c255eb5
C
131 logger.info('Making requests to friends.')
132
528a9efa 133 // Requests by pods id
8c255eb5 134 const requestsToMake = {}
9f10b292 135
3c8ee69f 136 requests.forEach(function (poolRequest) {
528a9efa
C
137 poolRequest.to.forEach(function (toPodId) {
138 if (!requestsToMake[toPodId]) {
139 requestsToMake[toPodId] = {
140 ids: [],
141 datas: []
142 }
143 }
144
145 requestsToMake[toPodId].ids.push(poolRequest._id)
146 requestsToMake[toPodId].datas.push(poolRequest.request)
147 })
3c8ee69f 148 })
8d6ae227 149
528a9efa
C
150 const goodPods = []
151 const badPods = []
152
1a42c9e2 153 eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
528a9efa
C
154 const requestToMake = requestsToMake[toPodId]
155
156 // FIXME: mongodb request inside a loop :/
a3ee6fa2 157 Pod.load(toPodId, function (err, toPod) {
00057e85
C
158 if (err) {
159 logger.error('Error finding pod by id.', { err: err })
160 return callbackEach()
161 }
528a9efa
C
162
163 // Maybe the pod is not our friend anymore so simply remove them
164 if (!toPod) {
00057e85 165 removePodOf.call(self, requestToMake.ids, toPodId)
528a9efa
C
166 return callbackEach()
167 }
168
169 makeRequest(toPod, requestToMake.datas, function (success) {
528a9efa
C
170 if (success === true) {
171 logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids })
3c8ee69f 172
528a9efa 173 // Remove the pod id of these request ids
00057e85 174 removePodOf.call(self, requestToMake.ids, toPodId)
528a9efa
C
175 goodPods.push(toPodId)
176 } else {
177 badPods.push(toPodId)
178 }
179
180 callbackEach()
3c8ee69f 181 })
528a9efa
C
182 })
183 }, function () {
184 // All the requests were made, we update the pods score
185 updatePodsScore(goodPods, badPods)
186 // Flush requests with no pod
00057e85 187 removeWithEmptyTo.call(self)
528a9efa 188 })
9f10b292
C
189 })
190}
0b697522 191
8c255eb5 192// Remove pods with a score of 0 (too many requests where they were unreachable)
9f10b292 193function removeBadPods () {
1a42c9e2 194 waterfall([
e856e334 195 function findBadPods (callback) {
a3ee6fa2 196 Pod.listBadPods(function (err, pods) {
e856e334
C
197 if (err) {
198 logger.error('Cannot find bad pods.', { error: err })
199 return callback(err)
200 }
8d6ae227 201
e856e334
C
202 return callback(null, pods)
203 })
204 },
8d6ae227 205
e856e334
C
206 function listVideosOfTheseBadPods (pods, callback) {
207 if (pods.length === 0) return callback(null)
0b697522 208
e856e334 209 const urls = map(pods, 'url')
0b697522 210
aaf61f38 211 Video.listByUrls(urls, function (err, videosList) {
8425cb89 212 if (err) {
e856e334 213 logger.error('Cannot list videos urls.', { error: err, urls: urls })
a3ee6fa2 214 return callback(null, pods, [])
8425cb89 215 }
e856e334 216
a3ee6fa2 217 return callback(null, pods, videosList)
45239549 218 })
e856e334
C
219 },
220
a3ee6fa2 221 function removeVideosOfTheseBadPods (pods, videosList, callback) {
e856e334 222 // We don't have to remove pods, skip
a3ee6fa2
C
223 if (typeof pods === 'function') {
224 callback = pods
225 return callback(null)
226 }
e856e334 227
1a42c9e2 228 each(videosList, function (video, callbackEach) {
aaf61f38
C
229 video.remove(callbackEach)
230 }, function (err) {
231 if (err) {
232 // Don't stop the process
233 logger.error('Error while removing videos of bad pods.', { error: err })
234 return
235 }
e856e334 236
a3ee6fa2 237 return callback(null, pods)
e856e334
C
238 })
239 },
240
a3ee6fa2 241 function removeBadPodsFromDB (pods, callback) {
e856e334 242 // We don't have to remove pods, skip
a3ee6fa2
C
243 if (typeof pods === 'function') {
244 callback = pods
245 return callback(null)
246 }
247
1a42c9e2 248 each(pods, function (pod, callbackEach) {
a3ee6fa2
C
249 pod.remove(callbackEach)
250 }, function (err) {
251 if (err) return callback(err)
e856e334 252
a3ee6fa2
C
253 return callback(null, pods.length)
254 })
e856e334 255 }
a3ee6fa2 256 ], function (err, numberOfPodsRemoved) {
e856e334
C
257 if (err) {
258 logger.error('Cannot remove bad pods.', { error: err })
a3ee6fa2
C
259 } else if (numberOfPodsRemoved) {
260 logger.info('Removed %d pods.', numberOfPodsRemoved)
e856e334
C
261 } else {
262 logger.info('No need to remove bad pods.')
263 }
9f10b292
C
264 })
265}
0b697522 266
bc503c2a
C
267function updatePodsScore (goodPods, badPods) {
268 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
0b697522 269
a3ee6fa2 270 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
9f10b292
C
271 if (err) logger.error('Cannot increment scores of good pods.')
272 })
8425cb89 273
a3ee6fa2 274 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
8c255eb5 275 if (err) logger.error('Cannot decrement scores of bad pods.')
9f10b292
C
276 removeBadPods()
277 })
278}
00057e85 279
b3595463
C
280function listWithLimit (limit, callback) {
281 this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit).exec(callback)
00057e85
C
282}
283
284function removeAll (callback) {
285 this.remove({ }, callback)
286}
287
288function removePodOf (requestsIds, podId, callback) {
289 if (!callback) callback = function () {}
290
291 this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback)
292}
293
294function removeWithEmptyTo (callback) {
295 if (!callback) callback = function () {}
296
297 this.remove({ to: { $size: 0 } }, callback)
298}