]>
Commit | Line | Data |
---|---|---|
f481c4f9 | 1 | import { move } from 'fs-extra' |
de94ac86 C |
2 | import { join } from 'path' |
3 | import { getServerActor } from '@server/models/application/application' | |
d9a2a031 | 4 | import { TrackerModel } from '@server/models/server/tracker' |
de94ac86 | 5 | import { VideoModel } from '@server/models/video/video' |
453e83ea | 6 | import { |
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 | 16 | import { VideosRedundancyStrategy } from '../../../shared/models/redundancy' |
52b1fd15 | 17 | import { logger, loggerTagsFactory } from '../../helpers/logger' |
de94ac86 C |
18 | import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent' |
19 | import { CONFIG } from '../../initializers/config' | |
90a8bd30 | 20 | import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants' |
de94ac86 C |
21 | import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy' |
22 | import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send' | |
23 | import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url' | |
304a84d5 | 24 | import { getOrCreateAPVideo } from '../activitypub/videos' |
de94ac86 C |
25 | import { downloadPlaylistSegments } from '../hls' |
26 | import { removeVideoRedundancy } from '../redundancy' | |
0305db28 | 27 | import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-urls' |
de94ac86 | 28 | import { AbstractScheduler } from './abstract-scheduler' |
09209296 | 29 | |
52b1fd15 C |
30 | const lTags = loggerTagsFactory('redundancy') |
31 | ||
09209296 | 32 | type CandidateToDuplicate = { |
a1587156 C |
33 | redundancy: VideosRedundancyStrategy |
34 | video: MVideoWithAllFiles | |
35 | files: MVideoFile[] | |
66fb2aa3 | 36 | streamingPlaylists: MStreamingPlaylistFiles[] |
453e83ea C |
37 | } |
38 | ||
0283eaac C |
39 | function isMVideoRedundancyFileVideo ( |
40 | o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo | |
41 | ): o is MVideoRedundancyFileVideo { | |
453e83ea | 42 | return !!(o as MVideoRedundancyFileVideo).VideoFile |
09209296 | 43 | } |
c48e82b5 C |
44 | |
45 | export class VideosRedundancyScheduler extends AbstractScheduler { | |
46 | ||
b764380a | 47 | private static instance: VideosRedundancyScheduler |
c48e82b5 | 48 | |
f9f899b9 | 49 | protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL |
c48e82b5 C |
50 | |
51 | private constructor () { | |
52 | super() | |
53 | } | |
54 | ||
b764380a C |
55 | async createManualRedundancy (videoId: number) { |
56 | const videoToDuplicate = await VideoModel.loadWithFiles(videoId) | |
57 | ||
58 | if (!videoToDuplicate) { | |
52b1fd15 | 59 | logger.warn('Video to manually duplicate %d does not exist anymore.', videoId, lTags()) |
b764380a C |
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 | ||
2f5c6b2f | 71 | protected async internalExecute () { |
09209296 | 72 | for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) { |
52b1fd15 | 73 | logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy, lTags()) |
1cfa8d68 | 74 | |
c48e82b5 | 75 | try { |
09209296 | 76 | const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig) |
c48e82b5 C |
77 | if (!videoToDuplicate) continue |
78 | ||
09209296 C |
79 | const candidateToDuplicate = { |
80 | video: videoToDuplicate, | |
81 | redundancy: redundancyConfig, | |
82 | files: videoToDuplicate.VideoFiles, | |
83 | streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists | |
84 | } | |
c48e82b5 | 85 | |
09209296 | 86 | await this.purgeCacheIfNeeded(candidateToDuplicate) |
e5565833 | 87 | |
09209296 | 88 | if (await this.isTooHeavy(candidateToDuplicate)) { |
52b1fd15 | 89 | logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url, lTags(videoToDuplicate.uuid)) |
c48e82b5 C |
90 | continue |
91 | } | |
92 | ||
52b1fd15 C |
93 | logger.info( |
94 | 'Will duplicate video %s in redundancy scheduler "%s".', | |
95 | videoToDuplicate.url, redundancyConfig.strategy, lTags(videoToDuplicate.uuid) | |
96 | ) | |
c48e82b5 | 97 | |
09209296 | 98 | await this.createVideoRedundancies(candidateToDuplicate) |
c48e82b5 | 99 | } catch (err) { |
52b1fd15 | 100 | logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err, ...lTags() }) |
c48e82b5 C |
101 | } |
102 | } | |
103 | ||
e5565833 C |
104 | await this.extendsLocalExpiration() |
105 | ||
106 | await this.purgeRemoteExpired() | |
f9f899b9 C |
107 | } |
108 | ||
109 | static get Instance () { | |
110 | return this.instance || (this.instance = new this()) | |
111 | } | |
112 | ||
e5565833 C |
113 | private async extendsLocalExpiration () { |
114 | const expired = await VideoRedundancyModel.listLocalExpired() | |
115 | ||
116 | for (const redundancyModel of expired) { | |
117 | try { | |
09209296 | 118 | const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy) |
b764380a | 119 | const candidate: CandidateToDuplicate = { |
09209296 C |
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)) { | |
52b1fd15 C |
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 | ||
09209296 C |
133 | await removeVideoRedundancy(redundancyModel) |
134 | } else { | |
135 | await this.extendsRedundancy(redundancyModel) | |
136 | } | |
e5565833 | 137 | } catch (err) { |
09209296 | 138 | logger.error( |
52b1fd15 C |
139 | 'Cannot extend or remove expiration of %s video from our redundancy system.', |
140 | this.buildEntryLogId(redundancyModel), { err, ...lTags(redundancyModel.getVideoUUID()) } | |
09209296 | 141 | ) |
e5565833 C |
142 | } |
143 | } | |
144 | } | |
c48e82b5 | 145 | |
453e83ea | 146 | private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) { |
be691a57 | 147 | const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy) |
09209296 | 148 | // Redundancy strategy disabled, remove our redundancy instead of extending expiration |
0b353d1d C |
149 | if (!redundancy) { |
150 | await removeVideoRedundancy(redundancyModel) | |
151 | return | |
152 | } | |
09209296 | 153 | |
be691a57 C |
154 | await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime) |
155 | } | |
156 | ||
e5565833 C |
157 | private async purgeRemoteExpired () { |
158 | const expired = await VideoRedundancyModel.listRemoteExpired() | |
c48e82b5 | 159 | |
e5565833 | 160 | for (const redundancyModel of expired) { |
c48e82b5 | 161 | try { |
e5565833 | 162 | await removeVideoRedundancy(redundancyModel) |
c48e82b5 | 163 | } catch (err) { |
52b1fd15 C |
164 | logger.error( |
165 | 'Cannot remove redundancy %s from our redundancy system.', | |
166 | this.buildEntryLogId(redundancyModel), lTags(redundancyModel.getVideoUUID()) | |
167 | ) | |
c48e82b5 C |
168 | } |
169 | } | |
c48e82b5 C |
170 | } |
171 | ||
b764380a | 172 | private findVideoToDuplicate (cache: VideosRedundancyStrategy) { |
3f6b6a56 C |
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 | } | |
b36f41ca | 180 | |
3f6b6a56 | 181 | if (cache.strategy === 'recently-added') { |
7348b1fd | 182 | const minViews = cache.minViews |
3f6b6a56 C |
183 | return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews) |
184 | } | |
c48e82b5 C |
185 | } |
186 | ||
09209296 C |
187 | private async createVideoRedundancies (data: CandidateToDuplicate) { |
188 | const video = await this.loadAndRefreshVideo(data.video.url) | |
189 | ||
190 | if (!video) { | |
52b1fd15 | 191 | logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url, lTags(data.video.uuid)) |
c48e82b5 | 192 | |
09209296 C |
193 | return |
194 | } | |
26649b42 | 195 | |
09209296 | 196 | for (const file of data.files) { |
be691a57 C |
197 | const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id) |
198 | if (existingRedundancy) { | |
09209296 | 199 | await this.extendsRedundancy(existingRedundancy) |
c48e82b5 | 200 | |
c48e82b5 C |
201 | continue |
202 | } | |
203 | ||
09209296 C |
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) | |
26649b42 C |
211 | |
212 | continue | |
213 | } | |
c48e82b5 | 214 | |
09209296 C |
215 | await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist) |
216 | } | |
217 | } | |
c48e82b5 | 218 | |
b764380a C |
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 | ||
453e83ea | 228 | const file = fileArg as MVideoFileVideo |
09209296 | 229 | file.Video = video |
c48e82b5 | 230 | |
09209296 | 231 | const serverActor = await getServerActor() |
c48e82b5 | 232 | |
52b1fd15 | 233 | logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy, lTags(video.uuid)) |
c48e82b5 | 234 | |
d9a2a031 C |
235 | const trackerUrls = await TrackerModel.listUrlsByVideoId(video.id) |
236 | const magnetUri = generateMagnetUri(video, file, trackerUrls) | |
c48e82b5 | 237 | |
09209296 | 238 | const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT) |
792e5b8e | 239 | |
90a8bd30 | 240 | const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename) |
217ffacf | 241 | await move(tmpPath, destPath, { overwrite: true }) |
09209296 | 242 | |
453e83ea | 243 | const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({ |
b764380a | 244 | expiresOn, |
de94ac86 | 245 | url: getLocalVideoCacheFileActivityPubUrl(file), |
90a8bd30 | 246 | fileUrl: generateWebTorrentRedundancyUrl(file), |
b764380a | 247 | strategy, |
09209296 C |
248 | videoFileId: file.id, |
249 | actorId: serverActor.id | |
250 | }) | |
251 | ||
252 | createdModel.VideoFile = file | |
253 | ||
254 | await sendCreateCacheFile(serverActor, video, createdModel) | |
255 | ||
52b1fd15 | 256 | logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url, lTags(video.uuid)) |
09209296 C |
257 | } |
258 | ||
453e83ea | 259 | private async createStreamingPlaylistRedundancy ( |
b764380a | 260 | redundancy: VideosRedundancyStrategy, |
453e83ea | 261 | video: MVideoAccountLight, |
18998c45 | 262 | playlistArg: MStreamingPlaylistFiles |
453e83ea | 263 | ) { |
b764380a C |
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 | ||
18998c45 | 272 | const playlist = Object.assign(playlistArg, { Video: video }) |
09209296 C |
273 | const serverActor = await getServerActor() |
274 | ||
52b1fd15 | 275 | logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy, lTags(video.uuid)) |
09209296 C |
276 | |
277 | const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid) | |
764b1a14 | 278 | const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video) |
18998c45 C |
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) | |
09209296 | 283 | |
453e83ea | 284 | const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({ |
b764380a | 285 | expiresOn, |
de94ac86 | 286 | url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist), |
90a8bd30 | 287 | fileUrl: generateHLSRedundancyUrl(video, playlistArg), |
b764380a | 288 | strategy, |
09209296 C |
289 | videoStreamingPlaylistId: playlist.id, |
290 | actorId: serverActor.id | |
291 | }) | |
292 | ||
293 | createdModel.VideoStreamingPlaylist = playlist | |
294 | ||
295 | await sendCreateCacheFile(serverActor, video, createdModel) | |
296 | ||
52b1fd15 | 297 | logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url, lTags(video.uuid)) |
c48e82b5 C |
298 | } |
299 | ||
453e83ea | 300 | private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) { |
52b1fd15 | 301 | logger.info('Extending expiration of %s.', redundancy.url, lTags(redundancy.getVideoUUID())) |
e5565833 C |
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 | ||
09209296 | 311 | private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) { |
f8278b96 | 312 | while (await this.isTooHeavy(candidateToDuplicate)) { |
09209296 | 313 | const redundancy = candidateToDuplicate.redundancy |
453e83ea | 314 | const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime) |
e5565833 C |
315 | if (!toDelete) return |
316 | ||
89613cb4 C |
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 | } | |
e5565833 C |
326 | } |
327 | } | |
328 | ||
09209296 C |
329 | private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) { |
330 | const maxSize = candidateToDuplicate.redundancy.size | |
c48e82b5 | 331 | |
52b1fd15 C |
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) }) | |
c48e82b5 | 338 | |
52b1fd15 | 339 | return total > maxSize |
c48e82b5 C |
340 | } |
341 | ||
e5565833 C |
342 | private buildNewExpiration (expiresAfterMs: number) { |
343 | return new Date(Date.now() + expiresAfterMs) | |
c48e82b5 C |
344 | } |
345 | ||
453e83ea C |
346 | private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) { |
347 | if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}` | |
09209296 | 348 | |
764b1a14 | 349 | return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}` |
c48e82b5 C |
350 | } |
351 | ||
18998c45 | 352 | private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number { |
453e83ea | 353 | const fileReducer = (previous: number, current: MVideoFile) => previous + current.size |
c48e82b5 | 354 | |
66fb2aa3 C |
355 | let allFiles = files |
356 | for (const p of playlists) { | |
357 | allFiles = allFiles.concat(p.VideoFiles) | |
358 | } | |
26d78799 | 359 | |
66fb2aa3 | 360 | return allFiles.reduce(fileReducer, 0) |
c48e82b5 | 361 | } |
be691a57 C |
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 | } | |
304a84d5 | 370 | const { video } = await getOrCreateAPVideo(getVideoOptions) |
be691a57 C |
371 | |
372 | return video | |
373 | } | |
c48e82b5 | 374 | } |