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