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, 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 { SQLCommand } from '../miscs'
12 import { AbusesCommand } from '../moderation'
13 import { OverviewsCommand } from '../overviews'
14 import { SearchCommand } from '../search'
15 import { SocketIOCommand } from '../socket'
16 import { AccountsCommand, BlocklistCommand, LoginCommand, NotificationsCommand, SubscriptionsCommand, UsersCommand } from '../users'
20 ChangeOwnershipCommand,
27 StreamingPlaylistsCommand,
32 import { CommentsCommand } from '../videos/comments-command'
33 import { VideoStatsCommand } from '../videos/video-stats-command'
34 import { ConfigCommand } from './config-command'
35 import { ContactFormCommand } from './contact-form-command'
36 import { DebugCommand } from './debug-command'
37 import { FollowsCommand } from './follows-command'
38 import { JobsCommand } from './jobs-command'
39 import { ObjectStorageCommand } from './object-storage-command'
40 import { PluginsCommand } from './plugins-command'
41 import { RedundancyCommand } from './redundancy-command'
42 import { ServersCommand } from './servers-command'
43 import { StatsCommand } from './stats-command'
45 export type RunServerOptions = {
48 peertubeArgs?: string[]
49 env?: { [ id: string ]: string }
52 export class PeerTubeServer {
64 internalServerNumber: number
67 customConfigFile?: string
81 channel?: VideoChannel
84 videoCreated?: VideoCreateResult
85 videoDetails?: VideoDetails
87 videos?: { id: number, uuid: string }[]
95 customPage?: CustomPagesCommand
98 abuses?: AbusesCommand
99 overviews?: OverviewsCommand
100 search?: SearchCommand
101 contactForm?: ContactFormCommand
103 follows?: FollowsCommand
105 plugins?: PluginsCommand
106 redundancy?: RedundancyCommand
108 config?: ConfigCommand
109 socketIO?: SocketIOCommand
110 accounts?: AccountsCommand
111 blocklist?: BlocklistCommand
112 subscriptions?: SubscriptionsCommand
114 services?: ServicesCommand
115 blacklist?: BlacklistCommand
116 captions?: CaptionsCommand
117 changeOwnership?: ChangeOwnershipCommand
118 playlists?: PlaylistsCommand
119 history?: HistoryCommand
120 imports?: ImportsCommand
121 streamingPlaylists?: StreamingPlaylistsCommand
122 channels?: ChannelsCommand
123 comments?: CommentsCommand
125 notifications?: NotificationsCommand
126 servers?: ServersCommand
129 objectStorage?: ObjectStorageCommand
130 videoStudio?: VideoStudioCommand
131 videos?: VideosCommand
132 videoStats?: VideoStatsCommand
135 constructor (options: { serverNumber: number } | { url: string }) {
136 if ((options as any).url) {
137 this.setUrl((options as any).url)
139 this.setServerNumber((options as any).serverNumber)
153 this.assignCommands()
156 setServerNumber (serverNumber: number) {
157 this.serverNumber = serverNumber
159 this.parallel = parallelTests()
161 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
162 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
163 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
164 this.port = 9000 + this.internalServerNumber
166 this.url = `http://localhost:${this.port}`
167 this.host = `localhost:${this.port}`
168 this.hostname = 'localhost'
171 setUrl (url: string) {
172 const parsed = new URL(url)
175 this.host = parsed.host
176 this.hostname = parsed.hostname
177 this.port = parseInt(parsed.port)
180 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
181 await ServersCommand.flushTests(this.internalServerNumber)
183 return this.run(configOverride, options)
186 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
187 // These actions are async so we need to be sure that they have both been done
188 const serverRunString = {
189 'HTTP server listening': false
191 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
192 serverRunString[key] = false
195 client_id: 'Client id: (.+)',
196 client_secret: 'Client secret: (.+)',
197 user_username: 'Username: (.+)',
198 user_password: 'User password: (.+)'
201 await this.assignCustomConfigFile()
203 const configOverride = this.buildConfigOverride()
205 if (configOverrideArg !== undefined) {
206 Object.assign(configOverride, configOverrideArg)
209 // Share the environment
210 const env = Object.create(process.env)
211 env['NODE_ENV'] = 'test'
212 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
213 env['NODE_CONFIG'] = JSON.stringify(configOverride)
216 Object.assign(env, options.env)
219 const execArgv = options.nodeArgs || []
220 // FIXME: too slow :/
221 // execArgv.push('--enable-source-maps')
223 const forkOptions = {
230 const peertubeArgs = options.peertubeArgs || []
232 return new Promise<void>((res, rej) => {
234 let aggregatedLogs = ''
236 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
238 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
239 const onParentExit = () => {
240 if (!this.app || !this.app.pid) return
243 process.kill(self.app.pid)
244 } catch { /* empty */ }
247 this.app.on('exit', onPeerTubeExit)
248 process.on('exit', onParentExit)
250 this.app.stdout.on('data', function onStdout (data) {
251 let dontContinue = false
253 const log: string = data.toString()
254 aggregatedLogs += log
256 // Capture things if we want to
257 for (const key of Object.keys(regexps)) {
258 const regexp = regexps[key]
259 const matches = log.match(regexp)
260 if (matches !== null) {
261 if (key === 'client_id') self.store.client.id = matches[1]
262 else if (key === 'client_secret') self.store.client.secret = matches[1]
263 else if (key === 'user_username') self.store.user.username = matches[1]
264 else if (key === 'user_password') self.store.user.password = matches[1]
268 // Check if all required sentences are here
269 for (const key of Object.keys(serverRunString)) {
270 if (log.includes(key)) serverRunString[key] = true
271 if (serverRunString[key] === false) dontContinue = true
274 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
275 if (dontContinue === true) return
277 if (options.hideLogs === false) {
280 process.removeListener('exit', onParentExit)
281 self.app.stdout.removeListener('data', onStdout)
282 self.app.removeListener('exit', onPeerTubeExit)
291 if (!this.app) return
293 await this.sql.cleanup()
295 process.kill(-this.app.pid)
300 private randomServer () {
304 return randomInt(low, high)
307 private randomRTMP () {
311 return randomInt(low, high)
314 private async assignCustomConfigFile () {
315 if (this.internalServerNumber === this.serverNumber) return
317 const basePath = join(root(), 'config')
319 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
320 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
322 this.customConfigFile = tmpConfigFile
325 private buildConfigOverride () {
326 if (!this.parallel) return {}
336 suffix: '_test' + this.internalServerNumber
339 tmp: `test${this.internalServerNumber}/tmp/`,
340 bin: `test${this.internalServerNumber}/bin/`,
341 avatars: `test${this.internalServerNumber}/avatars/`,
342 videos: `test${this.internalServerNumber}/videos/`,
343 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
344 redundancy: `test${this.internalServerNumber}/redundancy/`,
345 logs: `test${this.internalServerNumber}/logs/`,
346 previews: `test${this.internalServerNumber}/previews/`,
347 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
348 torrents: `test${this.internalServerNumber}/torrents/`,
349 captions: `test${this.internalServerNumber}/captions/`,
350 cache: `test${this.internalServerNumber}/cache/`,
351 plugins: `test${this.internalServerNumber}/plugins/`
354 email: `admin${this.internalServerNumber}@example.com`
364 private assignCommands () {
365 this.bulk = new BulkCommand(this)
366 this.cli = new CLICommand(this)
367 this.customPage = new CustomPagesCommand(this)
368 this.feed = new FeedCommand(this)
369 this.logs = new LogsCommand(this)
370 this.abuses = new AbusesCommand(this)
371 this.overviews = new OverviewsCommand(this)
372 this.search = new SearchCommand(this)
373 this.contactForm = new ContactFormCommand(this)
374 this.debug = new DebugCommand(this)
375 this.follows = new FollowsCommand(this)
376 this.jobs = new JobsCommand(this)
377 this.plugins = new PluginsCommand(this)
378 this.redundancy = new RedundancyCommand(this)
379 this.stats = new StatsCommand(this)
380 this.config = new ConfigCommand(this)
381 this.socketIO = new SocketIOCommand(this)
382 this.accounts = new AccountsCommand(this)
383 this.blocklist = new BlocklistCommand(this)
384 this.subscriptions = new SubscriptionsCommand(this)
385 this.live = new LiveCommand(this)
386 this.services = new ServicesCommand(this)
387 this.blacklist = new BlacklistCommand(this)
388 this.captions = new CaptionsCommand(this)
389 this.changeOwnership = new ChangeOwnershipCommand(this)
390 this.playlists = new PlaylistsCommand(this)
391 this.history = new HistoryCommand(this)
392 this.imports = new ImportsCommand(this)
393 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
394 this.channels = new ChannelsCommand(this)
395 this.comments = new CommentsCommand(this)
396 this.sql = new SQLCommand(this)
397 this.notifications = new NotificationsCommand(this)
398 this.servers = new ServersCommand(this)
399 this.login = new LoginCommand(this)
400 this.users = new UsersCommand(this)
401 this.videos = new VideosCommand(this)
402 this.objectStorage = new ObjectStorageCommand(this)
403 this.videoStudio = new VideoStudioCommand(this)
404 this.videoStats = new VideoStatsCommand(this)
405 this.views = new ViewsCommand(this)