Move to eslint
[oweals/peertube.git] / shared / extra-utils / server / servers.ts
1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
2
3 import { ChildProcess, exec, fork } from 'child_process'
4 import { join } from 'path'
5 import { root, wait } from '../miscs/miscs'
6 import { copy, pathExists, readdir, readFile, remove } from 'fs-extra'
7 import { expect } from 'chai'
8 import { VideoChannel } from '../../models/videos'
9 import { randomInt } from '../../core-utils/miscs/miscs'
10
11 interface ServerInfo {
12   app: ChildProcess
13   url: string
14   host: string
15
16   port: number
17   parallel: boolean
18   internalServerNumber: number
19   serverNumber: number
20
21   client: {
22     id: string
23     secret: string
24   }
25
26   user: {
27     username: string
28     password: string
29     email?: string
30   }
31
32   customConfigFile?: string
33
34   accessToken?: string
35   videoChannel?: VideoChannel
36
37   video?: {
38     id: number
39     uuid: string
40     name: string
41     account: {
42       name: string
43     }
44   }
45
46   remoteVideo?: {
47     id: number
48     uuid: string
49   }
50
51   videos?: { id: number, uuid: string }[]
52 }
53
54 function parallelTests () {
55   return process.env.MOCHA_PARALLEL === 'true'
56 }
57
58 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
59   const apps = []
60   let i = 0
61
62   return new Promise<ServerInfo[]>(res => {
63     function anotherServerDone (serverNumber, app) {
64       apps[serverNumber - 1] = app
65       i++
66       if (i === totalServers) {
67         return res(apps)
68       }
69     }
70
71     for (let j = 1; j <= totalServers; j++) {
72       flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
73     }
74   })
75 }
76
77 function flushTests (serverNumber?: number) {
78   return new Promise<void>((res, rej) => {
79     const suffix = serverNumber ? ` -- ${serverNumber}` : ''
80
81     return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
82       if (err || stderr) return rej(err || new Error(stderr))
83
84       return res()
85     })
86   })
87 }
88
89 function randomServer () {
90   const low = 10
91   const high = 10000
92
93   return randomInt(low, high)
94 }
95
96 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = []) {
97   const parallel = parallelTests()
98
99   const internalServerNumber = parallel ? randomServer() : serverNumber
100   const port = 9000 + internalServerNumber
101
102   await flushTests(internalServerNumber)
103
104   const server: ServerInfo = {
105     app: null,
106     port,
107     internalServerNumber,
108     parallel,
109     serverNumber,
110     url: `http://localhost:${port}`,
111     host: `localhost:${port}`,
112     client: {
113       id: null,
114       secret: null
115     },
116     user: {
117       username: null,
118       password: null
119     }
120   }
121
122   return runServer(server, configOverride, args)
123 }
124
125 async function runServer (server: ServerInfo, configOverrideArg?: any, args = []) {
126   // These actions are async so we need to be sure that they have both been done
127   const serverRunString = {
128     'Server listening': false
129   }
130   const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
131   serverRunString[key] = false
132
133   const regexps = {
134     client_id: 'Client id: (.+)',
135     client_secret: 'Client secret: (.+)',
136     user_username: 'Username: (.+)',
137     user_password: 'User password: (.+)'
138   }
139
140   if (server.internalServerNumber !== server.serverNumber) {
141     const basePath = join(root(), 'config')
142
143     const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
144     await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
145
146     server.customConfigFile = tmpConfigFile
147   }
148
149   const configOverride: any = {}
150
151   if (server.parallel) {
152     Object.assign(configOverride, {
153       listen: {
154         port: server.port
155       },
156       webserver: {
157         port: server.port
158       },
159       database: {
160         suffix: '_test' + server.internalServerNumber
161       },
162       storage: {
163         tmp: `test${server.internalServerNumber}/tmp/`,
164         avatars: `test${server.internalServerNumber}/avatars/`,
165         videos: `test${server.internalServerNumber}/videos/`,
166         streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
167         redundancy: `test${server.internalServerNumber}/redundancy/`,
168         logs: `test${server.internalServerNumber}/logs/`,
169         previews: `test${server.internalServerNumber}/previews/`,
170         thumbnails: `test${server.internalServerNumber}/thumbnails/`,
171         torrents: `test${server.internalServerNumber}/torrents/`,
172         captions: `test${server.internalServerNumber}/captions/`,
173         cache: `test${server.internalServerNumber}/cache/`,
174         plugins: `test${server.internalServerNumber}/plugins/`
175       },
176       admin: {
177         email: `admin${server.internalServerNumber}@example.com`
178       }
179     })
180   }
181
182   if (configOverrideArg !== undefined) {
183     Object.assign(configOverride, configOverrideArg)
184   }
185
186   // Share the environment
187   const env = Object.create(process.env)
188   env['NODE_ENV'] = 'test'
189   env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
190   env['NODE_CONFIG'] = JSON.stringify(configOverride)
191
192   const options = {
193     silent: true,
194     env,
195     detached: true
196   }
197
198   return new Promise<ServerInfo>(res => {
199     server.app = fork(join(root(), 'dist', 'server.js'), args, options)
200     server.app.stdout.on('data', function onStdout (data) {
201       let dontContinue = false
202
203       // Capture things if we want to
204       for (const key of Object.keys(regexps)) {
205         const regexp = regexps[key]
206         const matches = data.toString().match(regexp)
207         if (matches !== null) {
208           if (key === 'client_id') server.client.id = matches[1]
209           else if (key === 'client_secret') server.client.secret = matches[1]
210           else if (key === 'user_username') server.user.username = matches[1]
211           else if (key === 'user_password') server.user.password = matches[1]
212         }
213       }
214
215       // Check if all required sentences are here
216       for (const key of Object.keys(serverRunString)) {
217         if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
218         if (serverRunString[key] === false) dontContinue = true
219       }
220
221       // If no, there is maybe one thing not already initialized (client/user credentials generation...)
222       if (dontContinue === true) return
223
224       server.app.stdout.removeListener('data', onStdout)
225
226       process.on('exit', () => {
227         try {
228           process.kill(server.app.pid)
229         } catch { /* empty */ }
230       })
231
232       res(server)
233     })
234   })
235 }
236
237 async function reRunServer (server: ServerInfo, configOverride?: any) {
238   const newServer = await runServer(server, configOverride)
239   server.app = newServer.app
240
241   return server
242 }
243
244 function checkTmpIsEmpty (server: ServerInfo) {
245   return checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css' ])
246 }
247
248 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
249   const testDirectory = 'test' + server.internalServerNumber
250
251   const directoryPath = join(root(), testDirectory, directory)
252
253   const directoryExists = await pathExists(directoryPath)
254   expect(directoryExists).to.be.true
255
256   const files = await readdir(directoryPath)
257   const filtered = files.filter(f => exceptions.includes(f) === false)
258
259   expect(filtered).to.have.lengthOf(0)
260 }
261
262 function killallServers (servers: ServerInfo[]) {
263   for (const server of servers) {
264     if (!server.app) continue
265
266     process.kill(-server.app.pid)
267     server.app = null
268   }
269 }
270
271 function cleanupTests (servers: ServerInfo[]) {
272   killallServers(servers)
273
274   const p: Promise<any>[] = []
275   for (const server of servers) {
276     if (server.parallel) {
277       p.push(flushTests(server.internalServerNumber))
278     }
279
280     if (server.customConfigFile) {
281       p.push(remove(server.customConfigFile))
282     }
283   }
284
285   return Promise.all(p)
286 }
287
288 async function waitUntilLog (server: ServerInfo, str: string, count = 1) {
289   const logfile = join(root(), 'test' + server.internalServerNumber, 'logs/peertube.log')
290
291   while (true) {
292     const buf = await readFile(logfile)
293
294     const matches = buf.toString().match(new RegExp(str, 'g'))
295     if (matches && matches.length === count) return
296
297     await wait(1000)
298   }
299 }
300
301 // ---------------------------------------------------------------------------
302
303 export {
304   checkDirectoryIsEmpty,
305   checkTmpIsEmpty,
306   ServerInfo,
307   parallelTests,
308   cleanupTests,
309   flushAndRunMultipleServers,
310   flushTests,
311   flushAndRunServer,
312   killallServers,
313   reRunServer,
314   waitUntilLog
315 }