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