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