]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/job-queue.ts
Support video views/viewers stats in server
[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 class JobQueue {
110
111 private static instance: JobQueue
112
113 private queues: { [id in JobType]?: Queue } = {}
114 private initialized = false
115 private jobRedisPrefix: string
116
117 private constructor () {
118 }
119
120 init (produceOnly = false) {
121 // Already initialized
122 if (this.initialized === true) return
123 this.initialized = true
124
125 this.jobRedisPrefix = 'bull-' + WEBSERVER.HOST
126
127 const queueOptions: Bull.QueueOptions = {
128 prefix: this.jobRedisPrefix,
129 redis: {
130 password: CONFIG.REDIS.AUTH,
131 db: CONFIG.REDIS.DB,
132 host: CONFIG.REDIS.HOSTNAME,
133 port: CONFIG.REDIS.PORT,
134 path: CONFIG.REDIS.SOCKET
135 },
136 settings: {
137 maxStalledCount: 10 // transcoding could be long, so jobs can often be interrupted by restarts
138 }
139 }
140
141 for (const handlerName of (Object.keys(handlers) as JobType[])) {
142 const queue = new Bull(handlerName, queueOptions)
143
144 if (produceOnly) {
145 queue.pause(true)
146 .catch(err => logger.error('Cannot pause queue %s in produced only job queue', handlerName, { err }))
147 }
148
149 const handler = handlers[handlerName]
150
151 queue.process(this.getJobConcurrency(handlerName), handler)
152 .catch(err => logger.error('Error in job queue processor %s.', handlerName, { err }))
153
154 queue.on('failed', (job, err) => {
155 logger.error('Cannot execute job %d in queue %s.', job.id, handlerName, { payload: job.data, err })
156 })
157
158 queue.on('error', err => {
159 logger.error('Error in job queue %s.', handlerName, { err })
160 })
161
162 this.queues[handlerName] = queue
163 }
164
165 this.addRepeatableJobs()
166 }
167
168 terminate () {
169 for (const queueName of Object.keys(this.queues)) {
170 const queue = this.queues[queueName]
171 queue.close()
172 }
173 }
174
175 async pause () {
176 for (const handler of Object.keys(this.queues)) {
177 await this.queues[handler].pause(true)
178 }
179 }
180
181 async resume () {
182 for (const handler of Object.keys(this.queues)) {
183 await this.queues[handler].resume(true)
184 }
185 }
186
187 createJob (obj: CreateJobArgument, options: CreateJobOptions = {}): void {
188 this.createJobWithPromise(obj, options)
189 .catch(err => logger.error('Cannot create job.', { err, obj }))
190 }
191
192 createJobWithPromise (obj: CreateJobArgument, options: CreateJobOptions = {}) {
193 const queue: Queue = this.queues[obj.type]
194 if (queue === undefined) {
195 logger.error('Unknown queue %s: cannot create job.', obj.type)
196 return
197 }
198
199 const jobArgs: JobOptions = {
200 backoff: { delay: 60 * 1000, type: 'exponential' },
201 attempts: JOB_ATTEMPTS[obj.type],
202 timeout: JOB_TTL[obj.type],
203 priority: options.priority,
204 delay: options.delay
205 }
206
207 return queue.add(obj.payload, jobArgs)
208 }
209
210 async listForApi (options: {
211 state?: JobState
212 start: number
213 count: number
214 asc?: boolean
215 jobType: JobType
216 }): Promise<Job[]> {
217 const { state, start, count, asc, jobType } = options
218
219 const states = state ? [ state ] : jobStates
220 let results: Job[] = []
221
222 const filteredJobTypes = this.filterJobTypes(jobType)
223
224 for (const jobType of filteredJobTypes) {
225 const queue = this.queues[jobType]
226 if (queue === undefined) {
227 logger.error('Unknown queue %s to list jobs.', jobType)
228 continue
229 }
230
231 const jobs = await queue.getJobs(states, 0, start + count, asc)
232 results = results.concat(jobs)
233 }
234
235 results.sort((j1: any, j2: any) => {
236 if (j1.timestamp < j2.timestamp) return -1
237 else if (j1.timestamp === j2.timestamp) return 0
238
239 return 1
240 })
241
242 if (asc === false) results.reverse()
243
244 return results.slice(start, start + count)
245 }
246
247 async count (state: JobState, jobType?: JobType): Promise<number> {
248 const states = state ? [ state ] : jobStates
249 let total = 0
250
251 const filteredJobTypes = this.filterJobTypes(jobType)
252
253 for (const type of filteredJobTypes) {
254 const queue = this.queues[type]
255 if (queue === undefined) {
256 logger.error('Unknown queue %s to count jobs.', type)
257 continue
258 }
259
260 const counts = await queue.getJobCounts()
261
262 for (const s of states) {
263 total += counts[s]
264 }
265 }
266
267 return total
268 }
269
270 async removeOldJobs () {
271 for (const key of Object.keys(this.queues)) {
272 const queue = this.queues[key]
273 await queue.clean(JOB_COMPLETED_LIFETIME, 'completed')
274 }
275 }
276
277 private addRepeatableJobs () {
278 this.queues['videos-views-stats'].add({}, {
279 repeat: REPEAT_JOBS['videos-views-stats']
280 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
281
282 if (CONFIG.FEDERATION.VIDEOS.CLEANUP_REMOTE_INTERACTIONS) {
283 this.queues['activitypub-cleaner'].add({}, {
284 repeat: REPEAT_JOBS['activitypub-cleaner']
285 }).catch(err => logger.error('Cannot add repeatable job.', { err }))
286 }
287 }
288
289 private filterJobTypes (jobType?: JobType) {
290 if (!jobType) return jobTypes
291
292 return jobTypes.filter(t => t === jobType)
293 }
294
295 private getJobConcurrency (jobType: JobType) {
296 if (jobType === 'video-transcoding') return CONFIG.TRANSCODING.CONCURRENCY
297 if (jobType === 'video-import') return CONFIG.IMPORT.VIDEOS.CONCURRENCY
298
299 return JOB_CONCURRENCY[jobType]
300 }
301
302 static get Instance () {
303 return this.instance || (this.instance = new this())
304 }
305 }
306
307 // ---------------------------------------------------------------------------
308
309 export {
310 jobTypes,
311 JobQueue
312 }