]>
Commit | Line | Data |
---|---|---|
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 { getOrCreateAPVideo } 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 | const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video) | |
271 | await downloadPlaylistSegments(masterPlaylistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT) | |
272 | ||
273 | const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({ | |
274 | expiresOn, | |
275 | url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist), | |
276 | fileUrl: generateHLSRedundancyUrl(video, playlistArg), | |
277 | strategy, | |
278 | videoStreamingPlaylistId: playlist.id, | |
279 | actorId: serverActor.id | |
280 | }) | |
281 | ||
282 | createdModel.VideoStreamingPlaylist = playlist | |
283 | ||
284 | await sendCreateCacheFile(serverActor, video, createdModel) | |
285 | ||
286 | logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url) | |
287 | } | |
288 | ||
289 | private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) { | |
290 | logger.info('Extending expiration of %s.', redundancy.url) | |
291 | ||
292 | const serverActor = await getServerActor() | |
293 | ||
294 | redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs) | |
295 | await redundancy.save() | |
296 | ||
297 | await sendUpdateCacheFile(serverActor, redundancy) | |
298 | } | |
299 | ||
300 | private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) { | |
301 | while (await this.isTooHeavy(candidateToDuplicate)) { | |
302 | const redundancy = candidateToDuplicate.redundancy | |
303 | const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime) | |
304 | if (!toDelete) return | |
305 | ||
306 | const videoId = toDelete.VideoFile | |
307 | ? toDelete.VideoFile.videoId | |
308 | : toDelete.VideoStreamingPlaylist.videoId | |
309 | ||
310 | const redundancies = await VideoRedundancyModel.listLocalByVideoId(videoId) | |
311 | ||
312 | for (const redundancy of redundancies) { | |
313 | await removeVideoRedundancy(redundancy) | |
314 | } | |
315 | } | |
316 | } | |
317 | ||
318 | private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) { | |
319 | const maxSize = candidateToDuplicate.redundancy.size | |
320 | ||
321 | const { totalUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy) | |
322 | const totalWillDuplicate = totalUsed + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists) | |
323 | ||
324 | return totalWillDuplicate > maxSize | |
325 | } | |
326 | ||
327 | private buildNewExpiration (expiresAfterMs: number) { | |
328 | return new Date(Date.now() + expiresAfterMs) | |
329 | } | |
330 | ||
331 | private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) { | |
332 | if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}` | |
333 | ||
334 | return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}` | |
335 | } | |
336 | ||
337 | private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]) { | |
338 | const fileReducer = (previous: number, current: MVideoFile) => previous + current.size | |
339 | ||
340 | let allFiles = files | |
341 | for (const p of playlists) { | |
342 | allFiles = allFiles.concat(p.VideoFiles) | |
343 | } | |
344 | ||
345 | return allFiles.reduce(fileReducer, 0) | |
346 | } | |
347 | ||
348 | private async loadAndRefreshVideo (videoUrl: string) { | |
349 | // We need more attributes and check if the video still exists | |
350 | const getVideoOptions = { | |
351 | videoObject: videoUrl, | |
352 | syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true }, | |
353 | fetchType: 'all' as 'all' | |
354 | } | |
355 | const { video } = await getOrCreateAPVideo(getVideoOptions) | |
356 | ||
357 | return video | |
358 | } | |
359 | } |