]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/schedulers/videos-redundancy-scheduler.ts
Disable openapi generation
[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'
d9a2a031 4import { TrackerModel } from '@server/models/server/tracker'
de94ac86 5import { VideoModel } from '@server/models/video/video'
453e83ea 6import {
de94ac86 7 MStreamingPlaylistFiles,
453e83ea
C
8 MVideoAccountLight,
9 MVideoFile,
10 MVideoFileVideo,
11 MVideoRedundancyFileVideo,
12 MVideoRedundancyStreamingPlaylistVideo,
13 MVideoRedundancyVideo,
14 MVideoWithAllFiles
26d6bf65 15} from '@server/types/models'
de94ac86
C
16import { VideosRedundancyStrategy } from '../../../shared/models/redundancy'
17import { logger } from '../../helpers/logger'
18import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent'
19import { CONFIG } from '../../initializers/config'
90a8bd30 20import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants'
de94ac86
C
21import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
22import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
23import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
304a84d5 24import { getOrCreateAPVideo } from '../activitypub/videos'
de94ac86
C
25import { downloadPlaylistSegments } from '../hls'
26import { removeVideoRedundancy } from '../redundancy'
90a8bd30 27import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-paths'
de94ac86 28import { AbstractScheduler } from './abstract-scheduler'
09209296
C
29
30type CandidateToDuplicate = {
a1587156
C
31 redundancy: VideosRedundancyStrategy
32 video: MVideoWithAllFiles
33 files: MVideoFile[]
66fb2aa3 34 streamingPlaylists: MStreamingPlaylistFiles[]
453e83ea
C
35}
36
0283eaac
C
37function isMVideoRedundancyFileVideo (
38 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
39): o is MVideoRedundancyFileVideo {
453e83ea 40 return !!(o as MVideoRedundancyFileVideo).VideoFile
09209296 41}
c48e82b5
C
42
43export class VideosRedundancyScheduler extends AbstractScheduler {
44
b764380a 45 private static instance: VideosRedundancyScheduler
c48e82b5 46
f9f899b9 47 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
c48e82b5
C
48
49 private constructor () {
50 super()
51 }
52
b764380a
C
53 async createManualRedundancy (videoId: number) {
54 const videoToDuplicate = await VideoModel.loadWithFiles(videoId)
55
56 if (!videoToDuplicate) {
57 logger.warn('Video to manually duplicate %d does not exist anymore.', videoId)
58 return
59 }
60
61 return this.createVideoRedundancies({
62 video: videoToDuplicate,
63 redundancy: null,
64 files: videoToDuplicate.VideoFiles,
65 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
66 })
67 }
68
2f5c6b2f 69 protected async internalExecute () {
09209296
C
70 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
71 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
1cfa8d68 72
c48e82b5 73 try {
09209296 74 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
c48e82b5
C
75 if (!videoToDuplicate) continue
76
09209296
C
77 const candidateToDuplicate = {
78 video: videoToDuplicate,
79 redundancy: redundancyConfig,
80 files: videoToDuplicate.VideoFiles,
81 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
82 }
c48e82b5 83
09209296 84 await this.purgeCacheIfNeeded(candidateToDuplicate)
e5565833 85
09209296 86 if (await this.isTooHeavy(candidateToDuplicate)) {
e5565833 87 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
c48e82b5
C
88 continue
89 }
90
09209296 91 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
c48e82b5 92
09209296 93 await this.createVideoRedundancies(candidateToDuplicate)
c48e82b5 94 } catch (err) {
09209296 95 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
c48e82b5
C
96 }
97 }
98
e5565833
C
99 await this.extendsLocalExpiration()
100
101 await this.purgeRemoteExpired()
f9f899b9
C
102 }
103
104 static get Instance () {
105 return this.instance || (this.instance = new this())
106 }
107
e5565833
C
108 private async extendsLocalExpiration () {
109 const expired = await VideoRedundancyModel.listLocalExpired()
110
111 for (const redundancyModel of expired) {
112 try {
09209296 113 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
b764380a 114 const candidate: CandidateToDuplicate = {
09209296
C
115 redundancy: redundancyConfig,
116 video: null,
117 files: [],
118 streamingPlaylists: []
119 }
120
121 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
122 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
123 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
124 await removeVideoRedundancy(redundancyModel)
125 } else {
126 await this.extendsRedundancy(redundancyModel)
127 }
e5565833 128 } catch (err) {
09209296
C
129 logger.error(
130 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
131 { err }
132 )
e5565833
C
133 }
134 }
135 }
c48e82b5 136
453e83ea 137 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
be691a57 138 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
09209296 139 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
0b353d1d
C
140 if (!redundancy) {
141 await removeVideoRedundancy(redundancyModel)
142 return
143 }
09209296 144
be691a57
C
145 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
146 }
147
e5565833
C
148 private async purgeRemoteExpired () {
149 const expired = await VideoRedundancyModel.listRemoteExpired()
c48e82b5 150
e5565833 151 for (const redundancyModel of expired) {
c48e82b5 152 try {
e5565833 153 await removeVideoRedundancy(redundancyModel)
c48e82b5 154 } catch (err) {
e5565833 155 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
c48e82b5
C
156 }
157 }
c48e82b5
C
158 }
159
b764380a 160 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
3f6b6a56
C
161 if (cache.strategy === 'most-views') {
162 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
163 }
164
165 if (cache.strategy === 'trending') {
166 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
167 }
b36f41ca 168
3f6b6a56 169 if (cache.strategy === 'recently-added') {
7348b1fd 170 const minViews = cache.minViews
3f6b6a56
C
171 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
172 }
c48e82b5
C
173 }
174
09209296
C
175 private async createVideoRedundancies (data: CandidateToDuplicate) {
176 const video = await this.loadAndRefreshVideo(data.video.url)
177
178 if (!video) {
179 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
c48e82b5 180
09209296
C
181 return
182 }
26649b42 183
09209296 184 for (const file of data.files) {
be691a57
C
185 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
186 if (existingRedundancy) {
09209296 187 await this.extendsRedundancy(existingRedundancy)
c48e82b5 188
c48e82b5
C
189 continue
190 }
191
09209296
C
192 await this.createVideoFileRedundancy(data.redundancy, video, file)
193 }
194
195 for (const streamingPlaylist of data.streamingPlaylists) {
196 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
197 if (existingRedundancy) {
198 await this.extendsRedundancy(existingRedundancy)
26649b42
C
199
200 continue
201 }
c48e82b5 202
09209296
C
203 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
204 }
205 }
c48e82b5 206
b764380a
C
207 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
208 let strategy = 'manual'
209 let expiresOn: Date = null
210
211 if (redundancy) {
212 strategy = redundancy.strategy
213 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
214 }
215
453e83ea 216 const file = fileArg as MVideoFileVideo
09209296 217 file.Video = video
c48e82b5 218
09209296 219 const serverActor = await getServerActor()
c48e82b5 220
b764380a 221 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy)
c48e82b5 222
d9a2a031
C
223 const trackerUrls = await TrackerModel.listUrlsByVideoId(video.id)
224 const magnetUri = generateMagnetUri(video, file, trackerUrls)
c48e82b5 225
09209296 226 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
792e5b8e 227
90a8bd30 228 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename)
217ffacf 229 await move(tmpPath, destPath, { overwrite: true })
09209296 230
453e83ea 231 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
b764380a 232 expiresOn,
de94ac86 233 url: getLocalVideoCacheFileActivityPubUrl(file),
90a8bd30 234 fileUrl: generateWebTorrentRedundancyUrl(file),
b764380a 235 strategy,
09209296
C
236 videoFileId: file.id,
237 actorId: serverActor.id
238 })
239
240 createdModel.VideoFile = file
241
242 await sendCreateCacheFile(serverActor, video, createdModel)
243
244 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
245 }
246
453e83ea 247 private async createStreamingPlaylistRedundancy (
b764380a 248 redundancy: VideosRedundancyStrategy,
453e83ea 249 video: MVideoAccountLight,
18998c45 250 playlistArg: MStreamingPlaylistFiles
453e83ea 251 ) {
b764380a
C
252 let strategy = 'manual'
253 let expiresOn: Date = null
254
255 if (redundancy) {
256 strategy = redundancy.strategy
257 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
258 }
259
18998c45 260 const playlist = Object.assign(playlistArg, { Video: video })
09209296
C
261 const serverActor = await getServerActor()
262
b764380a 263 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy)
09209296
C
264
265 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
764b1a14 266 const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video)
18998c45
C
267
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)
09209296 271
453e83ea 272 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
b764380a 273 expiresOn,
de94ac86 274 url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
90a8bd30 275 fileUrl: generateHLSRedundancyUrl(video, playlistArg),
b764380a 276 strategy,
09209296
C
277 videoStreamingPlaylistId: playlist.id,
278 actorId: serverActor.id
279 })
280
281 createdModel.VideoStreamingPlaylist = playlist
282
283 await sendCreateCacheFile(serverActor, video, createdModel)
284
764b1a14 285 logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url)
c48e82b5
C
286 }
287
453e83ea 288 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
e5565833
C
289 logger.info('Extending expiration of %s.', redundancy.url)
290
291 const serverActor = await getServerActor()
292
293 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
294 await redundancy.save()
295
296 await sendUpdateCacheFile(serverActor, redundancy)
297 }
298
09209296 299 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
f8278b96 300 while (await this.isTooHeavy(candidateToDuplicate)) {
09209296 301 const redundancy = candidateToDuplicate.redundancy
453e83ea 302 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
e5565833
C
303 if (!toDelete) return
304
89613cb4
C
305 const videoId = toDelete.VideoFile
306 ? toDelete.VideoFile.videoId
307 : toDelete.VideoStreamingPlaylist.videoId
308
309 const redundancies = await VideoRedundancyModel.listLocalByVideoId(videoId)
310
311 for (const redundancy of redundancies) {
312 await removeVideoRedundancy(redundancy)
313 }
e5565833
C
314 }
315 }
316
09209296
C
317 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
318 const maxSize = candidateToDuplicate.redundancy.size
c48e82b5 319
53e7f82f
C
320 const { totalUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy)
321 const totalWillDuplicate = totalUsed + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
c48e82b5 322
742ddee1 323 return totalWillDuplicate > maxSize
c48e82b5
C
324 }
325
e5565833
C
326 private buildNewExpiration (expiresAfterMs: number) {
327 return new Date(Date.now() + expiresAfterMs)
c48e82b5
C
328 }
329
453e83ea
C
330 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
331 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
09209296 332
764b1a14 333 return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}`
c48e82b5
C
334 }
335
18998c45 336 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number {
453e83ea 337 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
c48e82b5 338
66fb2aa3
C
339 let allFiles = files
340 for (const p of playlists) {
341 allFiles = allFiles.concat(p.VideoFiles)
342 }
26d78799 343
66fb2aa3 344 return allFiles.reduce(fileReducer, 0)
c48e82b5 345 }
be691a57
C
346
347 private async loadAndRefreshVideo (videoUrl: string) {
348 // We need more attributes and check if the video still exists
349 const getVideoOptions = {
350 videoObject: videoUrl,
351 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
352 fetchType: 'all' as 'all'
353 }
304a84d5 354 const { video } = await getOrCreateAPVideo(getVideoOptions)
be691a57
C
355
356 return video
357 }
c48e82b5 358}