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