]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/extra-utils/server/servers.ts
Fix CLI import script
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / server / servers.ts
CommitLineData
a1587156 1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
89231874 2
c655c9ef 3import { expect } from 'chai'
0e1dc3e7 4import { ChildProcess, exec, fork } from 'child_process'
8d2be0ed 5import { copy, pathExists, readdir, readFile, remove } from 'fs-extra'
c655c9ef 6import { join } from 'path'
7c3b7976 7import { randomInt } from '../../core-utils/miscs/miscs'
c655c9ef
C
8import { VideoChannel } from '../../models/videos'
9import { root, wait } from '../miscs/miscs'
0e1dc3e7
C
10
11interface ServerInfo {
a1587156 12 app: ChildProcess
af4ae64f 13
0e1dc3e7
C
14 url: string
15 host: string
af4ae64f 16 hostname: string
86ebdf8c 17 port: number
af4ae64f 18
c655c9ef
C
19 rtmpPort: number
20
86ebdf8c
C
21 parallel: boolean
22 internalServerNumber: number
fdbda9e3 23 serverNumber: number
0e1dc3e7
C
24
25 client: {
a1587156 26 id: string
0e1dc3e7
C
27 secret: string
28 }
29
30 user: {
a1587156
C
31 username: string
32 password: string
0e1dc3e7
C
33 email?: string
34 }
35
7c3b7976
C
36 customConfigFile?: string
37
0e1dc3e7 38 accessToken?: string
df0b219d 39 videoChannel?: VideoChannel
0e1dc3e7
C
40
41 video?: {
42 id: number
43 uuid: string
310b5219
C
44 name?: string
45 account?: {
b64c950a
C
46 name: string
47 }
0e1dc3e7
C
48 }
49
50 remoteVideo?: {
51 id: number
52 uuid: string
53 }
df0b219d
C
54
55 videos?: { id: number, uuid: string }[]
0e1dc3e7
C
56}
57
7c3b7976
C
58function parallelTests () {
59 return process.env.MOCHA_PARALLEL === 'true'
60}
61
b36f41ca 62function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
a1587156 63 const apps = []
0e1dc3e7
C
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
210feb6c
C
75 for (let j = 1; j <= totalServers; j++) {
76 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
77 }
0e1dc3e7
C
78 })
79}
80
210feb6c 81function flushTests (serverNumber?: number) {
0e1dc3e7 82 return new Promise<void>((res, rej) => {
210feb6c
C
83 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
84
2284f202
C
85 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
86 if (err || stderr) return rej(err || new Error(stderr))
0e1dc3e7
C
87
88 return res()
89 })
90 })
91}
92
86ebdf8c
C
93function randomServer () {
94 const low = 10
95 const high = 10000
96
7c3b7976 97 return randomInt(low, high)
86ebdf8c
C
98}
99
c655c9ef
C
100function randomRTMP () {
101 const low = 1900
102 const high = 2100
103
104 return randomInt(low, high)
105}
106
913b1d71 107async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = []) {
7c3b7976 108 const parallel = parallelTests()
86ebdf8c
C
109
110 const internalServerNumber = parallel ? randomServer() : serverNumber
c655c9ef 111 const rtmpPort = parallel ? randomRTMP() : null
86ebdf8c
C
112 const port = 9000 + internalServerNumber
113
7c3b7976 114 await flushTests(internalServerNumber)
42e1ec25 115
0e1dc3e7
C
116 const server: ServerInfo = {
117 app: null,
86ebdf8c
C
118 port,
119 internalServerNumber,
c655c9ef 120 rtmpPort,
86ebdf8c 121 parallel,
7c3b7976 122 serverNumber,
86ebdf8c
C
123 url: `http://localhost:${port}`,
124 host: `localhost:${port}`,
af4ae64f 125 hostname: 'localhost',
0e1dc3e7
C
126 client: {
127 id: null,
128 secret: null
129 },
130 user: {
131 username: null,
132 password: null
133 }
134 }
135
913b1d71
C
136 return runServer(server, configOverride, args)
137}
138
7c3b7976 139async function runServer (server: ServerInfo, configOverrideArg?: any, args = []) {
0e1dc3e7
C
140 // These actions are async so we need to be sure that they have both been done
141 const serverRunString = {
bf6e8e3e 142 'Server listening': false
0e1dc3e7 143 }
913b1d71 144 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
0e1dc3e7
C
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
7c3b7976
C
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 }
fdbda9e3 162
7c3b7976 163 const configOverride: any = {}
86ebdf8c 164
913b1d71 165 if (server.parallel) {
7c3b7976 166 Object.assign(configOverride, {
86ebdf8c 167 listen: {
913b1d71 168 port: server.port
86ebdf8c
C
169 },
170 webserver: {
913b1d71 171 port: server.port
86ebdf8c
C
172 },
173 database: {
913b1d71 174 suffix: '_test' + server.internalServerNumber
86ebdf8c
C
175 },
176 storage: {
913b1d71
C
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/`,
89cd1275
C
187 cache: `test${server.internalServerNumber}/cache/`,
188 plugins: `test${server.internalServerNumber}/plugins/`
86ebdf8c
C
189 },
190 admin: {
913b1d71 191 email: `admin${server.internalServerNumber}@example.com`
c655c9ef
C
192 },
193 live: {
194 rtmp: {
195 port: server.rtmpPort
196 }
86ebdf8c 197 }
7c3b7976 198 })
86ebdf8c
C
199 }
200
201 if (configOverrideArg !== undefined) {
202 Object.assign(configOverride, configOverrideArg)
fdbda9e3
C
203 }
204
7c3b7976
C
205 // Share the environment
206 const env = Object.create(process.env)
207 env['NODE_ENV'] = 'test'
208 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
86ebdf8c
C
209 env['NODE_CONFIG'] = JSON.stringify(configOverride)
210
0e1dc3e7
C
211 const options = {
212 silent: true,
7c3b7976 213 env,
0e1dc3e7
C
214 detached: true
215 }
216
217 return new Promise<ServerInfo>(res => {
42e1ec25
C
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)) {
a1587156 224 const regexp = regexps[key]
42e1ec25
C
225 const matches = data.toString().match(regexp)
226 if (matches !== null) {
a1587156
C
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]
42e1ec25
C
231 }
232 }
233
234 // Check if all required sentences are here
235 for (const key of Object.keys(serverRunString)) {
a1587156
C
236 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
237 if (serverRunString[key] === false) dontContinue = true
42e1ec25
C
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 */ }
dc094603 249 })
42e1ec25
C
250
251 res(server)
252 })
0e1dc3e7
C
253 })
254}
255
e5565833 256async function reRunServer (server: ServerInfo, configOverride?: any) {
913b1d71 257 const newServer = await runServer(server, configOverride)
7bc29171
C
258 server.app = newServer.app
259
260 return server
261}
262
8d2be0ed
C
263function checkTmpIsEmpty (server: ServerInfo) {
264 return checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css' ])
09209296
C
265}
266
8d2be0ed 267async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
48f07b4a 268 const testDirectory = 'test' + server.internalServerNumber
89231874 269
09209296 270 const directoryPath = join(root(), testDirectory, directory)
89231874 271
8d2be0ed 272 const directoryExists = await pathExists(directoryPath)
89231874
C
273 expect(directoryExists).to.be.true
274
275 const files = await readdir(directoryPath)
8d2be0ed
C
276 const filtered = files.filter(f => exceptions.includes(f) === false)
277
278 expect(filtered).to.have.lengthOf(0)
89231874
C
279}
280
0e1dc3e7
C
281function killallServers (servers: ServerInfo[]) {
282 for (const server of servers) {
7c3b7976
C
283 if (!server.app) continue
284
0e1dc3e7 285 process.kill(-server.app.pid)
7c3b7976 286 server.app = null
0e1dc3e7
C
287 }
288}
289
86ebdf8c
C
290function 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 }
7c3b7976
C
298
299 if (server.customConfigFile) {
300 p.push(remove(server.customConfigFile))
301 }
86ebdf8c
C
302 }
303
304 return Promise.all(p)
305}
306
1b05d82d 307async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
7243f84d 308 const logfile = join(root(), 'test' + server.internalServerNumber, 'logs/peertube.log')
792e5b8e
C
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
1b05d82d 315 if (matches && strictCount === false && matches.length >= count) return
792e5b8e
C
316
317 await wait(1000)
318 }
319}
320
0e1dc3e7
C
321// ---------------------------------------------------------------------------
322
323export {
09209296 324 checkDirectoryIsEmpty,
89231874 325 checkTmpIsEmpty,
0e1dc3e7 326 ServerInfo,
7c3b7976 327 parallelTests,
86ebdf8c 328 cleanupTests,
0e1dc3e7
C
329 flushAndRunMultipleServers,
330 flushTests,
210feb6c 331 flushAndRunServer,
7bc29171 332 killallServers,
792e5b8e
C
333 reRunServer,
334 waitUntilLog
0e1dc3e7 335}