]>
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 C |
6 | MStreamingPlaylist, |
7 | MStreamingPlaylistFiles, | |
453e83ea C |
8 | MStreamingPlaylistVideo, |
9 | MVideoAccountLight, | |
10 | MVideoFile, | |
11 | MVideoFileVideo, | |
12 | MVideoRedundancyFileVideo, | |
13 | MVideoRedundancyStreamingPlaylistVideo, | |
14 | MVideoRedundancyVideo, | |
15 | MVideoWithAllFiles | |
26d6bf65 | 16 | } from '@server/types/models' |
de94ac86 C |
17 | import { VideosRedundancyStrategy } from '../../../shared/models/redundancy' |
18 | import { logger } from '../../helpers/logger' | |
19 | import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent' | |
20 | import { CONFIG } from '../../initializers/config' | |
90a8bd30 | 21 | import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers/constants' |
de94ac86 C |
22 | import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy' |
23 | import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send' | |
24 | import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url' | |
25 | import { getOrCreateVideoAndAccountAndChannel } from '../activitypub/videos' | |
26 | import { downloadPlaylistSegments } from '../hls' | |
27 | import { removeVideoRedundancy } from '../redundancy' | |
90a8bd30 | 28 | import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-paths' |
de94ac86 | 29 | import { AbstractScheduler } from './abstract-scheduler' |
09209296 C |
30 | |
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) { | |
58 | logger.warn('Video to manually duplicate %d does not exist anymore.', videoId) | |
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 C |
71 | for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) { |
72 | logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy) | |
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)) { |
e5565833 | 88 | logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url) |
c48e82b5 C |
89 | continue |
90 | } | |
91 | ||
09209296 | 92 | logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy) |
c48e82b5 | 93 | |
09209296 | 94 | await this.createVideoRedundancies(candidateToDuplicate) |
c48e82b5 | 95 | } catch (err) { |
09209296 | 96 | logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err }) |
c48e82b5 C |
97 | } |
98 | } | |
99 | ||
e5565833 C |
100 | await this.extendsLocalExpiration() |
101 | ||
102 | await this.purgeRemoteExpired() | |
f9f899b9 C |
103 | } |
104 | ||
105 | static get Instance () { | |
106 | return this.instance || (this.instance = new this()) | |
107 | } | |
108 | ||
e5565833 C |
109 | private async extendsLocalExpiration () { |
110 | const expired = await VideoRedundancyModel.listLocalExpired() | |
111 | ||
112 | for (const redundancyModel of expired) { | |
113 | try { | |
09209296 | 114 | const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy) |
b764380a | 115 | const candidate: CandidateToDuplicate = { |
09209296 C |
116 | redundancy: redundancyConfig, |
117 | video: null, | |
118 | files: [], | |
119 | streamingPlaylists: [] | |
120 | } | |
121 | ||
122 | // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it | |
123 | if (!redundancyConfig || await this.isTooHeavy(candidate)) { | |
124 | logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy) | |
125 | await removeVideoRedundancy(redundancyModel) | |
126 | } else { | |
127 | await this.extendsRedundancy(redundancyModel) | |
128 | } | |
e5565833 | 129 | } catch (err) { |
09209296 C |
130 | logger.error( |
131 | 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel), | |
132 | { err } | |
133 | ) | |
e5565833 C |
134 | } |
135 | } | |
136 | } | |
c48e82b5 | 137 | |
453e83ea | 138 | private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) { |
be691a57 | 139 | const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy) |
09209296 | 140 | // Redundancy strategy disabled, remove our redundancy instead of extending expiration |
0b353d1d C |
141 | if (!redundancy) { |
142 | await removeVideoRedundancy(redundancyModel) | |
143 | return | |
144 | } | |
09209296 | 145 | |
be691a57 C |
146 | await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime) |
147 | } | |
148 | ||
e5565833 C |
149 | private async purgeRemoteExpired () { |
150 | const expired = await VideoRedundancyModel.listRemoteExpired() | |
c48e82b5 | 151 | |
e5565833 | 152 | for (const redundancyModel of expired) { |
c48e82b5 | 153 | try { |
e5565833 | 154 | await removeVideoRedundancy(redundancyModel) |
c48e82b5 | 155 | } catch (err) { |
e5565833 | 156 | logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel)) |
c48e82b5 C |
157 | } |
158 | } | |
c48e82b5 C |
159 | } |
160 | ||
b764380a | 161 | private findVideoToDuplicate (cache: VideosRedundancyStrategy) { |
3f6b6a56 C |
162 | if (cache.strategy === 'most-views') { |
163 | return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR) | |
164 | } | |
165 | ||
166 | if (cache.strategy === 'trending') { | |
167 | return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR) | |
168 | } | |
b36f41ca | 169 | |
3f6b6a56 | 170 | if (cache.strategy === 'recently-added') { |
7348b1fd | 171 | const minViews = cache.minViews |
3f6b6a56 C |
172 | return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews) |
173 | } | |
c48e82b5 C |
174 | } |
175 | ||
09209296 C |
176 | private async createVideoRedundancies (data: CandidateToDuplicate) { |
177 | const video = await this.loadAndRefreshVideo(data.video.url) | |
178 | ||
179 | if (!video) { | |
180 | logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url) | |
c48e82b5 | 181 | |
09209296 C |
182 | return |
183 | } | |
26649b42 | 184 | |
09209296 | 185 | for (const file of data.files) { |
be691a57 C |
186 | const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id) |
187 | if (existingRedundancy) { | |
09209296 | 188 | await this.extendsRedundancy(existingRedundancy) |
c48e82b5 | 189 | |
c48e82b5 C |
190 | continue |
191 | } | |
192 | ||
09209296 C |
193 | await this.createVideoFileRedundancy(data.redundancy, video, file) |
194 | } | |
195 | ||
196 | for (const streamingPlaylist of data.streamingPlaylists) { | |
197 | const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id) | |
198 | if (existingRedundancy) { | |
199 | await this.extendsRedundancy(existingRedundancy) | |
26649b42 C |
200 | |
201 | continue | |
202 | } | |
c48e82b5 | 203 | |
09209296 C |
204 | await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist) |
205 | } | |
206 | } | |
c48e82b5 | 207 | |
b764380a C |
208 | private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) { |
209 | let strategy = 'manual' | |
210 | let expiresOn: Date = null | |
211 | ||
212 | if (redundancy) { | |
213 | strategy = redundancy.strategy | |
214 | expiresOn = this.buildNewExpiration(redundancy.minLifetime) | |
215 | } | |
216 | ||
453e83ea | 217 | const file = fileArg as MVideoFileVideo |
09209296 | 218 | file.Video = video |
c48e82b5 | 219 | |
09209296 | 220 | const serverActor = await getServerActor() |
c48e82b5 | 221 | |
b764380a | 222 | logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy) |
c48e82b5 | 223 | |
09209296 | 224 | const { baseUrlHttp, baseUrlWs } = video.getBaseUrls() |
90a8bd30 | 225 | const magnetUri = generateMagnetUri(video, video, file, baseUrlHttp, baseUrlWs) |
c48e82b5 | 226 | |
09209296 | 227 | const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT) |
792e5b8e | 228 | |
90a8bd30 | 229 | const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, file.filename) |
217ffacf | 230 | await move(tmpPath, destPath, { overwrite: true }) |
09209296 | 231 | |
453e83ea | 232 | const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({ |
b764380a | 233 | expiresOn, |
de94ac86 | 234 | url: getLocalVideoCacheFileActivityPubUrl(file), |
90a8bd30 | 235 | fileUrl: generateWebTorrentRedundancyUrl(file), |
b764380a | 236 | strategy, |
09209296 C |
237 | videoFileId: file.id, |
238 | actorId: serverActor.id | |
239 | }) | |
240 | ||
241 | createdModel.VideoFile = file | |
242 | ||
243 | await sendCreateCacheFile(serverActor, video, createdModel) | |
244 | ||
245 | logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url) | |
246 | } | |
247 | ||
453e83ea | 248 | private async createStreamingPlaylistRedundancy ( |
b764380a | 249 | redundancy: VideosRedundancyStrategy, |
453e83ea C |
250 | video: MVideoAccountLight, |
251 | playlistArg: MStreamingPlaylist | |
252 | ) { | |
b764380a C |
253 | let strategy = 'manual' |
254 | let expiresOn: Date = null | |
255 | ||
256 | if (redundancy) { | |
257 | strategy = redundancy.strategy | |
258 | expiresOn = this.buildNewExpiration(redundancy.minLifetime) | |
259 | } | |
260 | ||
453e83ea | 261 | const playlist = playlistArg as MStreamingPlaylistVideo |
09209296 C |
262 | playlist.Video = video |
263 | ||
264 | const serverActor = await getServerActor() | |
265 | ||
b764380a | 266 | logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy) |
09209296 C |
267 | |
268 | const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid) | |
269 | await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT) | |
270 | ||
453e83ea | 271 | const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({ |
b764380a | 272 | expiresOn, |
de94ac86 | 273 | url: getLocalVideoCacheStreamingPlaylistActivityPubUrl(video, playlist), |
90a8bd30 | 274 | fileUrl: generateHLSRedundancyUrl(video, playlistArg), |
b764380a | 275 | strategy, |
09209296 C |
276 | videoStreamingPlaylistId: playlist.id, |
277 | actorId: serverActor.id | |
278 | }) | |
279 | ||
280 | createdModel.VideoStreamingPlaylist = playlist | |
281 | ||
282 | await sendCreateCacheFile(serverActor, video, createdModel) | |
283 | ||
284 | logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url) | |
c48e82b5 C |
285 | } |
286 | ||
453e83ea | 287 | private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) { |
e5565833 C |
288 | logger.info('Extending expiration of %s.', redundancy.url) |
289 | ||
290 | const serverActor = await getServerActor() | |
291 | ||
292 | redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs) | |
293 | await redundancy.save() | |
294 | ||
295 | await sendUpdateCacheFile(serverActor, redundancy) | |
296 | } | |
297 | ||
09209296 | 298 | private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) { |
f8278b96 | 299 | while (await this.isTooHeavy(candidateToDuplicate)) { |
09209296 | 300 | const redundancy = candidateToDuplicate.redundancy |
453e83ea | 301 | const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime) |
e5565833 C |
302 | if (!toDelete) return |
303 | ||
89613cb4 C |
304 | const videoId = toDelete.VideoFile |
305 | ? toDelete.VideoFile.videoId | |
306 | : toDelete.VideoStreamingPlaylist.videoId | |
307 | ||
308 | const redundancies = await VideoRedundancyModel.listLocalByVideoId(videoId) | |
309 | ||
310 | for (const redundancy of redundancies) { | |
311 | await removeVideoRedundancy(redundancy) | |
312 | } | |
e5565833 C |
313 | } |
314 | } | |
315 | ||
09209296 C |
316 | private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) { |
317 | const maxSize = candidateToDuplicate.redundancy.size | |
c48e82b5 | 318 | |
09209296 C |
319 | const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy) |
320 | const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists) | |
c48e82b5 | 321 | |
742ddee1 | 322 | return totalWillDuplicate > maxSize |
c48e82b5 C |
323 | } |
324 | ||
e5565833 C |
325 | private buildNewExpiration (expiresAfterMs: number) { |
326 | return new Date(Date.now() + expiresAfterMs) | |
c48e82b5 C |
327 | } |
328 | ||
453e83ea C |
329 | private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) { |
330 | if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}` | |
09209296 C |
331 | |
332 | return `${object.VideoStreamingPlaylist.playlistUrl}` | |
c48e82b5 C |
333 | } |
334 | ||
66fb2aa3 | 335 | private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]) { |
453e83ea | 336 | const fileReducer = (previous: number, current: MVideoFile) => previous + current.size |
c48e82b5 | 337 | |
66fb2aa3 C |
338 | let allFiles = files |
339 | for (const p of playlists) { | |
340 | allFiles = allFiles.concat(p.VideoFiles) | |
341 | } | |
26d78799 | 342 | |
66fb2aa3 | 343 | return allFiles.reduce(fileReducer, 0) |
c48e82b5 | 344 | } |
be691a57 C |
345 | |
346 | private async loadAndRefreshVideo (videoUrl: string) { | |
347 | // We need more attributes and check if the video still exists | |
348 | const getVideoOptions = { | |
349 | videoObject: videoUrl, | |
350 | syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true }, | |
351 | fetchType: 'all' as 'all' | |
352 | } | |
353 | const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions) | |
354 | ||
355 | return video | |
356 | } | |
c48e82b5 | 357 | } |