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