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