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