]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/request.js
c2cfe83cedcc0a3607b56961665a8159ce8f3581
[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 values = require('lodash/values')
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
15 let timer = null
16 let lastRequestTimestamp = 0
17
18 // ---------------------------------------------------------------------------
19
20 const RequestSchema = mongoose.Schema({
21 request: mongoose.Schema.Types.Mixed,
22 endpoint: {
23 type: String,
24 enum: [ values(constants.REQUEST_ENDPOINTS) ]
25 },
26 to: [
27 {
28 type: mongoose.Schema.Types.ObjectId,
29 ref: 'Pod'
30 }
31 ]
32 })
33
34 RequestSchema.statics = {
35 activate,
36 deactivate,
37 flush,
38 forceSend,
39 list,
40 remainingMilliSeconds
41 }
42
43 RequestSchema.pre('save', function (next) {
44 const self = this
45
46 if (self.to.length === 0) {
47 Pod.listAllIds(function (err, podIds) {
48 if (err) return next(err)
49
50 // No friends
51 if (podIds.length === 0) return
52
53 self.to = podIds
54 return next()
55 })
56 } else {
57 return next()
58 }
59 })
60
61 mongoose.model('Request', RequestSchema)
62
63 // ------------------------------ STATICS ------------------------------
64
65 function activate () {
66 logger.info('Requests scheduler activated.')
67 lastRequestTimestamp = Date.now()
68
69 const self = this
70 timer = setInterval(function () {
71 lastRequestTimestamp = Date.now()
72 makeRequests.call(self)
73 }, constants.REQUESTS_INTERVAL)
74 }
75
76 function deactivate () {
77 logger.info('Requests scheduler deactivated.')
78 clearInterval(timer)
79 timer = null
80 }
81
82 function flush () {
83 removeAll.call(this, function (err) {
84 if (err) logger.error('Cannot flush the requests.', { error: err })
85 })
86 }
87
88 function forceSend () {
89 logger.info('Force requests scheduler sending.')
90 makeRequests.call(this)
91 }
92
93 function list (callback) {
94 this.find({ }, callback)
95 }
96
97 function remainingMilliSeconds () {
98 if (timer === null) return -1
99
100 return constants.REQUESTS_INTERVAL - (Date.now() - lastRequestTimestamp)
101 }
102
103 // ---------------------------------------------------------------------------
104
105 // Make a requests to friends of a certain type
106 function makeRequest (toPod, requestEndpoint, requestsToMake, callback) {
107 if (!callback) callback = function () {}
108
109 const params = {
110 toPod: toPod,
111 sign: true, // Prove our identity
112 method: 'POST',
113 path: '/api/' + constants.API_VERSION + '/remote/' + requestEndpoint,
114 data: requestsToMake // Requests we need to make
115 }
116
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)) {
121 logger.error(
122 'Error sending secure request to %s pod.',
123 toPod.host,
124 {
125 error: err || new Error('Status code not 20x : ' + res.statusCode)
126 }
127 )
128
129 return callback(false)
130 }
131
132 return callback(true)
133 })
134 }
135
136 // Make all the requests of the scheduler
137 function makeRequests () {
138 const self = this
139
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) {
143 if (err) {
144 logger.error('Cannot get the list of requests.', { err: err })
145 return // Abort
146 }
147
148 // If there are no requests, abort
149 if (requests.length === 0) {
150 logger.info('No requests to make.')
151 return
152 }
153
154 logger.info('Making requests to friends.')
155
156 // We want to group requests by destinations pod and endpoint
157 const requestsToMakeGrouped = {}
158
159 requests.forEach(function (poolRequest) {
160 poolRequest.to.forEach(function (toPodId) {
161 const hashKey = toPodId + poolRequest.endpoint
162 if (!requestsToMakeGrouped[hashKey]) {
163 requestsToMakeGrouped[hashKey] = {
164 toPodId,
165 endpoint: poolRequest.endpoint,
166 ids: [], // pool request ids, to delete them from the DB in the future
167 datas: [] // requests data,
168 }
169 }
170
171 requestsToMakeGrouped[hashKey].ids.push(poolRequest._id)
172 requestsToMakeGrouped[hashKey].datas.push(poolRequest.request)
173 })
174 })
175
176 const goodPods = []
177 const badPods = []
178
179 eachLimit(Object.keys(requestsToMakeGrouped), constants.REQUESTS_IN_PARALLEL, function (hashKey, callbackEach) {
180 const requestToMake = requestsToMakeGrouped[hashKey]
181
182 // FIXME: mongodb request inside a loop :/
183 Pod.load(requestToMake.toPodId, function (err, toPod) {
184 if (err) {
185 logger.error('Error finding pod by id.', { err: err })
186 return callbackEach()
187 }
188
189 // Maybe the pod is not our friend anymore so simply remove it
190 if (!toPod) {
191 const requestIdsToDelete = requestToMake.ids
192
193 logger.info('Removing %d requests of unexisting pod %s.', requestIdsToDelete.length, requestToMake.toPodId)
194 removePodOf.call(self, requestIdsToDelete, requestToMake.toPodId)
195 return callbackEach()
196 }
197
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 })
201
202 goodPods.push(requestToMake.toPodId)
203
204 // Remove the pod id of these request ids
205 removePodOf.call(self, requestToMake.ids, requestToMake.toPodId, callbackEach)
206 } else {
207 badPods.push(requestToMake.toPodId)
208 callbackEach()
209 }
210 })
211 })
212 }, function () {
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)
217 })
218 })
219 }
220
221 // Remove pods with a score of 0 (too many requests where they were unreachable)
222 function removeBadPods () {
223 waterfall([
224 function findBadPods (callback) {
225 Pod.listBadPods(function (err, pods) {
226 if (err) {
227 logger.error('Cannot find bad pods.', { error: err })
228 return callback(err)
229 }
230
231 return callback(null, pods)
232 })
233 },
234
235 function removeTheseBadPods (pods, callback) {
236 if (pods.length === 0) return callback(null, 0)
237
238 each(pods, function (pod, callbackEach) {
239 pod.remove(callbackEach)
240 }, function (err) {
241 return callback(err, pods.length)
242 })
243 }
244 ], function (err, numberOfPodsRemoved) {
245 if (err) {
246 logger.error('Cannot remove bad pods.', { error: err })
247 } else if (numberOfPodsRemoved) {
248 logger.info('Removed %d pods.', numberOfPodsRemoved)
249 } else {
250 logger.info('No need to remove bad pods.')
251 }
252 })
253 }
254
255 function updatePodsScore (goodPods, badPods) {
256 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
257
258 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
259 if (err) logger.error('Cannot increment scores of good pods.')
260 })
261
262 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
263 if (err) logger.error('Cannot decrement scores of bad pods.')
264 removeBadPods()
265 })
266 }
267
268 function listWithLimitAndRandom (limit, callback) {
269 const self = this
270
271 self.count(function (err, count) {
272 if (err) return callback(err)
273
274 let start = Math.floor(Math.random() * count) - limit
275 if (start < 0) start = 0
276
277 self.find().sort({ _id: 1 }).skip(start).limit(limit).exec(callback)
278 })
279 }
280
281 function removeAll (callback) {
282 this.remove({ }, callback)
283 }
284
285 function removePodOf (requestsIds, podId, callback) {
286 if (!callback) callback = function () {}
287
288 this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback)
289 }
290
291 function removeWithEmptyTo (callback) {
292 if (!callback) callback = function () {}
293
294 this.remove({ to: { $size: 0 } }, callback)
295 }