1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
3 import * as chai from 'chai'
5 import { VideoDetails } from '../../../../shared/models/videos'
8 checkVideoFilesWereRemoved,
11 flushAndRunMultipleServers,
12 getFollowingListPaginationAndSort,
22 setAccessTokensToServers,
28 } from '../../../../shared/extra-utils'
29 import { waitJobs } from '../../../../shared/extra-utils/server/jobs'
31 import * as magnetUtil from 'magnet-uri'
34 listVideoRedundancies,
35 removeVideoRedundancy,
37 } from '../../../../shared/extra-utils/server/redundancy'
38 import { ActorFollow } from '../../../../shared/models/actors'
39 import { readdir } from 'fs-extra'
40 import { join } from 'path'
41 import { VideoRedundancy, VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '../../../../shared/models/redundancy'
42 import { getStats } from '../../../../shared/extra-utils/server/stats'
43 import { ServerStats } from '../../../../shared/models/server/server-stats.model'
45 const expect = chai.expect
47 let servers: ServerInfo[] = []
48 let video1Server2UUID: string
49 let video1Server2Id: number
51 function checkMagnetWebseeds (file: { magnetUri: string, resolution: { id: number } }, baseWebseeds: string[], server: ServerInfo) {
52 const parsed = magnetUtil.decode(file.magnetUri)
54 for (const ws of baseWebseeds) {
55 const found = parsed.urlList.find(url => url === `${ws}-${file.resolution.id}.mp4`)
56 expect(found, `Webseed ${ws} not found in ${file.magnetUri} on server ${server.url}`).to.not.be.undefined
59 expect(parsed.urlList).to.have.lengthOf(baseWebseeds.length)
62 async function flushAndRunServers (strategy: VideoRedundancyStrategy | null, additionalParams: any = {}) {
63 const strategies: any[] = []
65 if (strategy !== null) {
68 min_lifetime: '1 hour',
83 check_interval: '5 seconds',
89 servers = await flushAndRunMultipleServers(3, config)
91 // Get the access tokens
92 await setAccessTokensToServers(servers)
95 const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 1 server 2' })
96 video1Server2UUID = res.body.video.uuid
97 video1Server2Id = res.body.video.id
99 await viewVideo(servers[1].url, video1Server2UUID)
102 await waitJobs(servers)
104 // Server 1 and server 2 follow each other
105 await doubleFollow(servers[0], servers[1])
106 // Server 1 and server 3 follow each other
107 await doubleFollow(servers[0], servers[2])
108 // Server 2 and server 3 follow each other
109 await doubleFollow(servers[1], servers[2])
111 await waitJobs(servers)
114 async function check1WebSeed (videoUUID?: string) {
115 if (!videoUUID) videoUUID = video1Server2UUID
118 `http://localhost:${servers[1].port}/static/webseed/${videoUUID}`
121 for (const server of servers) {
122 // With token to avoid issues with video follow constraints
123 const res = await getVideoWithToken(server.url, server.accessToken, videoUUID)
125 const video: VideoDetails = res.body
126 for (const f of video.files) {
127 checkMagnetWebseeds(f, webseeds, server)
132 async function check2Webseeds (videoUUID?: string) {
133 if (!videoUUID) videoUUID = video1Server2UUID
136 `http://localhost:${servers[0].port}/static/redundancy/${videoUUID}`,
137 `http://localhost:${servers[1].port}/static/webseed/${videoUUID}`
140 for (const server of servers) {
141 const res = await getVideo(server.url, videoUUID)
143 const video: VideoDetails = res.body
145 for (const file of video.files) {
146 checkMagnetWebseeds(file, webseeds, server)
148 await makeGetRequest({
150 statusCodeExpected: 200,
151 path: '/static/redundancy/' + `${videoUUID}-${file.resolution.id}.mp4`,
154 await makeGetRequest({
156 statusCodeExpected: 200,
157 path: `/static/webseed/${videoUUID}-${file.resolution.id}.mp4`,
163 const directories = [
164 'test' + servers[0].internalServerNumber + '/redundancy',
165 'test' + servers[1].internalServerNumber + '/videos'
168 for (const directory of directories) {
169 const files = await readdir(join(root(), directory))
170 expect(files).to.have.length.at.least(4)
172 for (const resolution of [ 240, 360, 480, 720 ]) {
173 expect(files.find(f => f === `${videoUUID}-${resolution}.mp4`)).to.not.be.undefined
178 async function check0PlaylistRedundancies (videoUUID?: string) {
179 if (!videoUUID) videoUUID = video1Server2UUID
181 for (const server of servers) {
182 // With token to avoid issues with video follow constraints
183 const res = await getVideoWithToken(server.url, server.accessToken, videoUUID)
184 const video: VideoDetails = res.body
186 expect(video.streamingPlaylists).to.be.an('array')
187 expect(video.streamingPlaylists).to.have.lengthOf(1)
188 expect(video.streamingPlaylists[0].redundancies).to.have.lengthOf(0)
192 async function check1PlaylistRedundancies (videoUUID?: string) {
193 if (!videoUUID) videoUUID = video1Server2UUID
195 for (const server of servers) {
196 const res = await getVideo(server.url, videoUUID)
197 const video: VideoDetails = res.body
199 expect(video.streamingPlaylists).to.have.lengthOf(1)
200 expect(video.streamingPlaylists[0].redundancies).to.have.lengthOf(1)
202 const redundancy = video.streamingPlaylists[0].redundancies[0]
204 expect(redundancy.baseUrl).to.equal(servers[0].url + '/static/redundancy/hls/' + videoUUID)
207 const baseUrlPlaylist = servers[1].url + '/static/streaming-playlists/hls'
208 const baseUrlSegment = servers[0].url + '/static/redundancy/hls'
210 const res = await getVideo(servers[0].url, videoUUID)
211 const hlsPlaylist = (res.body as VideoDetails).streamingPlaylists[0]
213 for (const resolution of [ 240, 360, 480, 720 ]) {
214 await checkSegmentHash(baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist)
217 const directories = [
218 'test' + servers[0].internalServerNumber + '/redundancy/hls',
219 'test' + servers[1].internalServerNumber + '/streaming-playlists/hls'
222 for (const directory of directories) {
223 const files = await readdir(join(root(), directory, videoUUID))
224 expect(files).to.have.length.at.least(4)
226 for (const resolution of [ 240, 360, 480, 720 ]) {
227 const filename = `${videoUUID}-${resolution}-fragmented.mp4`
229 expect(files.find(f => f === filename)).to.not.be.undefined
234 async function checkStatsGlobal (strategy: VideoRedundancyStrategyWithManual) {
235 let totalSize: number = null
238 if (strategy !== 'manual') {
243 const res = await getStats(servers[0].url)
244 const data: ServerStats = res.body
246 expect(data.videosRedundancy).to.have.lengthOf(statsLength)
248 const stat = data.videosRedundancy[0]
249 expect(stat.strategy).to.equal(strategy)
250 expect(stat.totalSize).to.equal(totalSize)
255 async function checkStatsWith2Webseed (strategy: VideoRedundancyStrategyWithManual) {
256 const stat = await checkStatsGlobal(strategy)
258 expect(stat.totalUsed).to.be.at.least(1).and.below(409601)
259 expect(stat.totalVideoFiles).to.equal(4)
260 expect(stat.totalVideos).to.equal(1)
263 async function checkStatsWith1Webseed (strategy: VideoRedundancyStrategyWithManual) {
264 const stat = await checkStatsGlobal(strategy)
266 expect(stat.totalUsed).to.equal(0)
267 expect(stat.totalVideoFiles).to.equal(0)
268 expect(stat.totalVideos).to.equal(0)
271 async function enableRedundancyOnServer1 () {
272 await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, true)
274 const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: '-createdAt' })
275 const follows: ActorFollow[] = res.body.data
276 const server2 = follows.find(f => f.following.host === `localhost:${servers[1].port}`)
277 const server3 = follows.find(f => f.following.host === `localhost:${servers[2].port}`)
279 expect(server3).to.not.be.undefined
280 expect(server3.following.hostRedundancyAllowed).to.be.false
282 expect(server2).to.not.be.undefined
283 expect(server2.following.hostRedundancyAllowed).to.be.true
286 async function disableRedundancyOnServer1 () {
287 await updateRedundancy(servers[0].url, servers[0].accessToken, servers[1].host, false)
289 const res = await getFollowingListPaginationAndSort({ url: servers[0].url, start: 0, count: 5, sort: '-createdAt' })
290 const follows: ActorFollow[] = res.body.data
291 const server2 = follows.find(f => f.following.host === `localhost:${servers[1].port}`)
292 const server3 = follows.find(f => f.following.host === `localhost:${servers[2].port}`)
294 expect(server3).to.not.be.undefined
295 expect(server3.following.hostRedundancyAllowed).to.be.false
297 expect(server2).to.not.be.undefined
298 expect(server2.following.hostRedundancyAllowed).to.be.false
301 describe('Test videos redundancy', function () {
303 describe('With most-views strategy', function () {
304 const strategy = 'most-views'
309 return flushAndRunServers(strategy)
312 it('Should have 1 webseed on the first video', async function () {
313 await check1WebSeed()
314 await check0PlaylistRedundancies()
315 await checkStatsWith1Webseed(strategy)
318 it('Should enable redundancy on server 1', function () {
319 return enableRedundancyOnServer1()
322 it('Should have 2 webseeds on the first video', async function () {
325 await waitJobs(servers)
326 await waitUntilLog(servers[0], 'Duplicated ', 5)
327 await waitJobs(servers)
329 await check2Webseeds()
330 await check1PlaylistRedundancies()
331 await checkStatsWith2Webseed(strategy)
334 it('Should undo redundancy on server 1 and remove duplicated videos', async function () {
337 await disableRedundancyOnServer1()
339 await waitJobs(servers)
342 await check1WebSeed()
343 await check0PlaylistRedundancies()
345 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].internalServerNumber, [ 'videos', join('playlists', 'hls') ])
348 after(async function () {
349 return cleanupTests(servers)
353 describe('With trending strategy', function () {
354 const strategy = 'trending'
359 return flushAndRunServers(strategy)
362 it('Should have 1 webseed on the first video', async function () {
363 await check1WebSeed()
364 await check0PlaylistRedundancies()
365 await checkStatsWith1Webseed(strategy)
368 it('Should enable redundancy on server 1', function () {
369 return enableRedundancyOnServer1()
372 it('Should have 2 webseeds on the first video', async function () {
375 await waitJobs(servers)
376 await waitUntilLog(servers[0], 'Duplicated ', 5)
377 await waitJobs(servers)
379 await check2Webseeds()
380 await check1PlaylistRedundancies()
381 await checkStatsWith2Webseed(strategy)
384 it('Should unfollow on server 1 and remove duplicated videos', async function () {
387 await unfollow(servers[0].url, servers[0].accessToken, servers[1])
389 await waitJobs(servers)
392 await check1WebSeed()
393 await check0PlaylistRedundancies()
395 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].internalServerNumber, [ 'videos' ])
398 after(async function () {
399 await cleanupTests(servers)
403 describe('With recently added strategy', function () {
404 const strategy = 'recently-added'
409 return flushAndRunServers(strategy, { min_views: 3 })
412 it('Should have 1 webseed on the first video', async function () {
413 await check1WebSeed()
414 await check0PlaylistRedundancies()
415 await checkStatsWith1Webseed(strategy)
418 it('Should enable redundancy on server 1', function () {
419 return enableRedundancyOnServer1()
422 it('Should still have 1 webseed on the first video', async function () {
425 await waitJobs(servers)
427 await waitJobs(servers)
429 await check1WebSeed()
430 await check0PlaylistRedundancies()
431 await checkStatsWith1Webseed(strategy)
434 it('Should view 2 times the first video to have > min_views config', async function () {
437 await viewVideo(servers[0].url, video1Server2UUID)
438 await viewVideo(servers[2].url, video1Server2UUID)
441 await waitJobs(servers)
444 it('Should have 2 webseeds on the first video', async function () {
447 await waitJobs(servers)
448 await waitUntilLog(servers[0], 'Duplicated ', 5)
449 await waitJobs(servers)
451 await check2Webseeds()
452 await check1PlaylistRedundancies()
453 await checkStatsWith2Webseed(strategy)
456 it('Should remove the video and the redundancy files', async function () {
459 await removeVideo(servers[1].url, servers[1].accessToken, video1Server2UUID)
461 await waitJobs(servers)
463 for (const server of servers) {
464 await checkVideoFilesWereRemoved(video1Server2UUID, server.internalServerNumber)
468 after(async function () {
469 await cleanupTests(servers)
473 describe('With manual strategy', function () {
477 return flushAndRunServers(null)
480 it('Should have 1 webseed on the first video', async function () {
481 await check1WebSeed()
482 await check0PlaylistRedundancies()
483 await checkStatsWith1Webseed('manual')
486 it('Should create a redundancy on first video', async function () {
487 await addVideoRedundancy({
489 accessToken: servers[0].accessToken,
490 videoId: video1Server2Id
494 it('Should have 2 webseeds on the first video', async function () {
497 await waitJobs(servers)
498 await waitUntilLog(servers[0], 'Duplicated ', 5)
499 await waitJobs(servers)
501 await check2Webseeds()
502 await check1PlaylistRedundancies()
503 await checkStatsWith2Webseed('manual')
506 it('Should manually remove redundancies on server 1 and remove duplicated videos', async function () {
509 const res = await listVideoRedundancies({
511 accessToken: servers[0].accessToken,
512 target: 'remote-videos'
515 const videos = res.body.data as VideoRedundancy[]
516 expect(videos).to.have.lengthOf(1)
518 const video = videos[0]
519 for (const r of video.redundancies.files.concat(video.redundancies.streamingPlaylists)) {
520 await removeVideoRedundancy({
522 accessToken: servers[0].accessToken,
527 await waitJobs(servers)
530 await check1WebSeed()
531 await check0PlaylistRedundancies()
533 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].serverNumber, [ 'videos' ])
536 after(async function () {
537 await cleanupTests(servers)
541 describe('Test expiration', function () {
542 const strategy = 'recently-added'
544 async function checkContains (servers: ServerInfo[], str: string) {
545 for (const server of servers) {
546 const res = await getVideo(server.url, video1Server2UUID)
547 const video: VideoDetails = res.body
549 for (const f of video.files) {
550 expect(f.magnetUri).to.contain(str)
555 async function checkNotContains (servers: ServerInfo[], str: string) {
556 for (const server of servers) {
557 const res = await getVideo(server.url, video1Server2UUID)
558 const video: VideoDetails = res.body
560 for (const f of video.files) {
561 expect(f.magnetUri).to.not.contain(str)
566 before(async function () {
569 await flushAndRunServers(strategy, { min_lifetime: '7 seconds', min_views: 0 })
571 await enableRedundancyOnServer1()
574 it('Should still have 2 webseeds after 10 seconds', async function () {
580 await checkContains(servers, 'http%3A%2F%2Flocalhost%3A' + servers[0].port)
582 // Maybe a server deleted a redundancy in the scheduler
585 await checkContains(servers, 'http%3A%2F%2Flocalhost%3A' + servers[0].port)
589 it('Should stop server 1 and expire video redundancy', async function () {
592 killallServers([ servers[0] ])
596 await checkNotContains([ servers[1], servers[2] ], 'http%3A%2F%2Flocalhost%3A' + servers[0].port)
599 after(async function () {
600 await cleanupTests(servers)
604 describe('Test file replacement', function () {
605 let video2Server2UUID: string
606 const strategy = 'recently-added'
608 before(async function () {
611 await flushAndRunServers(strategy, { min_lifetime: '7 seconds', min_views: 0 })
613 await enableRedundancyOnServer1()
615 await waitJobs(servers)
616 await waitUntilLog(servers[0], 'Duplicated ', 5)
617 await waitJobs(servers)
619 await check2Webseeds()
620 await check1PlaylistRedundancies()
621 await checkStatsWith2Webseed(strategy)
623 const res = await uploadVideo(servers[1].url, servers[1].accessToken, { name: 'video 2 server 2' })
624 video2Server2UUID = res.body.video.uuid
627 it('Should cache video 2 webseeds on the first video', async function () {
630 await waitJobs(servers)
634 while (checked === false) {
638 await check1WebSeed(video1Server2UUID)
639 await check0PlaylistRedundancies(video1Server2UUID)
640 await check2Webseeds(video2Server2UUID)
641 await check1PlaylistRedundancies(video2Server2UUID)
650 it('Should disable strategy and remove redundancies', async function () {
653 await waitJobs(servers)
655 killallServers([ servers[0] ])
656 await reRunServer(servers[0], {
659 check_interval: '1 second',
665 await waitJobs(servers)
667 await checkVideoFilesWereRemoved(video1Server2UUID, servers[0].internalServerNumber, [ join('redundancy', 'hls') ])
670 after(async function () {
671 await cleanupTests(servers)