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