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