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