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