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