]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/request.js
Server: do not forget to check the signature when another pod wants to
[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)) {
99 logger.error('Error sending secure request to %s pod.', toPod.url, { error: err || new Error('Status code not 20x') })
100
101 return callback(false)
9f10b292 102 }
c45f7f84 103
528a9efa 104 return callback(true)
9f10b292
C
105 })
106}
107
8c255eb5 108// Make all the requests of the scheduler
e3647ae2 109function makeRequests () {
00057e85
C
110 const self = this
111
b3595463 112 listWithLimit.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
9f10b292 113 if (err) {
e3647ae2 114 logger.error('Cannot get the list of requests.', { err: err })
9f10b292
C
115 return // Abort
116 }
117
8c255eb5
C
118 // If there are no requests, abort
119 if (requests.length === 0) {
120 logger.info('No requests to make.')
121 return
122 }
9f10b292 123
8c255eb5
C
124 logger.info('Making requests to friends.')
125
528a9efa 126 // Requests by pods id
8c255eb5 127 const requestsToMake = {}
9f10b292 128
3c8ee69f 129 requests.forEach(function (poolRequest) {
528a9efa
C
130 poolRequest.to.forEach(function (toPodId) {
131 if (!requestsToMake[toPodId]) {
132 requestsToMake[toPodId] = {
133 ids: [],
134 datas: []
135 }
136 }
137
138 requestsToMake[toPodId].ids.push(poolRequest._id)
139 requestsToMake[toPodId].datas.push(poolRequest.request)
140 })
3c8ee69f 141 })
8d6ae227 142
528a9efa
C
143 const goodPods = []
144 const badPods = []
145
1a42c9e2 146 eachLimit(Object.keys(requestsToMake), constants.REQUESTS_IN_PARALLEL, function (toPodId, callbackEach) {
528a9efa
C
147 const requestToMake = requestsToMake[toPodId]
148
149 // FIXME: mongodb request inside a loop :/
a3ee6fa2 150 Pod.load(toPodId, function (err, toPod) {
00057e85
C
151 if (err) {
152 logger.error('Error finding pod by id.', { err: err })
153 return callbackEach()
154 }
528a9efa
C
155
156 // Maybe the pod is not our friend anymore so simply remove them
157 if (!toPod) {
00057e85 158 removePodOf.call(self, requestToMake.ids, toPodId)
528a9efa
C
159 return callbackEach()
160 }
161
162 makeRequest(toPod, requestToMake.datas, function (success) {
163 if (err) {
164 logger.error('Errors when sent request to %s.', toPod.url, { error: err })
165 // Do not stop the process just for one error
166 return callbackEach()
167 }
168
169 if (success === true) {
170 logger.debug('Removing requests for %s pod.', toPodId, { requestsIds: requestToMake.ids })
3c8ee69f 171
528a9efa 172 // Remove the pod id of these request ids
00057e85 173 removePodOf.call(self, requestToMake.ids, toPodId)
528a9efa
C
174 goodPods.push(toPodId)
175 } else {
176 badPods.push(toPodId)
177 }
178
179 callbackEach()
3c8ee69f 180 })
528a9efa
C
181 })
182 }, function () {
183 // All the requests were made, we update the pods score
184 updatePodsScore(goodPods, badPods)
185 // Flush requests with no pod
00057e85 186 removeWithEmptyTo.call(self)
528a9efa 187 })
9f10b292
C
188 })
189}
0b697522 190
8c255eb5 191// Remove pods with a score of 0 (too many requests where they were unreachable)
9f10b292 192function removeBadPods () {
1a42c9e2 193 waterfall([
e856e334 194 function findBadPods (callback) {
a3ee6fa2 195 Pod.listBadPods(function (err, pods) {
e856e334
C
196 if (err) {
197 logger.error('Cannot find bad pods.', { error: err })
198 return callback(err)
199 }
8d6ae227 200
e856e334
C
201 return callback(null, pods)
202 })
203 },
8d6ae227 204
e856e334
C
205 function listVideosOfTheseBadPods (pods, callback) {
206 if (pods.length === 0) return callback(null)
0b697522 207
e856e334 208 const urls = map(pods, 'url')
0b697522 209
aaf61f38 210 Video.listByUrls(urls, function (err, videosList) {
8425cb89 211 if (err) {
e856e334 212 logger.error('Cannot list videos urls.', { error: err, urls: urls })
a3ee6fa2 213 return callback(null, pods, [])
8425cb89 214 }
e856e334 215
a3ee6fa2 216 return callback(null, pods, videosList)
45239549 217 })
e856e334
C
218 },
219
a3ee6fa2 220 function removeVideosOfTheseBadPods (pods, videosList, callback) {
e856e334 221 // We don't have to remove pods, skip
a3ee6fa2
C
222 if (typeof pods === 'function') {
223 callback = pods
224 return callback(null)
225 }
e856e334 226
1a42c9e2 227 each(videosList, function (video, callbackEach) {
aaf61f38
C
228 video.remove(callbackEach)
229 }, function (err) {
230 if (err) {
231 // Don't stop the process
232 logger.error('Error while removing videos of bad pods.', { error: err })
233 return
234 }
e856e334 235
a3ee6fa2 236 return callback(null, pods)
e856e334
C
237 })
238 },
239
a3ee6fa2 240 function removeBadPodsFromDB (pods, callback) {
e856e334 241 // We don't have to remove pods, skip
a3ee6fa2
C
242 if (typeof pods === 'function') {
243 callback = pods
244 return callback(null)
245 }
246
1a42c9e2 247 each(pods, function (pod, callbackEach) {
a3ee6fa2
C
248 pod.remove(callbackEach)
249 }, function (err) {
250 if (err) return callback(err)
e856e334 251
a3ee6fa2
C
252 return callback(null, pods.length)
253 })
e856e334 254 }
a3ee6fa2 255 ], function (err, numberOfPodsRemoved) {
e856e334
C
256 if (err) {
257 logger.error('Cannot remove bad pods.', { error: err })
a3ee6fa2
C
258 } else if (numberOfPodsRemoved) {
259 logger.info('Removed %d pods.', numberOfPodsRemoved)
e856e334
C
260 } else {
261 logger.info('No need to remove bad pods.')
262 }
9f10b292
C
263 })
264}
0b697522 265
bc503c2a
C
266function updatePodsScore (goodPods, badPods) {
267 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
0b697522 268
a3ee6fa2 269 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
9f10b292
C
270 if (err) logger.error('Cannot increment scores of good pods.')
271 })
8425cb89 272
a3ee6fa2 273 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
8c255eb5 274 if (err) logger.error('Cannot decrement scores of bad pods.')
9f10b292
C
275 removeBadPods()
276 })
277}
00057e85 278
b3595463
C
279function listWithLimit (limit, callback) {
280 this.find({ }, { _id: 1, request: 1, to: 1 }).sort({ _id: 1 }).limit(limit).exec(callback)
00057e85
C
281}
282
283function removeAll (callback) {
284 this.remove({ }, callback)
285}
286
287function removePodOf (requestsIds, podId, callback) {
288 if (!callback) callback = function () {}
289
290 this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback)
291}
292
293function removeWithEmptyTo (callback) {
294 if (!callback) callback = function () {}
295
296 this.remove({ to: { $size: 0 } }, callback)
297}