]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/server-commands/server/server.ts
Add missing job types to admin panel
[github/Chocobozzz/PeerTube.git] / shared / server-commands / server / server.ts
CommitLineData
254d3579
C
1import { ChildProcess, fork } from 'child_process'
2import { copy } from 'fs-extra'
3import { join } from 'path'
c55e3d72
C
4import { parallelTests, randomInt, root } from '@shared/core-utils'
5import { Video, VideoChannel, VideoCreateResult, VideoDetails } from '@shared/models'
254d3579
C
6import { BulkCommand } from '../bulk'
7import { CLICommand } from '../cli'
8import { CustomPagesCommand } from '../custom-pages'
9import { FeedCommand } from '../feeds'
10import { LogsCommand } from '../logs'
c55e3d72 11import { SQLCommand } from '../miscs'
254d3579
C
12import { AbusesCommand } from '../moderation'
13import { OverviewsCommand } from '../overviews'
14import { SearchCommand } from '../search'
15import { SocketIOCommand } from '../socket'
16import { AccountsCommand, BlocklistCommand, LoginCommand, NotificationsCommand, SubscriptionsCommand, UsersCommand } from '../users'
17import {
18 BlacklistCommand,
19 CaptionsCommand,
20 ChangeOwnershipCommand,
21 ChannelsCommand,
2a491182 22 ChannelSyncsCommand,
254d3579
C
23 HistoryCommand,
24 ImportsCommand,
25 LiveCommand,
26 PlaylistsCommand,
27 ServicesCommand,
28 StreamingPlaylistsCommand,
b2111066 29 VideosCommand,
92e66e04 30 VideoStudioCommand,
b2111066 31 ViewsCommand
254d3579
C
32} from '../videos'
33import { CommentsCommand } from '../videos/comments-command'
b2111066 34import { VideoStatsCommand } from '../videos/video-stats-command'
254d3579
C
35import { ConfigCommand } from './config-command'
36import { ContactFormCommand } from './contact-form-command'
37import { DebugCommand } from './debug-command'
38import { FollowsCommand } from './follows-command'
39import { JobsCommand } from './jobs-command'
c55e3d72 40import { ObjectStorageCommand } from './object-storage-command'
254d3579
C
41import { PluginsCommand } from './plugins-command'
42import { RedundancyCommand } from './redundancy-command'
43import { ServersCommand } from './servers-command'
44import { StatsCommand } from './stats-command'
45
46export type RunServerOptions = {
47 hideLogs?: boolean
2e980ed3
C
48 nodeArgs?: string[]
49 peertubeArgs?: string[]
0305db28 50 env?: { [ id: string ]: string }
254d3579
C
51}
52
53export class PeerTubeServer {
54 app?: ChildProcess
55
56 url: string
57 host?: string
58 hostname?: string
59 port?: number
60
61 rtmpPort?: number
df1db951 62 rtmpsPort?: number
254d3579
C
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
83903cb6
C
84 video?: Video
85 videoCreated?: VideoCreateResult
86 videoDetails?: VideoDetails
254d3579
C
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
2a491182 122 channelSyncs?: ChannelSyncsCommand
254d3579
C
123 streamingPlaylists?: StreamingPlaylistsCommand
124 channels?: ChannelsCommand
125 comments?: CommentsCommand
126 sql?: SQLCommand
127 notifications?: NotificationsCommand
128 servers?: ServersCommand
129 login?: LoginCommand
130 users?: UsersCommand
0305db28 131 objectStorage?: ObjectStorageCommand
92e66e04 132 videoStudio?: VideoStudioCommand
254d3579 133 videos?: VideosCommand
b2111066
C
134 videoStats?: VideoStatsCommand
135 views?: ViewsCommand
254d3579
C
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
df1db951 165 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
254d3579
C
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
2e980ed3 182 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
254d3579
C
183 await ServersCommand.flushTests(this.internalServerNumber)
184
2e980ed3 185 return this.run(configOverride, options)
254d3579
C
186 }
187
2e980ed3 188 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
254d3579
C
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
0305db28
JB
217 if (options.env) {
218 Object.assign(env, options.env)
219 }
220
7298cad6 221 const execArgv = options.nodeArgs || []
8f5a1f36
C
222 // FIXME: too slow :/
223 // execArgv.push('--enable-source-maps')
7298cad6 224
254d3579
C
225 const forkOptions = {
226 silent: true,
227 env,
228 detached: true,
7298cad6 229 execArgv
254d3579
C
230 }
231
9270bd3a 232 const peertubeArgs = options.peertubeArgs || []
9270bd3a 233
0305db28 234 return new Promise<void>((res, rej) => {
08642a76 235 const self = this
f307255e 236 let aggregatedLogs = ''
08642a76 237
9270bd3a 238 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
0305db28 239
f307255e 240 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
706a450f
C
241 const onParentExit = () => {
242 if (!this.app || !this.app.pid) return
243
244 try {
245 process.kill(self.app.pid)
246 } catch { /* empty */ }
0305db28
JB
247 }
248
706a450f
C
249 this.app.on('exit', onPeerTubeExit)
250 process.on('exit', onParentExit)
0305db28 251
254d3579
C
252 this.app.stdout.on('data', function onStdout (data) {
253 let dontContinue = false
254
f307255e
C
255 const log: string = data.toString()
256 aggregatedLogs += log
257
254d3579
C
258 // Capture things if we want to
259 for (const key of Object.keys(regexps)) {
260 const regexp = regexps[key]
f307255e 261 const matches = log.match(regexp)
254d3579 262 if (matches !== null) {
08642a76
C
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]
254d3579
C
267 }
268 }
269
270 // Check if all required sentences are here
271 for (const key of Object.keys(serverRunString)) {
f307255e 272 if (log.includes(key)) serverRunString[key] = true
254d3579
C
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) {
f307255e 280 console.log(log)
254d3579 281 } else {
706a450f 282 process.removeListener('exit', onParentExit)
08642a76 283 self.app.stdout.removeListener('data', onStdout)
706a450f 284 self.app.removeListener('exit', onPeerTubeExit)
254d3579
C
285 }
286
254d3579
C
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/`,
5678353d 342 bin: `test${this.internalServerNumber}/bin/`,
254d3579
C
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)
2a491182 395 this.channelSyncs = new ChannelSyncsCommand(this)
254d3579
C
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)
0305db28 405 this.objectStorage = new ObjectStorageCommand(this)
92e66e04 406 this.videoStudio = new VideoStudioCommand(this)
b2111066
C
407 this.videoStats = new VideoStatsCommand(this)
408 this.views = new ViewsCommand(this)
254d3579
C
409 }
410}