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