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