aboutsummaryrefslogtreecommitdiffhomepage
path: root/shared/server-commands/server/server.ts
diff options
context:
space:
mode:
Diffstat (limited to 'shared/server-commands/server/server.ts')
-rw-r--r--shared/server-commands/server/server.ts398
1 files changed, 398 insertions, 0 deletions
diff --git a/shared/server-commands/server/server.ts b/shared/server-commands/server/server.ts
new file mode 100644
index 000000000..da89fd876
--- /dev/null
+++ b/shared/server-commands/server/server.ts
@@ -0,0 +1,398 @@
1import { ChildProcess, fork } from 'child_process'
2import { copy } from 'fs-extra'
3import { join } from 'path'
4import { parallelTests, randomInt, root } from '@shared/core-utils'
5import { Video, VideoChannel, VideoCreateResult, VideoDetails } from '@shared/models'
6import { BulkCommand } from '../bulk'
7import { CLICommand } from '../cli'
8import { CustomPagesCommand } from '../custom-pages'
9import { FeedCommand } from '../feeds'
10import { LogsCommand } from '../logs'
11import { SQLCommand } from '../miscs'
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,
28 VideosCommand
29} from '../videos'
30import { CommentsCommand } from '../videos/comments-command'
31import { ConfigCommand } from './config-command'
32import { ContactFormCommand } from './contact-form-command'
33import { DebugCommand } from './debug-command'
34import { FollowsCommand } from './follows-command'
35import { JobsCommand } from './jobs-command'
36import { ObjectStorageCommand } from './object-storage-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
44 nodeArgs?: string[]
45 peertubeArgs?: string[]
46 env?: { [ id: string ]: string }
47}
48
49export class PeerTubeServer {
50 app?: ChildProcess
51
52 url: string
53 host?: string
54 hostname?: string
55 port?: number
56
57 rtmpPort?: number
58 rtmpsPort?: 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
80 video?: Video
81 videoCreated?: VideoCreateResult
82 videoDetails?: VideoDetails
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
126 objectStorage?: ObjectStorageCommand
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.rtmpsPort = this.parallel ? this.randomRTMP() : 1937
158 this.port = 9000 + this.internalServerNumber
159
160 this.url = `http://localhost:${this.port}`
161 this.host = `localhost:${this.port}`
162 this.hostname = 'localhost'
163 }
164
165 setUrl (url: string) {
166 const parsed = new URL(url)
167
168 this.url = url
169 this.host = parsed.host
170 this.hostname = parsed.hostname
171 this.port = parseInt(parsed.port)
172 }
173
174 async flushAndRun (configOverride?: Object, options: RunServerOptions = {}) {
175 await ServersCommand.flushTests(this.internalServerNumber)
176
177 return this.run(configOverride, options)
178 }
179
180 async run (configOverrideArg?: any, options: RunServerOptions = {}) {
181 // These actions are async so we need to be sure that they have both been done
182 const serverRunString = {
183 'HTTP server listening': false
184 }
185 const key = 'Database peertube_test' + this.internalServerNumber + ' is ready'
186 serverRunString[key] = false
187
188 const regexps = {
189 client_id: 'Client id: (.+)',
190 client_secret: 'Client secret: (.+)',
191 user_username: 'Username: (.+)',
192 user_password: 'User password: (.+)'
193 }
194
195 await this.assignCustomConfigFile()
196
197 const configOverride = this.buildConfigOverride()
198
199 if (configOverrideArg !== undefined) {
200 Object.assign(configOverride, configOverrideArg)
201 }
202
203 // Share the environment
204 const env = Object.create(process.env)
205 env['NODE_ENV'] = 'test'
206 env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString()
207 env['NODE_CONFIG'] = JSON.stringify(configOverride)
208
209 if (options.env) {
210 Object.assign(env, options.env)
211 }
212
213 const execArgv = options.nodeArgs || []
214 // FIXME: too slow :/
215 // execArgv.push('--enable-source-maps')
216
217 const forkOptions = {
218 silent: true,
219 env,
220 detached: true,
221 execArgv
222 }
223
224 const peertubeArgs = options.peertubeArgs || []
225
226 return new Promise<void>((res, rej) => {
227 const self = this
228 let aggregatedLogs = ''
229
230 this.app = fork(join(root(), 'dist', 'server.js'), peertubeArgs, forkOptions)
231
232 const onPeerTubeExit = () => rej(new Error('Process exited:\n' + aggregatedLogs))
233 const onParentExit = () => {
234 if (!this.app || !this.app.pid) return
235
236 try {
237 process.kill(self.app.pid)
238 } catch { /* empty */ }
239 }
240
241 this.app.on('exit', onPeerTubeExit)
242 process.on('exit', onParentExit)
243
244 this.app.stdout.on('data', function onStdout (data) {
245 let dontContinue = false
246
247 const log: string = data.toString()
248 aggregatedLogs += log
249
250 // Capture things if we want to
251 for (const key of Object.keys(regexps)) {
252 const regexp = regexps[key]
253 const matches = log.match(regexp)
254 if (matches !== null) {
255 if (key === 'client_id') self.store.client.id = matches[1]
256 else if (key === 'client_secret') self.store.client.secret = matches[1]
257 else if (key === 'user_username') self.store.user.username = matches[1]
258 else if (key === 'user_password') self.store.user.password = matches[1]
259 }
260 }
261
262 // Check if all required sentences are here
263 for (const key of Object.keys(serverRunString)) {
264 if (log.includes(key)) serverRunString[key] = true
265 if (serverRunString[key] === false) dontContinue = true
266 }
267
268 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
269 if (dontContinue === true) return
270
271 if (options.hideLogs === false) {
272 console.log(log)
273 } else {
274 process.removeListener('exit', onParentExit)
275 self.app.stdout.removeListener('data', onStdout)
276 self.app.removeListener('exit', onPeerTubeExit)
277 }
278
279 res()
280 })
281 })
282 }
283
284 async kill () {
285 if (!this.app) return
286
287 await this.sql.cleanup()
288
289 process.kill(-this.app.pid)
290
291 this.app = null
292 }
293
294 private randomServer () {
295 const low = 10
296 const high = 10000
297
298 return randomInt(low, high)
299 }
300
301 private randomRTMP () {
302 const low = 1900
303 const high = 2100
304
305 return randomInt(low, high)
306 }
307
308 private async assignCustomConfigFile () {
309 if (this.internalServerNumber === this.serverNumber) return
310
311 const basePath = join(root(), 'config')
312
313 const tmpConfigFile = join(basePath, `test-${this.internalServerNumber}.yaml`)
314 await copy(join(basePath, `test-${this.serverNumber}.yaml`), tmpConfigFile)
315
316 this.customConfigFile = tmpConfigFile
317 }
318
319 private buildConfigOverride () {
320 if (!this.parallel) return {}
321
322 return {
323 listen: {
324 port: this.port
325 },
326 webserver: {
327 port: this.port
328 },
329 database: {
330 suffix: '_test' + this.internalServerNumber
331 },
332 storage: {
333 tmp: `test${this.internalServerNumber}/tmp/`,
334 bin: `test${this.internalServerNumber}/bin/`,
335 avatars: `test${this.internalServerNumber}/avatars/`,
336 videos: `test${this.internalServerNumber}/videos/`,
337 streaming_playlists: `test${this.internalServerNumber}/streaming-playlists/`,
338 redundancy: `test${this.internalServerNumber}/redundancy/`,
339 logs: `test${this.internalServerNumber}/logs/`,
340 previews: `test${this.internalServerNumber}/previews/`,
341 thumbnails: `test${this.internalServerNumber}/thumbnails/`,
342 torrents: `test${this.internalServerNumber}/torrents/`,
343 captions: `test${this.internalServerNumber}/captions/`,
344 cache: `test${this.internalServerNumber}/cache/`,
345 plugins: `test${this.internalServerNumber}/plugins/`
346 },
347 admin: {
348 email: `admin${this.internalServerNumber}@example.com`
349 },
350 live: {
351 rtmp: {
352 port: this.rtmpPort
353 }
354 }
355 }
356 }
357
358 private assignCommands () {
359 this.bulk = new BulkCommand(this)
360 this.cli = new CLICommand(this)
361 this.customPage = new CustomPagesCommand(this)
362 this.feed = new FeedCommand(this)
363 this.logs = new LogsCommand(this)
364 this.abuses = new AbusesCommand(this)
365 this.overviews = new OverviewsCommand(this)
366 this.search = new SearchCommand(this)
367 this.contactForm = new ContactFormCommand(this)
368 this.debug = new DebugCommand(this)
369 this.follows = new FollowsCommand(this)
370 this.jobs = new JobsCommand(this)
371 this.plugins = new PluginsCommand(this)
372 this.redundancy = new RedundancyCommand(this)
373 this.stats = new StatsCommand(this)
374 this.config = new ConfigCommand(this)
375 this.socketIO = new SocketIOCommand(this)
376 this.accounts = new AccountsCommand(this)
377 this.blocklist = new BlocklistCommand(this)
378 this.subscriptions = new SubscriptionsCommand(this)
379 this.live = new LiveCommand(this)
380 this.services = new ServicesCommand(this)
381 this.blacklist = new BlacklistCommand(this)
382 this.captions = new CaptionsCommand(this)
383 this.changeOwnership = new ChangeOwnershipCommand(this)
384 this.playlists = new PlaylistsCommand(this)
385 this.history = new HistoryCommand(this)
386 this.imports = new ImportsCommand(this)
387 this.streamingPlaylists = new StreamingPlaylistsCommand(this)
388 this.channels = new ChannelsCommand(this)
389 this.comments = new CommentsCommand(this)
390 this.sql = new SQLCommand(this)
391 this.notifications = new NotificationsCommand(this)
392 this.servers = new ServersCommand(this)
393 this.login = new LoginCommand(this)
394 this.users = new UsersCommand(this)
395 this.videos = new VideosCommand(this)
396 this.objectStorage = new ObjectStorageCommand(this)
397 }
398}