]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/schedulers/videos-redundancy-scheduler.ts
06cfa1101d744132133f6a9cf67974f5950a6265
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / videos-redundancy-scheduler.ts
1 import { AbstractScheduler } from './abstract-scheduler'
2 import { CONFIG, JOB_TTL, REDUNDANCY } 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 { 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 { removeVideoRedundancy } from '../redundancy'
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 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 await this.purgeCacheIfNeeded(obj, videoFiles)
43
44 if (await this.isTooHeavy(obj, videoFiles)) {
45 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
46 continue
47 }
48
49 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, obj.strategy)
50
51 await this.createVideoRedundancy(obj, videoFiles)
52 } catch (err) {
53 logger.error('Cannot run videos redundancy %s.', obj.strategy, { err })
54 }
55 }
56
57 await this.extendsLocalExpiration()
58
59 await this.purgeRemoteExpired()
60
61 this.executing = false
62 }
63
64 static get Instance () {
65 return this.instance || (this.instance = new this())
66 }
67
68 private async extendsLocalExpiration () {
69 const expired = await VideoRedundancyModel.listLocalExpired()
70
71 for (const redundancyModel of expired) {
72 try {
73 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
74 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
75 } catch (err) {
76 logger.error('Cannot extend expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel))
77 }
78 }
79 }
80
81 private async purgeRemoteExpired () {
82 const expired = await VideoRedundancyModel.listRemoteExpired()
83
84 for (const redundancyModel of expired) {
85 try {
86 await removeVideoRedundancy(redundancyModel)
87 } catch (err) {
88 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
89 }
90 }
91 }
92
93 private findVideoToDuplicate (cache: VideosRedundancy) {
94 if (cache.strategy === 'most-views') {
95 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
96 }
97
98 if (cache.strategy === 'trending') {
99 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
100 }
101
102 if (cache.strategy === 'recently-added') {
103 const minViews = cache.minViews
104 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
105 }
106 }
107
108 private async createVideoRedundancy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
109 const serverActor = await getServerActor()
110
111 for (const file of filesToDuplicate) {
112 const existing = await VideoRedundancyModel.loadByFileId(file.id)
113 if (existing) {
114 await this.extendsExpirationOf(existing, redundancy.minLifetime)
115
116 continue
117 }
118
119 // We need more attributes and check if the video still exists
120 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(file.Video.id)
121 if (!video) continue
122
123 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
124
125 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
126 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
127
128 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, JOB_TTL['video-import'])
129
130 const destPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
131 await rename(tmpPath, destPath)
132
133 const createdModel = await VideoRedundancyModel.create({
134 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
135 url: getVideoCacheFileActivityPubUrl(file),
136 fileUrl: video.getVideoFileUrl(file, CONFIG.WEBSERVER.URL),
137 strategy: redundancy.strategy,
138 videoFileId: file.id,
139 actorId: serverActor.id
140 })
141 createdModel.VideoFile = file
142
143 await sendCreateCacheFile(serverActor, createdModel)
144 }
145 }
146
147 private async extendsExpirationOf (redundancy: VideoRedundancyModel, expiresAfterMs: number) {
148 logger.info('Extending expiration of %s.', redundancy.url)
149
150 const serverActor = await getServerActor()
151
152 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
153 await redundancy.save()
154
155 await sendUpdateCacheFile(serverActor, redundancy)
156 }
157
158 private async purgeCacheIfNeeded (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
159 while (this.isTooHeavy(redundancy, filesToDuplicate)) {
160 const toDelete = await VideoRedundancyModel.loadOldestLocalThatAlreadyExpired(redundancy.strategy, redundancy.minLifetime)
161 if (!toDelete) return
162
163 await removeVideoRedundancy(toDelete)
164 }
165 }
166
167 private async isTooHeavy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
168 const maxSize = redundancy.size - this.getTotalFileSizes(filesToDuplicate)
169
170 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(redundancy.strategy)
171
172 return totalDuplicated > maxSize
173 }
174
175 private buildNewExpiration (expiresAfterMs: number) {
176 return new Date(Date.now() + expiresAfterMs)
177 }
178
179 private buildEntryLogId (object: VideoRedundancyModel) {
180 return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
181 }
182
183 private getTotalFileSizes (files: VideoFileModel[]) {
184 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
185
186 return files.reduce(fileReducer, 0)
187 }
188 }