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