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