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,
31 import { CommentsCommand } from '../videos/comments-command'
32 import { ConfigCommand } from './config-command'
33 import { ContactFormCommand } from './contact-form-command'
34 import { DebugCommand } from './debug-command'
35 import { FollowsCommand } from './follows-command'
36 import { JobsCommand } from './jobs-command'
37 import { ObjectStorageCommand } from './object-storage-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'
43 export type RunServerOptions = {
46 peertubeArgs?: string[]
47 env?: { [ id: string ]: string }
50 export class PeerTubeServer {
62 internalServerNumber: number
65 customConfigFile?: string
79 channel?: VideoChannel
82 videoCreated?: VideoCreateResult
83 videoDetails?: VideoDetails
85 videos?: { id: number, uuid: string }[]
93 customPage?: CustomPagesCommand
96 abuses?: AbusesCommand
97 overviews?: OverviewsCommand
98 search?: SearchCommand
99 contactForm?: ContactFormCommand
101 follows?: FollowsCommand
103 plugins?: PluginsCommand
104 redundancy?: RedundancyCommand
106 config?: ConfigCommand
107 socketIO?: SocketIOCommand
108 accounts?: AccountsCommand
109 blocklist?: BlocklistCommand
110 subscriptions?: SubscriptionsCommand
112 services?: ServicesCommand
113 blacklist?: BlacklistCommand
114 captions?: CaptionsCommand
115 changeOwnership?: ChangeOwnershipCommand
116 playlists?: PlaylistsCommand
117 history?: HistoryCommand
118 imports?: ImportsCommand
119 streamingPlaylists?: StreamingPlaylistsCommand
120 channels?: ChannelsCommand
121 comments?: CommentsCommand
123 notifications?: NotificationsCommand
124 servers?: ServersCommand
127 objectStorage?: ObjectStorageCommand
128 videoEditor?: VideoEditorCommand
129 videos?: VideosCommand
131 constructor (options: { serverNumber: number } | { url: string }) {
132 if ((options as any).url) {
133 this.setUrl((options as any).url)
135 this.setServerNumber((options as any).serverNumber)
149 this.assignCommands()
152 setServerNumber (serverNumber: number) {
153 this.serverNumber = serverNumber
155 this.parallel = parallelTests()
157 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
158 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
159 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
160 this.port = 9000 + this.internalServerNumber
162 this.url = `http://localhost:${this.port}`
163 this.host = `localhost:${this.port}`
164 this.hostname = 'localhost'
167 setUrl (url: string) {
168 const parsed = new URL(url)
171 this.host = parsed.host
172 this.hostname = parsed.hostname
173 this.port = parseInt(parsed.port)
176 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
177 await ServersCommand.flushTests(this.internalServerNumber)
179 return this.run(configOverride, options)
182 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
183 // These actions are async so we need to be sure that they have both been done
184 const serverRunString = {
185 'HTTP server listening': false
187 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
188 serverRunString[key] = false
191 client_id: 'Client id: (.+)',
192 client_secret: 'Client secret: (.+)',
193 user_username: 'Username: (.+)',
194 user_password: 'User password: (.+)'
197 await this.assignCustomConfigFile()
199 const configOverride = this.buildConfigOverride()
201 if (configOverrideArg !== undefined) {
202 Object.assign(configOverride, configOverrideArg)
205 // Share the environment
206 const env = Object.create(process.env)
207 env['NODE_ENV'] = 'test'
208 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
209 env['NODE_CONFIG'] = JSON.stringify(configOverride)
212 Object.assign(env, options.env)
215 const execArgv = options.nodeArgs || []
216 // FIXME: too slow :/
217 // execArgv.push('--enable-source-maps')
219 const forkOptions = {
226 const peertubeArgs = options.peertubeArgs || []
228 return new Promise<void>((res, rej) => {
230 let aggregatedLogs = ''
232 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
234 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
235 const onParentExit = () => {
236 if (!this.app || !this.app.pid) return
239 process.kill(self.app.pid)
240 } catch { /* empty */ }
243 this.app.on('exit', onPeerTubeExit)
244 process.on('exit', onParentExit)
246 this.app.stdout.on('data', function onStdout (data) {
247 let dontContinue = false
249 const log: string = data.toString()
250 aggregatedLogs += log
252 // Capture things if we want to
253 for (const key of Object.keys(regexps)) {
254 const regexp = regexps[key]
255 const matches = log.match(regexp)
256 if (matches !== null) {
257 if (key === 'client_id') self.store.client.id = matches[1]
258 else if (key === 'client_secret') self.store.client.secret = matches[1]
259 else if (key === 'user_username') self.store.user.username = matches[1]
260 else if (key === 'user_password') self.store.user.password = matches[1]
264 // Check if all required sentences are here
265 for (const key of Object.keys(serverRunString)) {
266 if (log.includes(key)) serverRunString[key] = true
267 if (serverRunString[key] === false) dontContinue = true
270 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
271 if (dontContinue === true) return
273 if (options.hideLogs === false) {
276 process.removeListener('exit', onParentExit)
277 self.app.stdout.removeListener('data', onStdout)
278 self.app.removeListener('exit', onPeerTubeExit)
287 if (!this.app) return
289 await this.sql.cleanup()
291 process.kill(-this.app.pid)
296 private randomServer () {
300 return randomInt(low, high)
303 private randomRTMP () {
307 return randomInt(low, high)
310 private async assignCustomConfigFile () {
311 if (this.internalServerNumber === this.serverNumber) return
313 const basePath = join(root(), 'config')
315 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
316 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
318 this.customConfigFile = tmpConfigFile
321 private buildConfigOverride () {
322 if (!this.parallel) return {}
332 suffix: '_test' + this.internalServerNumber
335 tmp: `test${this.internalServerNumber}/tmp/`,
336 bin: `test${this.internalServerNumber}/bin/`,
337 avatars: `test${this.internalServerNumber}/avatars/`,
338 videos: `test${this.internalServerNumber}/videos/`,
339 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
340 redundancy: `test${this.internalServerNumber}/redundancy/`,
341 logs: `test${this.internalServerNumber}/logs/`,
342 previews: `test${this.internalServerNumber}/previews/`,
343 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
344 torrents: `test${this.internalServerNumber}/torrents/`,
345 captions: `test${this.internalServerNumber}/captions/`,
346 cache: `test${this.internalServerNumber}/cache/`,
347 plugins: `test${this.internalServerNumber}/plugins/`
350 email: `admin${this.internalServerNumber}@example.com`
360 private assignCommands () {
361 this.bulk = new BulkCommand(this)
362 this.cli = new CLICommand(this)
363 this.customPage = new CustomPagesCommand(this)
364 this.feed = new FeedCommand(this)
365 this.logs = new LogsCommand(this)
366 this.abuses = new AbusesCommand(this)
367 this.overviews = new OverviewsCommand(this)
368 this.search = new SearchCommand(this)
369 this.contactForm = new ContactFormCommand(this)
370 this.debug = new DebugCommand(this)
371 this.follows = new FollowsCommand(this)
372 this.jobs = new JobsCommand(this)
373 this.plugins = new PluginsCommand(this)
374 this.redundancy = new RedundancyCommand(this)
375 this.stats = new StatsCommand(this)
376 this.config = new ConfigCommand(this)
377 this.socketIO = new SocketIOCommand(this)
378 this.accounts = new AccountsCommand(this)
379 this.blocklist = new BlocklistCommand(this)
380 this.subscriptions = new SubscriptionsCommand(this)
381 this.live = new LiveCommand(this)
382 this.services = new ServicesCommand(this)
383 this.blacklist = new BlacklistCommand(this)
384 this.captions = new CaptionsCommand(this)
385 this.changeOwnership = new ChangeOwnershipCommand(this)
386 this.playlists = new PlaylistsCommand(this)
387 this.history = new HistoryCommand(this)
388 this.imports = new ImportsCommand(this)
389 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
390 this.channels = new ChannelsCommand(this)
391 this.comments = new CommentsCommand(this)
392 this.sql = new SQLCommand(this)
393 this.notifications = new NotificationsCommand(this)
394 this.servers = new ServersCommand(this)
395 this.login = new LoginCommand(this)
396 this.users = new UsersCommand(this)
397 this.videos = new VideosCommand(this)
398 this.objectStorage = new ObjectStorageCommand(this)
399 this.videoEditor = new VideoEditorCommand(this)