]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/schedulers/videos-redundancy-scheduler.ts
155d43343858bc131df063c680e4a3e827dffe1a
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / videos-redundancy-scheduler.ts
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'
5 import {
6 MStreamingPlaylistFiles,
7 MVideoAccountLight,
8 MVideoFile,
9 MVideoFileVideo,
10 MVideoRedundancyFileVideo,
11 MVideoRedundancyStreamingPlaylistVideo,
12 MVideoRedundancyVideo,
13 MVideoWithAllFiles
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'
28
29 const lTags = loggerTagsFactory('redundancy')
30
31 type CandidateToDuplicate = {
32 redundancy: VideosRedundancyStrategy
33 video: MVideoWithAllFiles
34 files: MVideoFile[]
35 streamingPlaylists: MStreamingPlaylistFiles[]
36 }
37
38 function isMVideoRedundancyFileVideo (
39 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
40 ): o is MVideoRedundancyFileVideo {
41 return !!(o as MVideoRedundancyFileVideo).VideoFile
42 }
43
44 export class VideosRedundancyScheduler extends AbstractScheduler {
45
46 private static instance: VideosRedundancyScheduler
47
48 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
49
50 private constructor () {
51 super()
52 }
53
54 async createManualRedundancy (videoId: number) {
55 const videoToDuplicate = await VideoModel.loadWithFiles(videoId)
56
57 if (!videoToDuplicate) {
58 logger.warn('Video to manually duplicate %d does not exist anymore.', videoId, lTags())
59 return
60 }
61
62 return this.createVideoRedundancies({
63 video: videoToDuplicate,
64 redundancy: null,
65 files: videoToDuplicate.VideoFiles,
66 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
67 })
68 }
69
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())
73
74 try {
75 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
76 if (!videoToDuplicate) continue
77
78 const candidateToDuplicate = {
79 video: videoToDuplicate,
80 redundancy: redundancyConfig,
81 files: videoToDuplicate.VideoFiles,
82 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
83 }
84
85 await this.purgeCacheIfNeeded(candidateToDuplicate)
86
87 if (await this.isTooHeavy(candidateToDuplicate)) {
88 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url, lTags(videoToDuplicate.uuid))
89 continue
90 }
91
92 logger.info(
93 'Will duplicate video %s in redundancy scheduler "%s".',
94 videoToDuplicate.url, redundancyConfig.strategy, lTags(videoToDuplicate.uuid)
95 )
96
97 await this.createVideoRedundancies(candidateToDuplicate)
98 } catch (err) {
99 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err, ...lTags() })
100 }
101 }
102
103 await this.extendsLocalExpiration()
104
105 await this.purgeRemoteExpired()
106 }
107
108 static get Instance () {
109 return this.instance || (this.instance = new this())
110 }
111
112 private async extendsLocalExpiration () {
113 const expired = await VideoRedundancyModel.listLocalExpired()
114
115 for (const redundancyModel of expired) {
116 try {
117 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
118 const candidate: CandidateToDuplicate = {
119 redundancy: redundancyConfig,
120 video: null,
121 files: [],
122 streamingPlaylists: []
123 }
124
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)) {
127 logger.info(
128 'Destroying redundancy %s because the cache size %s is too heavy.',
129 redundancyModel.url, redundancyModel.strategy, lTags(candidate.video.uuid)
130 )
131
132 await removeVideoRedundancy(redundancyModel)
133 } else {
134 await this.extendsRedundancy(redundancyModel)
135 }
136 } catch (err) {
137 logger.error(
138 'Cannot extend or remove expiration of %s video from our redundancy system.',
139 this.buildEntryLogId(redundancyModel), { err, ...lTags(redundancyModel.getVideoUUID()) }
140 )
141 }
142 }
143 }
144
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
148 if (!redundancy) {
149 await removeVideoRedundancy(redundancyModel)
150 return
151 }
152
153 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
154 }
155
156 private async purgeRemoteExpired () {
157 const expired = await VideoRedundancyModel.listRemoteExpired()
158
159 for (const redundancyModel of expired) {
160 try {
161 await removeVideoRedundancy(redundancyModel)
162 } catch (err) {
163 logger.error(
164 'Cannot remove redundancy %s from our redundancy system.',
165 this.buildEntryLogId(redundancyModel), lTags(redundancyModel.getVideoUUID())
166 )
167 }
168 }
169 }
170
171 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
172 if (cache.strategy === 'most-views') {
173 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
174 }
175
176 if (cache.strategy === 'trending') {
177 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
178 }
179
180 if (cache.strategy === 'recently-added') {
181 const minViews = cache.minViews
182 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
183 }
184 }
185
186 private async createVideoRedundancies (data: CandidateToDuplicate) {
187 const video = await this.loadAndRefreshVideo(data.video.url)
188
189 if (!video) {
190 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url, lTags(data.video.uuid))
191
192 return
193 }
194
195 for (const file of data.files) {
196 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
197 if (existingRedundancy) {
198 await this.extendsRedundancy(existingRedundancy)
199
200 continue
201 }
202
203 await this.createVideoFileRedundancy(data.redundancy, video, file)
204 }
205
206 for (const streamingPlaylist of data.streamingPlaylists) {
207 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
208 if (existingRedundancy) {
209 await this.extendsRedundancy(existingRedundancy)
210
211 continue
212 }
213
214 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
215 }
216 }
217
218 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
219 let strategy = 'manual'
220 let expiresOn: Date = null
221
222 if (redundancy) {
223 strategy = redundancy.strategy
224 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
225 }
226
227 const file = fileArg as MVideoFileVideo
228 file.Video = video
229
230 const serverActor = await getServerActor()
231
232 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy, lTags(video.uuid))
233
234 const tmpPath = await downloadWebTorrentVideo({ uri: file.torrentUrl }, VIDEO_IMPORT_TIMEOUT)
235
236 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename)
237 await move(tmpPath, destPath, { overwrite: true })
238
239 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
240 expiresOn,
241 url: getLocalVideoCacheFileActivityPubUrl(file),
242 fileUrl: generateWebTorrentRedundancyUrl(file),
243 strategy,
244 videoFileId: file.id,
245 actorId: serverActor.id
246 })
247
248 createdModel.VideoFile = file
249
250 await sendCreateCacheFile(serverActor, video, createdModel)
251
252 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url, lTags(video.uuid))
253 }
254
255 private async createStreamingPlaylistRedundancy (
256 redundancy: VideosRedundancyStrategy,
257 video: MVideoAccountLight,
258 playlistArg: MStreamingPlaylistFiles
259 ) {
260 let strategy = 'manual'
261 let expiresOn: Date = null
262
263 if (redundancy) {
264 strategy = redundancy.strategy
265 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
266 }
267
268 const playlist = Object.assign(playlistArg, { Video: video })
269 const serverActor = await getServerActor()
270
271 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy, lTags(video.uuid))
272
273 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
274 const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video)
275
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)
279
280 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
281 expiresOn,
282 url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
283 fileUrl: generateHLSRedundancyUrl(video, playlistArg),
284 strategy,
285 videoStreamingPlaylistId: playlist.id,
286 actorId: serverActor.id
287 })
288
289 createdModel.VideoStreamingPlaylist = playlist
290
291 await sendCreateCacheFile(serverActor, video, createdModel)
292
293 logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url, lTags(video.uuid))
294 }
295
296 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
297 logger.info('Extending expiration of %s.', redundancy.url, lTags(redundancy.getVideoUUID()))
298
299 const serverActor = await getServerActor()
300
301 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
302 await redundancy.save()
303
304 await sendUpdateCacheFile(serverActor, redundancy)
305 }
306
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
312
313 const videoId = toDelete.VideoFile
314 ? toDelete.VideoFile.videoId
315 : toDelete.VideoStreamingPlaylist.videoId
316
317 const redundancies = await VideoRedundancyModel.listLocalByVideoId(videoId)
318
319 for (const redundancy of redundancies) {
320 await removeVideoRedundancy(redundancy)
321 }
322 }
323 }
324
325 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
326 const maxSize = candidateToDuplicate.redundancy.size
327
328 const { totalUsed: alreadyUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy)
329
330 const videoSize = this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
331 const willUse = alreadyUsed + videoSize
332
333 logger.debug('Checking candidate size.', { maxSize, alreadyUsed, videoSize, willUse, ...lTags(candidateToDuplicate.video.uuid) })
334
335 return willUse > maxSize
336 }
337
338 private buildNewExpiration (expiresAfterMs: number) {
339 return new Date(Date.now() + expiresAfterMs)
340 }
341
342 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
343 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
344
345 return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}`
346 }
347
348 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number {
349 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
350
351 let allFiles = files
352 for (const p of playlists) {
353 allFiles = allFiles.concat(p.VideoFiles)
354 }
355
356 return allFiles.reduce(fileReducer, 0)
357 }
358
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'
365 }
366 const { video } = await getOrCreateAPVideo(getVideoOptions)
367
368 return video
369 }
370 }