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