]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/server/servers.ts
Fix CLI import script
[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 { 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 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = []) {
108 const parallel = parallelTests()
109
110 const internalServerNumber = parallel ? randomServer() : serverNumber
111 const rtmpPort = parallel ? randomRTMP() : null
112 const port = 9000 + internalServerNumber
113
114 await flushTests(internalServerNumber)
115
116 const server: ServerInfo = {
117 app: null,
118 port,
119 internalServerNumber,
120 rtmpPort,
121 parallel,
122 serverNumber,
123 url: `http://localhost:${port}`,
124 host: `localhost:${port}`,
125 hostname: 'localhost',
126 client: {
127 id: null,
128 secret: null
129 },
130 user: {
131 username: null,
132 password: null
133 }
134 }
135
136 return runServer(server, configOverride, args)
137 }
138
139 async function runServer (server: ServerInfo, configOverrideArg?: any, args = []) {
140 // These actions are async so we need to be sure that they have both been done
141 const serverRunString = {
142 'Server listening': false
143 }
144 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
145 serverRunString[key] = false
146
147 const regexps = {
148 client_id: 'Client id: (.+)',
149 client_secret: 'Client secret: (.+)',
150 user_username: 'Username: (.+)',
151 user_password: 'User password: (.+)'
152 }
153
154 if (server.internalServerNumber !== server.serverNumber) {
155 const basePath = join(root(), 'config')
156
157 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
158 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
159
160 server.customConfigFile = tmpConfigFile
161 }
162
163 const configOverride: any = {}
164
165 if (server.parallel) {
166 Object.assign(configOverride, {
167 listen: {
168 port: server.port
169 },
170 webserver: {
171 port: server.port
172 },
173 database: {
174 suffix: '_test' + server.internalServerNumber
175 },
176 storage: {
177 tmp: `test${server.internalServerNumber}/tmp/`,
178 avatars: `test${server.internalServerNumber}/avatars/`,
179 videos: `test${server.internalServerNumber}/videos/`,
180 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
181 redundancy: `test${server.internalServerNumber}/redundancy/`,
182 logs: `test${server.internalServerNumber}/logs/`,
183 previews: `test${server.internalServerNumber}/previews/`,
184 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
185 torrents: `test${server.internalServerNumber}/torrents/`,
186 captions: `test${server.internalServerNumber}/captions/`,
187 cache: `test${server.internalServerNumber}/cache/`,
188 plugins: `test${server.internalServerNumber}/plugins/`
189 },
190 admin: {
191 email: `admin${server.internalServerNumber}@example.com`
192 },
193 live: {
194 rtmp: {
195 port: server.rtmpPort
196 }
197 }
198 })
199 }
200
201 if (configOverrideArg !== undefined) {
202 Object.assign(configOverride, configOverrideArg)
203 }
204
205 // Share the environment
206 const env = Object.create(process.env)
207 env['NODE_ENV'] = 'test'
208 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
209 env['NODE_CONFIG'] = JSON.stringify(configOverride)
210
211 const options = {
212 silent: true,
213 env,
214 detached: true
215 }
216
217 return new Promise<ServerInfo>(res => {
218 server.app = fork(join(root(), 'dist', 'server.js'), args, options)
219 server.app.stdout.on('data', function onStdout (data) {
220 let dontContinue = false
221
222 // Capture things if we want to
223 for (const key of Object.keys(regexps)) {
224 const regexp = regexps[key]
225 const matches = data.toString().match(regexp)
226 if (matches !== null) {
227 if (key === 'client_id') server.client.id = matches[1]
228 else if (key === 'client_secret') server.client.secret = matches[1]
229 else if (key === 'user_username') server.user.username = matches[1]
230 else if (key === 'user_password') server.user.password = matches[1]
231 }
232 }
233
234 // Check if all required sentences are here
235 for (const key of Object.keys(serverRunString)) {
236 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
237 if (serverRunString[key] === false) dontContinue = true
238 }
239
240 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
241 if (dontContinue === true) return
242
243 server.app.stdout.removeListener('data', onStdout)
244
245 process.on('exit', () => {
246 try {
247 process.kill(server.app.pid)
248 } catch { /* empty */ }
249 })
250
251 res(server)
252 })
253 })
254 }
255
256 async function reRunServer (server: ServerInfo, configOverride?: any) {
257 const newServer = await runServer(server, configOverride)
258 server.app = newServer.app
259
260 return server
261 }
262
263 function checkTmpIsEmpty (server: ServerInfo) {
264 return checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css' ])
265 }
266
267 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
268 const testDirectory = 'test' + server.internalServerNumber
269
270 const directoryPath = join(root(), testDirectory, directory)
271
272 const directoryExists = await pathExists(directoryPath)
273 expect(directoryExists).to.be.true
274
275 const files = await readdir(directoryPath)
276 const filtered = files.filter(f => exceptions.includes(f) === false)
277
278 expect(filtered).to.have.lengthOf(0)
279 }
280
281 function killallServers (servers: ServerInfo[]) {
282 for (const server of servers) {
283 if (!server.app) continue
284
285 process.kill(-server.app.pid)
286 server.app = null
287 }
288 }
289
290 function cleanupTests (servers: ServerInfo[]) {
291 killallServers(servers)
292
293 const p: Promise<any>[] = []
294 for (const server of servers) {
295 if (server.parallel) {
296 p.push(flushTests(server.internalServerNumber))
297 }
298
299 if (server.customConfigFile) {
300 p.push(remove(server.customConfigFile))
301 }
302 }
303
304 return Promise.all(p)
305 }
306
307 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
308 const logfile = join(root(), 'test' + server.internalServerNumber, 'logs/peertube.log')
309
310 while (true) {
311 const buf = await readFile(logfile)
312
313 const matches = buf.toString().match(new RegExp(str, 'g'))
314 if (matches && matches.length === count) return
315 if (matches && strictCount === false && matches.length >= count) return
316
317 await wait(1000)
318 }
319 }
320
321 // ---------------------------------------------------------------------------
322
323 export {
324 checkDirectoryIsEmpty,
325 checkTmpIsEmpty,
326 ServerInfo,
327 parallelTests,
328 cleanupTests,
329 flushAndRunMultipleServers,
330 flushTests,
331 flushAndRunServer,
332 killallServers,
333 reRunServer,
334 waitUntilLog
335 }