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