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