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