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