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