]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/schedulers/videos-redundancy-scheduler.ts
Fix image and plugin CSP
[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'
e5565833 4import { VideosRedundancy } from '../../../shared/models/redundancy'
c48e82b5
C
5import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
6import { VideoFileModel } from '../../models/video/video-file'
c48e82b5
C
7import { downloadWebTorrentVideo } from '../../helpers/webtorrent'
8import { join } from 'path'
f481c4f9 9import { move } from 'fs-extra'
c48e82b5
C
10import { getServerActor } from '../../helpers/utils'
11import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
09209296 12import { getVideoCacheFileActivityPubUrl, getVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
e5565833 13import { removeVideoRedundancy } from '../redundancy'
26649b42 14import { getOrCreateVideoAndAccountAndChannel } from '../activitypub'
09209296
C
15import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
16import { VideoModel } from '../../models/video/video'
17import { downloadPlaylistSegments } from '../hls'
6dd9de95 18import { CONFIG } from '../../initializers/config'
09209296
C
19
20type CandidateToDuplicate = {
21 redundancy: VideosRedundancy,
22 video: VideoModel,
23 files: VideoFileModel[],
24 streamingPlaylists: VideoStreamingPlaylistModel[]
25}
c48e82b5
C
26
27export class VideosRedundancyScheduler extends AbstractScheduler {
28
29 private static instance: AbstractScheduler
c48e82b5 30
f9f899b9 31 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
c48e82b5
C
32
33 private constructor () {
34 super()
35 }
36
2f5c6b2f 37 protected async internalExecute () {
09209296
C
38 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
39 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
1cfa8d68 40
c48e82b5 41 try {
09209296 42 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
c48e82b5
C
43 if (!videoToDuplicate) continue
44
09209296
C
45 const candidateToDuplicate = {
46 video: videoToDuplicate,
47 redundancy: redundancyConfig,
48 files: videoToDuplicate.VideoFiles,
49 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
50 }
c48e82b5 51
09209296 52 await this.purgeCacheIfNeeded(candidateToDuplicate)
e5565833 53
09209296 54 if (await this.isTooHeavy(candidateToDuplicate)) {
e5565833 55 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
c48e82b5
C
56 continue
57 }
58
09209296 59 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
c48e82b5 60
09209296 61 await this.createVideoRedundancies(candidateToDuplicate)
c48e82b5 62 } catch (err) {
09209296 63 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
c48e82b5
C
64 }
65 }
66
e5565833
C
67 await this.extendsLocalExpiration()
68
69 await this.purgeRemoteExpired()
f9f899b9
C
70 }
71
72 static get Instance () {
73 return this.instance || (this.instance = new this())
74 }
75
e5565833
C
76 private async extendsLocalExpiration () {
77 const expired = await VideoRedundancyModel.listLocalExpired()
78
79 for (const redundancyModel of expired) {
80 try {
09209296
C
81 const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
82 const candidate = {
83 redundancy: redundancyConfig,
84 video: null,
85 files: [],
86 streamingPlaylists: []
87 }
88
89 // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
90 if (!redundancyConfig || await this.isTooHeavy(candidate)) {
91 logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
92 await removeVideoRedundancy(redundancyModel)
93 } else {
94 await this.extendsRedundancy(redundancyModel)
95 }
e5565833 96 } catch (err) {
09209296
C
97 logger.error(
98 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
99 { err }
100 )
e5565833
C
101 }
102 }
103 }
c48e82b5 104
09209296 105 private async extendsRedundancy (redundancyModel: VideoRedundancyModel) {
be691a57 106 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
09209296 107 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
0b353d1d
C
108 if (!redundancy) {
109 await removeVideoRedundancy(redundancyModel)
110 return
111 }
09209296 112
be691a57
C
113 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
114 }
115
e5565833
C
116 private async purgeRemoteExpired () {
117 const expired = await VideoRedundancyModel.listRemoteExpired()
c48e82b5 118
e5565833 119 for (const redundancyModel of expired) {
c48e82b5 120 try {
e5565833 121 await removeVideoRedundancy(redundancyModel)
c48e82b5 122 } catch (err) {
e5565833 123 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
c48e82b5
C
124 }
125 }
c48e82b5
C
126 }
127
3f6b6a56
C
128 private findVideoToDuplicate (cache: VideosRedundancy) {
129 if (cache.strategy === 'most-views') {
130 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
131 }
132
133 if (cache.strategy === 'trending') {
134 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
135 }
b36f41ca 136
3f6b6a56 137 if (cache.strategy === 'recently-added') {
7348b1fd 138 const minViews = cache.minViews
3f6b6a56
C
139 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
140 }
c48e82b5
C
141 }
142
09209296
C
143 private async createVideoRedundancies (data: CandidateToDuplicate) {
144 const video = await this.loadAndRefreshVideo(data.video.url)
145
146 if (!video) {
147 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
c48e82b5 148
09209296
C
149 return
150 }
26649b42 151
09209296 152 for (const file of data.files) {
be691a57
C
153 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
154 if (existingRedundancy) {
09209296 155 await this.extendsRedundancy(existingRedundancy)
c48e82b5 156
c48e82b5
C
157 continue
158 }
159
09209296
C
160 await this.createVideoFileRedundancy(data.redundancy, video, file)
161 }
162
163 for (const streamingPlaylist of data.streamingPlaylists) {
164 const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
165 if (existingRedundancy) {
166 await this.extendsRedundancy(existingRedundancy)
26649b42
C
167
168 continue
169 }
c48e82b5 170
09209296
C
171 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
172 }
173 }
c48e82b5 174
09209296
C
175 private async createVideoFileRedundancy (redundancy: VideosRedundancy, video: VideoModel, file: VideoFileModel) {
176 file.Video = video
c48e82b5 177
09209296 178 const serverActor = await getServerActor()
c48e82b5 179
09209296 180 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
c48e82b5 181
09209296
C
182 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
183 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
c48e82b5 184
09209296 185 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
792e5b8e 186
09209296 187 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, video.getVideoFilename(file))
217ffacf 188 await move(tmpPath, destPath, { overwrite: true })
09209296
C
189
190 const createdModel = await VideoRedundancyModel.create({
191 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
192 url: getVideoCacheFileActivityPubUrl(file),
6dd9de95 193 fileUrl: video.getVideoRedundancyUrl(file, WEBSERVER.URL),
09209296
C
194 strategy: redundancy.strategy,
195 videoFileId: file.id,
196 actorId: serverActor.id
197 })
198
199 createdModel.VideoFile = file
200
201 await sendCreateCacheFile(serverActor, video, createdModel)
202
203 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
204 }
205
206 private async createStreamingPlaylistRedundancy (redundancy: VideosRedundancy, video: VideoModel, playlist: VideoStreamingPlaylistModel) {
207 playlist.Video = video
208
209 const serverActor = await getServerActor()
210
211 logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, redundancy.strategy)
212
213 const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
214 await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT)
215
216 const createdModel = await VideoRedundancyModel.create({
217 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
218 url: getVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
6dd9de95 219 fileUrl: playlist.getVideoRedundancyUrl(WEBSERVER.URL),
09209296
C
220 strategy: redundancy.strategy,
221 videoStreamingPlaylistId: playlist.id,
222 actorId: serverActor.id
223 })
224
225 createdModel.VideoStreamingPlaylist = playlist
226
227 await sendCreateCacheFile(serverActor, video, createdModel)
228
229 logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url)
c48e82b5
C
230 }
231
e5565833
C
232 private async extendsExpirationOf (redundancy: VideoRedundancyModel, expiresAfterMs: number) {
233 logger.info('Extending expiration of %s.', redundancy.url)
234
235 const serverActor = await getServerActor()
236
237 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
238 await redundancy.save()
239
240 await sendUpdateCacheFile(serverActor, redundancy)
241 }
242
09209296
C
243 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
244 while (this.isTooHeavy(candidateToDuplicate)) {
245 const redundancy = candidateToDuplicate.redundancy
e5565833
C
246 const toDelete = await VideoRedundancyModel.loadOldestLocalThatAlreadyExpired(redundancy.strategy, redundancy.minLifetime)
247 if (!toDelete) return
248
249 await removeVideoRedundancy(toDelete)
250 }
251 }
252
09209296
C
253 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
254 const maxSize = candidateToDuplicate.redundancy.size
c48e82b5 255
09209296
C
256 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
257 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
c48e82b5 258
742ddee1 259 return totalWillDuplicate > maxSize
c48e82b5
C
260 }
261
e5565833
C
262 private buildNewExpiration (expiresAfterMs: number) {
263 return new Date(Date.now() + expiresAfterMs)
c48e82b5
C
264 }
265
266 private buildEntryLogId (object: VideoRedundancyModel) {
09209296
C
267 if (object.VideoFile) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
268
269 return `${object.VideoStreamingPlaylist.playlistUrl}`
c48e82b5
C
270 }
271
09209296 272 private getTotalFileSizes (files: VideoFileModel[], playlists: VideoStreamingPlaylistModel[]) {
c48e82b5
C
273 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
274
26d78799
C
275 const totalSize = files.reduce(fileReducer, 0)
276 if (playlists.length === 0) return totalSize
277
278 return totalSize * playlists.length
c48e82b5 279 }
be691a57
C
280
281 private async loadAndRefreshVideo (videoUrl: string) {
282 // We need more attributes and check if the video still exists
283 const getVideoOptions = {
284 videoObject: videoUrl,
285 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
286 fetchType: 'all' as 'all'
287 }
288 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)
289
290 return video
291 }
c48e82b5 292}