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