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