videos-redundancy-scheduler.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import { AbstractScheduler } from './abstract-scheduler'
  2. import { HLS_REDUNDANCY_DIRECTORY, REDUNDANCY, VIDEO_IMPORT_TIMEOUT, WEBSERVER } from '../../initializers/constants'
  3. import { logger } from '../../helpers/logger'
  4. import { VideosRedundancy } from '../../../shared/models/redundancy'
  5. import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
  6. import { downloadWebTorrentVideo, generateMagnetUri } from '../../helpers/webtorrent'
  7. import { join } from 'path'
  8. import { move } from 'fs-extra'
  9. import { getServerActor } from '../../helpers/utils'
  10. import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
  11. import { getVideoCacheFileActivityPubUrl, getVideoCacheStreamingPlaylistActivityPubUrl } from '../activitypub/url'
  12. import { removeVideoRedundancy } from '../redundancy'
  13. import { getOrCreateVideoAndAccountAndChannel } from '../activitypub'
  14. import { downloadPlaylistSegments } from '../hls'
  15. import { CONFIG } from '../../initializers/config'
  16. import {
  17. MStreamingPlaylist,
  18. MStreamingPlaylistVideo,
  19. MVideoAccountLight,
  20. MVideoFile,
  21. MVideoFileVideo,
  22. MVideoRedundancyFileVideo,
  23. MVideoRedundancyStreamingPlaylistVideo,
  24. MVideoRedundancyVideo,
  25. MVideoWithAllFiles
  26. } from '@server/typings/models'
  27. import { getVideoFilename } from '../video-paths'
  28. type CandidateToDuplicate = {
  29. redundancy: VideosRedundancy,
  30. video: MVideoWithAllFiles,
  31. files: MVideoFile[],
  32. streamingPlaylists: MStreamingPlaylist[]
  33. }
  34. function isMVideoRedundancyFileVideo (
  35. o: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo
  36. ): o is MVideoRedundancyFileVideo {
  37. return !!(o as MVideoRedundancyFileVideo).VideoFile
  38. }
  39. export class VideosRedundancyScheduler extends AbstractScheduler {
  40. private static instance: AbstractScheduler
  41. protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
  42. private constructor () {
  43. super()
  44. }
  45. protected async internalExecute () {
  46. for (const redundancyConfig of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
  47. logger.info('Running redundancy scheduler for strategy %s.', redundancyConfig.strategy)
  48. try {
  49. const videoToDuplicate = await this.findVideoToDuplicate(redundancyConfig)
  50. if (!videoToDuplicate) continue
  51. const candidateToDuplicate = {
  52. video: videoToDuplicate,
  53. redundancy: redundancyConfig,
  54. files: videoToDuplicate.VideoFiles,
  55. streamingPlaylists: videoToDuplicate.VideoStreamingPlaylists
  56. }
  57. await this.purgeCacheIfNeeded(candidateToDuplicate)
  58. if (await this.isTooHeavy(candidateToDuplicate)) {
  59. logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
  60. continue
  61. }
  62. logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, redundancyConfig.strategy)
  63. await this.createVideoRedundancies(candidateToDuplicate)
  64. } catch (err) {
  65. logger.error('Cannot run videos redundancy %s.', redundancyConfig.strategy, { err })
  66. }
  67. }
  68. await this.extendsLocalExpiration()
  69. await this.purgeRemoteExpired()
  70. }
  71. static get Instance () {
  72. return this.instance || (this.instance = new this())
  73. }
  74. private async extendsLocalExpiration () {
  75. const expired = await VideoRedundancyModel.listLocalExpired()
  76. for (const redundancyModel of expired) {
  77. try {
  78. const redundancyConfig = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
  79. const candidate = {
  80. redundancy: redundancyConfig,
  81. video: null,
  82. files: [],
  83. streamingPlaylists: []
  84. }
  85. // If the administrator disabled the redundancy or decreased the cache size, remove this redundancy instead of extending it
  86. if (!redundancyConfig || await this.isTooHeavy(candidate)) {
  87. logger.info('Destroying redundancy %s because the cache size %s is too heavy.', redundancyModel.url, redundancyModel.strategy)
  88. await removeVideoRedundancy(redundancyModel)
  89. } else {
  90. await this.extendsRedundancy(redundancyModel)
  91. }
  92. } catch (err) {
  93. logger.error(
  94. 'Cannot extend or remove expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel),
  95. { err }
  96. )
  97. }
  98. }
  99. }
  100. private async extendsRedundancy (redundancyModel: MVideoRedundancyVideo) {
  101. const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
  102. // Redundancy strategy disabled, remove our redundancy instead of extending expiration
  103. if (!redundancy) {
  104. await removeVideoRedundancy(redundancyModel)
  105. return
  106. }
  107. await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
  108. }
  109. private async purgeRemoteExpired () {
  110. const expired = await VideoRedundancyModel.listRemoteExpired()
  111. for (const redundancyModel of expired) {
  112. try {
  113. await removeVideoRedundancy(redundancyModel)
  114. } catch (err) {
  115. logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
  116. }
  117. }
  118. }
  119. private findVideoToDuplicate (cache: VideosRedundancy) {
  120. if (cache.strategy === 'most-views') {
  121. return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
  122. }
  123. if (cache.strategy === 'trending') {
  124. return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
  125. }
  126. if (cache.strategy === 'recently-added') {
  127. const minViews = cache.minViews
  128. return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
  129. }
  130. }
  131. private async createVideoRedundancies (data: CandidateToDuplicate) {
  132. const video = await this.loadAndRefreshVideo(data.video.url)
  133. if (!video) {
  134. logger.info('Video %s we want to duplicate does not existing anymore, skipping.', data.video.url)
  135. return
  136. }
  137. for (const file of data.files) {
  138. const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
  139. if (existingRedundancy) {
  140. await this.extendsRedundancy(existingRedundancy)
  141. continue
  142. }
  143. await this.createVideoFileRedundancy(data.redundancy, video, file)
  144. }
  145. for (const streamingPlaylist of data.streamingPlaylists) {
  146. const existingRedundancy = await VideoRedundancyModel.loadLocalByStreamingPlaylistId(streamingPlaylist.id)
  147. if (existingRedundancy) {
  148. await this.extendsRedundancy(existingRedundancy)
  149. continue
  150. }
  151. await this.createStreamingPlaylistRedundancy(data.redundancy, video, streamingPlaylist)
  152. }
  153. }
  154. private async createVideoFileRedundancy (redundancy: VideosRedundancy, video: MVideoAccountLight, fileArg: MVideoFile) {
  155. const file = fileArg as MVideoFileVideo
  156. file.Video = video
  157. const serverActor = await getServerActor()
  158. logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
  159. const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
  160. const magnetUri = await generateMagnetUri(video, file, baseUrlHttp, baseUrlWs)
  161. const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
  162. const destPath = join(CONFIG.STORAGE.REDUNDANCY_DIR, getVideoFilename(video, file))
  163. await move(tmpPath, destPath, { overwrite: true })
  164. const createdModel: MVideoRedundancyFileVideo = await VideoRedundancyModel.create({
  165. expiresOn: this.buildNewExpiration(redundancy.minLifetime),
  166. url: getVideoCacheFileActivityPubUrl(file),
  167. fileUrl: video.getVideoRedundancyUrl(file, WEBSERVER.URL),
  168. strategy: redundancy.strategy,
  169. videoFileId: file.id,
  170. actorId: serverActor.id
  171. })
  172. createdModel.VideoFile = file
  173. await sendCreateCacheFile(serverActor, video, createdModel)
  174. logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
  175. }
  176. private async createStreamingPlaylistRedundancy (
  177. redundancy: VideosRedundancy,
  178. video: MVideoAccountLight,
  179. playlistArg: MStreamingPlaylist
  180. ) {
  181. const playlist = playlistArg as MStreamingPlaylistVideo
  182. playlist.Video = video
  183. const serverActor = await getServerActor()
  184. logger.info('Duplicating %s streaming playlist in videos redundancy with "%s" strategy.', video.url, redundancy.strategy)
  185. const destDirectory = join(HLS_REDUNDANCY_DIRECTORY, video.uuid)
  186. await downloadPlaylistSegments(playlist.playlistUrl, destDirectory, VIDEO_IMPORT_TIMEOUT)
  187. const createdModel: MVideoRedundancyStreamingPlaylistVideo = await VideoRedundancyModel.create({
  188. expiresOn: this.buildNewExpiration(redundancy.minLifetime),
  189. url: getVideoCacheStreamingPlaylistActivityPubUrl(video, playlist),
  190. fileUrl: playlist.getVideoRedundancyUrl(WEBSERVER.URL),
  191. strategy: redundancy.strategy,
  192. videoStreamingPlaylistId: playlist.id,
  193. actorId: serverActor.id
  194. })
  195. createdModel.VideoStreamingPlaylist = playlist
  196. await sendCreateCacheFile(serverActor, video, createdModel)
  197. logger.info('Duplicated playlist %s -> %s.', playlist.playlistUrl, createdModel.url)
  198. }
  199. private async extendsExpirationOf (redundancy: MVideoRedundancyVideo, expiresAfterMs: number) {
  200. logger.info('Extending expiration of %s.', redundancy.url)
  201. const serverActor = await getServerActor()
  202. redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
  203. await redundancy.save()
  204. await sendUpdateCacheFile(serverActor, redundancy)
  205. }
  206. private async purgeCacheIfNeeded (candidateToDuplicate: CandidateToDuplicate) {
  207. while (await this.isTooHeavy(candidateToDuplicate)) {
  208. const redundancy = candidateToDuplicate.redundancy
  209. const toDelete = await VideoRedundancyModel.loadOldestLocalExpired(redundancy.strategy, redundancy.minLifetime)
  210. if (!toDelete) return
  211. await removeVideoRedundancy(toDelete)
  212. }
  213. }
  214. private async isTooHeavy (candidateToDuplicate: CandidateToDuplicate) {
  215. const maxSize = candidateToDuplicate.redundancy.size
  216. const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(candidateToDuplicate.redundancy.strategy)
  217. const totalWillDuplicate = totalDuplicated + this.getTotalFileSizes(candidateToDuplicate.files, candidateToDuplicate.streamingPlaylists)
  218. return totalWillDuplicate > maxSize
  219. }
  220. private buildNewExpiration (expiresAfterMs: number) {
  221. return new Date(Date.now() + expiresAfterMs)
  222. }
  223. private buildEntryLogId (object: MVideoRedundancyFileVideo | MVideoRedundancyStreamingPlaylistVideo) {
  224. if (isMVideoRedundancyFileVideo(object)) return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
  225. return `${object.VideoStreamingPlaylist.playlistUrl}`
  226. }
  227. private getTotalFileSizes (files: MVideoFile[], playlists: MStreamingPlaylist[]) {
  228. const fileReducer = (previous: number, current: MVideoFile) => previous + current.size
  229. const totalSize = files.reduce(fileReducer, 0)
  230. return totalSize + (totalSize * playlists.length)
  231. }
  232. private async loadAndRefreshVideo (videoUrl: string) {
  233. // We need more attributes and check if the video still exists
  234. const getVideoOptions = {
  235. videoObject: videoUrl,
  236. syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
  237. fetchType: 'all' as 'all'
  238. }
  239. const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)
  240. return video
  241. }
  242. }