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