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