]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/job-queue.ts
50d732bebcf5c05c9df0c1eac2b12d3c6585ab24
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / job-queue.ts
1 import {
2 FlowJob,
3 FlowProducer,
4 Job,
5 JobsOptions,
6 Queue,
7 QueueEvents,
8 QueueEventsOptions,
9 QueueOptions,
10 QueueScheduler,
11 QueueSchedulerOptions,
12 Worker,
13 WorkerOptions
14 } from 'bullmq'
15 import { jobStates } from '@server/helpers/custom-validators/jobs'
16 import { CONFIG } from '@server/initializers/config'
17 import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy'
18 import { pick, timeoutPromise } from '@shared/core-utils'
19 import {
20 ActivitypubFollowPayload,
21 ActivitypubHttpBroadcastPayload,
22 ActivitypubHttpFetcherPayload,
23 ActivitypubHttpUnicastPayload,
24 ActorKeysPayload,
25 DeleteResumableUploadMetaFilePayload,
26 EmailPayload,
27 FederateVideoPayload,
28 JobState,
29 JobType,
30 ManageVideoTorrentPayload,
31 MoveObjectStoragePayload,
32 NotifyPayload,
33 RefreshPayload,
34 VideoFileImportPayload,
35 VideoImportPayload,
36 VideoLiveEndingPayload,
37 VideoRedundancyPayload,
38 VideoStudioEditionPayload,
39 VideoTranscodingPayload
40 } from '../../../shared/models'
41 import { logger } from '../../helpers/logger'
42 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
43 import { Hooks } from '../plugins/hooks'
44 import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
45 import { processActivityPubFollow } from './handlers/activitypub-follow'
46 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
47 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
48 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
49 import { refreshAPObject } from './handlers/activitypub-refresher'
50 import { processActorKeys } from './handlers/actor-keys'
51 import { processEmail } from './handlers/email'
52 import { processFederateVideo } from './handlers/federate-video'
53 import { processManageVideoTorrent } from './handlers/manage-video-torrent'
54 import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage'
55 import { processNotify } from './handlers/notify'
56 import { processVideoFileImport } from './handlers/video-file-import'
57 import { processVideoImport } from './handlers/video-import'
58 import { processVideoLiveEnding } from './handlers/video-live-ending'
59 import { processVideoStudioEdition } from './handlers/video-studio-edition'
60 import { processVideoTranscoding } from './handlers/video-transcoding'
61 import { processVideosViewsStats } from './handlers/video-views-stats'
62
63 export type CreateJobArgument =
64 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
65 { type: 'activitypub-http-broadcast-parallel', payload: ActivitypubHttpBroadcastPayload } |
66 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
67 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
68 { type: 'activitypub-http-cleaner', payload: {} } |
69 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
70 { type: 'video-file-import', payload: VideoFileImportPayload } |
71 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
72 { type: 'email', payload: EmailPayload } |
73 { type: 'video-import', payload: VideoImportPayload } |
74 { type: 'activitypub-refresher', payload: RefreshPayload } |
75 { type: 'videos-views-stats', payload: {} } |
76 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
77 { type: 'actor-keys', payload: ActorKeysPayload } |
78 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
79 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
80 { type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
81 { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
82 { type: 'notify', payload: NotifyPayload } |
83 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } |
84 { type: 'federate-video', payload: FederateVideoPayload }
85
86 export type CreateJobOptions = {
87 delay?: number
88 priority?: number
89 }
90
91 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
92 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
93 'activitypub-http-broadcast-parallel': processActivityPubHttpBroadcast,
94 'activitypub-http-unicast': processActivityPubHttpUnicast,
95 'activitypub-http-fetcher': processActivityPubHttpFetcher,
96 'activitypub-cleaner': processActivityPubCleaner,
97 'activitypub-follow': processActivityPubFollow,
98 'video-file-import': processVideoFileImport,
99 'video-transcoding': processVideoTranscoding,
100 'email': processEmail,
101 'video-import': processVideoImport,
102 'videos-views-stats': processVideosViewsStats,
103 'activitypub-refresher': refreshAPObject,
104 'video-live-ending': processVideoLiveEnding,
105 'actor-keys': processActorKeys,
106 'video-redundancy': processVideoRedundancy,
107 'move-to-object-storage': processMoveToObjectStorage,
108 'manage-video-torrent': processManageVideoTorrent,
109 'notify': processNotify,
110 'video-studio-edition': processVideoStudioEdition,
111 'federate-video': processFederateVideo
112 }
113
114 const errorHandlers: { [id in JobType]?: (job: Job, err: any) => Promise<any> } = {
115 'move-to-object-storage': onMoveToObjectStorageFailure
116 }
117
118 const jobTypes: JobType[] = [
119 'activitypub-follow',
120 'activitypub-http-broadcast',
121 'activitypub-http-broadcast-parallel',
122 'activitypub-http-fetcher',
123 'activitypub-http-unicast',
124 'activitypub-cleaner',
125 'email',
126 'video-transcoding',
127 'video-file-import',
128 'video-import',
129 'videos-views-stats',
130 'activitypub-refresher',
131 'video-redundancy',
132 'actor-keys',
133 'video-live-ending',
134 'move-to-object-storage',
135 'manage-video-torrent',
136 'video-studio-edition',
137 'notify',
138 'federate-video'
139 ]
140
141 const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
142
143 class JobQueue {
144
145 private static instance: JobQueue
146
147 private workers: { [id in JobType]?: Worker } = {}
148 private queues: { [id in JobType]?: Queue } = {}
149 private queueSchedulers: { [id in JobType]?: QueueScheduler } = {}
150 private queueEvents: { [id in JobType]?: QueueEvents } = {}
151
152 private flowProducer: FlowProducer
153
154 private initialized = false
155 private jobRedisPrefix: string
156
157 private constructor () {
158 }
159
160 init (produceOnly = false) {
161 // Already initialized
162 if (this.initialized === true) return
163 this.initialized = true
164
165 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
166
167 for (const handlerName of (Object.keys(handlers) as JobType[])) {
168 this.buildWorker(handlerName, produceOnly)
169 this.buildQueue(handlerName)
170 this.buildQueueScheduler(handlerName, produceOnly)
171 this.buildQueueEvent(handlerName, produceOnly)
172 }
173
174 this.flowProducer = new FlowProducer({
175 connection: this.getRedisConnection(),
176 prefix: this.jobRedisPrefix
177 })
178
179 this.addRepeatableJobs()
180 }
181
182 private buildWorker (handlerName: JobType, produceOnly: boolean) {
183 const workerOptions: WorkerOptions = {
184 autorun: !produceOnly,
185 concurrency: this.getJobConcurrency(handlerName),
186 prefix: this.jobRedisPrefix,
187 connection: this.getRedisConnection()
188 }
189
190 const handler = function (job: Job) {
191 const timeout = JOB_TTL[handlerName]
192 const p = handlers[handlerName](job)
193
194 if (!timeout) return p
195
196 return timeoutPromise(p, timeout)
197 }
198
199 const processor = async (jobArg: Job<any>) => {
200 const job = await Hooks.wrapObject(jobArg, 'filter:job-queue.process.params', { type: handlerName })
201
202 return Hooks.wrapPromiseFun(handler, job, 'filter:job-queue.process.result')
203 }
204
205 const worker = new Worker(handlerName, processor, workerOptions)
206
207 worker.on('failed', (job, err) => {
208 const logLevel = silentFailure.has(handlerName)
209 ? 'debug'
210 : 'error'
211
212 logger.log(logLevel, 'Cannot execute job %s in queue %s.', job.id, handlerName, { payload: job.data, err })
213
214 if (errorHandlers[job.name]) {
215 errorHandlers[job.name](job, err)
216 .catch(err => logger.error('Cannot run error handler for job failure %d in queue %s.', job.id, handlerName, { err }))
217 }
218 })
219
220 worker.on('error', err => {
221 logger.error('Error in job queue %s.', handlerName, { err })
222 })
223
224 this.workers[handlerName] = worker
225 }
226
227 private buildQueue (handlerName: JobType) {
228 const queueOptions: QueueOptions = {
229 connection: this.getRedisConnection(),
230 prefix: this.jobRedisPrefix
231 }
232
233 this.queues[handlerName] = new Queue(handlerName, queueOptions)
234 }
235
236 private buildQueueScheduler (handlerName: JobType, produceOnly: boolean) {
237 const queueSchedulerOptions: QueueSchedulerOptions = {
238 autorun: !produceOnly,
239 connection: this.getRedisConnection(),
240 prefix: this.jobRedisPrefix,
241 maxStalledCount: 10
242 }
243 this.queueSchedulers[handlerName] = new QueueScheduler(handlerName, queueSchedulerOptions)
244 }
245
246 private buildQueueEvent (handlerName: JobType, produceOnly: boolean) {
247 const queueEventsOptions: QueueEventsOptions = {
248 autorun: !produceOnly,
249 connection: this.getRedisConnection(),
250 prefix: this.jobRedisPrefix
251 }
252 this.queueEvents[handlerName] = new QueueEvents(handlerName, queueEventsOptions)
253 }
254
255 private getRedisConnection () {
256 return {
257 password: CONFIG.REDIS.AUTH,
258 db: CONFIG.REDIS.DB,
259 host: CONFIG.REDIS.HOSTNAME,
260 port: CONFIG.REDIS.PORT,
261 path: CONFIG.REDIS.SOCKET
262 }
263 }
264
265 // ---------------------------------------------------------------------------
266
267 async terminate () {
268 const promises = Object.keys(this.workers)
269 .map(handlerName => {
270 const worker: Worker = this.workers[handlerName]
271 const queue: Queue = this.queues[handlerName]
272 const queueScheduler: QueueScheduler = this.queueSchedulers[handlerName]
273 const queueEvent: QueueEvents = this.queueEvents[handlerName]
274
275 return Promise.all([
276 worker.close(false),
277 queue.close(),
278 queueScheduler.close(),
279 queueEvent.close()
280 ])
281 })
282
283 return Promise.all(promises)
284 }
285
286 async pause () {
287 for (const handler of Object.keys(this.workers)) {
288 const worker: Worker = this.workers[handler]
289
290 await worker.pause()
291 }
292 }
293
294 resume () {
295 for (const handler of Object.keys(this.workers)) {
296 const worker: Worker = this.workers[handler]
297
298 worker.resume()
299 }
300 }
301
302 // ---------------------------------------------------------------------------
303
304 createJobAsync (options: CreateJobArgument & CreateJobOptions): void {
305 this.createJob(options)
306 .catch(err => logger.error('Cannot create job.', { err, options }))
307 }
308
309 async createJob (options: CreateJobArgument & CreateJobOptions) {
310 const queue: Queue = this.queues[options.type]
311 if (queue === undefined) {
312 logger.error('Unknown queue %s: cannot create job.', options.type)
313 return
314 }
315
316 const jobOptions = this.buildJobOptions(options.type as JobType, pick(options, [ 'priority', 'delay' ]))
317
318 return queue.add('job', options.payload, jobOptions)
319 }
320
321 async createSequentialJobFlow (...jobs: ((CreateJobArgument & CreateJobOptions) | undefined)[]) {
322 let lastJob: FlowJob
323
324 for (const job of jobs) {
325 if (!job) continue
326
327 lastJob = {
328 name: 'job',
329 data: job.payload,
330 queueName: job.type,
331 opts: this.buildJobOptions(job.type as JobType, pick(job, [ 'priority', 'delay' ])),
332 children: lastJob
333 ? [ lastJob ]
334 : []
335 }
336 }
337
338 return this.flowProducer.add(lastJob)
339 }
340
341 private buildJobOptions (type: JobType, options: CreateJobOptions = {}): JobsOptions {
342 return {
343 backoff: { delay: 60 * 1000, type: 'exponential' },
344 attempts: JOB_ATTEMPTS[type],
345 priority: options.priority,
346 delay: options.delay
347 }
348 }
349
350 // ---------------------------------------------------------------------------
351
352 async listForApi (options: {
353 state?: JobState
354 start: number
355 count: number
356 asc?: boolean
357 jobType: JobType
358 }): Promise<Job[]> {
359 const { state, start, count, asc, jobType } = options
360
361 const states = state ? [ state ] : jobStates
362 let results: Job[] = []
363
364 const filteredJobTypes = this.filterJobTypes(jobType)
365
366 for (const jobType of filteredJobTypes) {
367 const queue: Queue = this.queues[jobType]
368
369 if (queue === undefined) {
370 logger.error('Unknown queue %s to list jobs.', jobType)
371 continue
372 }
373
374 const jobs = await queue.getJobs(states, 0, start + count, asc)
375 results = results.concat(jobs)
376 }
377
378 results.sort((j1: any, j2: any) => {
379 if (j1.timestamp < j2.timestamp) return -1
380 else if (j1.timestamp === j2.timestamp) return 0
381
382 return 1
383 })
384
385 if (asc === false) results.reverse()
386
387 return results.slice(start, start + count)
388 }
389
390 async count (state: JobState, jobType?: JobType): Promise<number> {
391 const states = state ? [ state ] : jobStates
392 let total = 0
393
394 const filteredJobTypes = this.filterJobTypes(jobType)
395
396 for (const type of filteredJobTypes) {
397 const queue = this.queues[type]
398 if (queue === undefined) {
399 logger.error('Unknown queue %s to count jobs.', type)
400 continue
401 }
402
403 const counts = await queue.getJobCounts()
404
405 for (const s of states) {
406 total += counts[s]
407 }
408 }
409
410 return total
411 }
412
413 async getStats () {
414 const promises = jobTypes.map(async t => ({ jobType: t, counts: await this.queues[t].getJobCounts() }))
415
416 return Promise.all(promises)
417 }
418
419 // ---------------------------------------------------------------------------
420
421 async removeOldJobs () {
422 for (const key of Object.keys(this.queues)) {
423 const queue: Queue = this.queues[key]
424 await queue.clean(JOB_COMPLETED_LIFETIME, 100, 'completed')
425 }
426 }
427
428 waitJob (job: Job) {
429 return job.waitUntilFinished(this.queueEvents[job.queueName])
430 }
431
432 private addRepeatableJobs () {
433 this.queues['videos-views-stats'].add('job', {}, {
434 repeat: REPEAT_JOBS['videos-views-stats']
435 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
436
437 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
438 this.queues['activitypub-cleaner'].add('job', {}, {
439 repeat: REPEAT_JOBS['activitypub-cleaner']
440 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
441 }
442 }
443
444 private filterJobTypes (jobType?: JobType) {
445 if (!jobType) return jobTypes
446
447 return jobTypes.filter(t => t === jobType)
448 }
449
450 private getJobConcurrency (jobType: JobType) {
451 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
452 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
453
454 return JOB_CONCURRENCY[jobType]
455 }
456
457 static get Instance () {
458 return this.instance || (this.instance = new this())
459 }
460 }
461
462 // ---------------------------------------------------------------------------
463
464 export {
465 jobTypes,
466 JobQueue
467 }