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