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