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