1 import express, { UploadFiles } from 'express'
2 import { retryTransactionWrapper } from '@server/helpers/database-utils'
3 import { createReqFiles } from '@server/helpers/express-utils'
4 import { logger, loggerTagsFactory } from '@server/helpers/logger'
5 import { generateRunnerJobToken } from '@server/helpers/token-generator'
6 import { MIMETYPES } from '@server/initializers/constants'
7 import { sequelizeTypescript } from '@server/initializers/database'
8 import { getRunnerJobHandlerClass, updateLastRunnerContact } from '@server/lib/runners'
14 runnerJobsSortValidator,
17 } from '@server/middlewares'
19 abortRunnerJobValidator,
20 acceptRunnerJobValidator,
21 cancelRunnerJobValidator,
22 errorRunnerJobValidator,
23 getRunnerFromTokenValidator,
24 jobOfRunnerGetValidator,
25 runnerJobGetValidator,
26 successRunnerJobValidator,
27 updateRunnerJobValidator
28 } from '@server/middlewares/validators/runners'
29 import { RunnerModel } from '@server/models/runner/runner'
30 import { RunnerJobModel } from '@server/models/runner/runner-job'
33 AcceptRunnerJobResult,
37 LiveRTMPHLSTranscodingUpdatePayload,
38 RequestRunnerJobResult,
41 RunnerJobSuccessPayload,
44 RunnerJobUpdatePayload,
47 VideoStudioTranscodingSuccess,
48 VODAudioMergeTranscodingSuccess,
49 VODHLSTranscodingSuccess,
50 VODWebVideoTranscodingSuccess
51 } from '@shared/models'
53 const postRunnerJobSuccessVideoFiles = createReqFiles(
54 [ 'payload[videoFile]', 'payload[resolutionPlaylistFile]' ],
55 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.M3U8.MIMETYPE_EXT }
58 const runnerJobUpdateVideoFiles = createReqFiles(
59 [ 'payload[videoChunkFile]', 'payload[resolutionPlaylistFile]', 'payload[masterPlaylistFile]' ],
60 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.M3U8.MIMETYPE_EXT }
63 const lTags = loggerTagsFactory('api', 'runner')
65 const runnerJobsRouter = express.Router()
67 // ---------------------------------------------------------------------------
68 // Controllers for runners
69 // ---------------------------------------------------------------------------
71 runnerJobsRouter.post('/jobs/request',
72 asyncMiddleware(getRunnerFromTokenValidator),
73 asyncMiddleware(requestRunnerJob)
76 runnerJobsRouter.post('/jobs/:jobUUID/accept',
77 asyncMiddleware(runnerJobGetValidator),
78 acceptRunnerJobValidator,
79 asyncMiddleware(getRunnerFromTokenValidator),
80 asyncMiddleware(acceptRunnerJob)
83 runnerJobsRouter.post('/jobs/:jobUUID/abort',
84 asyncMiddleware(jobOfRunnerGetValidator),
85 abortRunnerJobValidator,
86 asyncMiddleware(abortRunnerJob)
89 runnerJobsRouter.post('/jobs/:jobUUID/update',
90 runnerJobUpdateVideoFiles,
91 asyncMiddleware(jobOfRunnerGetValidator),
92 updateRunnerJobValidator,
93 asyncMiddleware(updateRunnerJobController)
96 runnerJobsRouter.post('/jobs/:jobUUID/error',
97 asyncMiddleware(jobOfRunnerGetValidator),
98 errorRunnerJobValidator,
99 asyncMiddleware(errorRunnerJob)
102 runnerJobsRouter.post('/jobs/:jobUUID/success',
103 postRunnerJobSuccessVideoFiles,
104 asyncMiddleware(jobOfRunnerGetValidator),
105 successRunnerJobValidator,
106 asyncMiddleware(postRunnerJobSuccess)
109 // ---------------------------------------------------------------------------
110 // Controllers for admins
111 // ---------------------------------------------------------------------------
113 runnerJobsRouter.post('/jobs/:jobUUID/cancel',
115 ensureUserHasRight(UserRight.MANAGE_RUNNERS),
116 asyncMiddleware(runnerJobGetValidator),
117 cancelRunnerJobValidator,
118 asyncMiddleware(cancelRunnerJob)
121 runnerJobsRouter.get('/jobs',
123 ensureUserHasRight(UserRight.MANAGE_RUNNERS),
125 runnerJobsSortValidator,
127 setDefaultPagination,
128 asyncMiddleware(listRunnerJobs)
131 // ---------------------------------------------------------------------------
137 // ---------------------------------------------------------------------------
139 // ---------------------------------------------------------------------------
140 // Controllers for runners
141 // ---------------------------------------------------------------------------
143 async function requestRunnerJob (req: express.Request, res: express.Response) {
144 const runner = res.locals.runner
145 const availableJobs = await RunnerJobModel.listAvailableJobs()
147 logger.debug('Runner %s requests for a job.', runner.name, { availableJobs, ...lTags(runner.name) })
149 const result: RequestRunnerJobResult = {
150 availableJobs: availableJobs.map(j => ({
157 updateLastRunnerContact(req, runner)
159 return res.json(result)
162 async function acceptRunnerJob (req: express.Request, res: express.Response) {
163 const runner = res.locals.runner
164 const runnerJob = res.locals.runnerJob
166 const newRunnerJob = await retryTransactionWrapper(() => {
167 return sequelizeTypescript.transaction(async transaction => {
168 await runnerJob.reload({ transaction })
170 if (runnerJob.state !== RunnerJobState.PENDING) {
172 type: ServerErrorCode.RUNNER_JOB_NOT_IN_PENDING_STATE,
173 message: 'This job is not in pending state anymore',
174 status: HttpStatusCode.CONFLICT_409
180 runnerJob.state = RunnerJobState.PROCESSING
181 runnerJob.processingJobToken = generateRunnerJobToken()
182 runnerJob.startedAt = new Date()
183 runnerJob.runnerId = runner.id
185 return runnerJob.save({ transaction })
188 if (!newRunnerJob) return
190 newRunnerJob.Runner = runner as RunnerModel
192 const result: AcceptRunnerJobResult = {
194 ...newRunnerJob.toFormattedJSON(),
196 jobToken: newRunnerJob.processingJobToken
200 updateLastRunnerContact(req, runner)
203 'Remote runner %s has accepted job %s (%s)', runner.name, runnerJob.uuid, runnerJob.type,
204 lTags(runner.name, runnerJob.uuid, runnerJob.type)
207 return res.json(result)
210 async function abortRunnerJob (req: express.Request, res: express.Response) {
211 const runnerJob = res.locals.runnerJob
212 const runner = runnerJob.Runner
213 const body: AbortRunnerJobBody = req.body
216 'Remote runner %s is aborting job %s (%s)', runner.name, runnerJob.uuid, runnerJob.type,
217 { reason: body.reason, ...lTags(runner.name, runnerJob.uuid, runnerJob.type) }
220 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
221 await new RunnerJobHandler().abort({ runnerJob })
223 updateLastRunnerContact(req, runnerJob.Runner)
225 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
228 async function errorRunnerJob (req: express.Request, res: express.Response) {
229 const runnerJob = res.locals.runnerJob
230 const runner = runnerJob.Runner
231 const body: ErrorRunnerJobBody = req.body
233 runnerJob.failures += 1
236 'Remote runner %s had an error with job %s (%s)', runner.name, runnerJob.uuid, runnerJob.type,
237 { errorMessage: body.message, totalFailures: runnerJob.failures, ...lTags(runner.name, runnerJob.uuid, runnerJob.type) }
240 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
241 await new RunnerJobHandler().error({ runnerJob, message: body.message })
243 updateLastRunnerContact(req, runnerJob.Runner)
245 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
248 // ---------------------------------------------------------------------------
250 const jobUpdateBuilders: {
251 [id in RunnerJobType]?: (payload: RunnerJobUpdatePayload, files?: UploadFiles) => RunnerJobUpdatePayload
253 'live-rtmp-hls-transcoding': (payload: LiveRTMPHLSTranscodingUpdatePayload, files) => {
257 masterPlaylistFile: files['payload[masterPlaylistFile]']?.[0].path,
258 resolutionPlaylistFile: files['payload[resolutionPlaylistFile]']?.[0].path,
259 videoChunkFile: files['payload[videoChunkFile]']?.[0].path
264 async function updateRunnerJobController (req: express.Request, res: express.Response) {
265 const runnerJob = res.locals.runnerJob
266 const runner = runnerJob.Runner
267 const body: RunnerJobUpdateBody = req.body
269 const payloadBuilder = jobUpdateBuilders[runnerJob.type]
270 const updatePayload = payloadBuilder
271 ? payloadBuilder(body.payload, req.files as UploadFiles)
275 'Remote runner %s is updating job %s (%s)', runnerJob.Runner.name, runnerJob.uuid, runnerJob.type,
276 { body, updatePayload, ...lTags(runner.name, runnerJob.uuid, runnerJob.type) }
279 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
280 await new RunnerJobHandler().update({
282 progress: req.body.progress,
286 updateLastRunnerContact(req, runnerJob.Runner)
288 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
291 // ---------------------------------------------------------------------------
293 const jobSuccessPayloadBuilders: {
294 [id in RunnerJobType]: (payload: RunnerJobSuccessPayload, files?: UploadFiles) => RunnerJobSuccessPayload
296 'vod-web-video-transcoding': (payload: VODWebVideoTranscodingSuccess, files) => {
300 videoFile: files['payload[videoFile]'][0].path
304 'vod-hls-transcoding': (payload: VODHLSTranscodingSuccess, files) => {
308 videoFile: files['payload[videoFile]'][0].path,
309 resolutionPlaylistFile: files['payload[resolutionPlaylistFile]'][0].path
313 'vod-audio-merge-transcoding': (payload: VODAudioMergeTranscodingSuccess, files) => {
317 videoFile: files['payload[videoFile]'][0].path
321 'video-studio-transcoding': (payload: VideoStudioTranscodingSuccess, files) => {
325 videoFile: files['payload[videoFile]'][0].path
329 'live-rtmp-hls-transcoding': () => ({})
332 async function postRunnerJobSuccess (req: express.Request, res: express.Response) {
333 const runnerJob = res.locals.runnerJob
334 const runner = runnerJob.Runner
335 const body: RunnerJobSuccessBody = req.body
337 const resultPayload = jobSuccessPayloadBuilders[runnerJob.type](body.payload, req.files as UploadFiles)
340 'Remote runner %s is sending success result for job %s (%s)', runnerJob.Runner.name, runnerJob.uuid, runnerJob.type,
341 { resultPayload, ...lTags(runner.name, runnerJob.uuid, runnerJob.type) }
344 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
345 await new RunnerJobHandler().complete({ runnerJob, resultPayload })
347 updateLastRunnerContact(req, runnerJob.Runner)
349 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
352 // ---------------------------------------------------------------------------
353 // Controllers for admins
354 // ---------------------------------------------------------------------------
356 async function cancelRunnerJob (req: express.Request, res: express.Response) {
357 const runnerJob = res.locals.runnerJob
359 logger.info('Cancelling job %s (%s)', runnerJob.uuid, runnerJob.type, lTags(runnerJob.uuid, runnerJob.type))
361 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
362 await new RunnerJobHandler().cancel({ runnerJob })
364 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
367 async function listRunnerJobs (req: express.Request, res: express.Response) {
368 const query: ListRunnerJobsQuery = req.query
370 const resultList = await RunnerJobModel.listForApi({
378 total: resultList.total,
379 data: resultList.data.map(d => d.toFormattedAdminJSON())