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