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