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