]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/extra-utils/server/server.ts
Simplify createServer args
[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'
5import { randomInt } from '../../core-utils/miscs/miscs'
6import { VideoChannel } from '../../models/videos'
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'
41
42export type RunServerOptions = {
43 hideLogs?: boolean
2e980ed3
C
44 nodeArgs?: string[]
45 peertubeArgs?: string[]
254d3579
C
46}
47
48export class PeerTubeServer {
49 app?: ChildProcess
50
51 url: string
52 host?: string
53 hostname?: string
54 port?: number
55
56 rtmpPort?: number
57
58 parallel?: boolean
59 internalServerNumber: number
60
61 serverNumber?: number
62 customConfigFile?: string
63
64 store?: {
65 client?: {
66 id?: string
67 secret?: string
68 }
69
70 user?: {
71 username: string
72 password: string
73 email?: string
74 }
75
76 channel?: VideoChannel
77
78 video?: {
79 id: number
80 uuid: string
81 shortUUID: string
82 name?: string
83 url?: string
84
85 account?: {
86 name: string
87 }
88
89 embedPath?: string
90 }
91
92 videos?: { id: number, uuid: string }[]
93 }
94
95 accessToken?: string
96 refreshToken?: string
97
98 bulk?: BulkCommand
99 cli?: CLICommand
100 customPage?: CustomPagesCommand
101 feed?: FeedCommand
102 logs?: LogsCommand
103 abuses?: AbusesCommand
104 overviews?: OverviewsCommand
105 search?: SearchCommand
106 contactForm?: ContactFormCommand
107 debug?: DebugCommand
108 follows?: FollowsCommand
109 jobs?: JobsCommand
110 plugins?: PluginsCommand
111 redundancy?: RedundancyCommand
112 stats?: StatsCommand
113 config?: ConfigCommand
114 socketIO?: SocketIOCommand
115 accounts?: AccountsCommand
116 blocklist?: BlocklistCommand
117 subscriptions?: SubscriptionsCommand
118 live?: LiveCommand
119 services?: ServicesCommand
120 blacklist?: BlacklistCommand
121 captions?: CaptionsCommand
122 changeOwnership?: ChangeOwnershipCommand
123 playlists?: PlaylistsCommand
124 history?: HistoryCommand
125 imports?: ImportsCommand
126 streamingPlaylists?: StreamingPlaylistsCommand
127 channels?: ChannelsCommand
128 comments?: CommentsCommand
129 sql?: SQLCommand
130 notifications?: NotificationsCommand
131 servers?: ServersCommand
132 login?: LoginCommand
133 users?: UsersCommand
134 videos?: VideosCommand
135
136 constructor (options: { serverNumber: number } | { url: string }) {
137 if ((options as any).url) {
138 this.setUrl((options as any).url)
139 } else {
140 this.setServerNumber((options as any).serverNumber)
141 }
142
143 this.store = {
144 client: {
145 id: null,
146 secret: null
147 },
148 user: {
149 username: null,
150 password: null
151 }
152 }
153
154 this.assignCommands()
155 }
156
157 setServerNumber (serverNumber: number) {
158 this.serverNumber = serverNumber
159
160 this.parallel = parallelTests()
161
162 this.internalServerNumber = this.parallel ? this.randomServer() : this.serverNumber
163 this.rtmpPort = this.parallel ? this.randomRTMP() : 1936
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
215 const forkOptions = {
216 silent: true,
217 env,
218 detached: true,
2e980ed3 219 execArgv: options.nodeArgs || []
254d3579
C
220 }
221
222 return new Promise<void>(res => {
08642a76
C
223 const self = this
224
2e980ed3 225 this.app = fork(join(root(), 'dist', 'server.js'), options.peertubeArgs || [], forkOptions)
254d3579
C
226 this.app.stdout.on('data', function onStdout (data) {
227 let dontContinue = false
228
229 // Capture things if we want to
230 for (const key of Object.keys(regexps)) {
231 const regexp = regexps[key]
232 const matches = data.toString().match(regexp)
233 if (matches !== null) {
08642a76
C
234 if (key === 'client_id') self.store.client.id = matches[1]
235 else if (key === 'client_secret') self.store.client.secret = matches[1]
236 else if (key === 'user_username') self.store.user.username = matches[1]
237 else if (key === 'user_password') self.store.user.password = matches[1]
254d3579
C
238 }
239 }
240
241 // Check if all required sentences are here
242 for (const key of Object.keys(serverRunString)) {
243 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
244 if (serverRunString[key] === false) dontContinue = true
245 }
246
247 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
248 if (dontContinue === true) return
249
250 if (options.hideLogs === false) {
251 console.log(data.toString())
252 } else {
08642a76 253 self.app.stdout.removeListener('data', onStdout)
254d3579
C
254 }
255
256 process.on('exit', () => {
257 try {
c0e8b12e 258 process.kill(self.app.pid)
254d3579
C
259 } catch { /* empty */ }
260 })
261
262 res()
263 })
264 })
265 }
266
267 async kill () {
268 if (!this.app) return
269
270 await this.sql.cleanup()
271
272 process.kill(-this.app.pid)
273
274 this.app = null
275 }
276
277 private randomServer () {
278 const low = 10
279 const high = 10000
280
281 return randomInt(low, high)
282 }
283
284 private randomRTMP () {
285 const low = 1900
286 const high = 2100
287
288 return randomInt(low, high)
289 }
290
291 private async assignCustomConfigFile () {
292 if (this.internalServerNumber === this.serverNumber) return
293
294 const basePath = join(root(), 'config')
295
296 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
297 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
298
299 this.customConfigFile = tmpConfigFile
300 }
301
302 private buildConfigOverride () {
303 if (!this.parallel) return {}
304
305 return {
306 listen: {
307 port: this.port
308 },
309 webserver: {
310 port: this.port
311 },
312 database: {
313 suffix: '_test' + this.internalServerNumber
314 },
315 storage: {
316 tmp: `test${this.internalServerNumber}/tmp/`,
317 avatars: `test${this.internalServerNumber}/avatars/`,
318 videos: `test${this.internalServerNumber}/videos/`,
319 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
320 redundancy: `test${this.internalServerNumber}/redundancy/`,
321 logs: `test${this.internalServerNumber}/logs/`,
322 previews: `test${this.internalServerNumber}/previews/`,
323 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
324 torrents: `test${this.internalServerNumber}/torrents/`,
325 captions: `test${this.internalServerNumber}/captions/`,
326 cache: `test${this.internalServerNumber}/cache/`,
327 plugins: `test${this.internalServerNumber}/plugins/`
328 },
329 admin: {
330 email: `admin${this.internalServerNumber}@example.com`
331 },
332 live: {
333 rtmp: {
334 port: this.rtmpPort
335 }
336 }
337 }
338 }
339
340 private assignCommands () {
341 this.bulk = new BulkCommand(this)
342 this.cli = new CLICommand(this)
343 this.customPage = new CustomPagesCommand(this)
344 this.feed = new FeedCommand(this)
345 this.logs = new LogsCommand(this)
346 this.abuses = new AbusesCommand(this)
347 this.overviews = new OverviewsCommand(this)
348 this.search = new SearchCommand(this)
349 this.contactForm = new ContactFormCommand(this)
350 this.debug = new DebugCommand(this)
351 this.follows = new FollowsCommand(this)
352 this.jobs = new JobsCommand(this)
353 this.plugins = new PluginsCommand(this)
354 this.redundancy = new RedundancyCommand(this)
355 this.stats = new StatsCommand(this)
356 this.config = new ConfigCommand(this)
357 this.socketIO = new SocketIOCommand(this)
358 this.accounts = new AccountsCommand(this)
359 this.blocklist = new BlocklistCommand(this)
360 this.subscriptions = new SubscriptionsCommand(this)
361 this.live = new LiveCommand(this)
362 this.services = new ServicesCommand(this)
363 this.blacklist = new BlacklistCommand(this)
364 this.captions = new CaptionsCommand(this)
365 this.changeOwnership = new ChangeOwnershipCommand(this)
366 this.playlists = new PlaylistsCommand(this)
367 this.history = new HistoryCommand(this)
368 this.imports = new ImportsCommand(this)
369 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
370 this.channels = new ChannelsCommand(this)
371 this.comments = new CommentsCommand(this)
372 this.sql = new SQLCommand(this)
373 this.notifications = new NotificationsCommand(this)
374 this.servers = new ServersCommand(this)
375 this.login = new LoginCommand(this)
376 this.users = new UsersCommand(this)
377 this.videos = new VideosCommand(this)
378 }
379}