]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/schedulers/videos-redundancy-scheduler.ts
Add video file size info in admin videos list
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / videos-redundancy-scheduler.ts
CommitLineData
f481c4f9 1import { move } from 'fs-extra'
de94ac86
C
2import { join } from 'path'
3import { getServerActor } from '@server/models/application/application'
4import { VideoModel } from '@server/models/video/video'
453e83ea 5import {
de94ac86 6 MStreamingPlaylistFiles,
453e83ea
C
7 MVideoAccountLight,
8 MVideoFile,
9 MVideoFileVideo,
10 MVideoRedundancyFileVideo,
11 MVideoRedundancyStreamingPlaylistVideo,
12 MVideoRedundancyVideo,
13 MVideoWithAllFiles
26d6bf65 14} from '@server/types/models'
de94ac86 15import { VideosRedundancyStrategy } from '../../../shared/models/redundancy'
52b1fd15 16import { logger, loggerTagsFactory } from '../../helpers/logger'
02b286f8 17import { downloadWebTorrentVideo } from '../../helpers/webtorrent'
de94ac86 18import { CONFIG } from '../../initializers/config'
90a8bd30 19import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants'
de94ac86
C
20import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
21import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
22import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
304a84d5 23import { getOrCreateAPVideo } from '../activitypub/videos'
de94ac86
C
24import { downloadPlaylistSegments } from '../hls'
25import { removeVideoRedundancy } from '../redundancy'
0305db28 26import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-urls'
de94ac86 27import { AbstractScheduler } from './abstract-scheduler'
09209296 28
52b1fd15
C
29const lTags = loggerTagsFactory('redundancy')
30
09209296 31type CandidateToDuplicate = {
a1587156
C
32 redundancy: VideosRedundancyStrategy
33 video: MVideoWithAllFiles
34 files: MVideoFile[]
66fb2aa3 35 streamingPlaylists: MStreamingPlaylistFiles[]
453e83ea
C
36}
37
0283eaac
C
38function isMVideoRedundancyFileVideo (
39 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
40): o is MVideoRedundancyFileVideo {
453e83ea 41 return !!(o as MVideoRedundancyFileVideo).VideoFile
09209296 42}
c48e82b5
C
43
44export class VideosRedundancyScheduler extends AbstractScheduler {
45
b764380a 46 private static instance: VideosRedundancyScheduler
c48e82b5 47
f9f899b9 48 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
c48e82b5
C
49
50 private constructor () {
51 super()
52 }
53
b764380a
C
54 async createManualRedundancy (videoId: number) {
55 const videoToDuplicate = await VideoModel.loadWithFiles(videoId)
56
57 if (!videoToDuplicate) {
52b1fd15 58 logger.warn('Video to manually duplicate %d does not exist anymore.', videoId, lTags())
b764380a
C
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
2f5c6b2f 70 protected async internalExecute () {
09209296 71 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
52b1fd15 72 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy, lTags())
1cfa8d68 73
c48e82b5 74 try {
09209296 75 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
c48e82b5
C
76 if (!videoToDuplicate) continue
77
09209296
C
78 const candidateToDuplicate = {
79 video: videoToDuplicate,
80 redundancy: redundancyConfig,
81 files: videoToDuplicate.VideoFiles,
82 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
83 }
c48e82b5 84
09209296 85 await this.purgeCacheIfNeeded(candidateToDuplicate)
e5565833 86
09209296 87 if (await this.isTooHeavy(candidateToDuplicate)) {
52b1fd15 88 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url, lTags(videoToDuplicate.uuid))
c48e82b5
C
89 continue
90 }
91
52b1fd15
C
92 logger.info(
93 'Will duplicate video %s in redundancy scheduler "%s".',
94 videoToDuplicate.url, redundancyConfig.strategy, lTags(videoToDuplicate.uuid)
95 )
c48e82b5 96
09209296 97 await this.createVideoRedundancies(candidateToDuplicate)
c48e82b5 98 } catch (err) {
52b1fd15 99 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err, ...lTags() })
c48e82b5
C
100 }
101 }
102
e5565833
C
103 await this.extendsLocalExpiration()
104
105 await this.purgeRemoteExpired()
f9f899b9
C
106 }
107
108 static get Instance () {
109 return this.instance || (this.instance = new this())
110 }
111
e5565833
C
112 private async extendsLocalExpiration () {
113 const expired = await VideoRedundancyModel.listLocalExpired()
114
115 for (const redundancyModel of expired) {
116 try {
09209296 117 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
b764380a 118 const candidate: CandidateToDuplicate = {
09209296
C
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)) {
52b1fd15
C
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
09209296
C
132 await removeVideoRedundancy(redundancyModel)
133 } else {
134 await this.extendsRedundancy(redundancyModel)
135 }
e5565833 136 } catch (err) {
09209296 137 logger.error(
52b1fd15
C
138 'Cannot extend or remove expiration of %s video from our redundancy system.',
139 this.buildEntryLogId(redundancyModel), { err, ...lTags(redundancyModel.getVideoUUID()) }
09209296 140 )
e5565833
C
141 }
142 }
143 }
c48e82b5 144
453e83ea 145 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
be691a57 146 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
09209296 147 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
0b353d1d
C
148 if (!redundancy) {
149 await removeVideoRedundancy(redundancyModel)
150 return
151 }
09209296 152
be691a57
C
153 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
154 }
155
e5565833
C
156 private async purgeRemoteExpired () {
157 const expired = await VideoRedundancyModel.listRemoteExpired()
c48e82b5 158
e5565833 159 for (const redundancyModel of expired) {
c48e82b5 160 try {
e5565833 161 await removeVideoRedundancy(redundancyModel)
c48e82b5 162 } catch (err) {
52b1fd15
C
163 logger.error(
164 'Cannot remove redundancy %s from our redundancy system.',
165 this.buildEntryLogId(redundancyModel), lTags(redundancyModel.getVideoUUID())
166 )
c48e82b5
C
167 }
168 }
c48e82b5
C
169 }
170
b764380a 171 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
3f6b6a56
C
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 }
b36f41ca 179
3f6b6a56 180 if (cache.strategy === 'recently-added') {
7348b1fd 181 const minViews = cache.minViews
3f6b6a56
C
182 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
183 }
c48e82b5
C
184 }
185
09209296
C
186 private async createVideoRedundancies (data: CandidateToDuplicate) {
187 const video = await this.loadAndRefreshVideo(data.video.url)
188
189 if (!video) {
52b1fd15 190 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url, lTags(data.video.uuid))
c48e82b5 191
09209296
C
192 return
193 }
26649b42 194
09209296 195 for (const file of data.files) {
be691a57
C
196 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
197 if (existingRedundancy) {
09209296 198 await this.extendsRedundancy(existingRedundancy)
c48e82b5 199
c48e82b5
C
200 continue
201 }
202
09209296
C
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)
26649b42
C
210
211 continue
212 }
c48e82b5 213
09209296
C
214 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
215 }
216 }
c48e82b5 217
b764380a
C
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
453e83ea 227 const file = fileArg as MVideoFileVideo
09209296 228 file.Video = video
c48e82b5 229
09209296 230 const serverActor = await getServerActor()
c48e82b5 231
52b1fd15 232 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy, lTags(video.uuid))
c48e82b5 233
02b286f8 234 const tmpPath = await downloadWebTorrentVideo({ uri: file.torrentUrl }, VIDEO_IMPORT_TIMEOUT)
792e5b8e 235
90a8bd30 236 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename)
217ffacf 237 await move(tmpPath, destPath, { overwrite: true })
09209296 238
453e83ea 239 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
b764380a 240 expiresOn,
de94ac86 241 url: getLocalVideoCacheFileActivityPubUrl(file),
90a8bd30 242 fileUrl: generateWebTorrentRedundancyUrl(file),
b764380a 243 strategy,
09209296
C
244 videoFileId: file.id,
245 actorId: serverActor.id
246 })
247
248 createdModel.VideoFile = file
249
250 await sendCreateCacheFile(serverActor, video, createdModel)
251
52b1fd15 252 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url, lTags(video.uuid))
09209296
C
253 }
254
453e83ea 255 private async createStreamingPlaylistRedundancy (
b764380a 256 redundancy: VideosRedundancyStrategy,
453e83ea 257 video: MVideoAccountLight,
18998c45 258 playlistArg: MStreamingPlaylistFiles
453e83ea 259 ) {
b764380a
C
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
18998c45 268 const playlist = Object.assign(playlistArg, { Video: video })
09209296
C
269 const serverActor = await getServerActor()
270
52b1fd15 271 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy, lTags(video.uuid))
09209296
C
272
273 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
764b1a14 274 const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video)
18998c45
C
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)
09209296 279
453e83ea 280 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
b764380a 281 expiresOn,
de94ac86 282 url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
90a8bd30 283 fileUrl: generateHLSRedundancyUrl(video, playlistArg),
b764380a 284 strategy,
09209296
C
285 videoStreamingPlaylistId: playlist.id,
286 actorId: serverActor.id
287 })
288
289 createdModel.VideoStreamingPlaylist = playlist
290
291 await sendCreateCacheFile(serverActor, video, createdModel)
292
52b1fd15 293 logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url, lTags(video.uuid))
c48e82b5
C
294 }
295
453e83ea 296 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
52b1fd15 297 logger.info('Extending expiration of %s.', redundancy.url, lTags(redundancy.getVideoUUID()))
e5565833
C
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
09209296 307 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
f8278b96 308 while (await this.isTooHeavy(candidateToDuplicate)) {
09209296 309 const redundancy = candidateToDuplicate.redundancy
453e83ea 310 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
e5565833
C
311 if (!toDelete) return
312
89613cb4
C
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 }
e5565833
C
322 }
323 }
324
09209296
C
325 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
326 const maxSize = candidateToDuplicate.redundancy.size
c48e82b5 327
0bae6663 328 const { totalUsed: alreadyUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy)
52b1fd15
C
329
330 const videoSize = this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
0bae6663 331 const willUse = alreadyUsed + videoSize
52b1fd15 332
0bae6663 333 logger.debug('Checking candidate size.', { maxSize, alreadyUsed, videoSize, willUse, ...lTags(candidateToDuplicate.video.uuid) })
c48e82b5 334
0bae6663 335 return willUse > maxSize
c48e82b5
C
336 }
337
e5565833
C
338 private buildNewExpiration (expiresAfterMs: number) {
339 return new Date(Date.now() + expiresAfterMs)
c48e82b5
C
340 }
341
453e83ea
C
342 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
343 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
09209296 344
764b1a14 345 return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}`
c48e82b5
C
346 }
347
18998c45 348 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number {
453e83ea 349 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
c48e82b5 350
66fb2aa3
C
351 let allFiles = files
352 for (const p of playlists) {
353 allFiles = allFiles.concat(p.VideoFiles)
354 }
26d78799 355
66fb2aa3 356 return allFiles.reduce(fileReducer, 0)
c48e82b5 357 }
be691a57
C
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 }
304a84d5 366 const { video } = await getOrCreateAPVideo(getVideoOptions)
be691a57
C
367
368 return video
369 }
c48e82b5 370}