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