]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/schedulers/videos-redundancy-scheduler.ts
Merge branch 'release/3.2.0' into develop
[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 MStreamingPlaylist,
8 MStreamingPlaylistFiles,
9 MStreamingPlaylistVideo,
10 MVideoAccountLight,
11 MVideoFile,
12 MVideoFileVideo,
13 MVideoRedundancyFileVideo,
14 MVideoRedundancyStreamingPlaylistVideo,
15 MVideoRedundancyVideo,
16 MVideoWithAllFiles
17 } from '@server/types/models'
18 import { VideosRedundancyStrategy } from '../../../shared/models/redundancy'
19 import { logger } from '../../helpers/logger'
20 import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent'
21 import { CONFIG } from '../../initializers/config'
22 import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants'
23 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
24 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
25 import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
26 import { getOrCreateVideoAndAccountAndChannel } from '../activitypub/videos'
27 import { downloadPlaylistSegments } from '../hls'
28 import { removeVideoRedundancy } from '../redundancy'
29 import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-paths'
30 import { AbstractScheduler } from './abstract-scheduler'
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)
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)
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)
90 continue
91 }
92
93 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
94
95 await this.createVideoRedundancies(candidateToDuplicate)
96 } catch (err) {
97 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
98 }
99 }
100
101 await this.extendsLocalExpiration()
102
103 await this.purgeRemoteExpired()
104 }
105
106 static get Instance () {
107 return this.instance || (this.instance = new this())
108 }
109
110 private async extendsLocalExpiration () {
111 const expired = await VideoRedundancyModel.listLocalExpired()
112
113 for (const redundancyModel of expired) {
114 try {
115 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
116 const candidate: CandidateToDuplicate = {
117 redundancy: redundancyConfig,
118 video: null,
119 files: [],
120 streamingPlaylists: []
121 }
122
123 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
124 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
125 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
126 await removeVideoRedundancy(redundancyModel)
127 } else {
128 await this.extendsRedundancy(redundancyModel)
129 }
130 } catch (err) {
131 logger.error(
132 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
133 { err }
134 )
135 }
136 }
137 }
138
139 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
140 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
141 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
142 if (!redundancy) {
143 await removeVideoRedundancy(redundancyModel)
144 return
145 }
146
147 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
148 }
149
150 private async purgeRemoteExpired () {
151 const expired = await VideoRedundancyModel.listRemoteExpired()
152
153 for (const redundancyModel of expired) {
154 try {
155 await removeVideoRedundancy(redundancyModel)
156 } catch (err) {
157 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
158 }
159 }
160 }
161
162 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
163 if (cache.strategy === 'most-views') {
164 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
165 }
166
167 if (cache.strategy === 'trending') {
168 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
169 }
170
171 if (cache.strategy === 'recently-added') {
172 const minViews = cache.minViews
173 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
174 }
175 }
176
177 private async createVideoRedundancies (data: CandidateToDuplicate) {
178 const video = await this.loadAndRefreshVideo(data.video.url)
179
180 if (!video) {
181 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
182
183 return
184 }
185
186 for (const file of data.files) {
187 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
188 if (existingRedundancy) {
189 await this.extendsRedundancy(existingRedundancy)
190
191 continue
192 }
193
194 await this.createVideoFileRedundancy(data.redundancy, video, file)
195 }
196
197 for (const streamingPlaylist of data.streamingPlaylists) {
198 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
199 if (existingRedundancy) {
200 await this.extendsRedundancy(existingRedundancy)
201
202 continue
203 }
204
205 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
206 }
207 }
208
209 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
210 let strategy = 'manual'
211 let expiresOn: Date = null
212
213 if (redundancy) {
214 strategy = redundancy.strategy
215 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
216 }
217
218 const file = fileArg as MVideoFileVideo
219 file.Video = video
220
221 const serverActor = await getServerActor()
222
223 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy)
224
225 const trackerUrls = await TrackerModel.listUrlsByVideoId(video.id)
226 const magnetUri = generateMagnetUri(video, file, trackerUrls)
227
228 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
229
230 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename)
231 await move(tmpPath, destPath, { overwrite: true })
232
233 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
234 expiresOn,
235 url: getLocalVideoCacheFileActivityPubUrl(file),
236 fileUrl: generateWebTorrentRedundancyUrl(file),
237 strategy,
238 videoFileId: file.id,
239 actorId: serverActor.id
240 })
241
242 createdModel.VideoFile = file
243
244 await sendCreateCacheFile(serverActor, video, createdModel)
245
246 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
247 }
248
249 private async createStreamingPlaylistRedundancy (
250 redundancy: VideosRedundancyStrategy,
251 video: MVideoAccountLight,
252 playlistArg: MStreamingPlaylist
253 ) {
254 let strategy = 'manual'
255 let expiresOn: Date = null
256
257 if (redundancy) {
258 strategy = redundancy.strategy
259 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
260 }
261
262 const playlist = playlistArg as MStreamingPlaylistVideo
263 playlist.Video = video
264
265 const serverActor = await getServerActor()
266
267 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy)
268
269 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
270 await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT)
271
272 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
273 expiresOn,
274 url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
275 fileUrl: generateHLSRedundancyUrl(video, playlistArg),
276 strategy,
277 videoStreamingPlaylistId: playlist.id,
278 actorId: serverActor.id
279 })
280
281 createdModel.VideoStreamingPlaylist = playlist
282
283 await sendCreateCacheFile(serverActor, video, createdModel)
284
285 logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url)
286 }
287
288 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
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
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
304
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 }
314 }
315 }
316
317 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
318 const maxSize = candidateToDuplicate.redundancy.size
319
320 const { totalUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy)
321 const totalWillDuplicate = totalUsed + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
322
323 return totalWillDuplicate > maxSize
324 }
325
326 private buildNewExpiration (expiresAfterMs: number) {
327 return new Date(Date.now() + expiresAfterMs)
328 }
329
330 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
331 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
332
333 return `${object.VideoStreamingPlaylist.playlistUrl}`
334 }
335
336 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]) {
337 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
338
339 let allFiles = files
340 for (const p of playlists) {
341 allFiles = allFiles.concat(p.VideoFiles)
342 }
343
344 return allFiles.reduce(fileReducer, 0)
345 }
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 }
354 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)
355
356 return video
357 }
358 }