]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/schedulers/videos-redundancy-scheduler.ts
998d2295aed2e0782521d806fd4c07ee2a065085
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / videos-redundancy-scheduler.ts
1 import { AbstractScheduler } from './abstract-scheduler'
2 import { CONFIG, JOB_TTL, REDUNDANCY, SCHEDULER_INTERVALS_MS } from '../../initializers'
3 import { logger } from '../../helpers/logger'
4 import { VideoRedundancyStrategy, 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 { rename } from 'fs-extra'
10 import { getServerActor } from '../../helpers/utils'
11 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
12 import { VideoModel } from '../../models/video/video'
13 import { getVideoCacheFileActivityPubUrl } from '../activitypub/url'
14 import { isTestInstance } from '../../helpers/core-utils'
15
16 export class VideosRedundancyScheduler extends AbstractScheduler {
17
18 private static instance: AbstractScheduler
19 private executing = false
20
21 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
22
23 private constructor () {
24 super()
25 }
26
27 async execute () {
28 if (this.executing) return
29
30 this.executing = true
31
32 for (const obj of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
33 if (!isTestInstance()) logger.info('Running redundancy scheduler for strategy %s.', obj.strategy)
34
35 try {
36 const videoToDuplicate = await this.findVideoToDuplicate(obj)
37 if (!videoToDuplicate) continue
38
39 const videoFiles = videoToDuplicate.VideoFiles
40 videoFiles.forEach(f => f.Video = videoToDuplicate)
41
42 if (await this.isTooHeavy(obj.strategy, videoFiles, obj.size)) {
43 if (!isTestInstance()) logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
44 continue
45 }
46
47 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, obj.strategy)
48
49 await this.createVideoRedundancy(obj.strategy, videoFiles)
50 } catch (err) {
51 logger.error('Cannot run videos redundancy %s.', obj.strategy, { err })
52 }
53 }
54
55 await this.removeExpired()
56
57 this.executing = false
58 }
59
60 static get Instance () {
61 return this.instance || (this.instance = new this())
62 }
63
64 private async removeExpired () {
65 const expired = await VideoRedundancyModel.listAllExpired()
66
67 for (const m of expired) {
68 logger.info('Removing expired video %s from our redundancy system.', this.buildEntryLogId(m))
69
70 try {
71 await m.destroy()
72 } catch (err) {
73 logger.error('Cannot remove %s video from our redundancy system.', this.buildEntryLogId(m))
74 }
75 }
76 }
77
78 private findVideoToDuplicate (cache: VideosRedundancy) {
79 if (cache.strategy === 'most-views') {
80 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
81 }
82
83 if (cache.strategy === 'trending') {
84 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
85 }
86
87 if (cache.strategy === 'recently-added') {
88 const minViews = cache.minViews
89 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
90 }
91 }
92
93 private async createVideoRedundancy (strategy: VideoRedundancyStrategy, filesToDuplicate: VideoFileModel[]) {
94 const serverActor = await getServerActor()
95
96 for (const file of filesToDuplicate) {
97 const existing = await VideoRedundancyModel.loadByFileId(file.id)
98 if (existing) {
99 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', file.Video.url, file.resolution, strategy)
100
101 existing.expiresOn = this.buildNewExpiration()
102 await existing.save()
103
104 await sendUpdateCacheFile(serverActor, existing)
105 continue
106 }
107
108 // We need more attributes and check if the video still exists
109 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(file.Video.id)
110 if (!video) continue
111
112 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy)
113
114 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
115 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
116
117 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, JOB_TTL['video-import'])
118
119 const destPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
120 await rename(tmpPath, destPath)
121
122 const createdModel = await VideoRedundancyModel.create({
123 expiresOn: new Date(Date.now() + REDUNDANCY.VIDEOS.EXPIRES_AFTER_MS),
124 url: getVideoCacheFileActivityPubUrl(file),
125 fileUrl: video.getVideoFileUrl(file, CONFIG.WEBSERVER.URL),
126 strategy,
127 videoFileId: file.id,
128 actorId: serverActor.id
129 })
130 createdModel.VideoFile = file
131
132 await sendCreateCacheFile(serverActor, createdModel)
133 }
134 }
135
136 private async isTooHeavy (strategy: VideoRedundancyStrategy, filesToDuplicate: VideoFileModel[], maxSizeArg: number) {
137 const maxSize = maxSizeArg - this.getTotalFileSizes(filesToDuplicate)
138
139 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(strategy)
140
141 return totalDuplicated > maxSize
142 }
143
144 private buildNewExpiration () {
145 return new Date(Date.now() + REDUNDANCY.VIDEOS.EXPIRES_AFTER_MS)
146 }
147
148 private buildEntryLogId (object: VideoRedundancyModel) {
149 return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
150 }
151
152 private getTotalFileSizes (files: VideoFileModel[]) {
153 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
154
155 return files.reduce(fileReducer, 0)
156 }
157 }