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