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