]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/extra-utils/server/servers.ts
Introduce sql 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'
6910f20f
C
21import {
22 BlacklistCommand,
23 CaptionsCommand,
24 ChangeOwnershipCommand,
a5461888 25 ChannelsCommand,
6910f20f
C
26 HistoryCommand,
27 ImportsCommand,
28 LiveCommand,
29 PlaylistsCommand,
57f879a5
C
30 ServicesCommand,
31 StreamingPlaylistsCommand
6910f20f 32} from '../videos'
9293139f 33import { SQLCommand } from '../miscs'
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
0e1dc3e7
C
128}
129
7c3b7976
C
130function parallelTests () {
131 return process.env.MOCHA_PARALLEL === 'true'
132}
133
b36f41ca 134function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
a1587156 135 const apps = []
0e1dc3e7
C
136 let i = 0
137
138 return new Promise<ServerInfo[]>(res => {
139 function anotherServerDone (serverNumber, app) {
140 apps[serverNumber - 1] = app
141 i++
142 if (i === totalServers) {
143 return res(apps)
144 }
145 }
146
210feb6c
C
147 for (let j = 1; j <= totalServers; j++) {
148 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
149 }
0e1dc3e7
C
150 })
151}
152
210feb6c 153function flushTests (serverNumber?: number) {
0e1dc3e7 154 return new Promise<void>((res, rej) => {
210feb6c
C
155 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
156
2284f202
C
157 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
158 if (err || stderr) return rej(err || new Error(stderr))
0e1dc3e7
C
159
160 return res()
161 })
162 })
163}
164
86ebdf8c
C
165function randomServer () {
166 const low = 10
167 const high = 10000
168
7c3b7976 169 return randomInt(low, high)
86ebdf8c
C
170}
171
c655c9ef
C
172function randomRTMP () {
173 const low = 1900
174 const high = 2100
175
176 return randomInt(low, high)
177}
178
bd2e2f11
C
179type RunServerOptions = {
180 hideLogs?: boolean
181 execArgv?: string[]
182}
183
184async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
7c3b7976 185 const parallel = parallelTests()
86ebdf8c
C
186
187 const internalServerNumber = parallel ? randomServer() : serverNumber
3e8584b9 188 const rtmpPort = parallel ? randomRTMP() : 1936
86ebdf8c
C
189 const port = 9000 + internalServerNumber
190
7c3b7976 191 await flushTests(internalServerNumber)
42e1ec25 192
0e1dc3e7
C
193 const server: ServerInfo = {
194 app: null,
86ebdf8c
C
195 port,
196 internalServerNumber,
c655c9ef 197 rtmpPort,
86ebdf8c 198 parallel,
7c3b7976 199 serverNumber,
86ebdf8c
C
200 url: `http://localhost:${port}`,
201 host: `localhost:${port}`,
af4ae64f 202 hostname: 'localhost',
0e1dc3e7
C
203 client: {
204 id: null,
205 secret: null
206 },
207 user: {
208 username: null,
209 password: null
210 }
211 }
212
bd2e2f11 213 return runServer(server, configOverride, args, options)
913b1d71
C
214}
215
bd2e2f11 216async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
0e1dc3e7
C
217 // These actions are async so we need to be sure that they have both been done
218 const serverRunString = {
fcb77122 219 'HTTP server listening': false
0e1dc3e7 220 }
913b1d71 221 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
0e1dc3e7
C
222 serverRunString[key] = false
223
224 const regexps = {
225 client_id: 'Client id: (.+)',
226 client_secret: 'Client secret: (.+)',
227 user_username: 'Username: (.+)',
228 user_password: 'User password: (.+)'
229 }
230
7c3b7976
C
231 if (server.internalServerNumber !== server.serverNumber) {
232 const basePath = join(root(), 'config')
233
234 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
235 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
236
237 server.customConfigFile = tmpConfigFile
238 }
fdbda9e3 239
7c3b7976 240 const configOverride: any = {}
86ebdf8c 241
913b1d71 242 if (server.parallel) {
7c3b7976 243 Object.assign(configOverride, {
86ebdf8c 244 listen: {
913b1d71 245 port: server.port
86ebdf8c
C
246 },
247 webserver: {
913b1d71 248 port: server.port
86ebdf8c
C
249 },
250 database: {
913b1d71 251 suffix: '_test' + server.internalServerNumber
86ebdf8c
C
252 },
253 storage: {
913b1d71
C
254 tmp: `test${server.internalServerNumber}/tmp/`,
255 avatars: `test${server.internalServerNumber}/avatars/`,
256 videos: `test${server.internalServerNumber}/videos/`,
257 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
258 redundancy: `test${server.internalServerNumber}/redundancy/`,
259 logs: `test${server.internalServerNumber}/logs/`,
260 previews: `test${server.internalServerNumber}/previews/`,
261 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
262 torrents: `test${server.internalServerNumber}/torrents/`,
263 captions: `test${server.internalServerNumber}/captions/`,
89cd1275
C
264 cache: `test${server.internalServerNumber}/cache/`,
265 plugins: `test${server.internalServerNumber}/plugins/`
86ebdf8c
C
266 },
267 admin: {
913b1d71 268 email: `admin${server.internalServerNumber}@example.com`
c655c9ef
C
269 },
270 live: {
271 rtmp: {
272 port: server.rtmpPort
273 }
86ebdf8c 274 }
7c3b7976 275 })
86ebdf8c
C
276 }
277
278 if (configOverrideArg !== undefined) {
279 Object.assign(configOverride, configOverrideArg)
fdbda9e3
C
280 }
281
7c3b7976
C
282 // Share the environment
283 const env = Object.create(process.env)
284 env['NODE_ENV'] = 'test'
285 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
86ebdf8c
C
286 env['NODE_CONFIG'] = JSON.stringify(configOverride)
287
bd2e2f11 288 const forkOptions = {
0e1dc3e7 289 silent: true,
7c3b7976 290 env,
bd2e2f11
C
291 detached: true,
292 execArgv: options.execArgv || []
0e1dc3e7
C
293 }
294
295 return new Promise<ServerInfo>(res => {
bd2e2f11 296 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
42e1ec25
C
297 server.app.stdout.on('data', function onStdout (data) {
298 let dontContinue = false
299
300 // Capture things if we want to
301 for (const key of Object.keys(regexps)) {
a1587156 302 const regexp = regexps[key]
42e1ec25
C
303 const matches = data.toString().match(regexp)
304 if (matches !== null) {
a1587156
C
305 if (key === 'client_id') server.client.id = matches[1]
306 else if (key === 'client_secret') server.client.secret = matches[1]
307 else if (key === 'user_username') server.user.username = matches[1]
308 else if (key === 'user_password') server.user.password = matches[1]
42e1ec25
C
309 }
310 }
311
312 // Check if all required sentences are here
313 for (const key of Object.keys(serverRunString)) {
a1587156
C
314 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
315 if (serverRunString[key] === false) dontContinue = true
42e1ec25
C
316 }
317
318 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
319 if (dontContinue === true) return
320
bd2e2f11 321 if (options.hideLogs === false) {
5a547f69
C
322 console.log(data.toString())
323 } else {
324 server.app.stdout.removeListener('data', onStdout)
325 }
42e1ec25
C
326
327 process.on('exit', () => {
328 try {
329 process.kill(server.app.pid)
330 } catch { /* empty */ }
dc094603 331 })
42e1ec25 332
078f17e6 333 assignCommands(server)
329619b3 334
42e1ec25
C
335 res(server)
336 })
0e1dc3e7
C
337 })
338}
339
078f17e6
C
340function assignCommands (server: ServerInfo) {
341 server.bulkCommand = new BulkCommand(server)
342 server.cliCommand = new CLICommand(server)
343 server.customPageCommand = new CustomPagesCommand(server)
344 server.feedCommand = new FeedCommand(server)
345 server.logsCommand = new LogsCommand(server)
346 server.abusesCommand = new AbusesCommand(server)
347 server.overviewsCommand = new OverviewsCommand(server)
348 server.searchCommand = new SearchCommand(server)
349 server.contactFormCommand = new ContactFormCommand(server)
350 server.debugCommand = new DebugCommand(server)
351 server.followsCommand = new FollowsCommand(server)
352 server.jobsCommand = new JobsCommand(server)
353 server.pluginsCommand = new PluginsCommand(server)
354 server.redundancyCommand = new RedundancyCommand(server)
355 server.statsCommand = new StatsCommand(server)
356 server.configCommand = new ConfigCommand(server)
357 server.socketIOCommand = new SocketIOCommand(server)
358 server.accountsCommand = new AccountsCommand(server)
359 server.blocklistCommand = new BlocklistCommand(server)
360 server.subscriptionsCommand = new SubscriptionsCommand(server)
361 server.liveCommand = new LiveCommand(server)
362 server.servicesCommand = new ServicesCommand(server)
363 server.blacklistCommand = new BlacklistCommand(server)
364 server.captionsCommand = new CaptionsCommand(server)
365 server.changeOwnershipCommand = new ChangeOwnershipCommand(server)
366 server.playlistsCommand = new PlaylistsCommand(server)
367 server.historyCommand = new HistoryCommand(server)
368 server.importsCommand = new ImportsCommand(server)
369 server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server)
370 server.channelsCommand = new ChannelsCommand(server)
371 server.commentsCommand = new CommentsCommand(server)
9293139f 372 server.sqlCommand = new SQLCommand(server)
078f17e6
C
373}
374
e5565833 375async function reRunServer (server: ServerInfo, configOverride?: any) {
913b1d71 376 const newServer = await runServer(server, configOverride)
7bc29171
C
377 server.app = newServer.app
378
379 return server
380}
381
d1a2ce5e 382async function checkTmpIsEmpty (server: ServerInfo) {
f6d6e7f8 383 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
d1a2ce5e
C
384
385 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
386 await checkDirectoryIsEmpty(server, 'tmp/hls')
387 }
09209296
C
388}
389
8d2be0ed 390async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
48f07b4a 391 const testDirectory = 'test' + server.internalServerNumber
89231874 392
09209296 393 const directoryPath = join(root(), testDirectory, directory)
89231874 394
8d2be0ed 395 const directoryExists = await pathExists(directoryPath)
89231874
C
396 expect(directoryExists).to.be.true
397
398 const files = await readdir(directoryPath)
8d2be0ed
C
399 const filtered = files.filter(f => exceptions.includes(f) === false)
400
401 expect(filtered).to.have.lengthOf(0)
89231874
C
402}
403
9293139f 404async function killallServers (servers: ServerInfo[]) {
0e1dc3e7 405 for (const server of servers) {
7c3b7976
C
406 if (!server.app) continue
407
9293139f
C
408 await server.sqlCommand.cleanup()
409
0e1dc3e7 410 process.kill(-server.app.pid)
9293139f 411
7c3b7976 412 server.app = null
0e1dc3e7
C
413 }
414}
415
83ef31fe 416async function cleanupTests (servers: ServerInfo[]) {
9293139f 417 await killallServers(servers)
86ebdf8c 418
83ef31fe
C
419 if (isGithubCI()) {
420 await ensureDir('artifacts')
421 }
422
86ebdf8c
C
423 const p: Promise<any>[] = []
424 for (const server of servers) {
83ef31fe
C
425 if (isGithubCI()) {
426 const origin = await buildServerDirectory(server, 'logs/peertube.log')
427 const destname = `peertube-${server.internalServerNumber}.log`
428 console.log('Saving logs %s.', destname)
429
430 await copy(origin, join('artifacts', destname))
431 }
432
86ebdf8c
C
433 if (server.parallel) {
434 p.push(flushTests(server.internalServerNumber))
435 }
7c3b7976
C
436
437 if (server.customConfigFile) {
438 p.push(remove(server.customConfigFile))
439 }
86ebdf8c
C
440 }
441
442 return Promise.all(p)
443}
444
1b05d82d 445async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
ca5c612b 446 const logfile = buildServerDirectory(server, 'logs/peertube.log')
792e5b8e
C
447
448 while (true) {
449 const buf = await readFile(logfile)
450
451 const matches = buf.toString().match(new RegExp(str, 'g'))
452 if (matches && matches.length === count) return
1b05d82d 453 if (matches && strictCount === false && matches.length >= count) return
792e5b8e
C
454
455 await wait(1000)
456 }
457}
458
d218e7de 459async function getServerFileSize (server: ServerInfo, subPath: string) {
ca5c612b 460 const path = buildServerDirectory(server, subPath)
d218e7de
C
461
462 return getFileSize(path)
463}
464
78d62f4d
C
465function makePingRequest (server: ServerInfo) {
466 return makeGetRequest({
467 url: server.url,
468 path: '/api/v1/ping',
469 statusCodeExpected: 200
470 })
471}
472
0e1dc3e7
C
473// ---------------------------------------------------------------------------
474
475export {
09209296 476 checkDirectoryIsEmpty,
89231874 477 checkTmpIsEmpty,
d218e7de 478 getServerFileSize,
0e1dc3e7 479 ServerInfo,
7c3b7976 480 parallelTests,
86ebdf8c 481 cleanupTests,
0e1dc3e7
C
482 flushAndRunMultipleServers,
483 flushTests,
78d62f4d 484 makePingRequest,
210feb6c 485 flushAndRunServer,
7bc29171 486 killallServers,
792e5b8e 487 reRunServer,
078f17e6 488 assignCommands,
792e5b8e 489 waitUntilLog
0e1dc3e7 490}