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