]>
Commit | Line | Data |
---|---|---|
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 { totalUsed } = await VideoRedundancyModel.getStats(redundancyConfig.strategy) | |
119 | ||
120 | // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it | |
121 | if (!redundancyConfig || totalUsed > redundancyConfig.size) { | |
122 | logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy) | |
123 | ||
124 | await removeVideoRedundancy(redundancyModel) | |
125 | } else { | |
126 | await this.extendsRedundancy(redundancyModel) | |
127 | } | |
128 | } catch (err) { | |
129 | logger.error( | |
130 | 'Cannot extend or remove expiration of %s video from our redundancy system.', | |
131 | this.buildEntryLogId(redundancyModel), { err, ...lTags(redundancyModel.getVideoUUID()) } | |
132 | ) | |
133 | } | |
134 | } | |
135 | } | |
136 | ||
137 | private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) { | |
138 | const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy) | |
139 | // Redundancy strategy disabled, remove our redundancy instead of extending expiration | |
140 | if (!redundancy) { | |
141 | await removeVideoRedundancy(redundancyModel) | |
142 | return | |
143 | } | |
144 | ||
145 | await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime) | |
146 | } | |
147 | ||
148 | private async purgeRemoteExpired () { | |
149 | const expired = await VideoRedundancyModel.listRemoteExpired() | |
150 | ||
151 | for (const redundancyModel of expired) { | |
152 | try { | |
153 | await removeVideoRedundancy(redundancyModel) | |
154 | } catch (err) { | |
155 | logger.error( | |
156 | 'Cannot remove redundancy %s from our redundancy system.', | |
157 | this.buildEntryLogId(redundancyModel), lTags(redundancyModel.getVideoUUID()) | |
158 | ) | |
159 | } | |
160 | } | |
161 | } | |
162 | ||
163 | private findVideoToDuplicate (cache: VideosRedundancyStrategy) { | |
164 | if (cache.strategy === 'most-views') { | |
165 | return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR) | |
166 | } | |
167 | ||
168 | if (cache.strategy === 'trending') { | |
169 | return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR) | |
170 | } | |
171 | ||
172 | if (cache.strategy === 'recently-added') { | |
173 | const minViews = cache.minViews | |
174 | return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews) | |
175 | } | |
176 | } | |
177 | ||
178 | private async createVideoRedundancies (data: CandidateToDuplicate) { | |
179 | const video = await this.loadAndRefreshVideo(data.video.url) | |
180 | ||
181 | if (!video) { | |
182 | logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url, lTags(data.video.uuid)) | |
183 | ||
184 | return | |
185 | } | |
186 | ||
187 | for (const file of data.files) { | |
188 | const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id) | |
189 | if (existingRedundancy) { | |
190 | await this.extendsRedundancy(existingRedundancy) | |
191 | ||
192 | continue | |
193 | } | |
194 | ||
195 | await this.createVideoFileRedundancy(data.redundancy, video, file) | |
196 | } | |
197 | ||
198 | for (const streamingPlaylist of data.streamingPlaylists) { | |
199 | const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id) | |
200 | if (existingRedundancy) { | |
201 | await this.extendsRedundancy(existingRedundancy) | |
202 | ||
203 | continue | |
204 | } | |
205 | ||
206 | await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist) | |
207 | } | |
208 | } | |
209 | ||
210 | private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) { | |
211 | let strategy = 'manual' | |
212 | let expiresOn: Date = null | |
213 | ||
214 | if (redundancy) { | |
215 | strategy = redundancy.strategy | |
216 | expiresOn = this.buildNewExpiration(redundancy.minLifetime) | |
217 | } | |
218 | ||
219 | const file = fileArg as MVideoFileVideo | |
220 | file.Video = video | |
221 | ||
222 | const serverActor = await getServerActor() | |
223 | ||
224 | logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy, lTags(video.uuid)) | |
225 | ||
226 | const tmpPath = await downloadWebTorrentVideo({ uri: file.torrentUrl }, VIDEO_IMPORT_TIMEOUT) | |
227 | ||
228 | const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename) | |
229 | await move(tmpPath, destPath, { overwrite: true }) | |
230 | ||
231 | const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({ | |
232 | expiresOn, | |
233 | url: getLocalVideoCacheFileActivityPubUrl(file), | |
234 | fileUrl: generateWebTorrentRedundancyUrl(file), | |
235 | strategy, | |
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, lTags(video.uuid)) | |
245 | } | |
246 | ||
247 | private async createStreamingPlaylistRedundancy ( | |
248 | redundancy: VideosRedundancyStrategy, | |
249 | video: MVideoAccountLight, | |
250 | playlistArg: MStreamingPlaylistFiles | |
251 | ) { | |
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 | ||
260 | const playlist = Object.assign(playlistArg, { Video: video }) | |
261 | const serverActor = await getServerActor() | |
262 | ||
263 | logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy, lTags(video.uuid)) | |
264 | ||
265 | const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid) | |
266 | const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video) | |
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) | |
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.', masterPlaylistUrl, createdModel.url, lTags(video.uuid)) | |
286 | } | |
287 | ||
288 | private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) { | |
289 | logger.info('Extending expiration of %s.', redundancy.url, lTags(redundancy.getVideoUUID())) | |
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: alreadyUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy) | |
321 | ||
322 | const videoSize = this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists) | |
323 | const willUse = alreadyUsed + videoSize | |
324 | ||
325 | logger.debug('Checking candidate size.', { maxSize, alreadyUsed, videoSize, willUse, ...lTags(candidateToDuplicate.video.uuid) }) | |
326 | ||
327 | return willUse > maxSize | |
328 | } | |
329 | ||
330 | private buildNewExpiration (expiresAfterMs: number) { | |
331 | return new Date(Date.now() + expiresAfterMs) | |
332 | } | |
333 | ||
334 | private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) { | |
335 | if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}` | |
336 | ||
337 | return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}` | |
338 | } | |
339 | ||
340 | private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number { | |
341 | const fileReducer = (previous: number, current: MVideoFile) => previous + current.size | |
342 | ||
343 | let allFiles = files | |
344 | for (const p of playlists) { | |
345 | allFiles = allFiles.concat(p.VideoFiles) | |
346 | } | |
347 | ||
348 | return allFiles.reduce(fileReducer, 0) | |
349 | } | |
350 | ||
351 | private async loadAndRefreshVideo (videoUrl: string) { | |
352 | // We need more attributes and check if the video still exists | |
353 | const getVideoOptions = { | |
354 | videoObject: videoUrl, | |
355 | syncParam: { rates: false, shares: false, comments: false, thumbnail: false, refreshVideo: true }, | |
356 | fetchType: 'all' as 'all' | |
357 | } | |
358 | const { video } = await getOrCreateAPVideo(getVideoOptions) | |
359 | ||
360 | return video | |
361 | } | |
362 | } |