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 { totalUsed } = await VideoRedundancyModel.getStats(redundancyConfig.strategy)
120 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
121 if (!redundancyConfig || totalUsed > redundancyConfig.size) {
122 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
124 await removeVideoRedundancy(redundancyModel)
126 await this.extendsRedundancy(redundancyModel)
130 'Cannot extend or remove expiration of %s video from our redundancy system.',
131 this.buildEntryLogId(redundancyModel), { err, ...lTags(redundancyModel.getVideoUUID()) }
137 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
138 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
139 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
141 await removeVideoRedundancy(redundancyModel)
145 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
148 private async purgeRemoteExpired () {
149 const expired = await VideoRedundancyModel.listRemoteExpired()
151 for (const redundancyModel of expired) {
153 await removeVideoRedundancy(redundancyModel)
156 'Cannot remove redundancy %s from our redundancy system.',
157 this.buildEntryLogId(redundancyModel), lTags(redundancyModel.getVideoUUID())
163 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
164 if (cache.strategy === 'most-views') {
165 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
168 if (cache.strategy === 'trending') {
169 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
172 if (cache.strategy === 'recently-added') {
173 const minViews = cache.minViews
174 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
178 private async createVideoRedundancies (data: CandidateToDuplicate) {
179 const video = await this.loadAndRefreshVideo(data.video.url)
182 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url, lTags(data.video.uuid))
187 for (const file of data.files) {
188 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
189 if (existingRedundancy) {
190 await this.extendsRedundancy(existingRedundancy)
195 await this.createVideoFileRedundancy(data.redundancy, video, file)
198 for (const streamingPlaylist of data.streamingPlaylists) {
199 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
200 if (existingRedundancy) {
201 await this.extendsRedundancy(existingRedundancy)
206 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
210 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
211 let strategy = 'manual'
212 let expiresOn: Date = null
215 strategy = redundancy.strategy
216 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
219 const file = fileArg as MVideoFileVideo
222 const serverActor = await getServerActor()
224 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy, lTags(video.uuid))
226 const tmpPath = await downloadWebTorrentVideo({ uri: file.torrentUrl }, VIDEO_IMPORT_TIMEOUT)
228 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename)
229 await move(tmpPath, destPath, { overwrite: true })
231 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
233 url: getLocalVideoCacheFileActivityPubUrl(file),
234 fileUrl: generateWebTorrentRedundancyUrl(file),
236 videoFileId: file.id,
237 actorId: serverActor.id
240 createdModel.VideoFile = file
242 await sendCreateCacheFile(serverActor, video, createdModel)
244 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url, lTags(video.uuid))
247 private async createStreamingPlaylistRedundancy (
248 redundancy: VideosRedundancyStrategy,
249 video: MVideoAccountLight,
250 playlistArg: MStreamingPlaylistFiles
252 let strategy = 'manual'
253 let expiresOn: Date = null
256 strategy = redundancy.strategy
257 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
260 const playlist = Object.assign(playlistArg, { Video: video })
261 const serverActor = await getServerActor()
263 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy, lTags(video.uuid))
265 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
266 const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video)
268 const maxSizeKB = this.getTotalFileSizes([], [ playlist ]) / 1000
269 const toleranceKB = maxSizeKB + ((5 * maxSizeKB) / 100) // 5% more tolerance
270 await downloadPlaylistSegments(masterPlaylistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT, toleranceKB)
272 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
274 url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
275 fileUrl: generateHLSRedundancyUrl(video, playlistArg),
277 videoStreamingPlaylistId: playlist.id,
278 actorId: serverActor.id
281 createdModel.VideoStreamingPlaylist = playlist
283 await sendCreateCacheFile(serverActor, video, createdModel)
285 logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url, lTags(video.uuid))
288 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
289 logger.info('Extending expiration of %s.', redundancy.url, lTags(redundancy.getVideoUUID()))
291 const serverActor = await getServerActor()
293 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
294 await redundancy.save()
296 await sendUpdateCacheFile(serverActor, redundancy)
299 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
300 while (await this.isTooHeavy(candidateToDuplicate)) {
301 const redundancy = candidateToDuplicate.redundancy
302 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
303 if (!toDelete) return
305 const videoId = toDelete.VideoFile
306 ? toDelete.VideoFile.videoId
307 : toDelete.VideoStreamingPlaylist.videoId
309 const redundancies = await VideoRedundancyModel.listLocalByVideoId(videoId)
311 for (const redundancy of redundancies) {
312 await removeVideoRedundancy(redundancy)
317 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
318 const maxSize = candidateToDuplicate.redundancy.size
320 const { totalUsed: alreadyUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy)
322 const videoSize = this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
323 const willUse = alreadyUsed + videoSize
325 logger.debug('Checking candidate size.', { maxSize, alreadyUsed, videoSize, willUse, ...lTags(candidateToDuplicate.video.uuid) })
327 return willUse > maxSize
330 private buildNewExpiration (expiresAfterMs: number) {
331 return new Date(Date.now() + expiresAfterMs)
334 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
335 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
337 return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}`
340 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number {
341 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
344 for (const p of playlists) {
345 allFiles = allFiles.concat(p.VideoFiles)
348 return allFiles.reduce(fileReducer, 0)
351 private async loadAndRefreshVideo (videoUrl: string) {
352 // We need more attributes and check if the video still exists
353 const getVideoOptions = {
354 videoObject: videoUrl,
355 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
356 fetchType: 'all' as 'all'
358 const { video } = await getOrCreateAPVideo(getVideoOptions)