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