]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/request.js
Update migrations code
[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')
1a42c9e2 5const waterfall = require('async/waterfall')
9f10b292 6
f0f5567b
C
7const constants = require('../initializers/constants')
8const logger = require('../helpers/logger')
f0f5567b 9const requests = require('../helpers/requests')
aaf61f38 10
f0f5567b 11let timer = null
5abeec31 12let lastRequestTimestamp = 0
9f10b292 13
00057e85 14// ---------------------------------------------------------------------------
9f10b292 15
feb4bdfd
C
16module.exports = function (sequelize, DataTypes) {
17 const Request = sequelize.define('Request',
18 {
19 request: {
20 type: DataTypes.JSON
21 },
22 endpoint: {
23 // TODO: enum?
24 type: DataTypes.STRING
25 }
26 },
4b08096b 27 {
feb4bdfd
C
28 classMethods: {
29 associate,
30
31 activate,
32 countTotalRequests,
33 deactivate,
34 flush,
35 forceSend,
36 remainingMilliSeconds
37 }
4b08096b 38 }
feb4bdfd 39 )
528a9efa 40
feb4bdfd
C
41 return Request
42}
00057e85
C
43
44// ------------------------------ STATICS ------------------------------
45
feb4bdfd
C
46function associate (models) {
47 this.belongsToMany(models.Pod, {
48 foreignKey: {
49 name: 'requestId',
50 allowNull: false
51 },
52 through: models.RequestToPod,
53 onDelete: 'CASCADE'
54 })
55}
56
00057e85
C
57function activate () {
58 logger.info('Requests scheduler activated.')
5abeec31
C
59 lastRequestTimestamp = Date.now()
60
61 const self = this
62 timer = setInterval(function () {
63 lastRequestTimestamp = Date.now()
64 makeRequests.call(self)
65 }, constants.REQUESTS_INTERVAL)
9f10b292 66}
1fe5076f 67
feb4bdfd
C
68function countTotalRequests (callback) {
69 const query = {
70 include: [ this.sequelize.models.Pod ]
71 }
72
73 return this.count(query).asCallback(callback)
74}
75
9f10b292 76function deactivate () {
e3647ae2 77 logger.info('Requests scheduler deactivated.')
9f10b292 78 clearInterval(timer)
5abeec31 79 timer = null
9f10b292 80}
1fe5076f 81
7920c273 82function flush (callback) {
00057e85
C
83 removeAll.call(this, function (err) {
84 if (err) logger.error('Cannot flush the requests.', { error: err })
7920c273
C
85
86 return callback(err)
528a9efa
C
87 })
88}
89
9f10b292 90function forceSend () {
e3647ae2 91 logger.info('Force requests scheduler sending.')
00057e85 92 makeRequests.call(this)
9f10b292 93}
c45f7f84 94
5abeec31
C
95function remainingMilliSeconds () {
96 if (timer === null) return -1
97
98 return constants.REQUESTS_INTERVAL - (Date.now() - lastRequestTimestamp)
99}
100
9f10b292 101// ---------------------------------------------------------------------------
c45f7f84 102
8c255eb5 103// Make a requests to friends of a certain type
4b08096b 104function makeRequest (toPod, requestEndpoint, requestsToMake, callback) {
9f10b292 105 if (!callback) callback = function () {}
c45f7f84 106
528a9efa
C
107 const params = {
108 toPod: toPod,
38d78e5b 109 sign: true, // Prove our identity
528a9efa 110 method: 'POST',
4b08096b 111 path: '/api/' + constants.API_VERSION + '/remote/' + requestEndpoint,
528a9efa
C
112 data: requestsToMake // Requests we need to make
113 }
114
115 // Make multiple retry requests to all of pods
116 // The function fire some useful callbacks
117 requests.makeSecureRequest(params, function (err, res) {
118 if (err || (res.statusCode !== 200 && res.statusCode !== 201 && res.statusCode !== 204)) {
b9135905
C
119 logger.error(
120 'Error sending secure request to %s pod.',
49abbbbe 121 toPod.host,
b9135905 122 {
7c34bc64 123 error: err || new Error('Status code not 20x : ' + res.statusCode)
b9135905
C
124 }
125 )
528a9efa
C
126
127 return callback(false)
9f10b292 128 }
c45f7f84 129
528a9efa 130 return callback(true)
9f10b292
C
131 })
132}
133
8c255eb5 134// Make all the requests of the scheduler
e3647ae2 135function makeRequests () {
00057e85 136 const self = this
feb4bdfd 137 const RequestToPod = this.sequelize.models.RequestToPod
00057e85 138
43666d61
C
139 // We limit the size of the requests (REQUESTS_LIMIT)
140 // We don't want to stuck with the same failing requests so we get a random list
141 listWithLimitAndRandom.call(self, constants.REQUESTS_LIMIT, function (err, requests) {
9f10b292 142 if (err) {
e3647ae2 143 logger.error('Cannot get the list of requests.', { err: err })
9f10b292
C
144 return // Abort
145 }
146
8c255eb5
C
147 // If there are no requests, abort
148 if (requests.length === 0) {
149 logger.info('No requests to make.')
150 return
151 }
9f10b292 152
8c255eb5
C
153 logger.info('Making requests to friends.')
154
4b08096b
C
155 // We want to group requests by destinations pod and endpoint
156 const requestsToMakeGrouped = {}
9f10b292 157
feb4bdfd
C
158 requests.forEach(function (request) {
159 request.Pods.forEach(function (toPod) {
160 const hashKey = toPod.id + request.endpoint
4b08096b
C
161 if (!requestsToMakeGrouped[hashKey]) {
162 requestsToMakeGrouped[hashKey] = {
feb4bdfd
C
163 toPodId: toPod.id,
164 endpoint: request.endpoint,
165 ids: [], // request ids, to delete them from the DB in the future
4b08096b 166 datas: [] // requests data,
528a9efa
C
167 }
168 }
169
feb4bdfd
C
170 requestsToMakeGrouped[hashKey].ids.push(request.id)
171 requestsToMakeGrouped[hashKey].datas.push(request.request)
528a9efa 172 })
3c8ee69f 173 })
8d6ae227 174
528a9efa
C
175 const goodPods = []
176 const badPods = []
177
4b08096b
C
178 eachLimit(Object.keys(requestsToMakeGrouped), constants.REQUESTS_IN_PARALLEL, function (hashKey, callbackEach) {
179 const requestToMake = requestsToMakeGrouped[hashKey]
528a9efa 180
feb4bdfd
C
181 // FIXME: SQL request inside a loop :/
182 self.sequelize.models.Pod.load(requestToMake.toPodId, function (err, toPod) {
00057e85
C
183 if (err) {
184 logger.error('Error finding pod by id.', { err: err })
185 return callbackEach()
186 }
528a9efa 187
5abeec31 188 // Maybe the pod is not our friend anymore so simply remove it
528a9efa 189 if (!toPod) {
4b08096b
C
190 const requestIdsToDelete = requestToMake.ids
191
192 logger.info('Removing %d requests of unexisting pod %s.', requestIdsToDelete.length, requestToMake.toPodId)
feb4bdfd 193 RequestToPod.removePodOf.call(self, requestIdsToDelete, requestToMake.toPodId)
528a9efa
C
194 return callbackEach()
195 }
196
4b08096b 197 makeRequest(toPod, requestToMake.endpoint, requestToMake.datas, function (success) {
528a9efa 198 if (success === true) {
4b08096b 199 logger.debug('Removing requests for %s pod.', requestToMake.toPodId, { requestsIds: requestToMake.ids })
3c8ee69f 200
4b08096b 201 goodPods.push(requestToMake.toPodId)
c2ee5ce8
C
202
203 // Remove the pod id of these request ids
feb4bdfd 204 RequestToPod.removePodOf(requestToMake.ids, requestToMake.toPodId, callbackEach)
528a9efa 205 } else {
4b08096b 206 badPods.push(requestToMake.toPodId)
c2ee5ce8 207 callbackEach()
528a9efa 208 }
3c8ee69f 209 })
528a9efa
C
210 })
211 }, function () {
212 // All the requests were made, we update the pods score
feb4bdfd 213 updatePodsScore.call(self, goodPods, badPods)
528a9efa 214 // Flush requests with no pod
feb4bdfd
C
215 removeWithEmptyTo.call(self, function (err) {
216 if (err) logger.error('Error when removing requests with no pods.', { error: err })
217 })
528a9efa 218 })
9f10b292
C
219 })
220}
0b697522 221
8c255eb5 222// Remove pods with a score of 0 (too many requests where they were unreachable)
9f10b292 223function removeBadPods () {
feb4bdfd
C
224 const self = this
225
1a42c9e2 226 waterfall([
e856e334 227 function findBadPods (callback) {
feb4bdfd 228 self.sequelize.models.Pod.listBadPods(function (err, pods) {
e856e334
C
229 if (err) {
230 logger.error('Cannot find bad pods.', { error: err })
231 return callback(err)
232 }
8d6ae227 233
e856e334
C
234 return callback(null, pods)
235 })
236 },
8d6ae227 237
80a6c9e7 238 function removeTheseBadPods (pods, callback) {
1a42c9e2 239 each(pods, function (pod, callbackEach) {
feb4bdfd 240 pod.destroy().asCallback(callbackEach)
a3ee6fa2 241 }, function (err) {
80a6c9e7 242 return callback(err, pods.length)
a3ee6fa2 243 })
e856e334 244 }
a3ee6fa2 245 ], function (err, numberOfPodsRemoved) {
e856e334
C
246 if (err) {
247 logger.error('Cannot remove bad pods.', { error: err })
a3ee6fa2
C
248 } else if (numberOfPodsRemoved) {
249 logger.info('Removed %d pods.', numberOfPodsRemoved)
e856e334
C
250 } else {
251 logger.info('No need to remove bad pods.')
252 }
9f10b292
C
253 })
254}
0b697522 255
bc503c2a 256function updatePodsScore (goodPods, badPods) {
feb4bdfd
C
257 const self = this
258 const Pod = this.sequelize.models.Pod
259
bc503c2a 260 logger.info('Updating %d good pods and %d bad pods scores.', goodPods.length, badPods.length)
0b697522 261
feb4bdfd
C
262 if (goodPods.length !== 0) {
263 Pod.incrementScores(goodPods, constants.PODS_SCORE.BONUS, function (err) {
264 if (err) logger.error('Cannot increment scores of good pods.')
265 })
266 }
8425cb89 267
feb4bdfd
C
268 if (badPods.length !== 0) {
269 Pod.incrementScores(badPods, constants.PODS_SCORE.MALUS, function (err) {
270 if (err) logger.error('Cannot decrement scores of bad pods.')
271 removeBadPods.call(self)
272 })
273 }
9f10b292 274}
00057e85 275
43666d61
C
276function listWithLimitAndRandom (limit, callback) {
277 const self = this
278
feb4bdfd 279 self.count().asCallback(function (err, count) {
43666d61
C
280 if (err) return callback(err)
281
feb4bdfd
C
282 // Optimization...
283 if (count === 0) return callback(null, [])
284
43666d61
C
285 let start = Math.floor(Math.random() * count) - limit
286 if (start < 0) start = 0
287
feb4bdfd
C
288 const query = {
289 order: [
290 [ 'id', 'ASC' ]
291 ],
292 offset: start,
293 limit: limit,
294 include: [ this.sequelize.models.Pod ]
295 }
296
297 self.findAll(query).asCallback(callback)
43666d61 298 })
00057e85
C
299}
300
301function removeAll (callback) {
feb4bdfd 302 // Delete all requests
7920c273 303 this.truncate({ cascade: true }).asCallback(callback)
00057e85
C
304}
305
306function removeWithEmptyTo (callback) {
307 if (!callback) callback = function () {}
308
feb4bdfd
C
309 const query = {
310 where: {
311 id: {
312 $notIn: [
313 this.sequelize.literal('SELECT "requestId" FROM "RequestToPods"')
314 ]
315 }
316 }
317 }
318
319 this.destroy(query).asCallback(callback)
00057e85 320}