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