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