]>
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' | |
4 | import { VideoModel } from '@server/models/video/video' | |
453e83ea | 5 | import { |
de94ac86 | 6 | MStreamingPlaylistFiles, |
453e83ea C |
7 | MVideoAccountLight, |
8 | MVideoFile, | |
9 | MVideoFileVideo, | |
10 | MVideoRedundancyFileVideo, | |
11 | MVideoRedundancyStreamingPlaylistVideo, | |
12 | MVideoRedundancyVideo, | |
13 | MVideoWithAllFiles | |
26d6bf65 | 14 | } from '@server/types/models' |
de94ac86 | 15 | import { VideosRedundancyStrategy } from '../../../shared/models/redundancy' |
52b1fd15 | 16 | import { logger, loggerTagsFactory } from '../../helpers/logger' |
02b286f8 | 17 | import { downloadWebTorrentVideo } from '../../helpers/webtorrent' |
de94ac86 | 18 | import { CONFIG } from '../../initializers/config' |
3545e72c | 19 | import { DIRECTORIES, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants' |
de94ac86 C |
20 | import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy' |
21 | import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send' | |
22 | import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url' | |
304a84d5 | 23 | import { getOrCreateAPVideo } from '../activitypub/videos' |
de94ac86 C |
24 | import { downloadPlaylistSegments } from '../hls' |
25 | import { removeVideoRedundancy } from '../redundancy' | |
0305db28 | 26 | import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-urls' |
de94ac86 | 27 | import { AbstractScheduler } from './abstract-scheduler' |
09209296 | 28 | |
52b1fd15 C |
29 | const lTags = loggerTagsFactory('redundancy') |
30 | ||
09209296 | 31 | type CandidateToDuplicate = { |
a1587156 C |
32 | redundancy: VideosRedundancyStrategy |
33 | video: MVideoWithAllFiles | |
34 | files: MVideoFile[] | |
66fb2aa3 | 35 | streamingPlaylists: MStreamingPlaylistFiles[] |
453e83ea C |
36 | } |
37 | ||
0283eaac C |
38 | function isMVideoRedundancyFileVideo ( |
39 | o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo | |
40 | ): o is MVideoRedundancyFileVideo { | |
453e83ea | 41 | return !!(o as MVideoRedundancyFileVideo).VideoFile |
09209296 | 42 | } |
c48e82b5 C |
43 | |
44 | export class VideosRedundancyScheduler extends AbstractScheduler { | |
45 | ||
b764380a | 46 | private static instance: VideosRedundancyScheduler |
c48e82b5 | 47 | |
f9f899b9 | 48 | protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL |
c48e82b5 C |
49 | |
50 | private constructor () { | |
51 | super() | |
52 | } | |
53 | ||
b764380a C |
54 | async createManualRedundancy (videoId: number) { |
55 | const videoToDuplicate = await VideoModel.loadWithFiles(videoId) | |
56 | ||
57 | if (!videoToDuplicate) { | |
52b1fd15 | 58 | logger.warn('Video to manually duplicate %d does not exist anymore.', videoId, lTags()) |
b764380a C |
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 | ||
2f5c6b2f | 70 | protected async internalExecute () { |
09209296 | 71 | for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) { |
52b1fd15 | 72 | logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy, lTags()) |
1cfa8d68 | 73 | |
c48e82b5 | 74 | try { |
09209296 | 75 | const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig) |
c48e82b5 C |
76 | if (!videoToDuplicate) continue |
77 | ||
09209296 C |
78 | const candidateToDuplicate = { |
79 | video: videoToDuplicate, | |
80 | redundancy: redundancyConfig, | |
81 | files: videoToDuplicate.VideoFiles, | |
82 | streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists | |
83 | } | |
c48e82b5 | 84 | |
09209296 | 85 | await this.purgeCacheIfNeeded(candidateToDuplicate) |
e5565833 | 86 | |
09209296 | 87 | if (await this.isTooHeavy(candidateToDuplicate)) { |
52b1fd15 | 88 | logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url, lTags(videoToDuplicate.uuid)) |
c48e82b5 C |
89 | continue |
90 | } | |
91 | ||
52b1fd15 C |
92 | logger.info( |
93 | 'Will duplicate video %s in redundancy scheduler "%s".', | |
94 | videoToDuplicate.url, redundancyConfig.strategy, lTags(videoToDuplicate.uuid) | |
95 | ) | |
c48e82b5 | 96 | |
09209296 | 97 | await this.createVideoRedundancies(candidateToDuplicate) |
c48e82b5 | 98 | } catch (err) { |
52b1fd15 | 99 | logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err, ...lTags() }) |
c48e82b5 C |
100 | } |
101 | } | |
102 | ||
e5565833 C |
103 | await this.extendsLocalExpiration() |
104 | ||
105 | await this.purgeRemoteExpired() | |
f9f899b9 C |
106 | } |
107 | ||
108 | static get Instance () { | |
109 | return this.instance || (this.instance = new this()) | |
110 | } | |
111 | ||
e5565833 C |
112 | private async extendsLocalExpiration () { |
113 | const expired = await VideoRedundancyModel.listLocalExpired() | |
114 | ||
115 | for (const redundancyModel of expired) { | |
116 | try { | |
09209296 | 117 | const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy) |
91c72729 C |
118 | |
119 | // If the admin disabled the redundancy, remove this redundancy instead of extending it | |
120 | if (!redundancyConfig) { | |
121 | logger.info( | |
122 | 'Destroying redundancy %s because the redundancy %s does not exist anymore.', | |
123 | redundancyModel.url, redundancyModel.strategy | |
124 | ) | |
125 | ||
126 | await removeVideoRedundancy(redundancyModel) | |
127 | continue | |
128 | } | |
129 | ||
3ef5909a | 130 | const { totalUsed } = await VideoRedundancyModel.getStats(redundancyConfig.strategy) |
09209296 | 131 | |
91c72729 C |
132 | // If the admin decreased the cache size, remove this redundancy instead of extending it |
133 | if (totalUsed > redundancyConfig.size) { | |
3ef5909a | 134 | logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy) |
52b1fd15 | 135 | |
09209296 | 136 | await removeVideoRedundancy(redundancyModel) |
91c72729 | 137 | continue |
09209296 | 138 | } |
91c72729 C |
139 | |
140 | await this.extendsRedundancy(redundancyModel) | |
e5565833 | 141 | } catch (err) { |
09209296 | 142 | logger.error( |
52b1fd15 C |
143 | 'Cannot extend or remove expiration of %s video from our redundancy system.', |
144 | this.buildEntryLogId(redundancyModel), { err, ...lTags(redundancyModel.getVideoUUID()) } | |
09209296 | 145 | ) |
e5565833 C |
146 | } |
147 | } | |
148 | } | |
c48e82b5 | 149 | |
453e83ea | 150 | private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) { |
be691a57 | 151 | const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy) |
09209296 | 152 | // Redundancy strategy disabled, remove our redundancy instead of extending expiration |
0b353d1d C |
153 | if (!redundancy) { |
154 | await removeVideoRedundancy(redundancyModel) | |
155 | return | |
156 | } | |
09209296 | 157 | |
be691a57 C |
158 | await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime) |
159 | } | |
160 | ||
e5565833 C |
161 | private async purgeRemoteExpired () { |
162 | const expired = await VideoRedundancyModel.listRemoteExpired() | |
c48e82b5 | 163 | |
e5565833 | 164 | for (const redundancyModel of expired) { |
c48e82b5 | 165 | try { |
e5565833 | 166 | await removeVideoRedundancy(redundancyModel) |
c48e82b5 | 167 | } catch (err) { |
52b1fd15 C |
168 | logger.error( |
169 | 'Cannot remove redundancy %s from our redundancy system.', | |
170 | this.buildEntryLogId(redundancyModel), lTags(redundancyModel.getVideoUUID()) | |
171 | ) | |
c48e82b5 C |
172 | } |
173 | } | |
c48e82b5 C |
174 | } |
175 | ||
b764380a | 176 | private findVideoToDuplicate (cache: VideosRedundancyStrategy) { |
3f6b6a56 C |
177 | if (cache.strategy === 'most-views') { |
178 | return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR) | |
179 | } | |
180 | ||
181 | if (cache.strategy === 'trending') { | |
182 | return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR) | |
183 | } | |
b36f41ca | 184 | |
3f6b6a56 | 185 | if (cache.strategy === 'recently-added') { |
7348b1fd | 186 | const minViews = cache.minViews |
3f6b6a56 C |
187 | return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews) |
188 | } | |
c48e82b5 C |
189 | } |
190 | ||
09209296 C |
191 | private async createVideoRedundancies (data: CandidateToDuplicate) { |
192 | const video = await this.loadAndRefreshVideo(data.video.url) | |
193 | ||
194 | if (!video) { | |
52b1fd15 | 195 | logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url, lTags(data.video.uuid)) |
c48e82b5 | 196 | |
09209296 C |
197 | return |
198 | } | |
26649b42 | 199 | |
09209296 | 200 | for (const file of data.files) { |
be691a57 C |
201 | const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id) |
202 | if (existingRedundancy) { | |
09209296 | 203 | await this.extendsRedundancy(existingRedundancy) |
c48e82b5 | 204 | |
c48e82b5 C |
205 | continue |
206 | } | |
207 | ||
09209296 C |
208 | await this.createVideoFileRedundancy(data.redundancy, video, file) |
209 | } | |
210 | ||
211 | for (const streamingPlaylist of data.streamingPlaylists) { | |
212 | const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id) | |
213 | if (existingRedundancy) { | |
214 | await this.extendsRedundancy(existingRedundancy) | |
26649b42 C |
215 | |
216 | continue | |
217 | } | |
c48e82b5 | 218 | |
09209296 C |
219 | await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist) |
220 | } | |
221 | } | |
c48e82b5 | 222 | |
b764380a C |
223 | private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) { |
224 | let strategy = 'manual' | |
225 | let expiresOn: Date = null | |
226 | ||
227 | if (redundancy) { | |
228 | strategy = redundancy.strategy | |
229 | expiresOn = this.buildNewExpiration(redundancy.minLifetime) | |
230 | } | |
231 | ||
453e83ea | 232 | const file = fileArg as MVideoFileVideo |
09209296 | 233 | file.Video = video |
c48e82b5 | 234 | |
09209296 | 235 | const serverActor = await getServerActor() |
c48e82b5 | 236 | |
52b1fd15 | 237 | logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy, lTags(video.uuid)) |
c48e82b5 | 238 | |
02b286f8 | 239 | const tmpPath = await downloadWebTorrentVideo({ uri: file.torrentUrl }, VIDEO_IMPORT_TIMEOUT) |
792e5b8e | 240 | |
90a8bd30 | 241 | const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename) |
217ffacf | 242 | await move(tmpPath, destPath, { overwrite: true }) |
09209296 | 243 | |
453e83ea | 244 | const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({ |
b764380a | 245 | expiresOn, |
de94ac86 | 246 | url: getLocalVideoCacheFileActivityPubUrl(file), |
90a8bd30 | 247 | fileUrl: generateWebTorrentRedundancyUrl(file), |
b764380a | 248 | strategy, |
09209296 C |
249 | videoFileId: file.id, |
250 | actorId: serverActor.id | |
251 | }) | |
252 | ||
253 | createdModel.VideoFile = file | |
254 | ||
255 | await sendCreateCacheFile(serverActor, video, createdModel) | |
256 | ||
52b1fd15 | 257 | logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url, lTags(video.uuid)) |
09209296 C |
258 | } |
259 | ||
453e83ea | 260 | private async createStreamingPlaylistRedundancy ( |
b764380a | 261 | redundancy: VideosRedundancyStrategy, |
453e83ea | 262 | video: MVideoAccountLight, |
18998c45 | 263 | playlistArg: MStreamingPlaylistFiles |
453e83ea | 264 | ) { |
b764380a C |
265 | let strategy = 'manual' |
266 | let expiresOn: Date = null | |
267 | ||
268 | if (redundancy) { | |
269 | strategy = redundancy.strategy | |
270 | expiresOn = this.buildNewExpiration(redundancy.minLifetime) | |
271 | } | |
272 | ||
18998c45 | 273 | const playlist = Object.assign(playlistArg, { Video: video }) |
09209296 C |
274 | const serverActor = await getServerActor() |
275 | ||
52b1fd15 | 276 | logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy, lTags(video.uuid)) |
09209296 | 277 | |
3545e72c | 278 | const destDirectory = join(DIRECTORIES.HLS_REDUNDANCY, video.uuid) |
764b1a14 | 279 | const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video) |
18998c45 C |
280 | |
281 | const maxSizeKB = this.getTotalFileSizes([], [ playlist ]) / 1000 | |
282 | const toleranceKB = maxSizeKB + ((5 * maxSizeKB) / 100) // 5% more tolerance | |
283 | await downloadPlaylistSegments(masterPlaylistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT, toleranceKB) | |
09209296 | 284 | |
453e83ea | 285 | const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({ |
b764380a | 286 | expiresOn, |
de94ac86 | 287 | url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist), |
90a8bd30 | 288 | fileUrl: generateHLSRedundancyUrl(video, playlistArg), |
b764380a | 289 | strategy, |
09209296 C |
290 | videoStreamingPlaylistId: playlist.id, |
291 | actorId: serverActor.id | |
292 | }) | |
293 | ||
294 | createdModel.VideoStreamingPlaylist = playlist | |
295 | ||
296 | await sendCreateCacheFile(serverActor, video, createdModel) | |
297 | ||
52b1fd15 | 298 | logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url, lTags(video.uuid)) |
c48e82b5 C |
299 | } |
300 | ||
453e83ea | 301 | private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) { |
52b1fd15 | 302 | logger.info('Extending expiration of %s.', redundancy.url, lTags(redundancy.getVideoUUID())) |
e5565833 C |
303 | |
304 | const serverActor = await getServerActor() | |
305 | ||
306 | redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs) | |
307 | await redundancy.save() | |
308 | ||
309 | await sendUpdateCacheFile(serverActor, redundancy) | |
310 | } | |
311 | ||
09209296 | 312 | private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) { |
f8278b96 | 313 | while (await this.isTooHeavy(candidateToDuplicate)) { |
09209296 | 314 | const redundancy = candidateToDuplicate.redundancy |
453e83ea | 315 | const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime) |
e5565833 C |
316 | if (!toDelete) return |
317 | ||
89613cb4 C |
318 | const videoId = toDelete.VideoFile |
319 | ? toDelete.VideoFile.videoId | |
320 | : toDelete.VideoStreamingPlaylist.videoId | |
321 | ||
322 | const redundancies = await VideoRedundancyModel.listLocalByVideoId(videoId) | |
323 | ||
324 | for (const redundancy of redundancies) { | |
325 | await removeVideoRedundancy(redundancy) | |
326 | } | |
e5565833 C |
327 | } |
328 | } | |
329 | ||
09209296 C |
330 | private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) { |
331 | const maxSize = candidateToDuplicate.redundancy.size | |
c48e82b5 | 332 | |
0bae6663 | 333 | const { totalUsed: alreadyUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy) |
52b1fd15 C |
334 | |
335 | const videoSize = this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists) | |
0bae6663 | 336 | const willUse = alreadyUsed + videoSize |
52b1fd15 | 337 | |
0bae6663 | 338 | logger.debug('Checking candidate size.', { maxSize, alreadyUsed, videoSize, willUse, ...lTags(candidateToDuplicate.video.uuid) }) |
c48e82b5 | 339 | |
0bae6663 | 340 | return willUse > maxSize |
c48e82b5 C |
341 | } |
342 | ||
e5565833 C |
343 | private buildNewExpiration (expiresAfterMs: number) { |
344 | return new Date(Date.now() + expiresAfterMs) | |
c48e82b5 C |
345 | } |
346 | ||
453e83ea C |
347 | private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) { |
348 | if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}` | |
09209296 | 349 | |
764b1a14 | 350 | return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}` |
c48e82b5 C |
351 | } |
352 | ||
18998c45 | 353 | private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number { |
453e83ea | 354 | const fileReducer = (previous: number, current: MVideoFile) => previous + current.size |
c48e82b5 | 355 | |
66fb2aa3 C |
356 | let allFiles = files |
357 | for (const p of playlists) { | |
358 | allFiles = allFiles.concat(p.VideoFiles) | |
359 | } | |
26d78799 | 360 | |
66fb2aa3 | 361 | return allFiles.reduce(fileReducer, 0) |
c48e82b5 | 362 | } |
be691a57 C |
363 | |
364 | private async loadAndRefreshVideo (videoUrl: string) { | |
365 | // We need more attributes and check if the video still exists | |
366 | const getVideoOptions = { | |
367 | videoObject: videoUrl, | |
57e4e1c1 | 368 | syncParam: { rates: false, shares: false, comments: false, thumbnail: false, refreshVideo: true }, |
be691a57 C |
369 | fetchType: 'all' as 'all' |
370 | } | |
304a84d5 | 371 | const { video } = await getOrCreateAPVideo(getVideoOptions) |
be691a57 C |
372 | |
373 | return video | |
374 | } | |
c48e82b5 | 375 | } |