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