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,
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
85 videoCreated?: VideoCreateResult
86 videoDetails?: VideoDetails
88 videos?: { id: number, uuid: string }[]
96 customPage?: CustomPagesCommand
99 abuses?: AbusesCommand
100 overviews?: OverviewsCommand
101 search?: SearchCommand
102 contactForm?: ContactFormCommand
104 follows?: FollowsCommand
106 plugins?: PluginsCommand
107 redundancy?: RedundancyCommand
109 config?: ConfigCommand
110 socketIO?: SocketIOCommand
111 accounts?: AccountsCommand
112 blocklist?: BlocklistCommand
113 subscriptions?: SubscriptionsCommand
115 services?: ServicesCommand
116 blacklist?: BlacklistCommand
117 captions?: CaptionsCommand
118 changeOwnership?: ChangeOwnershipCommand
119 playlists?: PlaylistsCommand
120 history?: HistoryCommand
121 imports?: ImportsCommand
122 channelSyncs?: ChannelSyncsCommand
123 streamingPlaylists?: StreamingPlaylistsCommand
124 channels?: ChannelsCommand
125 comments?: CommentsCommand
127 notifications?: NotificationsCommand
128 servers?: ServersCommand
131 objectStorage?: ObjectStorageCommand
132 videoStudio?: VideoStudioCommand
133 videos?: VideosCommand
134 videoStats?: VideoStatsCommand
137 constructor (options: { serverNumber: number } | { url: string }) {
138 if ((options as any).url) {
139 this.setUrl((options as any).url)
141 this.setServerNumber((options as any).serverNumber)
155 this.assignCommands()
158 setServerNumber (serverNumber: number) {
159 this.serverNumber = serverNumber
161 this.parallel = parallelTests()
163 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
164 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
165 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
166 this.port = 9000 + this.internalServerNumber
168 this.url = `http://localhost:${this.port}`
169 this.host = `localhost:${this.port}`
170 this.hostname = 'localhost'
173 setUrl (url: string) {
174 const parsed = new URL(url)
177 this.host = parsed.host
178 this.hostname = parsed.hostname
179 this.port = parseInt(parsed.port)
182 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
183 await ServersCommand.flushTests(this.internalServerNumber)
185 return this.run(configOverride, options)
188 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
189 // These actions are async so we need to be sure that they have both been done
190 const serverRunString = {
191 'HTTP server listening': false
193 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
194 serverRunString[key] = false
197 client_id: 'Client id: (.+)',
198 client_secret: 'Client secret: (.+)',
199 user_username: 'Username: (.+)',
200 user_password: 'User password: (.+)'
203 await this.assignCustomConfigFile()
205 const configOverride = this.buildConfigOverride()
207 if (configOverrideArg !== undefined) {
208 Object.assign(configOverride, configOverrideArg)
211 // Share the environment
212 const env = Object.create(process.env)
213 env['NODE_ENV'] = 'test'
214 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
215 env['NODE_CONFIG'] = JSON.stringify(configOverride)
218 Object.assign(env, options.env)
221 const execArgv = options.nodeArgs || []
222 // FIXME: too slow :/
223 // execArgv.push('--enable-source-maps')
225 const forkOptions = {
232 const peertubeArgs = options.peertubeArgs || []
234 return new Promise<void>((res, rej) => {
236 let aggregatedLogs = ''
238 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
240 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
241 const onParentExit = () => {
242 if (!this.app || !this.app.pid) return
245 process.kill(self.app.pid)
246 } catch { /* empty */ }
249 this.app.on('exit', onPeerTubeExit)
250 process.on('exit', onParentExit)
252 this.app.stdout.on('data', function onStdout (data) {
253 let dontContinue = false
255 const log: string = data.toString()
256 aggregatedLogs += log
258 // Capture things if we want to
259 for (const key of Object.keys(regexps)) {
260 const regexp = regexps[key]
261 const matches = log.match(regexp)
262 if (matches !== null) {
263 if (key === 'client_id') self.store.client.id = matches[1]
264 else if (key === 'client_secret') self.store.client.secret = matches[1]
265 else if (key === 'user_username') self.store.user.username = matches[1]
266 else if (key === 'user_password') self.store.user.password = matches[1]
270 // Check if all required sentences are here
271 for (const key of Object.keys(serverRunString)) {
272 if (log.includes(key)) serverRunString[key] = true
273 if (serverRunString[key] === false) dontContinue = true
276 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
277 if (dontContinue === true) return
279 if (options.hideLogs === false) {
282 process.removeListener('exit', onParentExit)
283 self.app.stdout.removeListener('data', onStdout)
284 self.app.removeListener('exit', onPeerTubeExit)
293 if (!this.app) return
295 await this.sql.cleanup()
297 process.kill(-this.app.pid)
302 private randomServer () {
306 return randomInt(low, high)
309 private randomRTMP () {
313 return randomInt(low, high)
316 private async assignCustomConfigFile () {
317 if (this.internalServerNumber === this.serverNumber) return
319 const basePath = join(root(), 'config')
321 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
322 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
324 this.customConfigFile = tmpConfigFile
327 private buildConfigOverride () {
328 if (!this.parallel) return {}
338 suffix: '_test' + this.internalServerNumber
341 tmp: `test${this.internalServerNumber}/tmp/`,
342 bin: `test${this.internalServerNumber}/bin/`,
343 avatars: `test${this.internalServerNumber}/avatars/`,
344 videos: `test${this.internalServerNumber}/videos/`,
345 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
346 redundancy: `test${this.internalServerNumber}/redundancy/`,
347 logs: `test${this.internalServerNumber}/logs/`,
348 previews: `test${this.internalServerNumber}/previews/`,
349 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
350 torrents: `test${this.internalServerNumber}/torrents/`,
351 captions: `test${this.internalServerNumber}/captions/`,
352 cache: `test${this.internalServerNumber}/cache/`,
353 plugins: `test${this.internalServerNumber}/plugins/`
356 email: `admin${this.internalServerNumber}@example.com`
366 private assignCommands () {
367 this.bulk = new BulkCommand(this)
368 this.cli = new CLICommand(this)
369 this.customPage = new CustomPagesCommand(this)
370 this.feed = new FeedCommand(this)
371 this.logs = new LogsCommand(this)
372 this.abuses = new AbusesCommand(this)
373 this.overviews = new OverviewsCommand(this)
374 this.search = new SearchCommand(this)
375 this.contactForm = new ContactFormCommand(this)
376 this.debug = new DebugCommand(this)
377 this.follows = new FollowsCommand(this)
378 this.jobs = new JobsCommand(this)
379 this.plugins = new PluginsCommand(this)
380 this.redundancy = new RedundancyCommand(this)
381 this.stats = new StatsCommand(this)
382 this.config = new ConfigCommand(this)
383 this.socketIO = new SocketIOCommand(this)
384 this.accounts = new AccountsCommand(this)
385 this.blocklist = new BlocklistCommand(this)
386 this.subscriptions = new SubscriptionsCommand(this)
387 this.live = new LiveCommand(this)
388 this.services = new ServicesCommand(this)
389 this.blacklist = new BlacklistCommand(this)
390 this.captions = new CaptionsCommand(this)
391 this.changeOwnership = new ChangeOwnershipCommand(this)
392 this.playlists = new PlaylistsCommand(this)
393 this.history = new HistoryCommand(this)
394 this.imports = new ImportsCommand(this)
395 this.channelSyncs = new ChannelSyncsCommand(this)
396 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
397 this.channels = new ChannelsCommand(this)
398 this.comments = new CommentsCommand(this)
399 this.sql = new SQLCommand(this)
400 this.notifications = new NotificationsCommand(this)
401 this.servers = new ServersCommand(this)
402 this.login = new LoginCommand(this)
403 this.users = new UsersCommand(this)
404 this.videos = new VideosCommand(this)
405 this.objectStorage = new ObjectStorageCommand(this)
406 this.videoStudio = new VideoStudioCommand(this)
407 this.videoStats = new VideoStatsCommand(this)
408 this.views = new ViewsCommand(this)