]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/extra-utils/server/servers.ts
Introduce notifications command
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / server / servers.ts
CommitLineData
a1587156 1/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
89231874 2
c655c9ef 3import { expect } from 'chai'
0e1dc3e7 4import { ChildProcess, exec, fork } from 'child_process'
83ef31fe 5import { copy, ensureDir, pathExists, readdir, readFile, remove } from 'fs-extra'
c655c9ef 6import { join } from 'path'
7c3b7976 7import { randomInt } from '../../core-utils/miscs/miscs'
a35a2279 8import { VideoChannel } from '../../models/videos'
329619b3
C
9import { BulkCommand } from '../bulk'
10import { CLICommand } from '../cli'
e8bd7ce7 11import { CustomPagesCommand } from '../custom-pages'
c1bc8ee4 12import { FeedCommand } from '../feeds'
a92ddacb 13import { LogsCommand } from '../logs'
dd0ebb71 14import { SQLCommand } from '../miscs'
83ef31fe 15import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs'
0c1a77e9 16import { AbusesCommand } from '../moderation'
23a3a882 17import { OverviewsCommand } from '../overviews'
78d62f4d 18import { makeGetRequest } from '../requests/requests'
af971e06 19import { SearchCommand } from '../search'
87e2635a 20import { SocketIOCommand } from '../socket'
dd0ebb71 21import { AccountsCommand, BlocklistCommand, NotificationsCommand, SubscriptionsCommand } from '../users'
6910f20f
C
22import {
23 BlacklistCommand,
24 CaptionsCommand,
25 ChangeOwnershipCommand,
a5461888 26 ChannelsCommand,
6910f20f
C
27 HistoryCommand,
28 ImportsCommand,
29 LiveCommand,
30 PlaylistsCommand,
57f879a5
C
31 ServicesCommand,
32 StreamingPlaylistsCommand
6910f20f 33} from '../videos'
12edc149 34import { CommentsCommand } from '../videos/comments-command'
65e6e260 35import { ConfigCommand } from './config-command'
a9c58393 36import { ContactFormCommand } from './contact-form-command'
883a9019 37import { DebugCommand } from './debug-command'
c3d29f69 38import { FollowsCommand } from './follows-command'
9c6327f8 39import { JobsCommand } from './jobs-command'
ae2abfd3 40import { PluginsCommand } from './plugins-command'
dab04709 41import { RedundancyCommand } from './redundancy-command'
bc809041 42import { StatsCommand } from './stats-command'
0e1dc3e7
C
43
44interface ServerInfo {
078f17e6 45 app?: ChildProcess
af4ae64f 46
0e1dc3e7 47 url: string
078f17e6
C
48 host?: string
49 hostname?: string
50 port?: number
af4ae64f 51
078f17e6 52 rtmpPort?: number
c655c9ef 53
078f17e6 54 parallel?: boolean
86ebdf8c 55 internalServerNumber: number
078f17e6 56 serverNumber?: number
0e1dc3e7 57
078f17e6
C
58 client?: {
59 id?: string
60 secret?: string
0e1dc3e7
C
61 }
62
078f17e6 63 user?: {
a1587156
C
64 username: string
65 password: string
0e1dc3e7
C
66 email?: string
67 }
68
7c3b7976
C
69 customConfigFile?: string
70
0e1dc3e7 71 accessToken?: string
f43db2f4 72 refreshToken?: string
df0b219d 73 videoChannel?: VideoChannel
0e1dc3e7
C
74
75 video?: {
76 id: number
77 uuid: string
d4a8e7a6 78 shortUUID: string
310b5219 79 name?: string
a59f210f 80 url?: string
aea0b0e7 81
310b5219 82 account?: {
b64c950a
C
83 name: string
84 }
aea0b0e7
C
85
86 embedPath?: string
0e1dc3e7
C
87 }
88
89 remoteVideo?: {
90 id: number
91 uuid: string
92 }
df0b219d
C
93
94 videos?: { id: number, uuid: string }[]
329619b3
C
95
96 bulkCommand?: BulkCommand
97 cliCommand?: CLICommand
e8bd7ce7 98 customPageCommand?: CustomPagesCommand
c1bc8ee4 99 feedCommand?: FeedCommand
a92ddacb 100 logsCommand?: LogsCommand
0c1a77e9 101 abusesCommand?: AbusesCommand
23a3a882 102 overviewsCommand?: OverviewsCommand
af971e06 103 searchCommand?: SearchCommand
a9c58393 104 contactFormCommand?: ContactFormCommand
883a9019 105 debugCommand?: DebugCommand
c3d29f69 106 followsCommand?: FollowsCommand
9c6327f8 107 jobsCommand?: JobsCommand
ae2abfd3 108 pluginsCommand?: PluginsCommand
dab04709 109 redundancyCommand?: RedundancyCommand
bc809041 110 statsCommand?: StatsCommand
65e6e260 111 configCommand?: ConfigCommand
87e2635a 112 socketIOCommand?: SocketIOCommand
9fff08cf 113 accountsCommand?: AccountsCommand
5f8bd4cb 114 blocklistCommand?: BlocklistCommand
2c27e704 115 subscriptionsCommand?: SubscriptionsCommand
4f219914 116 liveCommand?: LiveCommand
d897210c 117 servicesCommand?: ServicesCommand
e3d15a6a 118 blacklistCommand?: BlacklistCommand
a2470c9f 119 captionsCommand?: CaptionsCommand
72cbfc56 120 changeOwnershipCommand?: ChangeOwnershipCommand
e6346d59 121 playlistsCommand?: PlaylistsCommand
313228e9 122 historyCommand?: HistoryCommand
6910f20f 123 importsCommand?: ImportsCommand
57f879a5 124 streamingPlaylistsCommand?: StreamingPlaylistsCommand
a5461888 125 channelsCommand?: ChannelsCommand
12edc149 126 commentsCommand?: CommentsCommand
9293139f 127 sqlCommand?: SQLCommand
dd0ebb71 128 notificationsCommand?: NotificationsCommand
0e1dc3e7
C
129}
130
7c3b7976
C
131function parallelTests () {
132 return process.env.MOCHA_PARALLEL === 'true'
133}
134
b36f41ca 135function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
a1587156 136 const apps = []
0e1dc3e7
C
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
210feb6c
C
148 for (let j = 1; j <= totalServers; j++) {
149 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
150 }
0e1dc3e7
C
151 })
152}
153
210feb6c 154function flushTests (serverNumber?: number) {
0e1dc3e7 155 return new Promise<void>((res, rej) => {
210feb6c
C
156 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
157
2284f202
C
158 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
159 if (err || stderr) return rej(err || new Error(stderr))
0e1dc3e7
C
160
161 return res()
162 })
163 })
164}
165
86ebdf8c
C
166function randomServer () {
167 const low = 10
168 const high = 10000
169
7c3b7976 170 return randomInt(low, high)
86ebdf8c
C
171}
172
c655c9ef
C
173function randomRTMP () {
174 const low = 1900
175 const high = 2100
176
177 return randomInt(low, high)
178}
179
bd2e2f11
C
180type RunServerOptions = {
181 hideLogs?: boolean
182 execArgv?: string[]
183}
184
185async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
7c3b7976 186 const parallel = parallelTests()
86ebdf8c
C
187
188 const internalServerNumber = parallel ? randomServer() : serverNumber
3e8584b9 189 const rtmpPort = parallel ? randomRTMP() : 1936
86ebdf8c
C
190 const port = 9000 + internalServerNumber
191
7c3b7976 192 await flushTests(internalServerNumber)
42e1ec25 193
0e1dc3e7
C
194 const server: ServerInfo = {
195 app: null,
86ebdf8c
C
196 port,
197 internalServerNumber,
c655c9ef 198 rtmpPort,
86ebdf8c 199 parallel,
7c3b7976 200 serverNumber,
86ebdf8c
C
201 url: `http://localhost:${port}`,
202 host: `localhost:${port}`,
af4ae64f 203 hostname: 'localhost',
0e1dc3e7
C
204 client: {
205 id: null,
206 secret: null
207 },
208 user: {
209 username: null,
210 password: null
211 }
212 }
213
bd2e2f11 214 return runServer(server, configOverride, args, options)
913b1d71
C
215}
216
bd2e2f11 217async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
0e1dc3e7
C
218 // These actions are async so we need to be sure that they have both been done
219 const serverRunString = {
fcb77122 220 'HTTP server listening': false
0e1dc3e7 221 }
913b1d71 222 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
0e1dc3e7
C
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
7c3b7976
C
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 }
fdbda9e3 240
7c3b7976 241 const configOverride: any = {}
86ebdf8c 242
913b1d71 243 if (server.parallel) {
7c3b7976 244 Object.assign(configOverride, {
86ebdf8c 245 listen: {
913b1d71 246 port: server.port
86ebdf8c
C
247 },
248 webserver: {
913b1d71 249 port: server.port
86ebdf8c
C
250 },
251 database: {
913b1d71 252 suffix: '_test' + server.internalServerNumber
86ebdf8c
C
253 },
254 storage: {
913b1d71
C
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/`,
89cd1275
C
265 cache: `test${server.internalServerNumber}/cache/`,
266 plugins: `test${server.internalServerNumber}/plugins/`
86ebdf8c
C
267 },
268 admin: {
913b1d71 269 email: `admin${server.internalServerNumber}@example.com`
c655c9ef
C
270 },
271 live: {
272 rtmp: {
273 port: server.rtmpPort
274 }
86ebdf8c 275 }
7c3b7976 276 })
86ebdf8c
C
277 }
278
279 if (configOverrideArg !== undefined) {
280 Object.assign(configOverride, configOverrideArg)
fdbda9e3
C
281 }
282
7c3b7976
C
283 // Share the environment
284 const env = Object.create(process.env)
285 env['NODE_ENV'] = 'test'
286 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
86ebdf8c
C
287 env['NODE_CONFIG'] = JSON.stringify(configOverride)
288
bd2e2f11 289 const forkOptions = {
0e1dc3e7 290 silent: true,
7c3b7976 291 env,
bd2e2f11
C
292 detached: true,
293 execArgv: options.execArgv || []
0e1dc3e7
C
294 }
295
296 return new Promise<ServerInfo>(res => {
bd2e2f11 297 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
42e1ec25
C
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)) {
a1587156 303 const regexp = regexps[key]
42e1ec25
C
304 const matches = data.toString().match(regexp)
305 if (matches !== null) {
a1587156
C
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]
42e1ec25
C
310 }
311 }
312
313 // Check if all required sentences are here
314 for (const key of Object.keys(serverRunString)) {
a1587156
C
315 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
316 if (serverRunString[key] === false) dontContinue = true
42e1ec25
C
317 }
318
319 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
320 if (dontContinue === true) return
321
bd2e2f11 322 if (options.hideLogs === false) {
5a547f69
C
323 console.log(data.toString())
324 } else {
325 server.app.stdout.removeListener('data', onStdout)
326 }
42e1ec25
C
327
328 process.on('exit', () => {
329 try {
330 process.kill(server.app.pid)
331 } catch { /* empty */ }
dc094603 332 })
42e1ec25 333
078f17e6 334 assignCommands(server)
329619b3 335
42e1ec25
C
336 res(server)
337 })
0e1dc3e7
C
338 })
339}
340
078f17e6
C
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)
9293139f 373 server.sqlCommand = new SQLCommand(server)
dd0ebb71 374 server.notificationsCommand = new NotificationsCommand(server)
078f17e6
C
375}
376
e5565833 377async function reRunServer (server: ServerInfo, configOverride?: any) {
913b1d71 378 const newServer = await runServer(server, configOverride)
7bc29171
C
379 server.app = newServer.app
380
381 return server
382}
383
d1a2ce5e 384async function checkTmpIsEmpty (server: ServerInfo) {
f6d6e7f8 385 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
d1a2ce5e
C
386
387 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
388 await checkDirectoryIsEmpty(server, 'tmp/hls')
389 }
09209296
C
390}
391
8d2be0ed 392async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
48f07b4a 393 const testDirectory = 'test' + server.internalServerNumber
89231874 394
09209296 395 const directoryPath = join(root(), testDirectory, directory)
89231874 396
8d2be0ed 397 const directoryExists = await pathExists(directoryPath)
89231874
C
398 expect(directoryExists).to.be.true
399
400 const files = await readdir(directoryPath)
8d2be0ed
C
401 const filtered = files.filter(f => exceptions.includes(f) === false)
402
403 expect(filtered).to.have.lengthOf(0)
89231874
C
404}
405
9293139f 406async function killallServers (servers: ServerInfo[]) {
0e1dc3e7 407 for (const server of servers) {
7c3b7976
C
408 if (!server.app) continue
409
9293139f
C
410 await server.sqlCommand.cleanup()
411
0e1dc3e7 412 process.kill(-server.app.pid)
9293139f 413
7c3b7976 414 server.app = null
0e1dc3e7
C
415 }
416}
417
83ef31fe 418async function cleanupTests (servers: ServerInfo[]) {
9293139f 419 await killallServers(servers)
86ebdf8c 420
83ef31fe
C
421 if (isGithubCI()) {
422 await ensureDir('artifacts')
423 }
424
86ebdf8c
C
425 const p: Promise<any>[] = []
426 for (const server of servers) {
83ef31fe
C
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
86ebdf8c
C
435 if (server.parallel) {
436 p.push(flushTests(server.internalServerNumber))
437 }
7c3b7976
C
438
439 if (server.customConfigFile) {
440 p.push(remove(server.customConfigFile))
441 }
86ebdf8c
C
442 }
443
444 return Promise.all(p)
445}
446
1b05d82d 447async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
ca5c612b 448 const logfile = buildServerDirectory(server, 'logs/peertube.log')
792e5b8e
C
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
1b05d82d 455 if (matches && strictCount === false && matches.length >= count) return
792e5b8e
C
456
457 await wait(1000)
458 }
459}
460
d218e7de 461async function getServerFileSize (server: ServerInfo, subPath: string) {
ca5c612b 462 const path = buildServerDirectory(server, subPath)
d218e7de
C
463
464 return getFileSize(path)
465}
466
78d62f4d
C
467function makePingRequest (server: ServerInfo) {
468 return makeGetRequest({
469 url: server.url,
470 path: '/api/v1/ping',
471 statusCodeExpected: 200
472 })
473}
474
0e1dc3e7
C
475// ---------------------------------------------------------------------------
476
477export {
09209296 478 checkDirectoryIsEmpty,
89231874 479 checkTmpIsEmpty,
d218e7de 480 getServerFileSize,
0e1dc3e7 481 ServerInfo,
7c3b7976 482 parallelTests,
86ebdf8c 483 cleanupTests,
0e1dc3e7
C
484 flushAndRunMultipleServers,
485 flushTests,
78d62f4d 486 makePingRequest,
210feb6c 487 flushAndRunServer,
7bc29171 488 killallServers,
792e5b8e 489 reRunServer,
078f17e6 490 assignCommands,
792e5b8e 491 waitUntilLog
0e1dc3e7 492}