]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/schedulers/videos-redundancy-scheduler.ts
Avoir some circular dependencies
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / videos-redundancy-scheduler.ts
CommitLineData
c48e82b5 1import { AbstractScheduler } from './abstract-scheduler'
74dc3bca 2import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT, WEBSERVER } from '../../initializers/constants'
c48e82b5 3import { logger } from '../../helpers/logger'
b764380a 4import { VideosRedundancyStrategy } from '../../../shared/models/redundancy'
c48e82b5 5import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
d7a25329 6import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent'
c48e82b5 7import { join } from 'path'
f481c4f9 8import { move } from 'fs-extra'
c48e82b5 9import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
09209296 10import { getVideoCacheFileActivityPubUrl, getVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
e5565833 11import { removeVideoRedundancy } from '../redundancy'
8dc8a34e 12import { getOrCreateVideoAndAccountAndChannel } from '../activitypub/videos'
09209296 13import { downloadPlaylistSegments } from '../hls'
6dd9de95 14import { CONFIG } from '../../initializers/config'
453e83ea 15import {
66fb2aa3 16 MStreamingPlaylist, MStreamingPlaylistFiles,
453e83ea
C
17 MStreamingPlaylistVideo,
18 MVideoAccountLight,
19 MVideoFile,
20 MVideoFileVideo,
21 MVideoRedundancyFileVideo,
22 MVideoRedundancyStreamingPlaylistVideo,
23 MVideoRedundancyVideo,
24 MVideoWithAllFiles
25} from '@server/typings/models'
d7a25329 26import { getVideoFilename } from '../video-paths'
b764380a 27import { VideoModel } from '@server/models/video/video'
8dc8a34e 28import { getServerActor } from '@server/models/application/application'
09209296
C
29
30type CandidateToDuplicate = {
a1587156
C
31 redundancy: VideosRedundancyStrategy
32 video: MVideoWithAllFiles
33 files: MVideoFile[]
66fb2aa3 34 streamingPlaylists: MStreamingPlaylistFiles[]
453e83ea
C
35}
36
0283eaac
C
37function isMVideoRedundancyFileVideo (
38 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
39): o is MVideoRedundancyFileVideo {
453e83ea 40 return !!(o as MVideoRedundancyFileVideo).VideoFile
09209296 41}
c48e82b5
C
42
43export class VideosRedundancyScheduler extends AbstractScheduler {
44
b764380a 45 private static instance: VideosRedundancyScheduler
c48e82b5 46
f9f899b9 47 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
c48e82b5
C
48
49 private constructor () {
50 super()
51 }
52
b764380a
C
53 async createManualRedundancy (videoId: number) {
54 const videoToDuplicate = await VideoModel.loadWithFiles(videoId)
55
56 if (!videoToDuplicate) {
57 logger.warn('Video to manually duplicate %d does not exist anymore.', videoId)
58 return
59 }
60
61 return this.createVideoRedundancies({
62 video: videoToDuplicate,
63 redundancy: null,
64 files: videoToDuplicate.VideoFiles,
65 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
66 })
67 }
68
2f5c6b2f 69 protected async internalExecute () {
09209296
C
70 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
71 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
1cfa8d68 72
c48e82b5 73 try {
09209296 74 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
c48e82b5
C
75 if (!videoToDuplicate) continue
76
09209296
C
77 const candidateToDuplicate = {
78 video: videoToDuplicate,
79 redundancy: redundancyConfig,
80 files: videoToDuplicate.VideoFiles,
81 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
82 }
c48e82b5 83
09209296 84 await this.purgeCacheIfNeeded(candidateToDuplicate)
e5565833 85
09209296 86 if (await this.isTooHeavy(candidateToDuplicate)) {
e5565833 87 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
c48e82b5
C
88 continue
89 }
90
09209296 91 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
c48e82b5 92
09209296 93 await this.createVideoRedundancies(candidateToDuplicate)
c48e82b5 94 } catch (err) {
09209296 95 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
c48e82b5
C
96 }
97 }
98
e5565833
C
99 await this.extendsLocalExpiration()
100
101 await this.purgeRemoteExpired()
f9f899b9
C
102 }
103
104 static get Instance () {
105 return this.instance || (this.instance = new this())
106 }
107
e5565833
C
108 private async extendsLocalExpiration () {
109 const expired = await VideoRedundancyModel.listLocalExpired()
110
111 for (const redundancyModel of expired) {
112 try {
09209296 113 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
b764380a 114 const candidate: CandidateToDuplicate = {
09209296
C
115 redundancy: redundancyConfig,
116 video: null,
117 files: [],
118 streamingPlaylists: []
119 }
120
121 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
122 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
123 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
124 await removeVideoRedundancy(redundancyModel)
125 } else {
126 await this.extendsRedundancy(redundancyModel)
127 }
e5565833 128 } catch (err) {
09209296
C
129 logger.error(
130 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
131 { err }
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) {
e5565833 155 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
c48e82b5
C
156 }
157 }
c48e82b5
C
158 }
159
b764380a 160 private findVideoToDuplicate (cache: VideosRedundancyStrategy) {
3f6b6a56
C
161 if (cache.strategy === 'most-views') {
162 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
163 }
164
165 if (cache.strategy === 'trending') {
166 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
167 }
b36f41ca 168
3f6b6a56 169 if (cache.strategy === 'recently-added') {
7348b1fd 170 const minViews = cache.minViews
3f6b6a56
C
171 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
172 }
c48e82b5
C
173 }
174
09209296
C
175 private async createVideoRedundancies (data: CandidateToDuplicate) {
176 const video = await this.loadAndRefreshVideo(data.video.url)
177
178 if (!video) {
179 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
c48e82b5 180
09209296
C
181 return
182 }
26649b42 183
09209296 184 for (const file of data.files) {
be691a57
C
185 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
186 if (existingRedundancy) {
09209296 187 await this.extendsRedundancy(existingRedundancy)
c48e82b5 188
c48e82b5
C
189 continue
190 }
191
09209296
C
192 await this.createVideoFileRedundancy(data.redundancy, video, file)
193 }
194
195 for (const streamingPlaylist of data.streamingPlaylists) {
196 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
197 if (existingRedundancy) {
198 await this.extendsRedundancy(existingRedundancy)
26649b42
C
199
200 continue
201 }
c48e82b5 202
09209296
C
203 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
204 }
205 }
c48e82b5 206
b764380a
C
207 private async createVideoFileRedundancy (redundancy: VideosRedundancyStrategy | null, video: MVideoAccountLight, fileArg: MVideoFile) {
208 let strategy = 'manual'
209 let expiresOn: Date = null
210
211 if (redundancy) {
212 strategy = redundancy.strategy
213 expiresOn = this.buildNewExpiration(redundancy.minLifetime)
214 }
215
453e83ea 216 const file = fileArg as MVideoFileVideo
09209296 217 file.Video = video
c48e82b5 218
09209296 219 const serverActor = await getServerActor()
c48e82b5 220
b764380a 221 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy)
c48e82b5 222
09209296 223 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
66fb2aa3 224 const magnetUri = generateMagnetUri(video, file, baseUrlHttp, baseUrlWs)
c48e82b5 225
09209296 226 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
792e5b8e 227
d7a25329 228 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, getVideoFilename(video, file))
217ffacf 229 await move(tmpPath, destPath, { overwrite: true })
09209296 230
453e83ea 231 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
b764380a 232 expiresOn,
09209296 233 url: getVideoCacheFileActivityPubUrl(file),
6dd9de95 234 fileUrl: video.getVideoRedundancyUrl(file, WEBSERVER.URL),
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
244 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
245 }
246
453e83ea 247 private async createStreamingPlaylistRedundancy (
b764380a 248 redundancy: VideosRedundancyStrategy,
453e83ea
C
249 video: MVideoAccountLight,
250 playlistArg: MStreamingPlaylist
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
453e83ea 260 const playlist = playlistArg as MStreamingPlaylistVideo
09209296
C
261 playlist.Video = video
262
263 const serverActor = await getServerActor()
264
b764380a 265 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, strategy)
09209296
C
266
267 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
268 await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT)
269
453e83ea 270 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
b764380a 271 expiresOn,
09209296 272 url: getVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
6dd9de95 273 fileUrl: playlist.getVideoRedundancyUrl(WEBSERVER.URL),
b764380a 274 strategy,
09209296
C
275 videoStreamingPlaylistId: playlist.id,
276 actorId: serverActor.id
277 })
278
279 createdModel.VideoStreamingPlaylist = playlist
280
281 await sendCreateCacheFile(serverActor, video, createdModel)
282
283 logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url)
c48e82b5
C
284 }
285
453e83ea 286 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
e5565833
C
287 logger.info('Extending expiration of %s.', redundancy.url)
288
289 const serverActor = await getServerActor()
290
291 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
292 await redundancy.save()
293
294 await sendUpdateCacheFile(serverActor, redundancy)
295 }
296
09209296 297 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
f8278b96 298 while (await this.isTooHeavy(candidateToDuplicate)) {
09209296 299 const redundancy = candidateToDuplicate.redundancy
453e83ea 300 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
e5565833
C
301 if (!toDelete) return
302
303 await removeVideoRedundancy(toDelete)
304 }
305 }
306
09209296
C
307 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
308 const maxSize = candidateToDuplicate.redundancy.size
c48e82b5 309
09209296
C
310 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
311 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
c48e82b5 312
742ddee1 313 return totalWillDuplicate > maxSize
c48e82b5
C
314 }
315
e5565833
C
316 private buildNewExpiration (expiresAfterMs: number) {
317 return new Date(Date.now() + expiresAfterMs)
c48e82b5
C
318 }
319
453e83ea
C
320 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
321 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
09209296
C
322
323 return `${object.VideoStreamingPlaylist.playlistUrl}`
c48e82b5
C
324 }
325
66fb2aa3 326 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylistFiles[]) {
453e83ea 327 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
c48e82b5 328
66fb2aa3
C
329 let allFiles = files
330 for (const p of playlists) {
331 allFiles = allFiles.concat(p.VideoFiles)
332 }
26d78799 333
66fb2aa3 334 return allFiles.reduce(fileReducer, 0)
c48e82b5 335 }
be691a57
C
336
337 private async loadAndRefreshVideo (videoUrl: string) {
338 // We need more attributes and check if the video still exists
339 const getVideoOptions = {
340 videoObject: videoUrl,
341 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
342 fetchType: 'all' as 'all'
343 }
344 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)
345
346 return video
347 }
c48e82b5 348}