]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/server/servers.ts
Introduce streaming playlists command
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / server / servers.ts
1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
2
3 import { expect } from 'chai'
4 import { ChildProcess, exec, fork } from 'child_process'
5 import { copy, ensureDir, pathExists, readdir, readFile, remove } from 'fs-extra'
6 import { join } from 'path'
7 import { randomInt } from '../../core-utils/miscs/miscs'
8 import { VideoChannel } from '../../models/videos'
9 import { BulkCommand } from '../bulk'
10 import { CLICommand } from '../cli'
11 import { CustomPagesCommand } from '../custom-pages'
12 import { FeedCommand } from '../feeds'
13 import { LogsCommand } from '../logs'
14 import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs'
15 import { AbusesCommand } from '../moderation'
16 import { OverviewsCommand } from '../overviews'
17 import { makeGetRequest } from '../requests/requests'
18 import { SearchCommand } from '../search'
19 import { SocketIOCommand } from '../socket'
20 import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users'
21 import {
22 BlacklistCommand,
23 CaptionsCommand,
24 ChangeOwnershipCommand,
25 HistoryCommand,
26 ImportsCommand,
27 LiveCommand,
28 PlaylistsCommand,
29 ServicesCommand,
30 StreamingPlaylistsCommand
31 } from '../videos'
32 import { ConfigCommand } from './config-command'
33 import { ContactFormCommand } from './contact-form-command'
34 import { DebugCommand } from './debug-command'
35 import { FollowsCommand } from './follows-command'
36 import { JobsCommand } from './jobs-command'
37 import { PluginsCommand } from './plugins-command'
38 import { RedundancyCommand } from './redundancy-command'
39 import { StatsCommand } from './stats-command'
40
41 interface ServerInfo {
42 app: ChildProcess
43
44 url: string
45 host: string
46 hostname: string
47 port: number
48
49 rtmpPort: number
50
51 parallel: boolean
52 internalServerNumber: number
53 serverNumber: number
54
55 client: {
56 id: string
57 secret: string
58 }
59
60 user: {
61 username: string
62 password: string
63 email?: string
64 }
65
66 customConfigFile?: string
67
68 accessToken?: string
69 refreshToken?: string
70 videoChannel?: VideoChannel
71
72 video?: {
73 id: number
74 uuid: string
75 shortUUID: string
76 name?: string
77 url?: string
78
79 account?: {
80 name: string
81 }
82
83 embedPath?: string
84 }
85
86 remoteVideo?: {
87 id: number
88 uuid: string
89 }
90
91 videos?: { id: number, uuid: string }[]
92
93 bulkCommand?: BulkCommand
94 cliCommand?: CLICommand
95 customPageCommand?: CustomPagesCommand
96 feedCommand?: FeedCommand
97 logsCommand?: LogsCommand
98 abusesCommand?: AbusesCommand
99 overviewsCommand?: OverviewsCommand
100 searchCommand?: SearchCommand
101 contactFormCommand?: ContactFormCommand
102 debugCommand?: DebugCommand
103 followsCommand?: FollowsCommand
104 jobsCommand?: JobsCommand
105 pluginsCommand?: PluginsCommand
106 redundancyCommand?: RedundancyCommand
107 statsCommand?: StatsCommand
108 configCommand?: ConfigCommand
109 socketIOCommand?: SocketIOCommand
110 accountsCommand?: AccountsCommand
111 blocklistCommand?: BlocklistCommand
112 subscriptionsCommand?: SubscriptionsCommand
113 liveCommand?: LiveCommand
114 servicesCommand?: ServicesCommand
115 blacklistCommand?: BlacklistCommand
116 captionsCommand?: CaptionsCommand
117 changeOwnershipCommand?: ChangeOwnershipCommand
118 playlistsCommand?: PlaylistsCommand
119 historyCommand?: HistoryCommand
120 importsCommand?: ImportsCommand
121 streamingPlaylistsCommand?: StreamingPlaylistsCommand
122 }
123
124 function parallelTests () {
125 return process.env.MOCHA_PARALLEL === 'true'
126 }
127
128 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
129 const apps = []
130 let i = 0
131
132 return new Promise<ServerInfo[]>(res => {
133 function anotherServerDone (serverNumber, app) {
134 apps[serverNumber - 1] = app
135 i++
136 if (i === totalServers) {
137 return res(apps)
138 }
139 }
140
141 for (let j = 1; j <= totalServers; j++) {
142 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
143 }
144 })
145 }
146
147 function flushTests (serverNumber?: number) {
148 return new Promise<void>((res, rej) => {
149 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
150
151 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
152 if (err || stderr) return rej(err || new Error(stderr))
153
154 return res()
155 })
156 })
157 }
158
159 function randomServer () {
160 const low = 10
161 const high = 10000
162
163 return randomInt(low, high)
164 }
165
166 function randomRTMP () {
167 const low = 1900
168 const high = 2100
169
170 return randomInt(low, high)
171 }
172
173 type RunServerOptions = {
174 hideLogs?: boolean
175 execArgv?: string[]
176 }
177
178 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
179 const parallel = parallelTests()
180
181 const internalServerNumber = parallel ? randomServer() : serverNumber
182 const rtmpPort = parallel ? randomRTMP() : 1936
183 const port = 9000 + internalServerNumber
184
185 await flushTests(internalServerNumber)
186
187 const server: ServerInfo = {
188 app: null,
189 port,
190 internalServerNumber,
191 rtmpPort,
192 parallel,
193 serverNumber,
194 url: `http://localhost:${port}`,
195 host: `localhost:${port}`,
196 hostname: 'localhost',
197 client: {
198 id: null,
199 secret: null
200 },
201 user: {
202 username: null,
203 password: null
204 }
205 }
206
207 return runServer(server, configOverride, args, options)
208 }
209
210 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
211 // These actions are async so we need to be sure that they have both been done
212 const serverRunString = {
213 'HTTP server listening': false
214 }
215 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
216 serverRunString[key] = false
217
218 const regexps = {
219 client_id: 'Client id: (.+)',
220 client_secret: 'Client secret: (.+)',
221 user_username: 'Username: (.+)',
222 user_password: 'User password: (.+)'
223 }
224
225 if (server.internalServerNumber !== server.serverNumber) {
226 const basePath = join(root(), 'config')
227
228 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
229 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
230
231 server.customConfigFile = tmpConfigFile
232 }
233
234 const configOverride: any = {}
235
236 if (server.parallel) {
237 Object.assign(configOverride, {
238 listen: {
239 port: server.port
240 },
241 webserver: {
242 port: server.port
243 },
244 database: {
245 suffix: '_test' + server.internalServerNumber
246 },
247 storage: {
248 tmp: `test${server.internalServerNumber}/tmp/`,
249 avatars: `test${server.internalServerNumber}/avatars/`,
250 videos: `test${server.internalServerNumber}/videos/`,
251 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
252 redundancy: `test${server.internalServerNumber}/redundancy/`,
253 logs: `test${server.internalServerNumber}/logs/`,
254 previews: `test${server.internalServerNumber}/previews/`,
255 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
256 torrents: `test${server.internalServerNumber}/torrents/`,
257 captions: `test${server.internalServerNumber}/captions/`,
258 cache: `test${server.internalServerNumber}/cache/`,
259 plugins: `test${server.internalServerNumber}/plugins/`
260 },
261 admin: {
262 email: `admin${server.internalServerNumber}@example.com`
263 },
264 live: {
265 rtmp: {
266 port: server.rtmpPort
267 }
268 }
269 })
270 }
271
272 if (configOverrideArg !== undefined) {
273 Object.assign(configOverride, configOverrideArg)
274 }
275
276 // Share the environment
277 const env = Object.create(process.env)
278 env['NODE_ENV'] = 'test'
279 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
280 env['NODE_CONFIG'] = JSON.stringify(configOverride)
281
282 const forkOptions = {
283 silent: true,
284 env,
285 detached: true,
286 execArgv: options.execArgv || []
287 }
288
289 return new Promise<ServerInfo>(res => {
290 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
291 server.app.stdout.on('data', function onStdout (data) {
292 let dontContinue = false
293
294 // Capture things if we want to
295 for (const key of Object.keys(regexps)) {
296 const regexp = regexps[key]
297 const matches = data.toString().match(regexp)
298 if (matches !== null) {
299 if (key === 'client_id') server.client.id = matches[1]
300 else if (key === 'client_secret') server.client.secret = matches[1]
301 else if (key === 'user_username') server.user.username = matches[1]
302 else if (key === 'user_password') server.user.password = matches[1]
303 }
304 }
305
306 // Check if all required sentences are here
307 for (const key of Object.keys(serverRunString)) {
308 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
309 if (serverRunString[key] === false) dontContinue = true
310 }
311
312 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
313 if (dontContinue === true) return
314
315 if (options.hideLogs === false) {
316 console.log(data.toString())
317 } else {
318 server.app.stdout.removeListener('data', onStdout)
319 }
320
321 process.on('exit', () => {
322 try {
323 process.kill(server.app.pid)
324 } catch { /* empty */ }
325 })
326
327 server.bulkCommand = new BulkCommand(server)
328 server.cliCommand = new CLICommand(server)
329 server.customPageCommand = new CustomPagesCommand(server)
330 server.feedCommand = new FeedCommand(server)
331 server.logsCommand = new LogsCommand(server)
332 server.abusesCommand = new AbusesCommand(server)
333 server.overviewsCommand = new OverviewsCommand(server)
334 server.searchCommand = new SearchCommand(server)
335 server.contactFormCommand = new ContactFormCommand(server)
336 server.debugCommand = new DebugCommand(server)
337 server.followsCommand = new FollowsCommand(server)
338 server.jobsCommand = new JobsCommand(server)
339 server.pluginsCommand = new PluginsCommand(server)
340 server.redundancyCommand = new RedundancyCommand(server)
341 server.statsCommand = new StatsCommand(server)
342 server.configCommand = new ConfigCommand(server)
343 server.socketIOCommand = new SocketIOCommand(server)
344 server.accountsCommand = new AccountsCommand(server)
345 server.blocklistCommand = new BlocklistCommand(server)
346 server.subscriptionsCommand = new SubscriptionsCommand(server)
347 server.liveCommand = new LiveCommand(server)
348 server.servicesCommand = new ServicesCommand(server)
349 server.blacklistCommand = new BlacklistCommand(server)
350 server.captionsCommand = new CaptionsCommand(server)
351 server.changeOwnershipCommand = new ChangeOwnershipCommand(server)
352 server.playlistsCommand = new PlaylistsCommand(server)
353 server.historyCommand = new HistoryCommand(server)
354 server.importsCommand = new ImportsCommand(server)
355 server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server)
356
357 res(server)
358 })
359 })
360 }
361
362 async function reRunServer (server: ServerInfo, configOverride?: any) {
363 const newServer = await runServer(server, configOverride)
364 server.app = newServer.app
365
366 return server
367 }
368
369 async function checkTmpIsEmpty (server: ServerInfo) {
370 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
371
372 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
373 await checkDirectoryIsEmpty(server, 'tmp/hls')
374 }
375 }
376
377 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
378 const testDirectory = 'test' + server.internalServerNumber
379
380 const directoryPath = join(root(), testDirectory, directory)
381
382 const directoryExists = await pathExists(directoryPath)
383 expect(directoryExists).to.be.true
384
385 const files = await readdir(directoryPath)
386 const filtered = files.filter(f => exceptions.includes(f) === false)
387
388 expect(filtered).to.have.lengthOf(0)
389 }
390
391 function killallServers (servers: ServerInfo[]) {
392 for (const server of servers) {
393 if (!server.app) continue
394
395 process.kill(-server.app.pid)
396 server.app = null
397 }
398 }
399
400 async function cleanupTests (servers: ServerInfo[]) {
401 killallServers(servers)
402
403 if (isGithubCI()) {
404 await ensureDir('artifacts')
405 }
406
407 const p: Promise<any>[] = []
408 for (const server of servers) {
409 if (isGithubCI()) {
410 const origin = await buildServerDirectory(server, 'logs/peertube.log')
411 const destname = `peertube-${server.internalServerNumber}.log`
412 console.log('Saving logs %s.', destname)
413
414 await copy(origin, join('artifacts', destname))
415 }
416
417 if (server.parallel) {
418 p.push(flushTests(server.internalServerNumber))
419 }
420
421 if (server.customConfigFile) {
422 p.push(remove(server.customConfigFile))
423 }
424 }
425
426 return Promise.all(p)
427 }
428
429 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
430 const logfile = buildServerDirectory(server, 'logs/peertube.log')
431
432 while (true) {
433 const buf = await readFile(logfile)
434
435 const matches = buf.toString().match(new RegExp(str, 'g'))
436 if (matches && matches.length === count) return
437 if (matches && strictCount === false && matches.length >= count) return
438
439 await wait(1000)
440 }
441 }
442
443 async function getServerFileSize (server: ServerInfo, subPath: string) {
444 const path = buildServerDirectory(server, subPath)
445
446 return getFileSize(path)
447 }
448
449 function makePingRequest (server: ServerInfo) {
450 return makeGetRequest({
451 url: server.url,
452 path: '/api/v1/ping',
453 statusCodeExpected: 200
454 })
455 }
456
457 // ---------------------------------------------------------------------------
458
459 export {
460 checkDirectoryIsEmpty,
461 checkTmpIsEmpty,
462 getServerFileSize,
463 ServerInfo,
464 parallelTests,
465 cleanupTests,
466 flushAndRunMultipleServers,
467 flushTests,
468 makePingRequest,
469 flushAndRunServer,
470 killallServers,
471 reRunServer,
472 waitUntilLog
473 }