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