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 { 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,
28 StreamingPlaylistsCommand,
33 import { CommentsCommand } from '../videos/comments-command'
34 import { VideoStatsCommand } from '../videos/video-stats-command'
35 import { ConfigCommand } from './config-command'
36 import { ContactFormCommand } from './contact-form-command'
37 import { DebugCommand } from './debug-command'
38 import { FollowsCommand } from './follows-command'
39 import { JobsCommand } from './jobs-command'
40 import { ObjectStorageCommand } from './object-storage-command'
41 import { PluginsCommand } from './plugins-command'
42 import { RedundancyCommand } from './redundancy-command'
43 import { ServersCommand } from './servers-command'
44 import { StatsCommand } from './stats-command'
46 export type RunServerOptions = {
49 peertubeArgs?: string[]
50 env?: { [ id: string ]: string }
53 export class PeerTubeServer {
65 internalServerNumber: number
68 customConfigFile?: string
82 channel?: VideoChannel
83 videoChannelSync?: Partial<VideoChannelSync>
86 videoCreated?: VideoCreateResult
87 videoDetails?: VideoDetails
89 videos?: { id: number, uuid: string }[]
97 customPage?: CustomPagesCommand
100 abuses?: AbusesCommand
101 overviews?: OverviewsCommand
102 search?: SearchCommand
103 contactForm?: ContactFormCommand
105 follows?: FollowsCommand
107 plugins?: PluginsCommand
108 redundancy?: RedundancyCommand
110 config?: ConfigCommand
111 socketIO?: SocketIOCommand
112 accounts?: AccountsCommand
113 blocklist?: BlocklistCommand
114 subscriptions?: SubscriptionsCommand
116 services?: ServicesCommand
117 blacklist?: BlacklistCommand
118 captions?: CaptionsCommand
119 changeOwnership?: ChangeOwnershipCommand
120 playlists?: PlaylistsCommand
121 history?: HistoryCommand
122 imports?: ImportsCommand
123 channelSyncs?: ChannelSyncsCommand
124 streamingPlaylists?: StreamingPlaylistsCommand
125 channels?: ChannelsCommand
126 comments?: CommentsCommand
128 notifications?: NotificationsCommand
129 servers?: ServersCommand
132 objectStorage?: ObjectStorageCommand
133 videoStudio?: VideoStudioCommand
134 videos?: VideosCommand
135 videoStats?: VideoStatsCommand
138 constructor (options: { serverNumber: number } | { url: string }) {
139 if ((options as any).url) {
140 this.setUrl((options as any).url)
142 this.setServerNumber((options as any).serverNumber)
156 this.assignCommands()
159 setServerNumber (serverNumber: number) {
160 this.serverNumber = serverNumber
162 this.parallel = parallelTests()
164 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
165 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
166 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
167 this.port = 9000 + this.internalServerNumber
169 this.url = `http://localhost:${this.port}`
170 this.host = `localhost:${this.port}`
171 this.hostname = 'localhost'
174 setUrl (url: string) {
175 const parsed = new URL(url)
178 this.host = parsed.host
179 this.hostname = parsed.hostname
180 this.port = parseInt(parsed.port)
183 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
184 await ServersCommand.flushTests(this.internalServerNumber)
186 return this.run(configOverride, options)
189 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
190 // These actions are async so we need to be sure that they have both been done
191 const serverRunString = {
192 'HTTP server listening': false
194 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
195 serverRunString[key] = false
198 client_id: 'Client id: (.+)',
199 client_secret: 'Client secret: (.+)',
200 user_username: 'Username: (.+)',
201 user_password: 'User password: (.+)'
204 await this.assignCustomConfigFile()
206 const configOverride = this.buildConfigOverride()
208 if (configOverrideArg !== undefined) {
209 Object.assign(configOverride, configOverrideArg)
212 // Share the environment
213 const env = Object.create(process.env)
214 env['NODE_ENV'] = 'test'
215 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
216 env['NODE_CONFIG'] = JSON.stringify(configOverride)
219 Object.assign(env, options.env)
222 const execArgv = options.nodeArgs || []
223 // FIXME: too slow :/
224 // execArgv.push('--enable-source-maps')
226 const forkOptions = {
233 const peertubeArgs = options.peertubeArgs || []
235 return new Promise<void>((res, rej) => {
237 let aggregatedLogs = ''
239 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
241 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
242 const onParentExit = () => {
243 if (!this.app || !this.app.pid) return
246 process.kill(self.app.pid)
247 } catch { /* empty */ }
250 this.app.on('exit', onPeerTubeExit)
251 process.on('exit', onParentExit)
253 this.app.stdout.on('data', function onStdout (data) {
254 let dontContinue = false
256 const log: string = data.toString()
257 aggregatedLogs += log
259 // Capture things if we want to
260 for (const key of Object.keys(regexps)) {
261 const regexp = regexps[key]
262 const matches = log.match(regexp)
263 if (matches !== null) {
264 if (key === 'client_id') self.store.client.id = matches[1]
265 else if (key === 'client_secret') self.store.client.secret = matches[1]
266 else if (key === 'user_username') self.store.user.username = matches[1]
267 else if (key === 'user_password') self.store.user.password = matches[1]
271 // Check if all required sentences are here
272 for (const key of Object.keys(serverRunString)) {
273 if (log.includes(key)) serverRunString[key] = true
274 if (serverRunString[key] === false) dontContinue = true
277 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
278 if (dontContinue === true) return
280 if (options.hideLogs === false) {
283 process.removeListener('exit', onParentExit)
284 self.app.stdout.removeListener('data', onStdout)
285 self.app.removeListener('exit', onPeerTubeExit)
294 if (!this.app) return
296 await this.sql.cleanup()
298 process.kill(-this.app.pid)
303 private randomServer () {
307 return randomInt(low, high)
310 private randomRTMP () {
314 return randomInt(low, high)
317 private async assignCustomConfigFile () {
318 if (this.internalServerNumber === this.serverNumber) return
320 const basePath = join(root(), 'config')
322 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
323 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
325 this.customConfigFile = tmpConfigFile
328 private buildConfigOverride () {
329 if (!this.parallel) return {}
339 suffix: '_test' + this.internalServerNumber
342 tmp: `test${this.internalServerNumber}/tmp/`,
343 bin: `test${this.internalServerNumber}/bin/`,
344 avatars: `test${this.internalServerNumber}/avatars/`,
345 videos: `test${this.internalServerNumber}/videos/`,
346 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
347 redundancy: `test${this.internalServerNumber}/redundancy/`,
348 logs: `test${this.internalServerNumber}/logs/`,
349 previews: `test${this.internalServerNumber}/previews/`,
350 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
351 torrents: `test${this.internalServerNumber}/torrents/`,
352 captions: `test${this.internalServerNumber}/captions/`,
353 cache: `test${this.internalServerNumber}/cache/`,
354 plugins: `test${this.internalServerNumber}/plugins/`
357 email: `admin${this.internalServerNumber}@example.com`
367 private assignCommands () {
368 this.bulk = new BulkCommand(this)
369 this.cli = new CLICommand(this)
370 this.customPage = new CustomPagesCommand(this)
371 this.feed = new FeedCommand(this)
372 this.logs = new LogsCommand(this)
373 this.abuses = new AbusesCommand(this)
374 this.overviews = new OverviewsCommand(this)
375 this.search = new SearchCommand(this)
376 this.contactForm = new ContactFormCommand(this)
377 this.debug = new DebugCommand(this)
378 this.follows = new FollowsCommand(this)
379 this.jobs = new JobsCommand(this)
380 this.plugins = new PluginsCommand(this)
381 this.redundancy = new RedundancyCommand(this)
382 this.stats = new StatsCommand(this)
383 this.config = new ConfigCommand(this)
384 this.socketIO = new SocketIOCommand(this)
385 this.accounts = new AccountsCommand(this)
386 this.blocklist = new BlocklistCommand(this)
387 this.subscriptions = new SubscriptionsCommand(this)
388 this.live = new LiveCommand(this)
389 this.services = new ServicesCommand(this)
390 this.blacklist = new BlacklistCommand(this)
391 this.captions = new CaptionsCommand(this)
392 this.changeOwnership = new ChangeOwnershipCommand(this)
393 this.playlists = new PlaylistsCommand(this)
394 this.history = new HistoryCommand(this)
395 this.imports = new ImportsCommand(this)
396 this.channelSyncs = new ChannelSyncsCommand(this)
397 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
398 this.channels = new ChannelsCommand(this)
399 this.comments = new CommentsCommand(this)
400 this.sql = new SQLCommand(this)
401 this.notifications = new NotificationsCommand(this)
402 this.servers = new ServersCommand(this)
403 this.login = new LoginCommand(this)
404 this.users = new UsersCommand(this)
405 this.videos = new VideosCommand(this)
406 this.objectStorage = new ObjectStorageCommand(this)
407 this.videoStudio = new VideoStudioCommand(this)
408 this.videoStats = new VideoStatsCommand(this)
409 this.views = new ViewsCommand(this)