1 import { retryTransactionWrapper } from '@server/helpers/database-utils'
2 import { logger, loggerTagsFactory } from '@server/helpers/logger'
3 import { RUNNER_JOBS } from '@server/initializers/constants'
4 import { sequelizeTypescript } from '@server/initializers/database'
5 import { PeerTubeSocket } from '@server/lib/peertube-socket'
6 import { RunnerJobModel } from '@server/models/runner/runner-job'
7 import { setAsUpdated } from '@server/models/shared'
8 import { MRunnerJob } from '@server/types/models/runners'
9 import { pick } from '@shared/core-utils'
11 RunnerJobLiveRTMPHLSTranscodingPayload,
12 RunnerJobLiveRTMPHLSTranscodingPrivatePayload,
14 RunnerJobSuccessPayload,
16 RunnerJobUpdatePayload,
17 RunnerJobVODAudioMergeTranscodingPayload,
18 RunnerJobVODAudioMergeTranscodingPrivatePayload,
19 RunnerJobVODHLSTranscodingPayload,
20 RunnerJobVODHLSTranscodingPrivatePayload,
21 RunnerJobVODWebVideoTranscodingPayload,
22 RunnerJobVODWebVideoTranscodingPrivatePayload
23 } from '@shared/models'
24 import { throttle } from 'lodash'
26 type CreateRunnerJobArg =
28 type: Extract<RunnerJobType, 'vod-web-video-transcoding'>
29 payload: RunnerJobVODWebVideoTranscodingPayload
30 privatePayload: RunnerJobVODWebVideoTranscodingPrivatePayload
33 type: Extract<RunnerJobType, 'vod-hls-transcoding'>
34 payload: RunnerJobVODHLSTranscodingPayload
35 privatePayload: RunnerJobVODHLSTranscodingPrivatePayload
38 type: Extract<RunnerJobType, 'vod-audio-merge-transcoding'>
39 payload: RunnerJobVODAudioMergeTranscodingPayload
40 privatePayload: RunnerJobVODAudioMergeTranscodingPrivatePayload
43 type: Extract<RunnerJobType, 'live-rtmp-hls-transcoding'>
44 payload: RunnerJobLiveRTMPHLSTranscodingPayload
45 privatePayload: RunnerJobLiveRTMPHLSTranscodingPrivatePayload
48 export abstract class AbstractJobHandler <C, U extends RunnerJobUpdatePayload, S extends RunnerJobSuccessPayload> {
50 protected readonly lTags = loggerTagsFactory('runner')
52 static setJobAsUpdatedThrottled = throttle(setAsUpdated, 2000)
54 // ---------------------------------------------------------------------------
56 abstract create (options: C): Promise<MRunnerJob>
58 protected async createRunnerJob (options: CreateRunnerJobArg & {
61 dependsOnRunnerJob?: MRunnerJob
62 }): Promise<MRunnerJob> {
63 const { priority, dependsOnRunnerJob } = options
65 const runnerJob = new RunnerJobModel({
66 ...pick(options, [ 'type', 'payload', 'privatePayload' ]),
68 uuid: options.jobUUID,
70 state: dependsOnRunnerJob
71 ? RunnerJobState.WAITING_FOR_PARENT_JOB
72 : RunnerJobState.PENDING,
74 dependsOnRunnerJobId: dependsOnRunnerJob?.id,
79 const job = await sequelizeTypescript.transaction(async transaction => {
80 return runnerJob.save({ transaction })
83 if (runnerJob.state === RunnerJobState.PENDING) {
84 PeerTubeSocket.Instance.sendAvailableJobsPingToRunners()
90 // ---------------------------------------------------------------------------
92 protected abstract specificUpdate (options: {
95 }): Promise<void> | void
97 async update (options: {
102 const { runnerJob, progress } = options
104 await this.specificUpdate(options)
106 if (progress) runnerJob.progress = progress
108 if (!runnerJob.changed()) {
110 await AbstractJobHandler.setJobAsUpdatedThrottled({ sequelize: sequelizeTypescript, table: 'runnerJob', id: runnerJob.id })
112 logger.warn('Cannot set remote job as updated', { err, ...this.lTags(runnerJob.id, runnerJob.type) })
118 await retryTransactionWrapper(() => {
119 return sequelizeTypescript.transaction(async transaction => {
120 return runnerJob.save({ transaction })
125 // ---------------------------------------------------------------------------
127 async complete (options: {
128 runnerJob: MRunnerJob
131 const { runnerJob } = options
134 await this.specificComplete(options)
136 runnerJob.state = RunnerJobState.COMPLETED
138 logger.error('Cannot complete runner job', { err, ...this.lTags(runnerJob.id, runnerJob.type) })
140 runnerJob.state = RunnerJobState.ERRORED
141 runnerJob.error = err.message
144 runnerJob.progress = null
145 runnerJob.finishedAt = new Date()
147 await retryTransactionWrapper(() => {
148 return sequelizeTypescript.transaction(async transaction => {
149 await runnerJob.save({ transaction })
153 const [ affectedCount ] = await RunnerJobModel.updateDependantJobsOf(runnerJob)
155 if (affectedCount !== 0) PeerTubeSocket.Instance.sendAvailableJobsPingToRunners()
158 protected abstract specificComplete (options: {
159 runnerJob: MRunnerJob
161 }): Promise<void> | void
163 // ---------------------------------------------------------------------------
165 async cancel (options: {
166 runnerJob: MRunnerJob
169 const { runnerJob, fromParent } = options
171 await this.specificCancel(options)
173 const cancelState = fromParent
174 ? RunnerJobState.PARENT_CANCELLED
175 : RunnerJobState.CANCELLED
177 runnerJob.setToErrorOrCancel(cancelState)
179 await retryTransactionWrapper(() => {
180 return sequelizeTypescript.transaction(async transaction => {
181 await runnerJob.save({ transaction })
185 const children = await RunnerJobModel.listChildrenOf(runnerJob)
186 for (const child of children) {
187 logger.info(`Cancelling child job ${child.uuid} of ${runnerJob.uuid} because of parent cancel`, this.lTags(child.uuid))
189 await this.cancel({ runnerJob: child, fromParent: true })
193 protected abstract specificCancel (options: {
194 runnerJob: MRunnerJob
195 }): Promise<void> | void
197 // ---------------------------------------------------------------------------
199 protected abstract isAbortSupported (): boolean
201 async abort (options: {
202 runnerJob: MRunnerJob
204 const { runnerJob } = options
206 if (this.isAbortSupported() !== true) {
207 return this.error({ runnerJob, message: 'Job has been aborted but it is not supported by this job type' })
210 await this.specificAbort(options)
212 runnerJob.resetToPending()
214 await retryTransactionWrapper(() => {
215 return sequelizeTypescript.transaction(async transaction => {
216 await runnerJob.save({ transaction })
221 protected setAbortState (runnerJob: MRunnerJob) {
222 runnerJob.resetToPending()
225 protected abstract specificAbort (options: {
226 runnerJob: MRunnerJob
227 }): Promise<void> | void
229 // ---------------------------------------------------------------------------
231 async error (options: {
232 runnerJob: MRunnerJob
236 const { runnerJob, message, fromParent } = options
238 const errorState = fromParent
239 ? RunnerJobState.PARENT_ERRORED
240 : RunnerJobState.ERRORED
242 const nextState = errorState === RunnerJobState.ERRORED && this.isAbortSupported() && runnerJob.failures < RUNNER_JOBS.MAX_FAILURES
243 ? RunnerJobState.PENDING
246 await this.specificError({ ...options, nextState })
248 if (nextState === errorState) {
249 runnerJob.setToErrorOrCancel(nextState)
250 runnerJob.error = message
252 runnerJob.resetToPending()
255 await retryTransactionWrapper(() => {
256 return sequelizeTypescript.transaction(async transaction => {
257 await runnerJob.save({ transaction })
261 if (runnerJob.state === errorState) {
262 const children = await RunnerJobModel.listChildrenOf(runnerJob)
264 for (const child of children) {
265 logger.info(`Erroring child job ${child.uuid} of ${runnerJob.uuid} because of parent error`, this.lTags(child.uuid))
267 await this.error({ runnerJob: child, message: 'Parent error', fromParent: true })
272 protected abstract specificError (options: {
273 runnerJob: MRunnerJob
275 nextState: RunnerJobState
276 }): Promise<void> | void