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