From 0305db28c98fd6cf43a3c50ba92c76215e99d512 Mon Sep 17 00:00:00 2001 From: Jelle Besseling Date: Tue, 17 Aug 2021 08:26:20 +0200 Subject: Add support for saving video files to object storage (#4290) * Add support for saving video files to object storage * Add support for custom url generation on s3 stored files Uses two config keys to support url generation that doesn't directly go to (compatible s3). Can be used to generate urls to any cache server or CDN. * Upload files to s3 concurrently and delete originals afterwards * Only publish after move to object storage is complete * Use base url instead of url template * Fix mistyped config field * Add rudenmentary way to download before transcode * Implement Chocobozzz suggestions https://github.com/Chocobozzz/PeerTube/pull/4290#issuecomment-891670478 The remarks in question: Try to use objectStorage prefix instead of s3 prefix for your function/variables/config names Prefer to use a tree for the config: s3.streaming_playlists_bucket -> object_storage.streaming_playlists.bucket Use uppercase for config: S3.STREAMING_PLAYLISTS_BUCKETINFO.bucket -> OBJECT_STORAGE.STREAMING_PLAYLISTS.BUCKET (maybe BUCKET_NAME instead of BUCKET) I suggest to rename moveJobsRunning to pendingMovingJobs (or better, create a dedicated videoJobInfo table with a pendingMove & videoId columns so we could also use this table to track pending transcoding jobs) https://github.com/Chocobozzz/PeerTube/pull/4290/files#diff-3e26d41ca4bda1de8e1747af70ca2af642abcc1e9e0bfb94239ff2165acfbde5R19 uses a string instead of an integer I think we should store the origin object storage URL in fileUrl, without base_url injection. Instead, inject the base_url at "runtime" so admins can easily change this configuration without running a script to update DB URLs * Import correct function * Support multipart upload * Remove import of node 15.0 module stream/promises * Extend maximum upload job length Using the same value as for redundancy downloading seems logical * Use dynamic part size for really large uploads Also adds very small part size for local testing * Fix decreasePendingMove query * Resolve various PR comments * Move to object storage after optimize * Make upload size configurable and increase default * Prune webtorrent files that are stored in object storage * Move files after transcoding jobs * Fix federation * Add video path manager * Support move to external storage job in client * Fix live object storage tests Co-authored-by: Chocobozzz --- .../models/video/formatter/video-format-utils.ts | 2 +- server/models/video/sql/shared/video-tables.ts | 9 +- server/models/video/video-file.ts | 26 +++++- server/models/video/video-job-info.ts | 100 +++++++++++++++++++++ server/models/video/video-streaming-playlist.ts | 30 ++++++- server/models/video/video.ts | 51 ++++++++--- 6 files changed, 196 insertions(+), 22 deletions(-) create mode 100644 server/models/video/video-job-info.ts (limited to 'server/models/video') diff --git a/server/models/video/formatter/video-format-utils.ts b/server/models/video/formatter/video-format-utils.ts index 8a54de3b0..b3c4f390d 100644 --- a/server/models/video/formatter/video-format-utils.ts +++ b/server/models/video/formatter/video-format-utils.ts @@ -1,6 +1,6 @@ import { uuidToShort } from '@server/helpers/uuid' import { generateMagnetUri } from '@server/helpers/webtorrent' -import { getLocalVideoFileMetadataUrl } from '@server/lib/video-paths' +import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls' import { VideoFile } from '@shared/models/videos/video-file.model' import { ActivityTagObject, ActivityUrlObject, VideoObject } from '../../../../shared/models/activitypub/objects' import { Video, VideoDetails } from '../../../../shared/models/videos' diff --git a/server/models/video/sql/shared/video-tables.ts b/server/models/video/sql/shared/video-tables.ts index 742d19099..75823864d 100644 --- a/server/models/video/sql/shared/video-tables.ts +++ b/server/models/video/sql/shared/video-tables.ts @@ -87,7 +87,8 @@ export class VideoTables { 'fps', 'metadataUrl', 'videoStreamingPlaylistId', - 'videoId' + 'videoId', + 'storage' ] } @@ -102,7 +103,8 @@ export class VideoTables { 'segmentsSha256Url', 'videoId', 'createdAt', - 'updatedAt' + 'updatedAt', + 'storage' ]) } @@ -258,7 +260,8 @@ export class VideoTables { 'originallyPublishedAt', 'channelId', 'createdAt', - 'updatedAt' + 'updatedAt', + 'moveJobsRunning' ] } } diff --git a/server/models/video/video-file.ts b/server/models/video/video-file.ts index 09fc5288b..627c95763 100644 --- a/server/models/video/video-file.ts +++ b/server/models/video/video-file.ts @@ -23,9 +23,11 @@ import validator from 'validator' import { buildRemoteVideoBaseUrl } from '@server/helpers/activitypub' import { logger } from '@server/helpers/logger' import { extractVideo } from '@server/helpers/video' -import { getTorrentFilePath } from '@server/lib/video-paths' +import { getHLSPublicFileUrl, getWebTorrentPublicFileUrl } from '@server/lib/object-storage' +import { getFSTorrentFilePath } from '@server/lib/paths' import { MStreamingPlaylistVideo, MVideo, MVideoWithHost } from '@server/types/models' import { AttributesOnly } from '@shared/core-utils' +import { VideoStorage } from '@shared/models' import { isVideoFileExtnameValid, isVideoFileInfoHashValid, @@ -214,6 +216,11 @@ export class VideoFileModel extends Model @Column videoId: number + @AllowNull(false) + @Default(VideoStorage.FILE_SYSTEM) + @Column + storage: VideoStorage + @BelongsTo(() => VideoModel, { foreignKey: { allowNull: true @@ -273,7 +280,7 @@ export class VideoFileModel extends Model static async doesOwnedWebTorrentVideoFileExist (filename: string) { const query = 'SELECT 1 FROM "videoFile" INNER JOIN "video" ON "video"."id" = "videoFile"."videoId" AND "video"."remote" IS FALSE ' + - 'WHERE "filename" = $filename LIMIT 1' + `WHERE "filename" = $filename AND "storage" = ${VideoStorage.FILE_SYSTEM} LIMIT 1` return doesExist(query, { filename }) } @@ -450,9 +457,20 @@ export class VideoFileModel extends Model return !!this.videoStreamingPlaylistId } + getObjectStorageUrl () { + if (this.isHLS()) { + return getHLSPublicFileUrl(this.fileUrl) + } + + return getWebTorrentPublicFileUrl(this.fileUrl) + } + getFileUrl (video: MVideo) { - if (!this.Video) this.Video = video as VideoModel + if (this.storage === VideoStorage.OBJECT_STORAGE) { + return this.getObjectStorageUrl() + } + if (!this.Video) this.Video = video as VideoModel if (video.isOwned()) return WEBSERVER.URL + this.getFileStaticPath(video) return this.fileUrl @@ -503,7 +521,7 @@ export class VideoFileModel extends Model removeTorrent () { if (!this.torrentFilename) return null - const torrentPath = getTorrentFilePath(this) + const torrentPath = getFSTorrentFilePath(this) return remove(torrentPath) .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err })) } diff --git a/server/models/video/video-job-info.ts b/server/models/video/video-job-info.ts new file mode 100644 index 000000000..7c1fe6734 --- /dev/null +++ b/server/models/video/video-job-info.ts @@ -0,0 +1,100 @@ +import { Op, QueryTypes, Transaction } from 'sequelize' +import { AllowNull, BelongsTo, Column, CreatedAt, Default, ForeignKey, IsInt, Model, Table, Unique, UpdatedAt } from 'sequelize-typescript' +import { AttributesOnly } from '@shared/core-utils' +import { VideoModel } from './video' + +@Table({ + tableName: 'videoJobInfo', + indexes: [ + { + fields: [ 'videoId' ], + where: { + videoId: { + [Op.ne]: null + } + } + } + ] +}) + +export class VideoJobInfoModel extends Model>> { + @CreatedAt + createdAt: Date + + @UpdatedAt + updatedAt: Date + + @AllowNull(false) + @Default(0) + @IsInt + @Column + pendingMove: number + + @AllowNull(false) + @Default(0) + @IsInt + @Column + pendingTranscode: number + + @ForeignKey(() => VideoModel) + @Unique + @Column + videoId: number + + @BelongsTo(() => VideoModel, { + foreignKey: { + allowNull: false + }, + onDelete: 'cascade' + }) + Video: VideoModel + + static load (videoId: number, transaction: Transaction) { + const where = { + videoId + } + + return VideoJobInfoModel.findOne({ where, transaction }) + } + + static async increaseOrCreate (videoUUID: string, column: 'pendingMove' | 'pendingTranscode'): Promise { + const options = { type: QueryTypes.SELECT as QueryTypes.SELECT, bind: { videoUUID } } + + const [ { pendingMove } ] = await VideoJobInfoModel.sequelize.query<{ pendingMove: number }>(` + INSERT INTO "videoJobInfo" ("videoId", "${column}", "createdAt", "updatedAt") + SELECT + "video"."id" AS "videoId", 1, NOW(), NOW() + FROM + "video" + WHERE + "video"."uuid" = $videoUUID + ON CONFLICT ("videoId") DO UPDATE + SET + "${column}" = "videoJobInfo"."${column}" + 1, + "updatedAt" = NOW() + RETURNING + "${column}" + `, options) + + return pendingMove + } + + static async decrease (videoUUID: string, column: 'pendingMove' | 'pendingTranscode'): Promise { + const options = { type: QueryTypes.SELECT as QueryTypes.SELECT, bind: { videoUUID } } + + const [ { pendingMove } ] = await VideoJobInfoModel.sequelize.query<{ pendingMove: number }>(` + UPDATE + "videoJobInfo" + SET + "${column}" = "videoJobInfo"."${column}" - 1, + "updatedAt" = NOW() + FROM "video" + WHERE + "video"."id" = "videoJobInfo"."videoId" AND "video"."uuid" = $videoUUID + RETURNING + "${column}"; + `, options) + + return pendingMove + } +} diff --git a/server/models/video/video-streaming-playlist.ts b/server/models/video/video-streaming-playlist.ts index d591a3134..3e9fd97c7 100644 --- a/server/models/video/video-streaming-playlist.ts +++ b/server/models/video/video-streaming-playlist.ts @@ -1,10 +1,25 @@ import * as memoizee from 'memoizee' import { join } from 'path' import { Op } from 'sequelize' -import { AllowNull, BelongsTo, Column, CreatedAt, DataType, ForeignKey, HasMany, Is, Model, Table, UpdatedAt } from 'sequelize-typescript' +import { + AllowNull, + BelongsTo, + Column, + CreatedAt, + DataType, + Default, + ForeignKey, + HasMany, + Is, + Model, + Table, + UpdatedAt +} from 'sequelize-typescript' +import { getHLSPublicFileUrl } from '@server/lib/object-storage' import { VideoFileModel } from '@server/models/video/video-file' import { MStreamingPlaylist, MVideo } from '@server/types/models' import { AttributesOnly } from '@shared/core-utils' +import { VideoStorage } from '@shared/models' import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type' import { sha1 } from '../../helpers/core-utils' import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' @@ -81,6 +96,11 @@ export class VideoStreamingPlaylistModel extends Model VideoModel, { foreignKey: { allowNull: false @@ -185,12 +205,20 @@ export class VideoStreamingPlaylistModel extends Model>> { }) VideoCaptions: VideoCaptionModel[] + @HasOne(() => VideoJobInfoModel, { + foreignKey: { + name: 'videoId', + allowNull: false + }, + onDelete: 'cascade' + }) + VideoJobInfo: VideoJobInfoModel + @BeforeDestroy static async sendDelete (instance: MVideoAccountLight, options) { if (!instance.isOwned()) return undefined @@ -1641,9 +1653,10 @@ export class VideoModel extends Model>> { getMaxQualityResolution () { const file = this.getMaxQualityFile() const videoOrPlaylist = file.getVideoOrStreamingPlaylist() - const originalFilePath = getVideoFilePath(videoOrPlaylist, file) - return getVideoFileResolution(originalFilePath) + return VideoPathManager.Instance.makeAvailableVideoFile(videoOrPlaylist, file, originalFilePath => { + return getVideoFileResolution(originalFilePath) + }) } getDescriptionAPIPath () { @@ -1673,16 +1686,24 @@ export class VideoModel extends Model>> { } removeFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) { - const filePath = getVideoFilePath(this, videoFile, isRedundancy) + const filePath = isRedundancy + ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile) + : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile) const promises: Promise[] = [ remove(filePath) ] if (!isRedundancy) promises.push(videoFile.removeTorrent()) + if (videoFile.storage === VideoStorage.OBJECT_STORAGE) { + promises.push(removeWebTorrentObjectStorage(videoFile)) + } + return Promise.all(promises) } async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) { - const directoryPath = getHLSDirectory(this, isRedundancy) + const directoryPath = isRedundancy + ? getHLSRedundancyDirectory(this) + : getHLSDirectory(this) await remove(directoryPath) @@ -1698,6 +1719,10 @@ export class VideoModel extends Model>> { await Promise.all( streamingPlaylistWithFiles.VideoFiles.map(file => file.removeTorrent()) ) + + if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) { + await removeHLSObjectStorage(streamingPlaylist, this) + } } } @@ -1741,16 +1766,16 @@ export class VideoModel extends Model>> { this.privacy === VideoPrivacy.INTERNAL } - async publishIfNeededAndSave (t: Transaction) { - if (this.state !== VideoState.PUBLISHED) { - this.state = VideoState.PUBLISHED - this.publishedAt = new Date() - await this.save({ transaction: t }) + async setNewState (newState: VideoState, transaction: Transaction) { + if (this.state === newState) throw new Error('Cannot use same state ' + newState) + + this.state = newState - return true + if (this.state === VideoState.PUBLISHED) { + this.publishedAt = new Date() } - return false + await this.save({ transaction }) } getBandwidthBits (videoFile: MVideoFile) { -- cgit v1.2.3