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