]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/schedulers/videos-redundancy-scheduler.ts
Fix new Angular 7 issues
[github/Chocobozzz/PeerTube.git] / server / lib / schedulers / videos-redundancy-scheduler.ts
CommitLineData
c48e82b5 1import { AbstractScheduler } from './abstract-scheduler'
cf9166cf 2import { CONFIG, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers'
c48e82b5 3import { logger } from '../../helpers/logger'
e5565833 4import { VideosRedundancy } from '../../../shared/models/redundancy'
c48e82b5
C
5import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
6import { VideoFileModel } from '../../models/video/video-file'
c48e82b5
C
7import { downloadWebTorrentVideo } from '../../helpers/webtorrent'
8import { join } from 'path'
9import { rename } from 'fs-extra'
10import { getServerActor } from '../../helpers/utils'
11import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
c48e82b5 12import { getVideoCacheFileActivityPubUrl } from '../activitypub/url'
e5565833 13import { removeVideoRedundancy } from '../redundancy'
26649b42 14import { getOrCreateVideoAndAccountAndChannel } from '../activitypub'
c48e82b5
C
15
16export class VideosRedundancyScheduler extends AbstractScheduler {
17
18 private static instance: AbstractScheduler
19 private executing = false
20
f9f899b9 21 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
c48e82b5
C
22
23 private constructor () {
24 super()
25 }
26
27 async execute () {
28 if (this.executing) return
29
30 this.executing = true
31
d9bdd007 32 for (const obj of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
e5565833 33 logger.info('Running redundancy scheduler for strategy %s.', obj.strategy)
1cfa8d68 34
c48e82b5 35 try {
3f6b6a56 36 const videoToDuplicate = await this.findVideoToDuplicate(obj)
c48e82b5
C
37 if (!videoToDuplicate) continue
38
39 const videoFiles = videoToDuplicate.VideoFiles
40 videoFiles.forEach(f => f.Video = videoToDuplicate)
41
e5565833
C
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)
c48e82b5
C
46 continue
47 }
48
49 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, obj.strategy)
50
e5565833 51 await this.createVideoRedundancy(obj, videoFiles)
c48e82b5
C
52 } catch (err) {
53 logger.error('Cannot run videos redundancy %s.', obj.strategy, { err })
54 }
55 }
56
e5565833
C
57 await this.extendsLocalExpiration()
58
59 await this.purgeRemoteExpired()
f9f899b9
C
60
61 this.executing = false
62 }
63
64 static get Instance () {
65 return this.instance || (this.instance = new this())
66 }
67
e5565833
C
68 private async extendsLocalExpiration () {
69 const expired = await VideoRedundancyModel.listLocalExpired()
70
71 for (const redundancyModel of expired) {
72 try {
be691a57 73 await this.extendsOrDeleteRedundancy(redundancyModel)
e5565833
C
74 } catch (err) {
75 logger.error('Cannot extend expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel))
76 }
77 }
78 }
c48e82b5 79
be691a57
C
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
e5565833
C
95 private async purgeRemoteExpired () {
96 const expired = await VideoRedundancyModel.listRemoteExpired()
c48e82b5 97
e5565833 98 for (const redundancyModel of expired) {
c48e82b5 99 try {
e5565833 100 await removeVideoRedundancy(redundancyModel)
c48e82b5 101 } catch (err) {
e5565833 102 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
c48e82b5
C
103 }
104 }
c48e82b5
C
105 }
106
3f6b6a56
C
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 }
b36f41ca 115
3f6b6a56 116 if (cache.strategy === 'recently-added') {
7348b1fd 117 const minViews = cache.minViews
3f6b6a56
C
118 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
119 }
c48e82b5
C
120 }
121
e5565833 122 private async createVideoRedundancy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
c48e82b5
C
123 const serverActor = await getServerActor()
124
125 for (const file of filesToDuplicate) {
be691a57 126 const video = await this.loadAndRefreshVideo(file.Video.url)
26649b42 127
be691a57
C
128 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
129 if (existingRedundancy) {
130 await this.extendsOrDeleteRedundancy(existingRedundancy)
c48e82b5 131
c48e82b5
C
132 continue
133 }
134
26649b42
C
135 if (!video) {
136 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', file.Video.url)
137
138 continue
139 }
c48e82b5 140
e5565833 141 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
c48e82b5
C
142
143 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
144 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
145
cf9166cf 146 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
c48e82b5
C
147
148 const destPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
149 await rename(tmpPath, destPath)
150
151 const createdModel = await VideoRedundancyModel.create({
e5565833 152 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
c48e82b5
C
153 url: getVideoCacheFileActivityPubUrl(file),
154 fileUrl: video.getVideoFileUrl(file, CONFIG.WEBSERVER.URL),
e5565833 155 strategy: redundancy.strategy,
c48e82b5
C
156 videoFileId: file.id,
157 actorId: serverActor.id
158 })
159 createdModel.VideoFile = file
160
161 await sendCreateCacheFile(serverActor, createdModel)
792e5b8e
C
162
163 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
c48e82b5
C
164 }
165 }
166
e5565833
C
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 - this.getTotalFileSizes(filesToDuplicate)
c48e82b5 189
e5565833 190 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(redundancy.strategy)
c48e82b5
C
191
192 return totalDuplicated > maxSize
193 }
194
e5565833
C
195 private buildNewExpiration (expiresAfterMs: number) {
196 return new Date(Date.now() + expiresAfterMs)
c48e82b5
C
197 }
198
199 private buildEntryLogId (object: VideoRedundancyModel) {
200 return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
201 }
202
203 private getTotalFileSizes (files: VideoFileModel[]) {
204 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
205
206 return files.reduce(fileReducer, 0)
207 }
be691a57
C
208
209 private async loadAndRefreshVideo (videoUrl: string) {
210 // We need more attributes and check if the video still exists
211 const getVideoOptions = {
212 videoObject: videoUrl,
213 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
214 fetchType: 'all' as 'all'
215 }
216 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)
217
218 return video
219 }
c48e82b5 220}