]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/schedulers/videos-redundancy-scheduler.ts
0b1ae76ff853d74c06f5a6844e74275083d40f71
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / videos-redundancy-scheduler.ts
1 import { AbstractScheduler } from './abstract-scheduler'
2 import { CONFIG, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } 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 { getVideoCacheFileActivityPubUrl } from '../activitypub/url'
13 import { removeVideoRedundancy } from '../redundancy'
14 import { getOrCreateVideoAndAccountAndChannel } from '../activitypub'
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 // We need more attributes and check if the video still exists
113 const getVideoOptions = {
114 videoObject: file.Video.url,
115 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
116 fetchType: 'all' as 'all'
117 }
118 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)
119
120 const existing = await VideoRedundancyModel.loadLocalByFileId(file.id)
121 if (existing) {
122 if (video) {
123 await this.extendsExpirationOf(existing, redundancy.minLifetime)
124 } else {
125 logger.info('Destroying existing redundancy %s, because the associated video does not exist anymore.', existing.url)
126
127 await existing.destroy()
128 }
129
130 continue
131 }
132
133 if (!video) {
134 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', file.Video.url)
135
136 continue
137 }
138
139 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
140
141 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
142 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
143
144 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
145
146 const destPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
147 await rename(tmpPath, destPath)
148
149 const createdModel = await VideoRedundancyModel.create({
150 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
151 url: getVideoCacheFileActivityPubUrl(file),
152 fileUrl: video.getVideoFileUrl(file, CONFIG.WEBSERVER.URL),
153 strategy: redundancy.strategy,
154 videoFileId: file.id,
155 actorId: serverActor.id
156 })
157 createdModel.VideoFile = file
158
159 await sendCreateCacheFile(serverActor, createdModel)
160 }
161 }
162
163 private async extendsExpirationOf (redundancy: VideoRedundancyModel, expiresAfterMs: number) {
164 logger.info('Extending expiration of %s.', redundancy.url)
165
166 const serverActor = await getServerActor()
167
168 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
169 await redundancy.save()
170
171 await sendUpdateCacheFile(serverActor, redundancy)
172 }
173
174 private async purgeCacheIfNeeded (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
175 while (this.isTooHeavy(redundancy, filesToDuplicate)) {
176 const toDelete = await VideoRedundancyModel.loadOldestLocalThatAlreadyExpired(redundancy.strategy, redundancy.minLifetime)
177 if (!toDelete) return
178
179 await removeVideoRedundancy(toDelete)
180 }
181 }
182
183 private async isTooHeavy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
184 const maxSize = redundancy.size - this.getTotalFileSizes(filesToDuplicate)
185
186 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(redundancy.strategy)
187
188 return totalDuplicated > maxSize
189 }
190
191 private buildNewExpiration (expiresAfterMs: number) {
192 return new Date(Date.now() + expiresAfterMs)
193 }
194
195 private buildEntryLogId (object: VideoRedundancyModel) {
196 return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
197 }
198
199 private getTotalFileSizes (files: VideoFileModel[]) {
200 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
201
202 return files.reduce(fileReducer, 0)
203 }
204 }