]>
Commit | Line | Data |
---|---|---|
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 | 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 | await this.extendsOrDeleteRedundancy(redundancyModel) | |
74 | } catch (err) { | |
75 | logger.error('Cannot extend expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel)) | |
76 | } | |
77 | } | |
78 | } | |
79 | ||
80 | private async extendsOrDeleteRedundancy (redundancyModel: VideoRedundancyModel) { | |
81 | // Refresh the video, maybe it was deleted | |
82 | const video = await this.loadAndRefreshVideo(redundancyModel.VideoFile.Video.url) | |
83 | ||
84 | if (!video) { | |
85 | logger.info('Destroying existing redundancy %s, because the associated video does not exist anymore.', redundancyModel.url) | |
86 | ||
87 | await redundancyModel.destroy() | |
88 | return | |
89 | } | |
90 | ||
91 | const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy) | |
92 | await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime) | |
93 | } | |
94 | ||
95 | private async purgeRemoteExpired () { | |
96 | const expired = await VideoRedundancyModel.listRemoteExpired() | |
97 | ||
98 | for (const redundancyModel of expired) { | |
99 | try { | |
100 | await removeVideoRedundancy(redundancyModel) | |
101 | } catch (err) { | |
102 | logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel)) | |
103 | } | |
104 | } | |
105 | } | |
106 | ||
107 | private findVideoToDuplicate (cache: VideosRedundancy) { | |
108 | if (cache.strategy === 'most-views') { | |
109 | return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR) | |
110 | } | |
111 | ||
112 | if (cache.strategy === 'trending') { | |
113 | return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR) | |
114 | } | |
115 | ||
116 | if (cache.strategy === 'recently-added') { | |
117 | const minViews = cache.minViews | |
118 | return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews) | |
119 | } | |
120 | } | |
121 | ||
122 | private async createVideoRedundancy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) { | |
123 | const serverActor = await getServerActor() | |
124 | ||
125 | for (const file of filesToDuplicate) { | |
126 | const video = await this.loadAndRefreshVideo(file.Video.url) | |
127 | ||
128 | const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id) | |
129 | if (existingRedundancy) { | |
130 | await this.extendsOrDeleteRedundancy(existingRedundancy) | |
131 | ||
132 | continue | |
133 | } | |
134 | ||
135 | if (!video) { | |
136 | logger.info('Video %s we want to duplicate does not existing anymore, skipping.', file.Video.url) | |
137 | ||
138 | continue | |
139 | } | |
140 | ||
141 | logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy) | |
142 | ||
143 | const { baseUrlHttp, baseUrlWs } = video.getBaseUrls() | |
144 | const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs) | |
145 | ||
146 | const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT) | |
147 | ||
148 | const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, video.getVideoFilename(file)) | |
149 | await move(tmpPath, destPath) | |
150 | ||
151 | const createdModel = await VideoRedundancyModel.create({ | |
152 | expiresOn: this.buildNewExpiration(redundancy.minLifetime), | |
153 | url: getVideoCacheFileActivityPubUrl(file), | |
154 | fileUrl: video.getVideoRedundancyUrl(file, CONFIG.WEBSERVER.URL), | |
155 | strategy: redundancy.strategy, | |
156 | videoFileId: file.id, | |
157 | actorId: serverActor.id | |
158 | }) | |
159 | createdModel.VideoFile = file | |
160 | ||
161 | await sendCreateCacheFile(serverActor, createdModel) | |
162 | ||
163 | logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url) | |
164 | } | |
165 | } | |
166 | ||
167 | private async extendsExpirationOf (redundancy: VideoRedundancyModel, expiresAfterMs: number) { | |
168 | logger.info('Extending expiration of %s.', redundancy.url) | |
169 | ||
170 | const serverActor = await getServerActor() | |
171 | ||
172 | redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs) | |
173 | await redundancy.save() | |
174 | ||
175 | await sendUpdateCacheFile(serverActor, redundancy) | |
176 | } | |
177 | ||
178 | private async purgeCacheIfNeeded (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) { | |
179 | while (this.isTooHeavy(redundancy, filesToDuplicate)) { | |
180 | const toDelete = await VideoRedundancyModel.loadOldestLocalThatAlreadyExpired(redundancy.strategy, redundancy.minLifetime) | |
181 | if (!toDelete) return | |
182 | ||
183 | await removeVideoRedundancy(toDelete) | |
184 | } | |
185 | } | |
186 | ||
187 | private async isTooHeavy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) { | |
188 | const maxSize = redundancy.size | |
189 | ||
190 | const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(redundancy.strategy) | |
191 | const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(filesToDuplicate) | |
192 | ||
193 | return totalWillDuplicate > maxSize | |
194 | } | |
195 | ||
196 | private buildNewExpiration (expiresAfterMs: number) { | |
197 | return new Date(Date.now() + expiresAfterMs) | |
198 | } | |
199 | ||
200 | private buildEntryLogId (object: VideoRedundancyModel) { | |
201 | return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}` | |
202 | } | |
203 | ||
204 | private getTotalFileSizes (files: VideoFileModel[]) { | |
205 | const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size | |
206 | ||
207 | return files.reduce(fileReducer, 0) | |
208 | } | |
209 | ||
210 | private async loadAndRefreshVideo (videoUrl: string) { | |
211 | // We need more attributes and check if the video still exists | |
212 | const getVideoOptions = { | |
213 | videoObject: videoUrl, | |
214 | syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true }, | |
215 | fetchType: 'all' as 'all' | |
216 | } | |
217 | const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions) | |
218 | ||
219 | return video | |
220 | } | |
221 | } |