]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/schedulers/videos-redundancy-scheduler.ts
Implement contact form in the client
[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 { move } 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
20 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
21
22 private constructor () {
23 super()
24 }
25
26 protected async internalExecute () {
27 for (const obj of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
28 logger.info('Running redundancy scheduler for strategy %s.', obj.strategy)
29
30 try {
31 const videoToDuplicate = await this.findVideoToDuplicate(obj)
32 if (!videoToDuplicate) continue
33
34 const videoFiles = videoToDuplicate.VideoFiles
35 videoFiles.forEach(f => f.Video = videoToDuplicate)
36
37 await this.purgeCacheIfNeeded(obj, videoFiles)
38
39 if (await this.isTooHeavy(obj, videoFiles)) {
40 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
41 continue
42 }
43
44 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, obj.strategy)
45
46 await this.createVideoRedundancy(obj, videoFiles)
47 } catch (err) {
48 logger.error('Cannot run videos redundancy %s.', obj.strategy, { err })
49 }
50 }
51
52 await this.extendsLocalExpiration()
53
54 await this.purgeRemoteExpired()
55 }
56
57 static get Instance () {
58 return this.instance || (this.instance = new this())
59 }
60
61 private async extendsLocalExpiration () {
62 const expired = await VideoRedundancyModel.listLocalExpired()
63
64 for (const redundancyModel of expired) {
65 try {
66 await this.extendsOrDeleteRedundancy(redundancyModel)
67 } catch (err) {
68 logger.error('Cannot extend expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel))
69 }
70 }
71 }
72
73 private async extendsOrDeleteRedundancy (redundancyModel: VideoRedundancyModel) {
74 // Refresh the video, maybe it was deleted
75 const video = await this.loadAndRefreshVideo(redundancyModel.VideoFile.Video.url)
76
77 if (!video) {
78 logger.info('Destroying existing redundancy %s, because the associated video does not exist anymore.', redundancyModel.url)
79
80 await redundancyModel.destroy()
81 return
82 }
83
84 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
85 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
86 }
87
88 private async purgeRemoteExpired () {
89 const expired = await VideoRedundancyModel.listRemoteExpired()
90
91 for (const redundancyModel of expired) {
92 try {
93 await removeVideoRedundancy(redundancyModel)
94 } catch (err) {
95 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
96 }
97 }
98 }
99
100 private findVideoToDuplicate (cache: VideosRedundancy) {
101 if (cache.strategy === 'most-views') {
102 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
103 }
104
105 if (cache.strategy === 'trending') {
106 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
107 }
108
109 if (cache.strategy === 'recently-added') {
110 const minViews = cache.minViews
111 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
112 }
113 }
114
115 private async createVideoRedundancy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
116 const serverActor = await getServerActor()
117
118 for (const file of filesToDuplicate) {
119 const video = await this.loadAndRefreshVideo(file.Video.url)
120
121 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
122 if (existingRedundancy) {
123 await this.extendsOrDeleteRedundancy(existingRedundancy)
124
125 continue
126 }
127
128 if (!video) {
129 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', file.Video.url)
130
131 continue
132 }
133
134 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
135
136 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
137 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
138
139 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
140
141 const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, video.getVideoFilename(file))
142 await move(tmpPath, destPath)
143
144 const createdModel = await VideoRedundancyModel.create({
145 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
146 url: getVideoCacheFileActivityPubUrl(file),
147 fileUrl: video.getVideoRedundancyUrl(file, CONFIG.WEBSERVER.URL),
148 strategy: redundancy.strategy,
149 videoFileId: file.id,
150 actorId: serverActor.id
151 })
152 createdModel.VideoFile = file
153
154 await sendCreateCacheFile(serverActor, createdModel)
155
156 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
157 }
158 }
159
160 private async extendsExpirationOf (redundancy: VideoRedundancyModel, expiresAfterMs: number) {
161 logger.info('Extending expiration of %s.', redundancy.url)
162
163 const serverActor = await getServerActor()
164
165 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
166 await redundancy.save()
167
168 await sendUpdateCacheFile(serverActor, redundancy)
169 }
170
171 private async purgeCacheIfNeeded (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
172 while (this.isTooHeavy(redundancy, filesToDuplicate)) {
173 const toDelete = await VideoRedundancyModel.loadOldestLocalThatAlreadyExpired(redundancy.strategy, redundancy.minLifetime)
174 if (!toDelete) return
175
176 await removeVideoRedundancy(toDelete)
177 }
178 }
179
180 private async isTooHeavy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
181 const maxSize = redundancy.size
182
183 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(redundancy.strategy)
184 const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(filesToDuplicate)
185
186 return totalWillDuplicate > maxSize
187 }
188
189 private buildNewExpiration (expiresAfterMs: number) {
190 return new Date(Date.now() + expiresAfterMs)
191 }
192
193 private buildEntryLogId (object: VideoRedundancyModel) {
194 return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
195 }
196
197 private getTotalFileSizes (files: VideoFileModel[]) {
198 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
199
200 return files.reduce(fileReducer, 0)
201 }
202
203 private async loadAndRefreshVideo (videoUrl: string) {
204 // We need more attributes and check if the video still exists
205 const getVideoOptions = {
206 videoObject: videoUrl,
207 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
208 fetchType: 'all' as 'all'
209 }
210 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)
211
212 return video
213 }
214 }