]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/job-queue.ts
22bd1f5d2c70b3d8a8228aef440f4c70d7f7d552
[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 async pause () {
166 for (const handler of Object.keys(this.queues)) {
167 await this.queues[handler].pause(true)
168 }
169 }
170
171 async resume () {
172 for (const handler of Object.keys(this.queues)) {
173 await this.queues[handler].resume(true)
174 }
175 }
176
177 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
178 this.createJobWithPromise(obj, options)
179 .catch(err => logger.error('Cannot create job.', { err, obj }))
180 }
181
182 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
183 const queue = this.queues[obj.type]
184 if (queue === undefined) {
185 logger.error('Unknown queue %s: cannot create job.', obj.type)
186 return
187 }
188
189 const jobArgs: JobOptions = {
190 backoff: { delay: 60 * 1000, type: 'exponential' },
191 attempts: JOB_ATTEMPTS[obj.type],
192 timeout: JOB_TTL[obj.type],
193 priority: options.priority,
194 delay: options.delay
195 }
196
197 return queue.add(obj.payload, jobArgs)
198 }
199
200 async listForApi (options: {
201 state?: JobState
202 start: number
203 count: number
204 asc?: boolean
205 jobType: JobType
206 }): Promise<Job[]> {
207 const { state, start, count, asc, jobType } = options
208
209 const states = state ? [ state ] : jobStates
210 let results: Job[] = []
211
212 const filteredJobTypes = this.filterJobTypes(jobType)
213
214 for (const jobType of filteredJobTypes) {
215 const queue = this.queues[jobType]
216 if (queue === undefined) {
217 logger.error('Unknown queue %s to list jobs.', jobType)
218 continue
219 }
220
221 const jobs = await queue.getJobs(states, 0, start + count, asc)
222 results = results.concat(jobs)
223 }
224
225 results.sort((j1: any, j2: any) => {
226 if (j1.timestamp < j2.timestamp) return -1
227 else if (j1.timestamp === j2.timestamp) return 0
228
229 return 1
230 })
231
232 if (asc === false) results.reverse()
233
234 return results.slice(start, start + count)
235 }
236
237 async count (state: JobState, jobType?: JobType): Promise<number> {
238 const states = state ? [ state ] : jobStates
239 let total = 0
240
241 const filteredJobTypes = this.filterJobTypes(jobType)
242
243 for (const type of filteredJobTypes) {
244 const queue = this.queues[type]
245 if (queue === undefined) {
246 logger.error('Unknown queue %s to count jobs.', type)
247 continue
248 }
249
250 const counts = await queue.getJobCounts()
251
252 for (const s of states) {
253 total += counts[s]
254 }
255 }
256
257 return total
258 }
259
260 async removeOldJobs () {
261 for (const key of Object.keys(this.queues)) {
262 const queue = this.queues[key]
263 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
264 }
265 }
266
267 private addRepeatableJobs () {
268 this.queues['videos-views-stats'].add({}, {
269 repeat: REPEAT_JOBS['videos-views-stats']
270 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
271
272 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
273 this.queues['activitypub-cleaner'].add({}, {
274 repeat: REPEAT_JOBS['activitypub-cleaner']
275 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
276 }
277 }
278
279 private filterJobTypes (jobType?: JobType) {
280 if (!jobType) return jobTypes
281
282 return jobTypes.filter(t => t === jobType)
283 }
284
285 private getJobConcurrency (jobType: JobType) {
286 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
287 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
288
289 return JOB_CONCURRENCY[jobType]
290 }
291
292 static get Instance () {
293 return this.instance || (this.instance = new this())
294 }
295 }
296
297 // ---------------------------------------------------------------------------
298
299 export {
300 jobTypes,
301 JobQueue
302 }