1 import { move } from 'fs-extra'
2 import { join } from 'path'
3 import { getServerActor } from '@server/models/application/application'
4 import { TrackerModel } from '@server/models/server/tracker'
5 import { VideoModel } from '@server/models/video/video'
7 MStreamingPlaylistFiles,
11 MVideoRedundancyFileVideo,
12 MVideoRedundancyStreamingPlaylistVideo,
13 MVideoRedundancyVideo,
15 } from '@server/types/models'
16 import { VideosRedundancyStrategy } from '../../../shared/models/redundancy'
17 import { logger, loggerTagsFactory } from '../../helpers/logger'
18 import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent'
19 import { CONFIG } from '../../initializers/config'
20 import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants'
21 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
22 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
23 import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
24 import { getOrCreateAPVideo } from '../activitypub/videos'
25 import { downloadPlaylistSegments } from '../hls'
26 import { removeVideoRedundancy } from '../redundancy'
27 import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-urls'
28 import { AbstractScheduler } from './abstract-scheduler'
30 const lTags = loggerTagsFactory('redundancy')
32 type CandidateToDuplicate = {
33 redundancy: VideosRedundancyStrategy
34 video: MVideoWithAllFiles
36 streamingPlaylists: MStreamingPlaylistFiles[]
39 function isMVideoRedundancyFileVideo (
40 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
41 ): o is MVideoRedundancyFileVideo {
42 return !!(o as MVideoRedundancyFileVideo).VideoFile
45 export class VideosRedundancyScheduler extends AbstractScheduler {
47 private static instance: VideosRedundancyScheduler
49 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
51 private constructor () {
55 async createManualRedundancy (videoId: number) {
56 const videoToDuplicate = await VideoModel.loadWithFiles(videoId)
58 if (!videoToDuplicate) {
59 logger.warn('Video to manually duplicate %d does not exist anymore.', videoId, lTags())
63 return this.createVideoRedundancies({
64 video: videoToDuplicate,
66 files: videoToDuplicate.VideoFiles,
67 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
71 protected async internalExecute () {
72 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
73 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy, lTags())
76 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
77 if (!videoToDuplicate) continue
79 const candidateToDuplicate = {
80 video: videoToDuplicate,
81 redundancy: redundancyConfig,
82 files: videoToDuplicate.VideoFiles,
83 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
86 await this.purgeCacheIfNeeded(candidateToDuplicate)
88 if (await this.isTooHeavy(candidateToDuplicate)) {
89 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url, lTags(videoToDuplicate.uuid))
94 'Will duplicate video %s in redundancy scheduler "%s".',
95 videoToDuplicate.url, redundancyConfig.strategy, lTags(videoToDuplicate.uuid)
98 await this.createVideoRedundancies(candidateToDuplicate)
100 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err, ...lTags() })
104 await this.extendsLocalExpiration()
106 await this.purgeRemoteExpired()
109 static get Instance () {
110 return this.instance || (this.instance = new this())
113 private async extendsLocalExpiration () {
114 const expired = await VideoRedundancyModel.listLocalExpired()
116 for (const redundancyModel of expired) {
118 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
119 const candidate: CandidateToDuplicate = {
120 redundancy: redundancyConfig,
123 streamingPlaylists: []
126 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
127 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
129 'Destroying redundancy %s because the cache size %s is too heavy.',
130 redundancyModel.url, redundancyModel.strategy, lTags(candidate.video.uuid)
133 await removeVideoRedundancy(redundancyModel)
135 await this.extendsRedundancy(redundancyModel)
139 'Cannot extend or remove expiration of %s video from our redundancy system.',
140 this.buildEntryLogId(redundancyModel), { err, ...lTags(redundancyModel.getVideoUUID()) }
146 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
147 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
148 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
150 await removeVideoRedundancy(redundancyModel)
154 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
157 private async purgeRemoteExpired () {
158 const expired = await VideoRedundancyModel.listRemoteExpired()
160 for (const redundancyModel of expired) {
162 await removeVideoRedundancy(redundancyModel)
165 'Cannot remove redundancy %s from our redundancy system.',
166 this.buildEntryLogId(redundancyModel), lTags(redundancyModel.getVideoUUID())
172 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
173 if (cache.strategy === 'most-views') {
174 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
177 if (cache.strategy === 'trending') {
178 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
181 if (cache.strategy === 'recently-added') {
182 const minViews = cache.minViews
183 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
187 private async createVideoRedundancies (data: CandidateToDuplicate) {
188 const video = await this.loadAndRefreshVideo(data.video.url)
191 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url, lTags(data.video.uuid))
196 for (const file of data.files) {
197 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
198 if (existingRedundancy) {
199 await this.extendsRedundancy(existingRedundancy)
204 await this.createVideoFileRedundancy(data.redundancy, video, file)
207 for (const streamingPlaylist of data.streamingPlaylists) {
208 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
209 if (existingRedundancy) {
210 await this.extendsRedundancy(existingRedundancy)
215 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
219 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
220 let strategy = 'manual'
221 let expiresOn: Date = null
224 strategy = redundancy.strategy
225 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
228 const file = fileArg as MVideoFileVideo
231 const serverActor = await getServerActor()
233 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy, lTags(video.uuid))
235 const trackerUrls = await TrackerModel.listUrlsByVideoId(video.id)
236 const magnetUri = generateMagnetUri(video, file, trackerUrls)
238 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
240 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename)
241 await move(tmpPath, destPath, { overwrite: true })
243 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
245 url: getLocalVideoCacheFileActivityPubUrl(file),
246 fileUrl: generateWebTorrentRedundancyUrl(file),
248 videoFileId: file.id,
249 actorId: serverActor.id
252 createdModel.VideoFile = file
254 await sendCreateCacheFile(serverActor, video, createdModel)
256 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url, lTags(video.uuid))
259 private async createStreamingPlaylistRedundancy (
260 redundancy: VideosRedundancyStrategy,
261 video: MVideoAccountLight,
262 playlistArg: MStreamingPlaylistFiles
264 let strategy = 'manual'
265 let expiresOn: Date = null
268 strategy = redundancy.strategy
269 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
272 const playlist = Object.assign(playlistArg, { Video: video })
273 const serverActor = await getServerActor()
275 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy, lTags(video.uuid))
277 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
278 const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video)
280 const maxSizeKB = this.getTotalFileSizes([], [ playlist ]) / 1000
281 const toleranceKB = maxSizeKB + ((5 * maxSizeKB) / 100) // 5% more tolerance
282 await downloadPlaylistSegments(masterPlaylistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT, toleranceKB)
284 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
286 url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
287 fileUrl: generateHLSRedundancyUrl(video, playlistArg),
289 videoStreamingPlaylistId: playlist.id,
290 actorId: serverActor.id
293 createdModel.VideoStreamingPlaylist = playlist
295 await sendCreateCacheFile(serverActor, video, createdModel)
297 logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url, lTags(video.uuid))
300 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
301 logger.info('Extending expiration of %s.', redundancy.url, lTags(redundancy.getVideoUUID()))
303 const serverActor = await getServerActor()
305 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
306 await redundancy.save()
308 await sendUpdateCacheFile(serverActor, redundancy)
311 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
312 while (await this.isTooHeavy(candidateToDuplicate)) {
313 const redundancy = candidateToDuplicate.redundancy
314 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
315 if (!toDelete) return
317 const videoId = toDelete.VideoFile
318 ? toDelete.VideoFile.videoId
319 : toDelete.VideoStreamingPlaylist.videoId
321 const redundancies = await VideoRedundancyModel.listLocalByVideoId(videoId)
323 for (const redundancy of redundancies) {
324 await removeVideoRedundancy(redundancy)
329 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
330 const maxSize = candidateToDuplicate.redundancy.size
332 const { totalUsed: used } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy)
334 const videoSize = this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
335 const total = used + videoSize
337 logger.debug('Checking candidate size.', { used, videoSize, total, ...lTags(candidateToDuplicate.video.uuid) })
339 return total > maxSize
342 private buildNewExpiration (expiresAfterMs: number) {
343 return new Date(Date.now() + expiresAfterMs)
346 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
347 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
349 return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}`
352 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number {
353 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
356 for (const p of playlists) {
357 allFiles = allFiles.concat(p.VideoFiles)
360 return allFiles.reduce(fileReducer, 0)
363 private async loadAndRefreshVideo (videoUrl: string) {
364 // We need more attributes and check if the video still exists
365 const getVideoOptions = {
366 videoObject: videoUrl,
367 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
368 fetchType: 'all' as 'all'
370 const { video } = await getOrCreateAPVideo(getVideoOptions)