1 import { move } from 'fs-extra'
2 import { join } from 'path'
3 import { getServerActor } from '@server/models/application/application'
4 import { VideoModel } from '@server/models/video/video'
6 MStreamingPlaylistFiles,
10 MVideoRedundancyFileVideo,
11 MVideoRedundancyStreamingPlaylistVideo,
12 MVideoRedundancyVideo,
14 } from '@server/types/models'
15 import { VideosRedundancyStrategy } from '../../../shared/models/redundancy'
16 import { logger, loggerTagsFactory } from '../../helpers/logger'
17 import { downloadWebTorrentVideo } from '../../helpers/webtorrent'
18 import { CONFIG } from '../../initializers/config'
19 import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants'
20 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
21 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
22 import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
23 import { getOrCreateAPVideo } from '../activitypub/videos'
24 import { downloadPlaylistSegments } from '../hls'
25 import { removeVideoRedundancy } from '../redundancy'
26 import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-urls'
27 import { AbstractScheduler } from './abstract-scheduler'
29 const lTags = loggerTagsFactory('redundancy')
31 type CandidateToDuplicate = {
32 redundancy: VideosRedundancyStrategy
33 video: MVideoWithAllFiles
35 streamingPlaylists: MStreamingPlaylistFiles[]
38 function isMVideoRedundancyFileVideo (
39 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
40 ): o is MVideoRedundancyFileVideo {
41 return !!(o as MVideoRedundancyFileVideo).VideoFile
44 export class VideosRedundancyScheduler extends AbstractScheduler {
46 private static instance: VideosRedundancyScheduler
48 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
50 private constructor () {
54 async createManualRedundancy (videoId: number) {
55 const videoToDuplicate = await VideoModel.loadWithFiles(videoId)
57 if (!videoToDuplicate) {
58 logger.warn('Video to manually duplicate %d does not exist anymore.', videoId, lTags())
62 return this.createVideoRedundancies({
63 video: videoToDuplicate,
65 files: videoToDuplicate.VideoFiles,
66 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
70 protected async internalExecute () {
71 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
72 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy, lTags())
75 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
76 if (!videoToDuplicate) continue
78 const candidateToDuplicate = {
79 video: videoToDuplicate,
80 redundancy: redundancyConfig,
81 files: videoToDuplicate.VideoFiles,
82 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
85 await this.purgeCacheIfNeeded(candidateToDuplicate)
87 if (await this.isTooHeavy(candidateToDuplicate)) {
88 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url, lTags(videoToDuplicate.uuid))
93 'Will duplicate video %s in redundancy scheduler "%s".',
94 videoToDuplicate.url, redundancyConfig.strategy, lTags(videoToDuplicate.uuid)
97 await this.createVideoRedundancies(candidateToDuplicate)
99 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err, ...lTags() })
103 await this.extendsLocalExpiration()
105 await this.purgeRemoteExpired()
108 static get Instance () {
109 return this.instance || (this.instance = new this())
112 private async extendsLocalExpiration () {
113 const expired = await VideoRedundancyModel.listLocalExpired()
115 for (const redundancyModel of expired) {
117 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
118 const candidate: CandidateToDuplicate = {
119 redundancy: redundancyConfig,
122 streamingPlaylists: []
125 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
126 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
128 'Destroying redundancy %s because the cache size %s is too heavy.',
129 redundancyModel.url, redundancyModel.strategy, lTags(candidate.video.uuid)
132 await removeVideoRedundancy(redundancyModel)
134 await this.extendsRedundancy(redundancyModel)
138 'Cannot extend or remove expiration of %s video from our redundancy system.',
139 this.buildEntryLogId(redundancyModel), { err, ...lTags(redundancyModel.getVideoUUID()) }
145 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
146 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
147 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
149 await removeVideoRedundancy(redundancyModel)
153 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
156 private async purgeRemoteExpired () {
157 const expired = await VideoRedundancyModel.listRemoteExpired()
159 for (const redundancyModel of expired) {
161 await removeVideoRedundancy(redundancyModel)
164 'Cannot remove redundancy %s from our redundancy system.',
165 this.buildEntryLogId(redundancyModel), lTags(redundancyModel.getVideoUUID())
171 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
172 if (cache.strategy === 'most-views') {
173 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
176 if (cache.strategy === 'trending') {
177 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
180 if (cache.strategy === 'recently-added') {
181 const minViews = cache.minViews
182 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
186 private async createVideoRedundancies (data: CandidateToDuplicate) {
187 const video = await this.loadAndRefreshVideo(data.video.url)
190 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url, lTags(data.video.uuid))
195 for (const file of data.files) {
196 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
197 if (existingRedundancy) {
198 await this.extendsRedundancy(existingRedundancy)
203 await this.createVideoFileRedundancy(data.redundancy, video, file)
206 for (const streamingPlaylist of data.streamingPlaylists) {
207 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
208 if (existingRedundancy) {
209 await this.extendsRedundancy(existingRedundancy)
214 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
218 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
219 let strategy = 'manual'
220 let expiresOn: Date = null
223 strategy = redundancy.strategy
224 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
227 const file = fileArg as MVideoFileVideo
230 const serverActor = await getServerActor()
232 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy, lTags(video.uuid))
234 const tmpPath = await downloadWebTorrentVideo({ uri: file.torrentUrl }, VIDEO_IMPORT_TIMEOUT)
236 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename)
237 await move(tmpPath, destPath, { overwrite: true })
239 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
241 url: getLocalVideoCacheFileActivityPubUrl(file),
242 fileUrl: generateWebTorrentRedundancyUrl(file),
244 videoFileId: file.id,
245 actorId: serverActor.id
248 createdModel.VideoFile = file
250 await sendCreateCacheFile(serverActor, video, createdModel)
252 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url, lTags(video.uuid))
255 private async createStreamingPlaylistRedundancy (
256 redundancy: VideosRedundancyStrategy,
257 video: MVideoAccountLight,
258 playlistArg: MStreamingPlaylistFiles
260 let strategy = 'manual'
261 let expiresOn: Date = null
264 strategy = redundancy.strategy
265 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
268 const playlist = Object.assign(playlistArg, { Video: video })
269 const serverActor = await getServerActor()
271 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy, lTags(video.uuid))
273 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
274 const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video)
276 const maxSizeKB = this.getTotalFileSizes([], [ playlist ]) / 1000
277 const toleranceKB = maxSizeKB + ((5 * maxSizeKB) / 100) // 5% more tolerance
278 await downloadPlaylistSegments(masterPlaylistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT, toleranceKB)
280 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
282 url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
283 fileUrl: generateHLSRedundancyUrl(video, playlistArg),
285 videoStreamingPlaylistId: playlist.id,
286 actorId: serverActor.id
289 createdModel.VideoStreamingPlaylist = playlist
291 await sendCreateCacheFile(serverActor, video, createdModel)
293 logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url, lTags(video.uuid))
296 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
297 logger.info('Extending expiration of %s.', redundancy.url, lTags(redundancy.getVideoUUID()))
299 const serverActor = await getServerActor()
301 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
302 await redundancy.save()
304 await sendUpdateCacheFile(serverActor, redundancy)
307 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
308 while (await this.isTooHeavy(candidateToDuplicate)) {
309 const redundancy = candidateToDuplicate.redundancy
310 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
311 if (!toDelete) return
313 const videoId = toDelete.VideoFile
314 ? toDelete.VideoFile.videoId
315 : toDelete.VideoStreamingPlaylist.videoId
317 const redundancies = await VideoRedundancyModel.listLocalByVideoId(videoId)
319 for (const redundancy of redundancies) {
320 await removeVideoRedundancy(redundancy)
325 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
326 const maxSize = candidateToDuplicate.redundancy.size
328 const { totalUsed: alreadyUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy)
330 const videoSize = this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
331 const willUse = alreadyUsed + videoSize
333 logger.debug('Checking candidate size.', { maxSize, alreadyUsed, videoSize, willUse, ...lTags(candidateToDuplicate.video.uuid) })
335 return willUse > maxSize
338 private buildNewExpiration (expiresAfterMs: number) {
339 return new Date(Date.now() + expiresAfterMs)
342 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
343 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
345 return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}`
348 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number {
349 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
352 for (const p of playlists) {
353 allFiles = allFiles.concat(p.VideoFiles)
356 return allFiles.reduce(fileReducer, 0)
359 private async loadAndRefreshVideo (videoUrl: string) {
360 // We need more attributes and check if the video still exists
361 const getVideoOptions = {
362 videoObject: videoUrl,
363 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
364 fetchType: 'all' as 'all'
366 const { video } = await getOrCreateAPVideo(getVideoOptions)