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