]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/server-commands/server/server.ts
Add ability to list imports of a channel sync
[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 { 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'
17 import {
18 BlacklistCommand,
19 CaptionsCommand,
20 ChangeOwnershipCommand,
21 ChannelsCommand,
22 ChannelSyncsCommand,
23 HistoryCommand,
24 ImportsCommand,
25 LiveCommand,
26 PlaylistsCommand,
27 ServicesCommand,
28 StreamingPlaylistsCommand,
29 VideosCommand,
30 VideoStudioCommand,
31 ViewsCommand
32 } from '../videos'
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'
45
46 export type RunServerOptions = {
47 hideLogs?: boolean
48 nodeArgs?: string[]
49 peertubeArgs?: string[]
50 env?: { [ id: string ]: string }
51 }
52
53 export class PeerTubeServer {
54 app?: ChildProcess
55
56 url: string
57 host?: string
58 hostname?: string
59 port?: number
60
61 rtmpPort?: number
62 rtmpsPort?: number
63
64 parallel?: boolean
65 internalServerNumber: number
66
67 serverNumber?: number
68 customConfigFile?: string
69
70 store?: {
71 client?: {
72 id?: string
73 secret?: string
74 }
75
76 user?: {
77 username: string
78 password: string
79 email?: string
80 }
81
82 channel?: VideoChannel
83 videoChannelSync?: Partial<VideoChannelSync>
84
85 video?: Video
86 videoCreated?: VideoCreateResult
87 videoDetails?: VideoDetails
88
89 videos?: { id: number, uuid: string }[]
90 }
91
92 accessToken?: string
93 refreshToken?: string
94
95 bulk?: BulkCommand
96 cli?: CLICommand
97 customPage?: CustomPagesCommand
98 feed?: FeedCommand
99 logs?: LogsCommand
100 abuses?: AbusesCommand
101 overviews?: OverviewsCommand
102 search?: SearchCommand
103 contactForm?: ContactFormCommand
104 debug?: DebugCommand
105 follows?: FollowsCommand
106 jobs?: JobsCommand
107 plugins?: PluginsCommand
108 redundancy?: RedundancyCommand
109 stats?: StatsCommand
110 config?: ConfigCommand
111 socketIO?: SocketIOCommand
112 accounts?: AccountsCommand
113 blocklist?: BlocklistCommand
114 subscriptions?: SubscriptionsCommand
115 live?: LiveCommand
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
127 sql?: SQLCommand
128 notifications?: NotificationsCommand
129 servers?: ServersCommand
130 login?: LoginCommand
131 users?: UsersCommand
132 objectStorage?: ObjectStorageCommand
133 videoStudio?: VideoStudioCommand
134 videos?: VideosCommand
135 videoStats?: VideoStatsCommand
136 views?: ViewsCommand
137
138 constructor (options: { serverNumber: number } | { url: string }) {
139 if ((options as any).url) {
140 this.setUrl((options as any).url)
141 } else {
142 this.setServerNumber((options as any).serverNumber)
143 }
144
145 this.store = {
146 client: {
147 id: null,
148 secret: null
149 },
150 user: {
151 username: null,
152 password: null
153 }
154 }
155
156 this.assignCommands()
157 }
158
159 setServerNumber (serverNumber: number) {
160 this.serverNumber = serverNumber
161
162 this.parallel = parallelTests()
163
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
168
169 this.url = `http://localhost:${this.port}`
170 this.host = `localhost:${this.port}`
171 this.hostname = 'localhost'
172 }
173
174 setUrl (url: string) {
175 const parsed = new URL(url)
176
177 this.url = url
178 this.host = parsed.host
179 this.hostname = parsed.hostname
180 this.port = parseInt(parsed.port)
181 }
182
183 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
184 await ServersCommand.flushTests(this.internalServerNumber)
185
186 return this.run(configOverride, options)
187 }
188
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
193 }
194 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
195 serverRunString[key] = false
196
197 const regexps = {
198 client_id: 'Client id: (.+)',
199 client_secret: 'Client secret: (.+)',
200 user_username: 'Username: (.+)',
201 user_password: 'User password: (.+)'
202 }
203
204 await this.assignCustomConfigFile()
205
206 const configOverride = this.buildConfigOverride()
207
208 if (configOverrideArg !== undefined) {
209 Object.assign(configOverride, configOverrideArg)
210 }
211
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)
217
218 if (options.env) {
219 Object.assign(env, options.env)
220 }
221
222 const execArgv = options.nodeArgs || []
223 // FIXME: too slow :/
224 // execArgv.push('--enable-source-maps')
225
226 const forkOptions = {
227 silent: true,
228 env,
229 detached: true,
230 execArgv
231 }
232
233 const peertubeArgs = options.peertubeArgs || []
234
235 return new Promise<void>((res, rej) => {
236 const self = this
237 let aggregatedLogs = ''
238
239 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
240
241 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
242 const onParentExit = () => {
243 if (!this.app || !this.app.pid) return
244
245 try {
246 process.kill(self.app.pid)
247 } catch { /* empty */ }
248 }
249
250 this.app.on('exit', onPeerTubeExit)
251 process.on('exit', onParentExit)
252
253 this.app.stdout.on('data', function onStdout (data) {
254 let dontContinue = false
255
256 const log: string = data.toString()
257 aggregatedLogs += log
258
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]
268 }
269 }
270
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
275 }
276
277 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
278 if (dontContinue === true) return
279
280 if (options.hideLogs === false) {
281 console.log(log)
282 } else {
283 process.removeListener('exit', onParentExit)
284 self.app.stdout.removeListener('data', onStdout)
285 self.app.removeListener('exit', onPeerTubeExit)
286 }
287
288 res()
289 })
290 })
291 }
292
293 async kill () {
294 if (!this.app) return
295
296 await this.sql.cleanup()
297
298 process.kill(-this.app.pid)
299
300 this.app = null
301 }
302
303 private randomServer () {
304 const low = 10
305 const high = 10000
306
307 return randomInt(low, high)
308 }
309
310 private randomRTMP () {
311 const low = 1900
312 const high = 2100
313
314 return randomInt(low, high)
315 }
316
317 private async assignCustomConfigFile () {
318 if (this.internalServerNumber === this.serverNumber) return
319
320 const basePath = join(root(), 'config')
321
322 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
323 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
324
325 this.customConfigFile = tmpConfigFile
326 }
327
328 private buildConfigOverride () {
329 if (!this.parallel) return {}
330
331 return {
332 listen: {
333 port: this.port
334 },
335 webserver: {
336 port: this.port
337 },
338 database: {
339 suffix: '_test' + this.internalServerNumber
340 },
341 storage: {
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/`
355 },
356 admin: {
357 email: `admin${this.internalServerNumber}@example.com`
358 },
359 live: {
360 rtmp: {
361 port: this.rtmpPort
362 }
363 }
364 }
365 }
366
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)
410 }
411 }