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