]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/schedulers/videos-redundancy-scheduler.ts
Merge branch 'release/1.4.0' into develop
[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 (
36 o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
37 ): o is MVideoRedundancyFileVideo {
38 return !!(o as MVideoRedundancyFileVideo).VideoFile
39 }
40
41 export class VideosRedundancyScheduler extends AbstractScheduler {
42
43 private static instance: AbstractScheduler
44
45 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
46
47 private constructor () {
48 super()
49 }
50
51 protected async internalExecute () {
52 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
53 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
54
55 try {
56 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
57 if (!videoToDuplicate) continue
58
59 const candidateToDuplicate = {
60 video: videoToDuplicate,
61 redundancy: redundancyConfig,
62 files: videoToDuplicate.VideoFiles,
63 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
64 }
65
66 await this.purgeCacheIfNeeded(candidateToDuplicate)
67
68 if (await this.isTooHeavy(candidateToDuplicate)) {
69 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
70 continue
71 }
72
73 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
74
75 await this.createVideoRedundancies(candidateToDuplicate)
76 } catch (err) {
77 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
78 }
79 }
80
81 await this.extendsLocalExpiration()
82
83 await this.purgeRemoteExpired()
84 }
85
86 static get Instance () {
87 return this.instance || (this.instance = new this())
88 }
89
90 private async extendsLocalExpiration () {
91 const expired = await VideoRedundancyModel.listLocalExpired()
92
93 for (const redundancyModel of expired) {
94 try {
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 }
110 } catch (err) {
111 logger.error(
112 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
113 { err }
114 )
115 }
116 }
117 }
118
119 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
120 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
121 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
122 if (!redundancy) {
123 await removeVideoRedundancy(redundancyModel)
124 return
125 }
126
127 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
128 }
129
130 private async purgeRemoteExpired () {
131 const expired = await VideoRedundancyModel.listRemoteExpired()
132
133 for (const redundancyModel of expired) {
134 try {
135 await removeVideoRedundancy(redundancyModel)
136 } catch (err) {
137 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
138 }
139 }
140 }
141
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 }
150
151 if (cache.strategy === 'recently-added') {
152 const minViews = cache.minViews
153 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
154 }
155 }
156
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)
162
163 return
164 }
165
166 for (const file of data.files) {
167 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
168 if (existingRedundancy) {
169 await this.extendsRedundancy(existingRedundancy)
170
171 continue
172 }
173
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)
181
182 continue
183 }
184
185 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
186 }
187 }
188
189 private async createVideoFileRedundancy (redundancy: VideosRedundancy, video: MVideoAccountLight, fileArg: MVideoFile) {
190 const file = fileArg as MVideoFileVideo
191 file.Video = video
192
193 const serverActor = await getServerActor()
194
195 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
196
197 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
198 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
199
200 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
201
202 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, video.getVideoFilename(file))
203 await move(tmpPath, destPath, { overwrite: true })
204
205 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
206 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
207 url: getVideoCacheFileActivityPubUrl(file),
208 fileUrl: video.getVideoRedundancyUrl(file, WEBSERVER.URL),
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
221 private async createStreamingPlaylistRedundancy (
222 redundancy: VideosRedundancy,
223 video: MVideoAccountLight,
224 playlistArg: MStreamingPlaylist
225 ) {
226 const playlist = playlistArg as MStreamingPlaylistVideo
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
236 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
237 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
238 url: getVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
239 fileUrl: playlist.getVideoRedundancyUrl(WEBSERVER.URL),
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)
250 }
251
252 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
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
263 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
264 while (this.isTooHeavy(candidateToDuplicate)) {
265 const redundancy = candidateToDuplicate.redundancy
266 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
267 if (!toDelete) return
268
269 await removeVideoRedundancy(toDelete)
270 }
271 }
272
273 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
274 const maxSize = candidateToDuplicate.redundancy.size
275
276 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
277 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
278
279 return totalWillDuplicate > maxSize
280 }
281
282 private buildNewExpiration (expiresAfterMs: number) {
283 return new Date(Date.now() + expiresAfterMs)
284 }
285
286 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
287 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
288
289 return `${object.VideoStreamingPlaylist.playlistUrl}`
290 }
291
292 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylist[]) {
293 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
294
295 const totalSize = files.reduce(fileReducer, 0)
296 if (playlists.length === 0) return totalSize
297
298 return totalSize * playlists.length
299 }
300
301 private async loadAndRefreshVideo (videoUrl: string) {
302 // We need more attributes and check if the video still exists
303 const getVideoOptions = {
304 videoObject: videoUrl,
305 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
306 fetchType: 'all' as 'all'
307 }
308 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)
309
310 return video
311 }
312 }