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