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