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