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