]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/server-commands/server/server.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / shared / server-commands / server / server.ts
1 import { ChildProcess, fork } from 'child_process'
2 import { copy } from 'fs-extra'
3 import { join } from 'path'
4 import { parallelTests, randomInt, root } from '@shared/core-utils'
5 import { Video, VideoChannel, VideoChannelSync, VideoCreateResult, VideoDetails } from '@shared/models'
6 import { BulkCommand } from '../bulk'
7 import { CLICommand } from '../cli'
8 import { CustomPagesCommand } from '../custom-pages'
9 import { FeedCommand } from '../feeds'
10 import { LogsCommand } from '../logs'
11 import { AbusesCommand } from '../moderation'
12 import { OverviewsCommand } from '../overviews'
13 import { RunnerJobsCommand, RunnerRegistrationTokensCommand, RunnersCommand } from '../runners'
14 import { SearchCommand } from '../search'
15 import { SocketIOCommand } from '../socket'
16 import {
17 AccountsCommand,
18 BlocklistCommand,
19 LoginCommand,
20 NotificationsCommand,
21 RegistrationsCommand,
22 SubscriptionsCommand,
23 TwoFactorCommand,
24 UsersCommand
25 } from '../users'
26 import {
27 BlacklistCommand,
28 CaptionsCommand,
29 ChangeOwnershipCommand,
30 ChannelsCommand,
31 ChannelSyncsCommand,
32 HistoryCommand,
33 ImportsCommand,
34 LiveCommand,
35 PlaylistsCommand,
36 ServicesCommand,
37 StreamingPlaylistsCommand,
38 VideosCommand,
39 VideoStudioCommand,
40 VideoTokenCommand,
41 ViewsCommand
42 } from '../videos'
43 import { CommentsCommand } from '../videos/comments-command'
44 import { VideoStatsCommand } from '../videos/video-stats-command'
45 import { ConfigCommand } from './config-command'
46 import { ContactFormCommand } from './contact-form-command'
47 import { DebugCommand } from './debug-command'
48 import { FollowsCommand } from './follows-command'
49 import { JobsCommand } from './jobs-command'
50 import { MetricsCommand } from './metrics-command'
51 import { PluginsCommand } from './plugins-command'
52 import { RedundancyCommand } from './redundancy-command'
53 import { ServersCommand } from './servers-command'
54 import { StatsCommand } from './stats-command'
55
56 export type RunServerOptions = {
57 hideLogs?: boolean
58 nodeArgs?: string[]
59 peertubeArgs?: string[]
60 env?: { [ id: string ]: string }
61 }
62
63 export class PeerTubeServer {
64 app?: ChildProcess
65
66 url: string
67 host?: string
68 hostname?: string
69 port?: number
70
71 rtmpPort?: number
72 rtmpsPort?: number
73
74 parallel?: boolean
75 internalServerNumber: number
76
77 serverNumber?: number
78 customConfigFile?: string
79
80 store?: {
81 client?: {
82 id?: string
83 secret?: string
84 }
85
86 user?: {
87 username: string
88 password: string
89 email?: string
90 }
91
92 channel?: VideoChannel
93 videoChannelSync?: Partial<VideoChannelSync>
94
95 video?: Video
96 videoCreated?: VideoCreateResult
97 videoDetails?: VideoDetails
98
99 videos?: { id: number, uuid: string }[]
100 }
101
102 accessToken?: string
103 refreshToken?: string
104
105 bulk?: BulkCommand
106 cli?: CLICommand
107 customPage?: CustomPagesCommand
108 feed?: FeedCommand
109 logs?: LogsCommand
110 abuses?: AbusesCommand
111 overviews?: OverviewsCommand
112 search?: SearchCommand
113 contactForm?: ContactFormCommand
114 debug?: DebugCommand
115 follows?: FollowsCommand
116 jobs?: JobsCommand
117 metrics?: MetricsCommand
118 plugins?: PluginsCommand
119 redundancy?: RedundancyCommand
120 stats?: StatsCommand
121 config?: ConfigCommand
122 socketIO?: SocketIOCommand
123 accounts?: AccountsCommand
124 blocklist?: BlocklistCommand
125 subscriptions?: SubscriptionsCommand
126 live?: LiveCommand
127 services?: ServicesCommand
128 blacklist?: BlacklistCommand
129 captions?: CaptionsCommand
130 changeOwnership?: ChangeOwnershipCommand
131 playlists?: PlaylistsCommand
132 history?: HistoryCommand
133 imports?: ImportsCommand
134 channelSyncs?: ChannelSyncsCommand
135 streamingPlaylists?: StreamingPlaylistsCommand
136 channels?: ChannelsCommand
137 comments?: CommentsCommand
138 notifications?: NotificationsCommand
139 servers?: ServersCommand
140 login?: LoginCommand
141 users?: UsersCommand
142 videoStudio?: VideoStudioCommand
143 videos?: VideosCommand
144 videoStats?: VideoStatsCommand
145 views?: ViewsCommand
146 twoFactor?: TwoFactorCommand
147 videoToken?: VideoTokenCommand
148 registrations?: RegistrationsCommand
149
150 runners?: RunnersCommand
151 runnerRegistrationTokens?: RunnerRegistrationTokensCommand
152 runnerJobs?: RunnerJobsCommand
153
154 constructor (options: { serverNumber: number } | { url: string }) {
155 if ((options as any).url) {
156 this.setUrl((options as any).url)
157 } else {
158 this.setServerNumber((options as any).serverNumber)
159 }
160
161 this.store = {
162 client: {
163 id: null,
164 secret: null
165 },
166 user: {
167 username: null,
168 password: null
169 }
170 }
171
172 this.assignCommands()
173 }
174
175 setServerNumber (serverNumber: number) {
176 this.serverNumber = serverNumber
177
178 this.parallel = parallelTests()
179
180 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
181 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
182 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
183 this.port = 9000 + this.internalServerNumber
184
185 this.url = `http://127.0.0.1:${this.port}`
186 this.host = `127.0.0.1:${this.port}`
187 this.hostname = '127.0.0.1'
188 }
189
190 setUrl (url: string) {
191 const parsed = new URL(url)
192
193 this.url = url
194 this.host = parsed.host
195 this.hostname = parsed.hostname
196 this.port = parseInt(parsed.port)
197 }
198
199 getDirectoryPath (directoryName: string) {
200 const testDirectory = 'test' + this.internalServerNumber
201
202 return join(root(), testDirectory, directoryName)
203 }
204
205 async flushAndRun (configOverride?: object, options: RunServerOptions = {}) {
206 await ServersCommand.flushTests(this.internalServerNumber)
207
208 return this.run(configOverride, options)
209 }
210
211 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
212 // These actions are async so we need to be sure that they have both been done
213 const serverRunString = {
214 'HTTP server listening': false
215 }
216 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
217 serverRunString[key] = false
218
219 const regexps = {
220 client_id: 'Client id: (.+)',
221 client_secret: 'Client secret: (.+)',
222 user_username: 'Username: (.+)',
223 user_password: 'User password: (.+)'
224 }
225
226 await this.assignCustomConfigFile()
227
228 const configOverride = this.buildConfigOverride()
229
230 if (configOverrideArg !== undefined) {
231 Object.assign(configOverride, configOverrideArg)
232 }
233
234 // Share the environment
235 const env = Object.create(process.env)
236 env['NODE_ENV'] = 'test'
237 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
238 env['NODE_CONFIG'] = JSON.stringify(configOverride)
239
240 if (options.env) {
241 Object.assign(env, options.env)
242 }
243
244 const execArgv = options.nodeArgs || []
245 // FIXME: too slow :/
246 // execArgv.push('--enable-source-maps')
247
248 const forkOptions = {
249 silent: true,
250 env,
251 detached: false,
252 execArgv
253 }
254
255 const peertubeArgs = options.peertubeArgs || []
256
257 return new Promise<void>((res, rej) => {
258 const self = this
259 let aggregatedLogs = ''
260
261 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
262
263 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
264 const onParentExit = () => {
265 if (!this.app?.pid) return
266
267 try {
268 process.kill(self.app.pid)
269 } catch { /* empty */ }
270 }
271
272 this.app.on('exit', onPeerTubeExit)
273 process.on('exit', onParentExit)
274
275 this.app.stdout.on('data', function onStdout (data) {
276 let dontContinue = false
277
278 const log: string = data.toString()
279 aggregatedLogs += log
280
281 // Capture things if we want to
282 for (const key of Object.keys(regexps)) {
283 const regexp = regexps[key]
284 const matches = log.match(regexp)
285 if (matches !== null) {
286 if (key === 'client_id') self.store.client.id = matches[1]
287 else if (key === 'client_secret') self.store.client.secret = matches[1]
288 else if (key === 'user_username') self.store.user.username = matches[1]
289 else if (key === 'user_password') self.store.user.password = matches[1]
290 }
291 }
292
293 // Check if all required sentences are here
294 for (const key of Object.keys(serverRunString)) {
295 if (log.includes(key)) serverRunString[key] = true
296 if (serverRunString[key] === false) dontContinue = true
297 }
298
299 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
300 if (dontContinue === true) return
301
302 if (options.hideLogs === false) {
303 console.log(log)
304 } else {
305 process.removeListener('exit', onParentExit)
306 self.app.stdout.removeListener('data', onStdout)
307 self.app.removeListener('exit', onPeerTubeExit)
308 }
309
310 res()
311 })
312 })
313 }
314
315 kill () {
316 if (!this.app) return Promise.resolve()
317
318 process.kill(this.app.pid)
319
320 this.app = null
321
322 return Promise.resolve()
323 }
324
325 private randomServer () {
326 const low = 2500
327 const high = 10000
328
329 return randomInt(low, high)
330 }
331
332 private randomRTMP () {
333 const low = 1900
334 const high = 2100
335
336 return randomInt(low, high)
337 }
338
339 private async assignCustomConfigFile () {
340 if (this.internalServerNumber === this.serverNumber) return
341
342 const basePath = join(root(), 'config')
343
344 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
345 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
346
347 this.customConfigFile = tmpConfigFile
348 }
349
350 private buildConfigOverride () {
351 if (!this.parallel) return {}
352
353 return {
354 listen: {
355 port: this.port
356 },
357 webserver: {
358 port: this.port
359 },
360 database: {
361 suffix: '_test' + this.internalServerNumber
362 },
363 storage: {
364 tmp: this.getDirectoryPath('tmp') + '/',
365 tmp_persistent: this.getDirectoryPath('tmp-persistent') + '/',
366 bin: this.getDirectoryPath('bin') + '/',
367 avatars: this.getDirectoryPath('avatars') + '/',
368 videos: this.getDirectoryPath('videos') + '/',
369 streaming_playlists: this.getDirectoryPath('streaming-playlists') + '/',
370 redundancy: this.getDirectoryPath('redundancy') + '/',
371 logs: this.getDirectoryPath('logs') + '/',
372 previews: this.getDirectoryPath('previews') + '/',
373 thumbnails: this.getDirectoryPath('thumbnails') + '/',
374 torrents: this.getDirectoryPath('torrents') + '/',
375 captions: this.getDirectoryPath('captions') + '/',
376 cache: this.getDirectoryPath('cache') + '/',
377 plugins: this.getDirectoryPath('plugins') + '/',
378 well_known: this.getDirectoryPath('well-known') + '/'
379 },
380 admin: {
381 email: `admin${this.internalServerNumber}@example.com`
382 },
383 live: {
384 rtmp: {
385 port: this.rtmpPort
386 }
387 }
388 }
389 }
390
391 private assignCommands () {
392 this.bulk = new BulkCommand(this)
393 this.cli = new CLICommand(this)
394 this.customPage = new CustomPagesCommand(this)
395 this.feed = new FeedCommand(this)
396 this.logs = new LogsCommand(this)
397 this.abuses = new AbusesCommand(this)
398 this.overviews = new OverviewsCommand(this)
399 this.search = new SearchCommand(this)
400 this.contactForm = new ContactFormCommand(this)
401 this.debug = new DebugCommand(this)
402 this.follows = new FollowsCommand(this)
403 this.jobs = new JobsCommand(this)
404 this.metrics = new MetricsCommand(this)
405 this.plugins = new PluginsCommand(this)
406 this.redundancy = new RedundancyCommand(this)
407 this.stats = new StatsCommand(this)
408 this.config = new ConfigCommand(this)
409 this.socketIO = new SocketIOCommand(this)
410 this.accounts = new AccountsCommand(this)
411 this.blocklist = new BlocklistCommand(this)
412 this.subscriptions = new SubscriptionsCommand(this)
413 this.live = new LiveCommand(this)
414 this.services = new ServicesCommand(this)
415 this.blacklist = new BlacklistCommand(this)
416 this.captions = new CaptionsCommand(this)
417 this.changeOwnership = new ChangeOwnershipCommand(this)
418 this.playlists = new PlaylistsCommand(this)
419 this.history = new HistoryCommand(this)
420 this.imports = new ImportsCommand(this)
421 this.channelSyncs = new ChannelSyncsCommand(this)
422 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
423 this.channels = new ChannelsCommand(this)
424 this.comments = new CommentsCommand(this)
425 this.notifications = new NotificationsCommand(this)
426 this.servers = new ServersCommand(this)
427 this.login = new LoginCommand(this)
428 this.users = new UsersCommand(this)
429 this.videos = new VideosCommand(this)
430 this.videoStudio = new VideoStudioCommand(this)
431 this.videoStats = new VideoStatsCommand(this)
432 this.views = new ViewsCommand(this)
433 this.twoFactor = new TwoFactorCommand(this)
434 this.videoToken = new VideoTokenCommand(this)
435 this.registrations = new RegistrationsCommand(this)
436
437 this.runners = new RunnersCommand(this)
438 this.runnerRegistrationTokens = new RunnerRegistrationTokensCommand(this)
439 this.runnerJobs = new RunnerJobsCommand(this)
440 }
441 }