]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/request.js
Server: add endpoint in requests
[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 encrypt: true, // Security
112 sign: true, // To prove our identity
113 method: 'POST',
114 path: '/api/' + constants.API_VERSION + '/remote/' + requestEndpoint,
115 data: requestsToMake // Requests we need to make
116 }
117
118 // Make multiple retry requests to all of pods
119 // The function fire some useful callbacks
120 requests.makeSecureRequest(params, function (err, res) {
121 if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
122 logger.error(
123 'Error sending secure request to %s pod.',
124 toPod.url,
125 {
126 error: err || new Error('Status code not 20x : ' + res.statusCode)
127 }
128 )
129
130 return callback(false)
131 }
132
133 return callback(true)
134 })
135 }
136
137 // Make all the requests of the scheduler
138 function makeRequests () {
139 const self = this
140
141 // We limit the size of the requests (REQUESTS_LIMIT)
142 // We don't want to stuck with the same failing requests so we get a random list
143 listWithLimitAndRandom.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
144 if (err) {
145 logger.error('Cannot get the list of requests.', { err: err })
146 return // Abort
147 }
148
149 // If there are no requests, abort
150 if (requests.length === 0) {
151 logger.info('No requests to make.')
152 return
153 }
154
155 logger.info('Making requests to friends.')
156
157 // We want to group requests by destinations pod and endpoint
158 const requestsToMakeGrouped = {}
159
160 requests.forEach(function (poolRequest) {
161 poolRequest.to.forEach(function (toPodId) {
162 const hashKey = toPodId + poolRequest.endpoint
163 if (!requestsToMakeGrouped[hashKey]) {
164 requestsToMakeGrouped[hashKey] = {
165 toPodId,
166 endpoint: poolRequest.endpoint,
167 ids: [], // pool request ids, to delete them from the DB in the future
168 datas: [] // requests data,
169 }
170 }
171
172 requestsToMakeGrouped[hashKey].ids.push(poolRequest._id)
173 requestsToMakeGrouped[hashKey].datas.push(poolRequest.request)
174 })
175 })
176
177 const goodPods = []
178 const badPods = []
179
180 eachLimit(Object.keys(requestsToMakeGrouped), constants.REQUESTS_IN_PARALLEL, function (hashKey, callbackEach) {
181 const requestToMake = requestsToMakeGrouped[hashKey]
182
183 // FIXME: mongodb request inside a loop :/
184 Pod.load(requestToMake.toPodId, function (err, toPod) {
185 if (err) {
186 logger.error('Error finding pod by id.', { err: err })
187 return callbackEach()
188 }
189
190 // Maybe the pod is not our friend anymore so simply remove it
191 if (!toPod) {
192 const requestIdsToDelete = requestToMake.ids
193
194 logger.info('Removing %d requests of unexisting pod %s.', requestIdsToDelete.length, requestToMake.toPodId)
195 removePodOf.call(self, requestIdsToDelete, requestToMake.toPodId)
196 return callbackEach()
197 }
198
199 makeRequest(toPod, requestToMake.endpoint, requestToMake.datas, function (success) {
200 if (success === true) {
201 logger.debug('Removing requests for %s pod.', requestToMake.toPodId, { requestsIds: requestToMake.ids })
202
203 goodPods.push(requestToMake.toPodId)
204
205 // Remove the pod id of these request ids
206 removePodOf.call(self, requestToMake.ids, requestToMake.toPodId, callbackEach)
207 } else {
208 badPods.push(requestToMake.toPodId)
209 callbackEach()
210 }
211 })
212 })
213 }, function () {
214 // All the requests were made, we update the pods score
215 updatePodsScore(goodPods, badPods)
216 // Flush requests with no pod
217 removeWithEmptyTo.call(self)
218 })
219 })
220 }
221
222 // Remove pods with a score of 0 (too many requests where they were unreachable)
223 function removeBadPods () {
224 waterfall([
225 function findBadPods (callback) {
226 Pod.listBadPods(function (err, pods) {
227 if (err) {
228 logger.error('Cannot find bad pods.', { error: err })
229 return callback(err)
230 }
231
232 return callback(null, pods)
233 })
234 },
235
236 function removeTheseBadPods (pods, callback) {
237 if (pods.length === 0) return callback(null, 0)
238
239 each(pods, function (pod, callbackEach) {
240 pod.remove(callbackEach)
241 }, function (err) {
242 return callback(err, pods.length)
243 })
244 }
245 ], function (err, numberOfPodsRemoved) {
246 if (err) {
247 logger.error('Cannot remove bad pods.', { error: err })
248 } else if (numberOfPodsRemoved) {
249 logger.info('Removed %d pods.', numberOfPodsRemoved)
250 } else {
251 logger.info('No need to remove bad pods.')
252 }
253 })
254 }
255
256 function updatePodsScore (goodPods, badPods) {
257 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
258
259 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
260 if (err) logger.error('Cannot increment scores of good pods.')
261 })
262
263 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
264 if (err) logger.error('Cannot decrement scores of bad pods.')
265 removeBadPods()
266 })
267 }
268
269 function listWithLimitAndRandom (limit, callback) {
270 const self = this
271
272 self.count(function (err, count) {
273 if (err) return callback(err)
274
275 let start = Math.floor(Math.random() * count) - limit
276 if (start < 0) start = 0
277
278 self.find().sort({ _id: 1 }).skip(start).limit(limit).exec(callback)
279 })
280 }
281
282 function removeAll (callback) {
283 this.remove({ }, callback)
284 }
285
286 function removePodOf (requestsIds, podId, callback) {
287 if (!callback) callback = function () {}
288
289 this.update({ _id: { $in: requestsIds } }, { $pull: { to: podId } }, { multi: true }, callback)
290 }
291
292 function removeWithEmptyTo (callback) {
293 if (!callback) callback = function () {}
294
295 this.remove({ to: { $size: 0 } }, callback)
296 }