]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/schedulers/videos-redundancy-scheduler.ts
Stronger model typings
[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
35function isMVideoRedundancyFileVideo (o: MVideoRedundancyVideo): o is MVideoRedundancyFileVideo {
36 return !!(o as MVideoRedundancyFileVideo).VideoFile
09209296 37}
c48e82b5
C
38
39export class VideosRedundancyScheduler extends AbstractScheduler {
40
41 private static instance: AbstractScheduler
c48e82b5 42
f9f899b9 43 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
c48e82b5
C
44
45 private constructor () {
46 super()
47 }
48
2f5c6b2f 49 protected async internalExecute () {
09209296
C
50 for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
51 logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
1cfa8d68 52
c48e82b5 53 try {
09209296 54 const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
c48e82b5
C
55 if (!videoToDuplicate) continue
56
09209296
C
57 const candidateToDuplicate = {
58 video: videoToDuplicate,
59 redundancy: redundancyConfig,
60 files: videoToDuplicate.VideoFiles,
61 streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
62 }
c48e82b5 63
09209296 64 await this.purgeCacheIfNeeded(candidateToDuplicate)
e5565833 65
09209296 66 if (await this.isTooHeavy(candidateToDuplicate)) {
e5565833 67 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
c48e82b5
C
68 continue
69 }
70
09209296 71 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
c48e82b5 72
09209296 73 await this.createVideoRedundancies(candidateToDuplicate)
c48e82b5 74 } catch (err) {
09209296 75 logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
c48e82b5
C
76 }
77 }
78
e5565833
C
79 await this.extendsLocalExpiration()
80
81 await this.purgeRemoteExpired()
f9f899b9
C
82 }
83
84 static get Instance () {
85 return this.instance || (this.instance = new this())
86 }
87
e5565833
C
88 private async extendsLocalExpiration () {
89 const expired = await VideoRedundancyModel.listLocalExpired()
90
91 for (const redundancyModel of expired) {
92 try {
09209296
C
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 }
e5565833 108 } catch (err) {
09209296
C
109 logger.error(
110 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
111 { err }
112 )
e5565833
C
113 }
114 }
115 }
c48e82b5 116
453e83ea 117 private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
be691a57 118 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
09209296 119 // Redundancy strategy disabled, remove our redundancy instead of extending expiration
0b353d1d
C
120 if (!redundancy) {
121 await removeVideoRedundancy(redundancyModel)
122 return
123 }
09209296 124
be691a57
C
125 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
126 }
127
e5565833
C
128 private async purgeRemoteExpired () {
129 const expired = await VideoRedundancyModel.listRemoteExpired()
c48e82b5 130
e5565833 131 for (const redundancyModel of expired) {
c48e82b5 132 try {
e5565833 133 await removeVideoRedundancy(redundancyModel)
c48e82b5 134 } catch (err) {
e5565833 135 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
c48e82b5
C
136 }
137 }
c48e82b5
C
138 }
139
3f6b6a56
C
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 }
b36f41ca 148
3f6b6a56 149 if (cache.strategy === 'recently-added') {
7348b1fd 150 const minViews = cache.minViews
3f6b6a56
C
151 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
152 }
c48e82b5
C
153 }
154
09209296
C
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)
c48e82b5 160
09209296
C
161 return
162 }
26649b42 163
09209296 164 for (const file of data.files) {
be691a57
C
165 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
166 if (existingRedundancy) {
09209296 167 await this.extendsRedundancy(existingRedundancy)
c48e82b5 168
c48e82b5
C
169 continue
170 }
171
09209296
C
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)
26649b42
C
179
180 continue
181 }
c48e82b5 182
09209296
C
183 await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
184 }
185 }
c48e82b5 186
453e83ea
C
187 private async createVideoFileRedundancy (redundancy: VideosRedundancy, video: MVideoAccountLight, fileArg: MVideoFile) {
188 const file = fileArg as MVideoFileVideo
09209296 189 file.Video = video
c48e82b5 190
09209296 191 const serverActor = await getServerActor()
c48e82b5 192
09209296 193 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
c48e82b5 194
09209296
C
195 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
196 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
c48e82b5 197
09209296 198 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
792e5b8e 199
09209296
C
200 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, video.getVideoFilename(file))
201 await move(tmpPath, destPath)
202
453e83ea 203 const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
09209296
C
204 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
205 url: getVideoCacheFileActivityPubUrl(file),
6dd9de95 206 fileUrl: video.getVideoRedundancyUrl(file, WEBSERVER.URL),
09209296
C
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
453e83ea
C
219 private async createStreamingPlaylistRedundancy (
220 redundancy: VideosRedundancy,
221 video: MVideoAccountLight,
222 playlistArg: MStreamingPlaylist
223 ) {
224 const playlist = playlistArg as MStreamingPlaylistVideo
09209296
C
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
453e83ea 234 const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
09209296
C
235 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
236 url: getVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
6dd9de95 237 fileUrl: playlist.getVideoRedundancyUrl(WEBSERVER.URL),
09209296
C
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)
c48e82b5
C
248 }
249
453e83ea 250 private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
e5565833
C
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
09209296
C
261 private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
262 while (this.isTooHeavy(candidateToDuplicate)) {
263 const redundancy = candidateToDuplicate.redundancy
453e83ea 264 const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
e5565833
C
265 if (!toDelete) return
266
267 await removeVideoRedundancy(toDelete)
268 }
269 }
270
09209296
C
271 private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
272 const maxSize = candidateToDuplicate.redundancy.size
c48e82b5 273
09209296
C
274 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
275 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
c48e82b5 276
742ddee1 277 return totalWillDuplicate > maxSize
c48e82b5
C
278 }
279
e5565833
C
280 private buildNewExpiration (expiresAfterMs: number) {
281 return new Date(Date.now() + expiresAfterMs)
c48e82b5
C
282 }
283
453e83ea
C
284 private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
285 if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
09209296
C
286
287 return `${object.VideoStreamingPlaylist.playlistUrl}`
c48e82b5
C
288 }
289
453e83ea
C
290 private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylist[]) {
291 const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
c48e82b5 292
26d78799
C
293 const totalSize = files.reduce(fileReducer, 0)
294 if (playlists.length === 0) return totalSize
295
296 return totalSize * playlists.length
c48e82b5 297 }
be691a57
C
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 }
c48e82b5 310}