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