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