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