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,
46 VideoStudioTranscodingSuccess,
47 VODAudioMergeTranscodingSuccess,
48 VODHLSTranscodingSuccess,
49 VODWebVideoTranscodingSuccess
50 } from '@shared/models'
52 const postRunnerJobSuccessVideoFiles = createReqFiles(
53 [ 'payload[videoFile]', 'payload[resolutionPlaylistFile]' ],
54 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.M3U8.MIMETYPE_EXT }
57 const runnerJobUpdateVideoFiles = createReqFiles(
58 [ 'payload[videoChunkFile]', 'payload[resolutionPlaylistFile]', 'payload[masterPlaylistFile]' ],
59 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.M3U8.MIMETYPE_EXT }
62 const lTags = loggerTagsFactory('api', 'runner')
64 const runnerJobsRouter = express.Router()
66 // ---------------------------------------------------------------------------
67 // Controllers for runners
68 // ---------------------------------------------------------------------------
70 runnerJobsRouter.post('/jobs/request',
71 asyncMiddleware(getRunnerFromTokenValidator),
72 asyncMiddleware(requestRunnerJob)
75 runnerJobsRouter.post('/jobs/:jobUUID/accept',
76 asyncMiddleware(runnerJobGetValidator),
77 acceptRunnerJobValidator,
78 asyncMiddleware(getRunnerFromTokenValidator),
79 asyncMiddleware(acceptRunnerJob)
82 runnerJobsRouter.post('/jobs/:jobUUID/abort',
83 asyncMiddleware(jobOfRunnerGetValidator),
84 abortRunnerJobValidator,
85 asyncMiddleware(abortRunnerJob)
88 runnerJobsRouter.post('/jobs/:jobUUID/update',
89 runnerJobUpdateVideoFiles,
90 asyncMiddleware(jobOfRunnerGetValidator),
91 updateRunnerJobValidator,
92 asyncMiddleware(updateRunnerJobController)
95 runnerJobsRouter.post('/jobs/:jobUUID/error',
96 asyncMiddleware(jobOfRunnerGetValidator),
97 errorRunnerJobValidator,
98 asyncMiddleware(errorRunnerJob)
101 runnerJobsRouter.post('/jobs/:jobUUID/success',
102 postRunnerJobSuccessVideoFiles,
103 asyncMiddleware(jobOfRunnerGetValidator),
104 successRunnerJobValidator,
105 asyncMiddleware(postRunnerJobSuccess)
108 // ---------------------------------------------------------------------------
109 // Controllers for admins
110 // ---------------------------------------------------------------------------
112 runnerJobsRouter.post('/jobs/:jobUUID/cancel',
114 ensureUserHasRight(UserRight.MANAGE_RUNNERS),
115 asyncMiddleware(runnerJobGetValidator),
116 cancelRunnerJobValidator,
117 asyncMiddleware(cancelRunnerJob)
120 runnerJobsRouter.get('/jobs',
122 ensureUserHasRight(UserRight.MANAGE_RUNNERS),
124 runnerJobsSortValidator,
126 setDefaultPagination,
127 asyncMiddleware(listRunnerJobs)
130 // ---------------------------------------------------------------------------
136 // ---------------------------------------------------------------------------
138 // ---------------------------------------------------------------------------
139 // Controllers for runners
140 // ---------------------------------------------------------------------------
142 async function requestRunnerJob (req: express.Request, res: express.Response) {
143 const runner = res.locals.runner
144 const availableJobs = await RunnerJobModel.listAvailableJobs()
146 logger.debug('Runner %s requests for a job.', runner.name, { availableJobs, ...lTags(runner.name) })
148 const result: RequestRunnerJobResult = {
149 availableJobs: availableJobs.map(j => ({
156 updateLastRunnerContact(req, runner)
158 return res.json(result)
161 async function acceptRunnerJob (req: express.Request, res: express.Response) {
162 const runner = res.locals.runner
163 const runnerJob = res.locals.runnerJob
165 const newRunnerJob = await retryTransactionWrapper(() => {
166 return sequelizeTypescript.transaction(async transaction => {
167 await runnerJob.reload({ transaction })
169 if (runnerJob.state !== RunnerJobState.PENDING) {
171 message: 'This job is not in pending state anymore',
172 status: HttpStatusCode.CONFLICT_409
178 runnerJob.state = RunnerJobState.PROCESSING
179 runnerJob.processingJobToken = generateRunnerJobToken()
180 runnerJob.startedAt = new Date()
181 runnerJob.runnerId = runner.id
183 return runnerJob.save({ transaction })
186 if (!newRunnerJob) return
188 newRunnerJob.Runner = runner as RunnerModel
190 const result: AcceptRunnerJobResult = {
192 ...newRunnerJob.toFormattedJSON(),
194 jobToken: newRunnerJob.processingJobToken
198 updateLastRunnerContact(req, runner)
201 'Remote runner %s has accepted job %s (%s)', runner.name, runnerJob.uuid, runnerJob.type,
202 lTags(runner.name, runnerJob.uuid, runnerJob.type)
205 return res.json(result)
208 async function abortRunnerJob (req: express.Request, res: express.Response) {
209 const runnerJob = res.locals.runnerJob
210 const runner = runnerJob.Runner
211 const body: AbortRunnerJobBody = req.body
214 'Remote runner %s is aborting job %s (%s)', runner.name, runnerJob.uuid, runnerJob.type,
215 { reason: body.reason, ...lTags(runner.name, runnerJob.uuid, runnerJob.type) }
218 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
219 await new RunnerJobHandler().abort({ runnerJob })
221 updateLastRunnerContact(req, runnerJob.Runner)
223 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
226 async function errorRunnerJob (req: express.Request, res: express.Response) {
227 const runnerJob = res.locals.runnerJob
228 const runner = runnerJob.Runner
229 const body: ErrorRunnerJobBody = req.body
231 runnerJob.failures += 1
234 'Remote runner %s had an error with job %s (%s)', runner.name, runnerJob.uuid, runnerJob.type,
235 { errorMessage: body.message, totalFailures: runnerJob.failures, ...lTags(runner.name, runnerJob.uuid, runnerJob.type) }
238 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
239 await new RunnerJobHandler().error({ runnerJob, message: body.message })
241 updateLastRunnerContact(req, runnerJob.Runner)
243 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
246 // ---------------------------------------------------------------------------
248 const jobUpdateBuilders: {
249 [id in RunnerJobType]?: (payload: RunnerJobUpdatePayload, files?: UploadFiles) => RunnerJobUpdatePayload
251 'live-rtmp-hls-transcoding': (payload: LiveRTMPHLSTranscodingUpdatePayload, files) => {
255 masterPlaylistFile: files['payload[masterPlaylistFile]']?.[0].path,
256 resolutionPlaylistFile: files['payload[resolutionPlaylistFile]']?.[0].path,
257 videoChunkFile: files['payload[videoChunkFile]']?.[0].path
262 async function updateRunnerJobController (req: express.Request, res: express.Response) {
263 const runnerJob = res.locals.runnerJob
264 const runner = runnerJob.Runner
265 const body: RunnerJobUpdateBody = req.body
267 const payloadBuilder = jobUpdateBuilders[runnerJob.type]
268 const updatePayload = payloadBuilder
269 ? payloadBuilder(body.payload, req.files as UploadFiles)
273 'Remote runner %s is updating job %s (%s)', runnerJob.Runner.name, runnerJob.uuid, runnerJob.type,
274 { body, updatePayload, ...lTags(runner.name, runnerJob.uuid, runnerJob.type) }
277 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
278 await new RunnerJobHandler().update({
280 progress: req.body.progress,
284 updateLastRunnerContact(req, runnerJob.Runner)
286 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
289 // ---------------------------------------------------------------------------
291 const jobSuccessPayloadBuilders: {
292 [id in RunnerJobType]: (payload: RunnerJobSuccessPayload, files?: UploadFiles) => RunnerJobSuccessPayload
294 'vod-web-video-transcoding': (payload: VODWebVideoTranscodingSuccess, files) => {
298 videoFile: files['payload[videoFile]'][0].path
302 'vod-hls-transcoding': (payload: VODHLSTranscodingSuccess, files) => {
306 videoFile: files['payload[videoFile]'][0].path,
307 resolutionPlaylistFile: files['payload[resolutionPlaylistFile]'][0].path
311 'vod-audio-merge-transcoding': (payload: VODAudioMergeTranscodingSuccess, files) => {
315 videoFile: files['payload[videoFile]'][0].path
319 'video-studio-transcoding': (payload: VideoStudioTranscodingSuccess, files) => {
323 videoFile: files['payload[videoFile]'][0].path
327 'live-rtmp-hls-transcoding': () => ({})
330 async function postRunnerJobSuccess (req: express.Request, res: express.Response) {
331 const runnerJob = res.locals.runnerJob
332 const runner = runnerJob.Runner
333 const body: RunnerJobSuccessBody = req.body
335 const resultPayload = jobSuccessPayloadBuilders[runnerJob.type](body.payload, req.files as UploadFiles)
338 'Remote runner %s is sending success result for job %s (%s)', runnerJob.Runner.name, runnerJob.uuid, runnerJob.type,
339 { resultPayload, ...lTags(runner.name, runnerJob.uuid, runnerJob.type) }
342 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
343 await new RunnerJobHandler().complete({ runnerJob, resultPayload })
345 updateLastRunnerContact(req, runnerJob.Runner)
347 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
350 // ---------------------------------------------------------------------------
351 // Controllers for admins
352 // ---------------------------------------------------------------------------
354 async function cancelRunnerJob (req: express.Request, res: express.Response) {
355 const runnerJob = res.locals.runnerJob
357 logger.info('Cancelling job %s (%s)', runnerJob.uuid, runnerJob.type, lTags(runnerJob.uuid, runnerJob.type))
359 const RunnerJobHandler = getRunnerJobHandlerClass(runnerJob)
360 await new RunnerJobHandler().cancel({ runnerJob })
362 return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
365 async function listRunnerJobs (req: express.Request, res: express.Response) {
366 const query: ListRunnerJobsQuery = req.query
368 const resultList = await RunnerJobModel.listForApi({
376 total: resultList.total,
377 data: resultList.data.map(d => d.toFormattedAdminJSON())