]>
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' |
90a8bd30 | 19 | import { HLS_REDUNDANCY_DIRECTORY, 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) |
3ef5909a | 118 | const { totalUsed } = await VideoRedundancyModel.getStats(redundancyConfig.strategy) |
09209296 C |
119 | |
120 | // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it | |
3ef5909a C |
121 | if (!redundancyConfig || totalUsed > redundancyConfig.size) { |
122 | logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy) | |
52b1fd15 | 123 | |
09209296 C |
124 | await removeVideoRedundancy(redundancyModel) |
125 | } else { | |
126 | await this.extendsRedundancy(redundancyModel) | |
127 | } | |
e5565833 | 128 | } catch (err) { |
09209296 | 129 | logger.error( |
52b1fd15 C |
130 | 'Cannot extend or remove expiration of %s video from our redundancy system.', |
131 | this.buildEntryLogId(redundancyModel), { err, ...lTags(redundancyModel.getVideoUUID()) } | |
09209296 | 132 | ) |
e5565833 C |
133 | } |
134 | } | |
135 | } | |
c48e82b5 | 136 | |
453e83ea | 137 | private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) { |
be691a57 | 138 | const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy) |
09209296 | 139 | // Redundancy strategy disabled, remove our redundancy instead of extending expiration |
0b353d1d C |
140 | if (!redundancy) { |
141 | await removeVideoRedundancy(redundancyModel) | |
142 | return | |
143 | } | |
09209296 | 144 | |
be691a57 C |
145 | await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime) |
146 | } | |
147 | ||
e5565833 C |
148 | private async purgeRemoteExpired () { |
149 | const expired = await VideoRedundancyModel.listRemoteExpired() | |
c48e82b5 | 150 | |
e5565833 | 151 | for (const redundancyModel of expired) { |
c48e82b5 | 152 | try { |
e5565833 | 153 | await removeVideoRedundancy(redundancyModel) |
c48e82b5 | 154 | } catch (err) { |
52b1fd15 C |
155 | logger.error( |
156 | 'Cannot remove redundancy %s from our redundancy system.', | |
157 | this.buildEntryLogId(redundancyModel), lTags(redundancyModel.getVideoUUID()) | |
158 | ) | |
c48e82b5 C |
159 | } |
160 | } | |
c48e82b5 C |
161 | } |
162 | ||
b764380a | 163 | private findVideoToDuplicate (cache: VideosRedundancyStrategy) { |
3f6b6a56 C |
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 | } | |
b36f41ca | 171 | |
3f6b6a56 | 172 | if (cache.strategy === 'recently-added') { |
7348b1fd | 173 | const minViews = cache.minViews |
3f6b6a56 C |
174 | return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews) |
175 | } | |
c48e82b5 C |
176 | } |
177 | ||
09209296 C |
178 | private async createVideoRedundancies (data: CandidateToDuplicate) { |
179 | const video = await this.loadAndRefreshVideo(data.video.url) | |
180 | ||
181 | if (!video) { | |
52b1fd15 | 182 | logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url, lTags(data.video.uuid)) |
c48e82b5 | 183 | |
09209296 C |
184 | return |
185 | } | |
26649b42 | 186 | |
09209296 | 187 | for (const file of data.files) { |
be691a57 C |
188 | const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id) |
189 | if (existingRedundancy) { | |
09209296 | 190 | await this.extendsRedundancy(existingRedundancy) |
c48e82b5 | 191 | |
c48e82b5 C |
192 | continue |
193 | } | |
194 | ||
09209296 C |
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) | |
26649b42 C |
202 | |
203 | continue | |
204 | } | |
c48e82b5 | 205 | |
09209296 C |
206 | await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist) |
207 | } | |
208 | } | |
c48e82b5 | 209 | |
b764380a C |
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 | ||
453e83ea | 219 | const file = fileArg as MVideoFileVideo |
09209296 | 220 | file.Video = video |
c48e82b5 | 221 | |
09209296 | 222 | const serverActor = await getServerActor() |
c48e82b5 | 223 | |
52b1fd15 | 224 | logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy, lTags(video.uuid)) |
c48e82b5 | 225 | |
02b286f8 | 226 | const tmpPath = await downloadWebTorrentVideo({ uri: file.torrentUrl }, VIDEO_IMPORT_TIMEOUT) |
792e5b8e | 227 | |
90a8bd30 | 228 | const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename) |
217ffacf | 229 | await move(tmpPath, destPath, { overwrite: true }) |
09209296 | 230 | |
453e83ea | 231 | const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({ |
b764380a | 232 | expiresOn, |
de94ac86 | 233 | url: getLocalVideoCacheFileActivityPubUrl(file), |
90a8bd30 | 234 | fileUrl: generateWebTorrentRedundancyUrl(file), |
b764380a | 235 | strategy, |
09209296 C |
236 | videoFileId: file.id, |
237 | actorId: serverActor.id | |
238 | }) | |
239 | ||
240 | createdModel.VideoFile = file | |
241 | ||
242 | await sendCreateCacheFile(serverActor, video, createdModel) | |
243 | ||
52b1fd15 | 244 | logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url, lTags(video.uuid)) |
09209296 C |
245 | } |
246 | ||
453e83ea | 247 | private async createStreamingPlaylistRedundancy ( |
b764380a | 248 | redundancy: VideosRedundancyStrategy, |
453e83ea | 249 | video: MVideoAccountLight, |
18998c45 | 250 | playlistArg: MStreamingPlaylistFiles |
453e83ea | 251 | ) { |
b764380a C |
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 | ||
18998c45 | 260 | const playlist = Object.assign(playlistArg, { Video: video }) |
09209296 C |
261 | const serverActor = await getServerActor() |
262 | ||
52b1fd15 | 263 | logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy, lTags(video.uuid)) |
09209296 C |
264 | |
265 | const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid) | |
764b1a14 | 266 | const masterPlaylistUrl = playlist.getMasterPlaylistUrl(video) |
18998c45 C |
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) | |
09209296 | 271 | |
453e83ea | 272 | const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({ |
b764380a | 273 | expiresOn, |
de94ac86 | 274 | url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist), |
90a8bd30 | 275 | fileUrl: generateHLSRedundancyUrl(video, playlistArg), |
b764380a | 276 | strategy, |
09209296 C |
277 | videoStreamingPlaylistId: playlist.id, |
278 | actorId: serverActor.id | |
279 | }) | |
280 | ||
281 | createdModel.VideoStreamingPlaylist = playlist | |
282 | ||
283 | await sendCreateCacheFile(serverActor, video, createdModel) | |
284 | ||
52b1fd15 | 285 | logger.info('Duplicated playlist %s -> %s.', masterPlaylistUrl, createdModel.url, lTags(video.uuid)) |
c48e82b5 C |
286 | } |
287 | ||
453e83ea | 288 | private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) { |
52b1fd15 | 289 | logger.info('Extending expiration of %s.', redundancy.url, lTags(redundancy.getVideoUUID())) |
e5565833 C |
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 | ||
09209296 | 299 | private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) { |
f8278b96 | 300 | while (await this.isTooHeavy(candidateToDuplicate)) { |
09209296 | 301 | const redundancy = candidateToDuplicate.redundancy |
453e83ea | 302 | const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime) |
e5565833 C |
303 | if (!toDelete) return |
304 | ||
89613cb4 C |
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 | } | |
e5565833 C |
314 | } |
315 | } | |
316 | ||
09209296 C |
317 | private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) { |
318 | const maxSize = candidateToDuplicate.redundancy.size | |
c48e82b5 | 319 | |
0bae6663 | 320 | const { totalUsed: alreadyUsed } = await VideoRedundancyModel.getStats(candidateToDuplicate.redundancy.strategy) |
52b1fd15 C |
321 | |
322 | const videoSize = this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists) | |
0bae6663 | 323 | const willUse = alreadyUsed + videoSize |
52b1fd15 | 324 | |
0bae6663 | 325 | logger.debug('Checking candidate size.', { maxSize, alreadyUsed, videoSize, willUse, ...lTags(candidateToDuplicate.video.uuid) }) |
c48e82b5 | 326 | |
0bae6663 | 327 | return willUse > maxSize |
c48e82b5 C |
328 | } |
329 | ||
e5565833 C |
330 | private buildNewExpiration (expiresAfterMs: number) { |
331 | return new Date(Date.now() + expiresAfterMs) | |
c48e82b5 C |
332 | } |
333 | ||
453e83ea C |
334 | private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) { |
335 | if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}` | |
09209296 | 336 | |
764b1a14 | 337 | return `${object.VideoStreamingPlaylist.getMasterPlaylistUrl(object.VideoStreamingPlaylist.Video)}` |
c48e82b5 C |
338 | } |
339 | ||
18998c45 | 340 | private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]): number { |
453e83ea | 341 | const fileReducer = (previous: number, current: MVideoFile) => previous + current.size |
c48e82b5 | 342 | |
66fb2aa3 C |
343 | let allFiles = files |
344 | for (const p of playlists) { | |
345 | allFiles = allFiles.concat(p.VideoFiles) | |
346 | } | |
26d78799 | 347 | |
66fb2aa3 | 348 | return allFiles.reduce(fileReducer, 0) |
c48e82b5 | 349 | } |
be691a57 C |
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, | |
57e4e1c1 | 355 | syncParam: { rates: false, shares: false, comments: false, thumbnail: false, refreshVideo: true }, |
be691a57 C |
356 | fetchType: 'all' as 'all' |
357 | } | |
304a84d5 | 358 | const { video } = await getOrCreateAPVideo(getVideoOptions) |
be691a57 C |
359 | |
360 | return video | |
361 | } | |
c48e82b5 | 362 | } |