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