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