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