ActivityPub-federated video streaming platform using P2P directly in your web browser
Correctly cleanup tmp runner files
Chocobozzz644e407cb24b
diff --git a/server/core/controllers/api/runners/jobs.ts b/server/core/controllers/api/runners/jobs.tsindex c9f53a99be..2447e5375a 100644--- a/server/core/controllers/api/runners/jobs.ts+++ b/server/core/controllers/api/runners/jobs.ts@@ -23,7 +23,7 @@ import {VideoStudioTranscodingSuccess} from '@peertube/peertube-models'import { retryTransactionWrapper } from '@server/helpers/database-utils.js'-import { createReqFiles } from '@server/helpers/express-utils.js'+import { cleanUpReqFiles, createReqFiles } from '@server/helpers/express-utils.js'import { logger, loggerTagsFactory } from '@server/helpers/logger.js'import { generateRunnerJobToken } from '@server/helpers/token-generator.js'import { MIMETYPES } from '@server/initializers/constants.js'@@ -316,6 +316,8 @@ async function updateRunnerJobController (req: express.Request, res: express.Resconst body: RunnerJobUpdateBody = req.bodyif (runnerJob.state === RunnerJobState.COMPLETING || runnerJob.state === RunnerJobState.COMPLETED) {+ cleanUpReqFiles(req)+return res.sendStatus(HttpStatusCode.NO_CONTENT_204)}diff --git a/server/core/helpers/express-utils.ts b/server/core/helpers/express-utils.tsindex 5f7bee6e1b..b902632aea 100644--- a/server/core/helpers/express-utils.ts+++ b/server/core/helpers/express-utils.ts@@ -6,8 +6,9 @@ import { CONFIG } from '../initializers/config.js'import { REMOTE_SCHEME } from '../initializers/constants.js'import { isArray } from './custom-validators/misc.js'import { logger } from './logger.js'-import { deleteFileAndCatch, generateRandomString } from './utils.js'+import { generateRandomString } from './utils.js'import { getExtFromMimetype } from './video.js'+import { deleteFileAndCatch } from './fs.js'// ---------------------------------------------------------------------------// Extract NSFW Filters options to list videosdiff --git a/server/core/helpers/fs.ts b/server/core/helpers/fs.tsindex 60d3ec630c..349cfff0d8 100644--- a/server/core/helpers/fs.ts+++ b/server/core/helpers/fs.ts@@ -1,5 +1,6 @@-import { move } from 'fs-extra/esm'+import { move, remove } from 'fs-extra/esm'import { rename } from 'fs/promises'+import { logger } from './logger.js'export async function tryAtomicMove (src: string, destination: string) {try {@@ -10,3 +11,8 @@ export async function tryAtomicMove (src: string, destination: string) {return move(src, destination, { overwrite: true })}}++export function deleteFileAndCatch (path: string) {+ remove(path)+ .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))+}diff --git a/server/core/helpers/utils.ts b/server/core/helpers/utils.tsindex cd0cc1b60c..bc55d68f90 100644--- a/server/core/helpers/utils.ts+++ b/server/core/helpers/utils.ts@@ -1,18 +1,11 @@-import { remove } from 'fs-extra/esm'+import { ResultList } from '@peertube/peertube-models'+import { sha256 } from '@peertube/peertube-node-utils'import { Instance as ParseTorrent } from 'parse-torrent'import { join } from 'path'-import { sha256 } from '@peertube/peertube-node-utils'-import { ResultList } from '@peertube/peertube-models'import { CONFIG } from '../initializers/config.js'import { randomBytesPromise } from './core-utils.js'-import { logger } from './logger.js'-function deleteFileAndCatch (path: string) {- remove(path)- .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))-}--async function generateRandomString (size: number) {+export async function generateRandomString (size: number) {const raw = await randomBytesPromise(size)return raw.toString('hex')@@ -22,7 +15,7 @@ interface FormattableToJSON<U, V> {toFormattedJSON(args?: U): V}-function getFormattedObjects<U, V, T extends FormattableToJSON<U, V>> (objects: T[], objectsTotal: number, formattedArg?: U) {+export function getFormattedObjects<U, V, T extends FormattableToJSON<U, V>> (objects: T[], objectsTotal: number, formattedArg?: U) {const formattedObjects = objects.map(o => o.toFormattedJSON(formattedArg))return {@@ -31,7 +24,7 @@ function getFormattedObjects<U, V, T extends FormattableToJSON<U, V>> (objects:} as ResultList<V>}-function generateVideoImportTmpPath (target: string | ParseTorrent, extension = '.mp4') {+export function generateVideoImportTmpPath (target: string | ParseTorrent, extension = '.mp4') {const id = typeof target === 'string'? target: target.infoHash@@ -45,7 +38,7 @@ function generateVideoImportTmpPath (target: string | ParseTorrent, extension =* only the "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3" part. If the filename does* not contain a UUID, returns null.*/-function getUUIDFromFilename (filename: string) {+export function getUUIDFromFilename (filename: string) {const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/const result = filename.match(regex)@@ -53,13 +46,3 @@ function getUUIDFromFilename (filename: string) {return result[0]}--// -----------------------------------------------------------------------------export {- deleteFileAndCatch,- generateRandomString,- getFormattedObjects,- generateVideoImportTmpPath,- getUUIDFromFilename-}diff --git a/server/core/lib/runners/job-handlers/abstract-job-handler.ts b/server/core/lib/runners/job-handlers/abstract-job-handler.tsindex 6cc481b173..2baffd9942 100644--- a/server/core/lib/runners/job-handlers/abstract-job-handler.ts+++ b/server/core/lib/runners/job-handlers/abstract-job-handler.ts@@ -21,6 +21,7 @@ import {RunnerJobVideoStudioTranscodingPrivatePayload} from '@peertube/peertube-models'import { saveInTransactionWithRetries } from '@server/helpers/database-utils.js'+import { deleteFileAndCatch } from '@server/helpers/fs.js'import { logger, loggerTagsFactory } from '@server/helpers/logger.js'import { RUNNER_JOBS } from '@server/initializers/constants.js'import { sequelizeTypescript } from '@server/initializers/database.js'@@ -67,7 +68,7 @@ type CreateRunnerJobArg =privatePayload: RunnerJobTranscriptionPrivatePayload}-export abstract class AbstractJobHandler<C, U extends RunnerJobUpdatePayload, S extends RunnerJobSuccessPayload> {+export abstract class AbstractJobHandler<C, UpdatePayload extends RunnerJobUpdatePayload, SuccessPayload extends RunnerJobSuccessPayload> {protected readonly lTags = loggerTagsFactory('runner')// ---------------------------------------------------------------------------@@ -112,13 +113,13 @@ export abstract class AbstractJobHandler<C, U extends RunnerJobUpdatePayload, Sprotected abstract specificUpdate (options: {runnerJob: MRunnerJob- updatePayload?: U+ updatePayload?: UpdatePayload}): Promise<void> | voidasync update (options: {runnerJob: MRunnerJobprogress?: number- updatePayload?: U+ updatePayload?: UpdatePayload}) {const { runnerJob, progress } = options@@ -146,9 +147,9 @@ export abstract class AbstractJobHandler<C, U extends RunnerJobUpdatePayload, Sasync complete (options: {runnerJob: MRunnerJob- resultPayload: S+ resultPayload: SuccessPayload}) {- const { runnerJob } = options+ const { runnerJob, resultPayload } = optionsrunnerJob.state = RunnerJobState.COMPLETINGawait saveInTransactionWithRetries(runnerJob)@@ -162,6 +163,10 @@ export abstract class AbstractJobHandler<C, U extends RunnerJobUpdatePayload, SrunnerJob.state = RunnerJobState.ERROREDrunnerJob.error = err.message+ } finally {+ // specificComplete() moves whatever uploaded file it consumes into permanent storage+ // Remove anything it left behind in tmp directory+ this.cleanupResultPayloadFiles(resultPayload)}runnerJob.progress = null@@ -174,9 +179,21 @@ export abstract class AbstractJobHandler<C, U extends RunnerJobUpdatePayload, Sif (affectedCount !== 0) PeerTubeSocket.Instance.sendAvailableJobsPingToRunners()}+ private cleanupResultPayloadFiles (resultPayload: SuccessPayload) {+ // Possible uploaded file paths across all RunnerJobSuccessPayload variants+ const resultPayloadFileKeys = [ 'videoFile', 'resolutionPlaylistFile', 'vttFile', 'storyboardFile' ] as const++ for (const key of resultPayloadFileKeys) {+ const value = (resultPayload as Record<string, unknown>)?.[key]+ if (typeof value !== 'string') continue++ deleteFileAndCatch(value)+ }+ }+protected abstract specificComplete (options: {runnerJob: MRunnerJob- resultPayload: S+ resultPayload: SuccessPayload}): Promise<void> | void// ---------------------------------------------------------------------------diff --git a/server/core/lib/runners/job-handlers/video-studio-transcoding-job-handler.ts b/server/core/lib/runners/job-handlers/video-studio-transcoding-job-handler.tsindex 77f87b23ab..7563122e76 100644--- a/server/core/lib/runners/job-handlers/video-studio-transcoding-job-handler.ts+++ b/server/core/lib/runners/job-handlers/video-studio-transcoding-job-handler.ts@@ -120,6 +120,7 @@ export class VideoStudioTranscodingJobHandlerconst video = await loadRunnerVideo(runnerJob, this.lTags)if (!video) {await safeCleanupStudioTMPFiles(privatePayload.originalTasks)+ return}const videoFilePath = resultPayload.videoFile as stringdiff --git a/server/core/lib/storyboard.ts b/server/core/lib/storyboard.tsindex fe132af0e2..9f5cb92594 100644--- a/server/core/lib/storyboard.ts+++ b/server/core/lib/storyboard.ts@@ -1,13 +1,13 @@import { ffprobePromise, getVideoStreamDimensionsInfo } from '@peertube/peertube-ffmpeg'import { retryTransactionWrapper } from '@server/helpers/database-utils.js'import { LoggerTags, logger } from '@server/helpers/logger.js'-import { deleteFileAndCatch } from '@server/helpers/utils.js'import { STORYBOARD } from '@server/initializers/constants.js'import { sequelizeTypescript } from '@server/initializers/database.js'import { StoryboardModel } from '@server/models/video/storyboard.js'import { VideoModel } from '@server/models/video/video.js'import { MVideo } from '@server/types/models/index.js'import { federateVideoIfNeeded } from './activitypub/videos/federate.js'+import { deleteFileAndCatch } from '@server/helpers/fs.js'export async function buildSpriteSize (videoPath: string) {const probe = await ffprobePromise(videoPath)diff --git a/server/core/lib/transcoding/hls-transcoding.ts b/server/core/lib/transcoding/hls-transcoding.tsindex 7ebb1faf24..5e7bba9ec5 100644--- a/server/core/lib/transcoding/hls-transcoding.ts+++ b/server/core/lib/transcoding/hls-transcoding.ts@@ -1,6 +1,7 @@import { pick } from '@peertube/peertube-core-utils'import { canCopyForHLS, getVideoStreamDuration, HLSFromTSTranscodeOptions, HLSTranscodeOptions } from '@peertube/peertube-ffmpeg'import { retryTransactionWrapper } from '@server/helpers/database-utils.js'+import { deleteFileAndCatch } from '@server/helpers/fs.js'import { sequelizeTypescript } from '@server/initializers/database.js'import { createTorrentAndSetInfoHash } from '@server/lib/webtorrent.js'import { MVideo } from '@server/types/models/index.js'@@ -211,15 +212,21 @@ async function generateHlsPlaylistCommon (options: {}}- await buildFFmpegVOD(job).transcode(transcodeOptions)+ try {+ await buildFFmpegVOD(job).transcode(transcodeOptions)- // Ensure the mutex is released if the ffmpeg command failed and did not release it- if (inputFileMutexReleaser) inputFileMutexReleaser()+ // Ensure the mutex is released if the ffmpeg command failed and did not release it+ if (inputFileMutexReleaser) inputFileMutexReleaser()- await onHLSVideoFileTranscoding({- video,- videoOutputPath,- preventInputFileLocking,- m3u8OutputPath- })+ await onHLSVideoFileTranscoding({+ video,+ videoOutputPath,+ preventInputFileLocking,+ m3u8OutputPath+ })+ } finally {+ // Cleanup temporary files+ deleteFileAndCatch(videoOutputPath)+ deleteFileAndCatch(m3u8OutputPath)+ }}diff --git a/server/core/lib/transcoding/web-transcoding.ts b/server/core/lib/transcoding/web-transcoding.tsindex af0683ab76..11bb79dca5 100644--- a/server/core/lib/transcoding/web-transcoding.ts+++ b/server/core/lib/transcoding/web-transcoding.ts@@ -7,11 +7,12 @@ import {} from '@peertube/peertube-ffmpeg'import { VideoFileStream } from '@peertube/peertube-models'import { computeOutputFPS } from '@server/helpers/ffmpeg/index.js'+import { deleteFileAndCatch } from '@server/helpers/fs.js'import { createTorrentAndSetInfoHash } from '@server/lib/webtorrent.js'import { VideoModel } from '@server/models/video/video.js'import { MVideoFile, MVideoFull } from '@server/types/models/index.js'import { Job } from 'bullmq'-import { move, remove } from 'fs-extra/esm'+import { move } from 'fs-extra/esm'import { copyFile } from 'fs/promises'import { basename, join } from 'path'import { CONFIG } from '../../initializers/config.js'@@ -51,22 +52,27 @@ export async function optimizeOriginalVideofile (options: {const resolution = buildOriginalFileResolution(inputVideoFile.resolution)const fps = computeOutputFPS({ inputFPS: inputVideoFile.fps, resolution, isOriginResolution: true, type: 'vod' })- // Could be very long!- await buildFFmpegVOD(job).transcode({- type: transcodeType,+ try {+ // Could be very long!+ await buildFFmpegVOD(job).transcode({+ type: transcodeType,- videoInputPath,- outputPath: videoOutputPath,+ videoInputPath,+ outputPath: videoOutputPath,- inputFileMutexReleaser,+ inputFileMutexReleaser,- resolution,- fps- })+ resolution,+ fps+ })- const { videoFile } = await onWebVideoFileTranscoding({ video, videoOutputPath, deleteWebInputVideoFile: inputVideoFile })+ const { videoFile } = await onWebVideoFileTranscoding({ video, videoOutputPath, deleteWebInputVideoFile: inputVideoFile })- return { transcodeType, videoFile }+ return { transcodeType, videoFile }+ } finally {+ // Cleanup temporary files+ deleteFileAndCatch(videoOutputPath)+ }})return result@@ -110,9 +116,14 @@ export async function transcodeNewWebVideoResolution (options: {fps}- await buildFFmpegVOD(job).transcode(transcodeOptions)+ try {+ await buildFFmpegVOD(job).transcode(transcodeOptions)- return onWebVideoFileTranscoding({ video, videoOutputPath })+ return await onWebVideoFileTranscoding({ video, videoOutputPath })+ } finally {+ // Cleanup temporary files+ deleteFileAndCatch(videoOutputPath)+ }})return result@@ -164,18 +175,17 @@ export async function mergeAudioVideofile (options: {try {await buildFFmpegVOD(job).transcode(transcodeOptions)- await remove(tmpThumbnailPath)- } catch (err) {- await remove(tmpThumbnailPath)- throw err+ await onWebVideoFileTranscoding({+ video,+ videoOutputPath,+ deleteWebInputVideoFile: inputVideoFile,+ wasAudioFile: true+ })+ } finally {+ // Cleanup temporary files+ deleteFileAndCatch(tmpThumbnailPath)+ deleteFileAndCatch(videoOutputPath)}-- await onWebVideoFileTranscoding({- video,- videoOutputPath,- deleteWebInputVideoFile: inputVideoFile,- wasAudioFile: true- })})return result