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