]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/server-commands/server/server.ts
Translated using Weblate (French (France) (fr_FR))
[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,
22 HistoryCommand,
23 ImportsCommand,
24 LiveCommand,
25 PlaylistsCommand,
26 ServicesCommand,
27 StreamingPlaylistsCommand,
b2111066 28 VideosCommand,
92e66e04 29 VideoStudioCommand,
b2111066 30 ViewsCommand
254d3579
C
31} from '../videos'
32import { CommentsCommand } from '../videos/comments-command'
b2111066 33import { VideoStatsCommand } from '../videos/video-stats-command'
254d3579
C
34import { ConfigCommand } from './config-command'
35import { ContactFormCommand } from './contact-form-command'
36import { DebugCommand } from './debug-command'
37import { FollowsCommand } from './follows-command'
38import { JobsCommand } from './jobs-command'
c55e3d72 39import { ObjectStorageCommand } from './object-storage-command'
254d3579
C
40import { PluginsCommand } from './plugins-command'
41import { RedundancyCommand } from './redundancy-command'
42import { ServersCommand } from './servers-command'
43import { StatsCommand } from './stats-command'
44
45export type RunServerOptions = {
46 hideLogs?: boolean
2e980ed3
C
47 nodeArgs?: string[]
48 peertubeArgs?: string[]
0305db28 49 env?: { [ id: string ]: string }
254d3579
C
50}
51
52export class PeerTubeServer {
53 app?: ChildProcess
54
55 url: string
56 host?: string
57 hostname?: string
58 port?: number
59
60 rtmpPort?: number
df1db951 61 rtmpsPort?: number
254d3579
C
62
63 parallel?: boolean
64 internalServerNumber: number
65
66 serverNumber?: number
67 customConfigFile?: string
68
69 store?: {
70 client?: {
71 id?: string
72 secret?: string
73 }
74
75 user?: {
76 username: string
77 password: string
78 email?: string
79 }
80
81 channel?: VideoChannel
82
83903cb6
C
83 video?: Video
84 videoCreated?: VideoCreateResult
85 videoDetails?: VideoDetails
254d3579
C
86
87 videos?: { id: number, uuid: string }[]
88 }
89
90 accessToken?: string
91 refreshToken?: string
92
93 bulk?: BulkCommand
94 cli?: CLICommand
95 customPage?: CustomPagesCommand
96 feed?: FeedCommand
97 logs?: LogsCommand
98 abuses?: AbusesCommand
99 overviews?: OverviewsCommand
100 search?: SearchCommand
101 contactForm?: ContactFormCommand
102 debug?: DebugCommand
103 follows?: FollowsCommand
104 jobs?: JobsCommand
105 plugins?: PluginsCommand
106 redundancy?: RedundancyCommand
107 stats?: StatsCommand
108 config?: ConfigCommand
109 socketIO?: SocketIOCommand
110 accounts?: AccountsCommand
111 blocklist?: BlocklistCommand
112 subscriptions?: SubscriptionsCommand
113 live?: LiveCommand
114 services?: ServicesCommand
115 blacklist?: BlacklistCommand
116 captions?: CaptionsCommand
117 changeOwnership?: ChangeOwnershipCommand
118 playlists?: PlaylistsCommand
119 history?: HistoryCommand
120 imports?: ImportsCommand
121 streamingPlaylists?: StreamingPlaylistsCommand
122 channels?: ChannelsCommand
123 comments?: CommentsCommand
124 sql?: SQLCommand
125 notifications?: NotificationsCommand
126 servers?: ServersCommand
127 login?: LoginCommand
128 users?: UsersCommand
0305db28 129 objectStorage?: ObjectStorageCommand
92e66e04 130 videoStudio?: VideoStudioCommand
254d3579 131 videos?: VideosCommand
b2111066
C
132 videoStats?: VideoStatsCommand
133 views?: ViewsCommand
254d3579
C
134
135 constructor (options: { serverNumber: number } | { url: string }) {
136 if ((options as any).url) {
137 this.setUrl((options as any).url)
138 } else {
139 this.setServerNumber((options as any).serverNumber)
140 }
141
142 this.store = {
143 client: {
144 id: null,
145 secret: null
146 },
147 user: {
148 username: null,
149 password: null
150 }
151 }
152
153 this.assignCommands()
154 }
155
156 setServerNumber (serverNumber: number) {
157 this.serverNumber = serverNumber
158
159 this.parallel = parallelTests()
160
161 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
162 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
df1db951 163 this.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
254d3579
C
164 this.port = 9000 + this.internalServerNumber
165
166 this.url = `http://localhost:${this.port}`
167 this.host = `localhost:${this.port}`
168 this.hostname = 'localhost'
169 }
170
171 setUrl (url: string) {
172 const parsed = new URL(url)
173
174 this.url = url
175 this.host = parsed.host
176 this.hostname = parsed.hostname
177 this.port = parseInt(parsed.port)
178 }
179
2e980ed3 180 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
254d3579
C
181 await ServersCommand.flushTests(this.internalServerNumber)
182
2e980ed3 183 return this.run(configOverride, options)
254d3579
C
184 }
185
2e980ed3 186 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
254d3579
C
187 // These actions are async so we need to be sure that they have both been done
188 const serverRunString = {
189 'HTTP server listening': false
190 }
191 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
192 serverRunString[key] = false
193
194 const regexps = {
195 client_id: 'Client id: (.+)',
196 client_secret: 'Client secret: (.+)',
197 user_username: 'Username: (.+)',
198 user_password: 'User password: (.+)'
199 }
200
201 await this.assignCustomConfigFile()
202
203 const configOverride = this.buildConfigOverride()
204
205 if (configOverrideArg !== undefined) {
206 Object.assign(configOverride, configOverrideArg)
207 }
208
209 // Share the environment
210 const env = Object.create(process.env)
211 env['NODE_ENV'] = 'test'
212 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
213 env['NODE_CONFIG'] = JSON.stringify(configOverride)
214
0305db28
JB
215 if (options.env) {
216 Object.assign(env, options.env)
217 }
218
7298cad6 219 const execArgv = options.nodeArgs || []
8f5a1f36
C
220 // FIXME: too slow :/
221 // execArgv.push('--enable-source-maps')
7298cad6 222
254d3579
C
223 const forkOptions = {
224 silent: true,
225 env,
226 detached: true,
7298cad6 227 execArgv
254d3579
C
228 }
229
9270bd3a 230 const peertubeArgs = options.peertubeArgs || []
9270bd3a 231
0305db28 232 return new Promise<void>((res, rej) => {
08642a76 233 const self = this
f307255e 234 let aggregatedLogs = ''
08642a76 235
9270bd3a 236 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
0305db28 237
f307255e 238 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
706a450f
C
239 const onParentExit = () => {
240 if (!this.app || !this.app.pid) return
241
242 try {
243 process.kill(self.app.pid)
244 } catch { /* empty */ }
0305db28
JB
245 }
246
706a450f
C
247 this.app.on('exit', onPeerTubeExit)
248 process.on('exit', onParentExit)
0305db28 249
254d3579
C
250 this.app.stdout.on('data', function onStdout (data) {
251 let dontContinue = false
252
f307255e
C
253 const log: string = data.toString()
254 aggregatedLogs += log
255
254d3579
C
256 // Capture things if we want to
257 for (const key of Object.keys(regexps)) {
258 const regexp = regexps[key]
f307255e 259 const matches = log.match(regexp)
254d3579 260 if (matches !== null) {
08642a76
C
261 if (key === 'client_id') self.store.client.id = matches[1]
262 else if (key === 'client_secret') self.store.client.secret = matches[1]
263 else if (key === 'user_username') self.store.user.username = matches[1]
264 else if (key === 'user_password') self.store.user.password = matches[1]
254d3579
C
265 }
266 }
267
268 // Check if all required sentences are here
269 for (const key of Object.keys(serverRunString)) {
f307255e 270 if (log.includes(key)) serverRunString[key] = true
254d3579
C
271 if (serverRunString[key] === false) dontContinue = true
272 }
273
274 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
275 if (dontContinue === true) return
276
277 if (options.hideLogs === false) {
f307255e 278 console.log(log)
254d3579 279 } else {
706a450f 280 process.removeListener('exit', onParentExit)
08642a76 281 self.app.stdout.removeListener('data', onStdout)
706a450f 282 self.app.removeListener('exit', onPeerTubeExit)
254d3579
C
283 }
284
254d3579
C
285 res()
286 })
287 })
288 }
289
290 async kill () {
291 if (!this.app) return
292
293 await this.sql.cleanup()
294
295 process.kill(-this.app.pid)
296
297 this.app = null
298 }
299
300 private randomServer () {
301 const low = 10
302 const high = 10000
303
304 return randomInt(low, high)
305 }
306
307 private randomRTMP () {
308 const low = 1900
309 const high = 2100
310
311 return randomInt(low, high)
312 }
313
314 private async assignCustomConfigFile () {
315 if (this.internalServerNumber === this.serverNumber) return
316
317 const basePath = join(root(), 'config')
318
319 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
320 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
321
322 this.customConfigFile = tmpConfigFile
323 }
324
325 private buildConfigOverride () {
326 if (!this.parallel) return {}
327
328 return {
329 listen: {
330 port: this.port
331 },
332 webserver: {
333 port: this.port
334 },
335 database: {
336 suffix: '_test' + this.internalServerNumber
337 },
338 storage: {
339 tmp: `test${this.internalServerNumber}/tmp/`,
5678353d 340 bin: `test${this.internalServerNumber}/bin/`,
254d3579
C
341 avatars: `test${this.internalServerNumber}/avatars/`,
342 videos: `test${this.internalServerNumber}/videos/`,
343 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
344 redundancy: `test${this.internalServerNumber}/redundancy/`,
345 logs: `test${this.internalServerNumber}/logs/`,
346 previews: `test${this.internalServerNumber}/previews/`,
347 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
348 torrents: `test${this.internalServerNumber}/torrents/`,
349 captions: `test${this.internalServerNumber}/captions/`,
350 cache: `test${this.internalServerNumber}/cache/`,
351 plugins: `test${this.internalServerNumber}/plugins/`
352 },
353 admin: {
354 email: `admin${this.internalServerNumber}@example.com`
355 },
356 live: {
357 rtmp: {
358 port: this.rtmpPort
359 }
360 }
361 }
362 }
363
364 private assignCommands () {
365 this.bulk = new BulkCommand(this)
366 this.cli = new CLICommand(this)
367 this.customPage = new CustomPagesCommand(this)
368 this.feed = new FeedCommand(this)
369 this.logs = new LogsCommand(this)
370 this.abuses = new AbusesCommand(this)
371 this.overviews = new OverviewsCommand(this)
372 this.search = new SearchCommand(this)
373 this.contactForm = new ContactFormCommand(this)
374 this.debug = new DebugCommand(this)
375 this.follows = new FollowsCommand(this)
376 this.jobs = new JobsCommand(this)
377 this.plugins = new PluginsCommand(this)
378 this.redundancy = new RedundancyCommand(this)
379 this.stats = new StatsCommand(this)
380 this.config = new ConfigCommand(this)
381 this.socketIO = new SocketIOCommand(this)
382 this.accounts = new AccountsCommand(this)
383 this.blocklist = new BlocklistCommand(this)
384 this.subscriptions = new SubscriptionsCommand(this)
385 this.live = new LiveCommand(this)
386 this.services = new ServicesCommand(this)
387 this.blacklist = new BlacklistCommand(this)
388 this.captions = new CaptionsCommand(this)
389 this.changeOwnership = new ChangeOwnershipCommand(this)
390 this.playlists = new PlaylistsCommand(this)
391 this.history = new HistoryCommand(this)
392 this.imports = new ImportsCommand(this)
393 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
394 this.channels = new ChannelsCommand(this)
395 this.comments = new CommentsCommand(this)
396 this.sql = new SQLCommand(this)
397 this.notifications = new NotificationsCommand(this)
398 this.servers = new ServersCommand(this)
399 this.login = new LoginCommand(this)
400 this.users = new UsersCommand(this)
401 this.videos = new VideosCommand(this)
0305db28 402 this.objectStorage = new ObjectStorageCommand(this)
92e66e04 403 this.videoStudio = new VideoStudioCommand(this)
b2111066
C
404 this.videoStats = new VideoStatsCommand(this)
405 this.views = new ViewsCommand(this)
254d3579
C
406 }
407}