]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/job-queue.ts
0ae325f4d979713e0ea28e635d7b2ded6047487a
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / job-queue.ts
1 import Bull, { Job, JobOptions, Queue } from 'bull'
2 import { jobStates } from '@server/helpers/custom-validators/jobs'
3 import { CONFIG } from '@server/initializers/config'
4 import { processVideoRedundancy } from '@server/lib/job-queue/handlers/video-redundancy'
5 import {
6 ActivitypubFollowPayload,
7 ActivitypubHttpBroadcastPayload,
8 ActivitypubHttpFetcherPayload,
9 ActivitypubHttpUnicastPayload,
10 ActorKeysPayload,
11 DeleteResumableUploadMetaFilePayload,
12 EmailPayload,
13 JobState,
14 JobType,
15 ManageVideoTorrentPayload,
16 MoveObjectStoragePayload,
17 RefreshPayload,
18 VideoFileImportPayload,
19 VideoImportPayload,
20 VideoLiveEndingPayload,
21 VideoRedundancyPayload,
22 VideoStudioEditionPayload,
23 VideoTranscodingPayload
24 } from '../../../shared/models'
25 import { logger } from '../../helpers/logger'
26 import { JOB_ATTEMPTS, JOB_COMPLETED_LIFETIME, JOB_CONCURRENCY, JOB_TTL, REPEAT_JOBS, WEBSERVER } from '../../initializers/constants'
27 import { Hooks } from '../plugins/hooks'
28 import { processActivityPubCleaner } from './handlers/activitypub-cleaner'
29 import { processActivityPubFollow } from './handlers/activitypub-follow'
30 import { processActivityPubHttpBroadcast } from './handlers/activitypub-http-broadcast'
31 import { processActivityPubHttpFetcher } from './handlers/activitypub-http-fetcher'
32 import { processActivityPubHttpUnicast } from './handlers/activitypub-http-unicast'
33 import { refreshAPObject } from './handlers/activitypub-refresher'
34 import { processActorKeys } from './handlers/actor-keys'
35 import { processEmail } from './handlers/email'
36 import { processManageVideoTorrent } from './handlers/manage-video-torrent'
37 import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage'
38 import { processVideoFileImport } from './handlers/video-file-import'
39 import { processVideoImport } from './handlers/video-import'
40 import { processVideoLiveEnding } from './handlers/video-live-ending'
41 import { processVideoStudioEdition } from './handlers/video-studio-edition'
42 import { processVideoTranscoding } from './handlers/video-transcoding'
43 import { processVideosViewsStats } from './handlers/video-views-stats'
44
45 type CreateJobArgument =
46 { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } |
47 { type: 'activitypub-http-broadcast-parallel', payload: ActivitypubHttpBroadcastPayload } |
48 { type: 'activitypub-http-unicast', payload: ActivitypubHttpUnicastPayload } |
49 { type: 'activitypub-http-fetcher', payload: ActivitypubHttpFetcherPayload } |
50 { type: 'activitypub-http-cleaner', payload: {} } |
51 { type: 'activitypub-follow', payload: ActivitypubFollowPayload } |
52 { type: 'video-file-import', payload: VideoFileImportPayload } |
53 { type: 'video-transcoding', payload: VideoTranscodingPayload } |
54 { type: 'email', payload: EmailPayload } |
55 { type: 'video-import', payload: VideoImportPayload } |
56 { type: 'activitypub-refresher', payload: RefreshPayload } |
57 { type: 'videos-views-stats', payload: {} } |
58 { type: 'video-live-ending', payload: VideoLiveEndingPayload } |
59 { type: 'actor-keys', payload: ActorKeysPayload } |
60 { type: 'video-redundancy', payload: VideoRedundancyPayload } |
61 { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } |
62 { type: 'video-studio-edition', payload: VideoStudioEditionPayload } |
63 { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } |
64 { type: 'move-to-object-storage', payload: MoveObjectStoragePayload }
65
66 export type CreateJobOptions = {
67 delay?: number
68 priority?: number
69 }
70
71 const handlers: { [id in JobType]: (job: Job) => Promise<any> } = {
72 'activitypub-http-broadcast': processActivityPubHttpBroadcast,
73 'activitypub-http-broadcast-parallel': processActivityPubHttpBroadcast,
74 'activitypub-http-unicast': processActivityPubHttpUnicast,
75 'activitypub-http-fetcher': processActivityPubHttpFetcher,
76 'activitypub-cleaner': processActivityPubCleaner,
77 'activitypub-follow': processActivityPubFollow,
78 'video-file-import': processVideoFileImport,
79 'video-transcoding': processVideoTranscoding,
80 'email': processEmail,
81 'video-import': processVideoImport,
82 'videos-views-stats': processVideosViewsStats,
83 'activitypub-refresher': refreshAPObject,
84 'video-live-ending': processVideoLiveEnding,
85 'actor-keys': processActorKeys,
86 'video-redundancy': processVideoRedundancy,
87 'move-to-object-storage': processMoveToObjectStorage,
88 'manage-video-torrent': processManageVideoTorrent,
89 'video-studio-edition': processVideoStudioEdition
90 }
91
92 const errorHandlers: { [id in JobType]?: (job: Job, err: any) => Promise<any> } = {
93 'move-to-object-storage': onMoveToObjectStorageFailure
94 }
95
96 const jobTypes: JobType[] = [
97 'activitypub-follow',
98 'activitypub-http-broadcast',
99 'activitypub-http-broadcast-parallel',
100 'activitypub-http-fetcher',
101 'activitypub-http-unicast',
102 'activitypub-cleaner',
103 'email',
104 'video-transcoding',
105 'video-file-import',
106 'video-import',
107 'videos-views-stats',
108 'activitypub-refresher',
109 'video-redundancy',
110 'actor-keys',
111 'video-live-ending',
112 'move-to-object-storage',
113 'manage-video-torrent',
114 'video-studio-edition'
115 ]
116
117 const silentFailure = new Set<JobType>([ 'activitypub-http-unicast' ])
118
119 class JobQueue {
120
121 private static instance: JobQueue
122
123 private queues: { [id in JobType]?: Queue } = {}
124 private initialized = false
125 private jobRedisPrefix: string
126
127 private constructor () {
128 }
129
130 init (produceOnly = false) {
131 // Already initialized
132 if (this.initialized === true) return
133 this.initialized = true
134
135 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
136
137 const queueOptions: Bull.QueueOptions = {
138 prefix: this.jobRedisPrefix,
139 redis: {
140 password: CONFIG.REDIS.AUTH,
141 db: CONFIG.REDIS.DB,
142 host: CONFIG.REDIS.HOSTNAME,
143 port: CONFIG.REDIS.PORT,
144 path: CONFIG.REDIS.SOCKET
145 },
146 settings: {
147 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
148 }
149 }
150
151 for (const handlerName of (Object.keys(handlers) as JobType[])) {
152 const queue = new Bull(handlerName, queueOptions)
153
154 if (produceOnly) {
155 queue.pause(true)
156 .catch(err => logger.error('Cannot pause queue %s in produced only job queue', handlerName, { err }))
157 }
158
159 const handler = handlers[handlerName]
160
161 queue.process(this.getJobConcurrency(handlerName), async (jobArg: Job<any>) => {
162 const job = await Hooks.wrapObject(jobArg, 'filter:job-queue.process.params', { type: handlerName })
163
164 return Hooks.wrapPromiseFun(handler, job, 'filter:job-queue.process.result')
165 }).catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
166
167 queue.on('failed', (job, err) => {
168 const logLevel = silentFailure.has(handlerName)
169 ? 'debug'
170 : 'error'
171
172 logger.log(logLevel, 'Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
173
174 if (errorHandlers[job.name]) {
175 errorHandlers[job.name](job, err)
176 .catch(err => logger.error('Cannot run error handler for job failure %d in queue %s.', job.id, handlerName, { err }))
177 }
178 })
179
180 queue.on('error', err => {
181 logger.error('Error in job queue %s.', handlerName, { err })
182 })
183
184 this.queues[handlerName] = queue
185 }
186
187 this.addRepeatableJobs()
188 }
189
190 terminate () {
191 for (const queueName of Object.keys(this.queues)) {
192 const queue = this.queues[queueName]
193 queue.close()
194 }
195 }
196
197 async pause () {
198 for (const handler of Object.keys(this.queues)) {
199 await this.queues[handler].pause(true)
200 }
201 }
202
203 async resume () {
204 for (const handler of Object.keys(this.queues)) {
205 await this.queues[handler].resume(true)
206 }
207 }
208
209 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
210 this.createJobWithPromise(obj, options)
211 .catch(err => logger.error('Cannot create job.', { err, obj }))
212 }
213
214 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
215 const queue: Queue = this.queues[obj.type]
216 if (queue === undefined) {
217 logger.error('Unknown queue %s: cannot create job.', obj.type)
218 return
219 }
220
221 const jobArgs: JobOptions = {
222 backoff: { delay: 60 * 1000, type: 'exponential' },
223 attempts: JOB_ATTEMPTS[obj.type],
224 timeout: JOB_TTL[obj.type],
225 priority: options.priority,
226 delay: options.delay
227 }
228
229 return queue.add(obj.payload, jobArgs)
230 }
231
232 async listForApi (options: {
233 state?: JobState
234 start: number
235 count: number
236 asc?: boolean
237 jobType: JobType
238 }): Promise<Job[]> {
239 const { state, start, count, asc, jobType } = options
240
241 const states = state ? [ state ] : jobStates
242 let results: Job[] = []
243
244 const filteredJobTypes = this.filterJobTypes(jobType)
245
246 for (const jobType of filteredJobTypes) {
247 const queue = this.queues[jobType]
248 if (queue === undefined) {
249 logger.error('Unknown queue %s to list jobs.', jobType)
250 continue
251 }
252
253 const jobs = await queue.getJobs(states, 0, start + count, asc)
254 results = results.concat(jobs)
255 }
256
257 results.sort((j1: any, j2: any) => {
258 if (j1.timestamp < j2.timestamp) return -1
259 else if (j1.timestamp === j2.timestamp) return 0
260
261 return 1
262 })
263
264 if (asc === false) results.reverse()
265
266 return results.slice(start, start + count)
267 }
268
269 async count (state: JobState, jobType?: JobType): Promise<number> {
270 const states = state ? [ state ] : jobStates
271 let total = 0
272
273 const filteredJobTypes = this.filterJobTypes(jobType)
274
275 for (const type of filteredJobTypes) {
276 const queue = this.queues[type]
277 if (queue === undefined) {
278 logger.error('Unknown queue %s to count jobs.', type)
279 continue
280 }
281
282 const counts = await queue.getJobCounts()
283
284 for (const s of states) {
285 total += counts[s]
286 }
287 }
288
289 return total
290 }
291
292 async getStats () {
293 const promises = jobTypes.map(async t => ({ jobType: t, counts: await this.queues[t].getJobCounts() }))
294
295 return Promise.all(promises)
296 }
297
298 async removeOldJobs () {
299 for (const key of Object.keys(this.queues)) {
300 const queue = this.queues[key]
301 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
302 }
303 }
304
305 private addRepeatableJobs () {
306 this.queues['videos-views-stats'].add({}, {
307 repeat: REPEAT_JOBS['videos-views-stats']
308 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
309
310 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
311 this.queues['activitypub-cleaner'].add({}, {
312 repeat: REPEAT_JOBS['activitypub-cleaner']
313 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
314 }
315 }
316
317 private filterJobTypes (jobType?: JobType) {
318 if (!jobType) return jobTypes
319
320 return jobTypes.filter(t => t === jobType)
321 }
322
323 private getJobConcurrency (jobType: JobType) {
324 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
325 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
326
327 return JOB_CONCURRENCY[jobType]
328 }
329
330 static get Instance () {
331 return this.instance || (this.instance = new this())
332 }
333 }
334
335 // ---------------------------------------------------------------------------
336
337 export {
338 jobTypes,
339 JobQueue
340 }