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