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