server.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // ----------- Node modules -----------
  2. import { registerOpentelemetryTracing } from './server/lib/opentelemetry/tracing'
  3. registerOpentelemetryTracing()
  4. import express from 'express'
  5. import morgan, { token } from 'morgan'
  6. import cors from 'cors'
  7. import cookieParser from 'cookie-parser'
  8. import { frameguard } from 'helmet'
  9. import { parse } from 'useragent'
  10. import anonymize from 'ip-anonymize'
  11. import { program as cli } from 'commander'
  12. process.title = 'peertube'
  13. // Create our main app
  14. const app = express().disable('x-powered-by')
  15. // ----------- Core checker -----------
  16. import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
  17. // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
  18. import { CONFIG } from './server/initializers/config'
  19. import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
  20. import { logger } from './server/helpers/logger'
  21. const missed = checkMissedConfig()
  22. if (missed.length !== 0) {
  23. logger.error('Your configuration files miss keys: ' + missed)
  24. process.exit(-1)
  25. }
  26. checkFFmpeg(CONFIG)
  27. .catch(err => {
  28. logger.error('Error in ffmpeg check.', { err })
  29. process.exit(-1)
  30. })
  31. try {
  32. checkNodeVersion()
  33. } catch (err) {
  34. logger.error('Error in NodeJS check.', { err })
  35. process.exit(-1)
  36. }
  37. import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
  38. checkConfig()
  39. // Trust our proxy (IP forwarding...)
  40. app.set('trust proxy', CONFIG.TRUST_PROXY)
  41. app.use((_req, res, next) => {
  42. res.locals.requestStart = Date.now()
  43. return next()
  44. })
  45. // Security middleware
  46. import { baseCSP } from './server/middlewares/csp'
  47. if (CONFIG.CSP.ENABLED) {
  48. app.use(baseCSP)
  49. }
  50. if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
  51. app.use(frameguard({
  52. action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
  53. }))
  54. }
  55. // ----------- Database -----------
  56. // Initialize database and models
  57. import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
  58. checkDatabaseConnectionOrDie()
  59. import { migrate } from './server/initializers/migrator'
  60. migrate()
  61. .then(() => initDatabaseModels(false))
  62. .then(() => startApplication())
  63. .catch(err => {
  64. logger.error('Cannot start application.', { err })
  65. process.exit(-1)
  66. })
  67. // ----------- Initialize -----------
  68. loadLanguages()
  69. // ----------- PeerTube modules -----------
  70. import { installApplication } from './server/initializers/installer'
  71. import { Emailer } from './server/lib/emailer'
  72. import { JobQueue } from './server/lib/job-queue'
  73. import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
  74. import {
  75. activityPubRouter,
  76. apiRouter,
  77. miscRouter,
  78. clientsRouter,
  79. feedsRouter,
  80. staticRouter,
  81. wellKnownRouter,
  82. lazyStaticRouter,
  83. servicesRouter,
  84. liveRouter,
  85. pluginsRouter,
  86. webfingerRouter,
  87. trackerRouter,
  88. createWebsocketTrackerServer,
  89. botsRouter,
  90. downloadRouter
  91. } from './server/controllers'
  92. import { advertiseDoNotTrack } from './server/middlewares/dnt'
  93. import { apiFailMiddleware } from './server/middlewares/error'
  94. import { Redis } from './server/lib/redis'
  95. import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
  96. import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
  97. import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
  98. import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
  99. import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
  100. import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
  101. import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
  102. import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
  103. import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
  104. import { VideoViewsBufferScheduler } from './server/lib/schedulers/video-views-buffer-scheduler'
  105. import { GeoIPUpdateScheduler } from './server/lib/schedulers/geo-ip-update-scheduler'
  106. import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
  107. import { PeerTubeSocket } from './server/lib/peertube-socket'
  108. import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
  109. import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
  110. import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
  111. import { Hooks } from './server/lib/plugins/hooks'
  112. import { PluginManager } from './server/lib/plugins/plugin-manager'
  113. import { LiveManager } from './server/lib/live'
  114. import { HttpStatusCode } from './shared/models/http/http-error-codes'
  115. import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
  116. import { ServerConfigManager } from '@server/lib/server-config-manager'
  117. import { VideoViewsManager } from '@server/lib/views/video-views-manager'
  118. import { isTestOrDevInstance } from './server/helpers/core-utils'
  119. import { OpenTelemetryMetrics } from '@server/lib/opentelemetry/metrics'
  120. import { ApplicationModel } from '@server/models/application/application'
  121. import { VideoChannelSyncLatestScheduler } from '@server/lib/schedulers/video-channel-sync-latest-scheduler'
  122. // ----------- Command line -----------
  123. cli
  124. .option('--no-client', 'Start PeerTube without client interface')
  125. .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
  126. .option('--benchmark-startup', 'Automatically stop server when initialized')
  127. .parse(process.argv)
  128. // ----------- App -----------
  129. // Enable CORS for develop
  130. if (isTestOrDevInstance()) {
  131. app.use(cors({
  132. origin: '*',
  133. exposedHeaders: 'Retry-After',
  134. credentials: true
  135. }))
  136. }
  137. // For the logger
  138. token('remote-addr', (req: express.Request) => {
  139. if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
  140. return anonymize(req.ip, 16, 16)
  141. }
  142. return req.ip
  143. })
  144. token('user-agent', (req: express.Request) => {
  145. if (req.get('DNT') === '1') {
  146. return parse(req.get('user-agent')).family
  147. }
  148. return req.get('user-agent')
  149. })
  150. app.use(morgan('combined', {
  151. stream: {
  152. write: (str: string) => logger.info(str.trim(), { tags: [ 'http' ] })
  153. },
  154. skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
  155. }))
  156. // Add .fail() helper to response
  157. app.use(apiFailMiddleware)
  158. // For body requests
  159. app.use(express.urlencoded({ extended: false }))
  160. app.use(express.json({
  161. type: [ 'application/json', 'application/*+json' ],
  162. limit: '500kb',
  163. verify: (req: express.Request, res: express.Response, buf: Buffer) => {
  164. const valid = isHTTPSignatureDigestValid(buf, req)
  165. if (valid !== true) {
  166. res.fail({
  167. status: HttpStatusCode.FORBIDDEN_403,
  168. message: 'Invalid digest'
  169. })
  170. }
  171. }
  172. }))
  173. // Cookies
  174. app.use(cookieParser())
  175. // W3C DNT Tracking Status
  176. app.use(advertiseDoNotTrack)
  177. // ----------- Open Telemetry -----------
  178. OpenTelemetryMetrics.Instance.init(app)
  179. // ----------- Views, routes and static files -----------
  180. // API
  181. const apiRoute = '/api/' + API_VERSION
  182. app.use(apiRoute, apiRouter)
  183. // Services (oembed...)
  184. app.use('/services', servicesRouter)
  185. // Live streaming
  186. app.use('/live', liveRouter)
  187. // Plugins & themes
  188. app.use('/', pluginsRouter)
  189. app.use('/', activityPubRouter)
  190. app.use('/', feedsRouter)
  191. app.use('/', webfingerRouter)
  192. app.use('/', trackerRouter)
  193. app.use('/', botsRouter)
  194. // Static files
  195. app.use('/', staticRouter)
  196. app.use('/', wellKnownRouter)
  197. app.use('/', miscRouter)
  198. app.use('/', downloadRouter)
  199. app.use('/', lazyStaticRouter)
  200. // Client files, last valid routes!
  201. const cliOptions = cli.opts<{ client: boolean, plugins: boolean }>()
  202. if (cliOptions.client) app.use('/', clientsRouter)
  203. // ----------- Errors -----------
  204. // Catch unmatched routes
  205. app.use((_req, res: express.Response) => {
  206. res.status(HttpStatusCode.NOT_FOUND_404).end()
  207. })
  208. // Catch thrown errors
  209. app.use((err, _req, res: express.Response, _next) => {
  210. // Format error to be logged
  211. let error = 'Unknown error.'
  212. if (err) {
  213. error = err.stack || err.message || err
  214. }
  215. // Handling Sequelize error traces
  216. const sql = err?.parent ? err.parent.sql : undefined
  217. // Help us to debug SequelizeConnectionAcquireTimeoutError errors
  218. const activeRequests = err?.name === 'SequelizeConnectionAcquireTimeoutError' && typeof (process as any)._getActiveRequests !== 'function'
  219. ? (process as any)._getActiveRequests()
  220. : undefined
  221. logger.error('Error in controller.', { err: error, sql, activeRequests })
  222. return res.fail({
  223. status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
  224. message: err.message,
  225. type: err.name
  226. })
  227. })
  228. const server = createWebsocketTrackerServer(app)
  229. // ----------- Run -----------
  230. async function startApplication () {
  231. const port = CONFIG.LISTEN.PORT
  232. const hostname = CONFIG.LISTEN.HOSTNAME
  233. await installApplication()
  234. // Check activity pub urls are valid
  235. checkActivityPubUrls()
  236. .catch(err => {
  237. logger.error('Error in ActivityPub URLs checker.', { err })
  238. process.exit(-1)
  239. })
  240. checkFFmpegVersion()
  241. .catch(err => logger.error('Cannot check ffmpeg version', { err }))
  242. Redis.Instance.init()
  243. Emailer.Instance.init()
  244. await Promise.all([
  245. Emailer.Instance.checkConnection(),
  246. JobQueue.Instance.init(),
  247. ServerConfigManager.Instance.init()
  248. ])
  249. // Caches initializations
  250. VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
  251. VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
  252. VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
  253. // Enable Schedulers
  254. ActorFollowScheduler.Instance.enable()
  255. RemoveOldJobsScheduler.Instance.enable()
  256. UpdateVideosScheduler.Instance.enable()
  257. YoutubeDlUpdateScheduler.Instance.enable()
  258. VideosRedundancyScheduler.Instance.enable()
  259. RemoveOldHistoryScheduler.Instance.enable()
  260. RemoveOldViewsScheduler.Instance.enable()
  261. PluginsCheckScheduler.Instance.enable()
  262. PeerTubeVersionCheckScheduler.Instance.enable()
  263. AutoFollowIndexInstances.Instance.enable()
  264. RemoveDanglingResumableUploadsScheduler.Instance.enable()
  265. VideoChannelSyncLatestScheduler.Instance.enable()
  266. VideoViewsBufferScheduler.Instance.enable()
  267. GeoIPUpdateScheduler.Instance.enable()
  268. OpenTelemetryMetrics.Instance.registerMetrics()
  269. PeerTubeSocket.Instance.init(server)
  270. VideoViewsManager.Instance.init()
  271. updateStreamingPlaylistsInfohashesIfNeeded()
  272. .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
  273. LiveManager.Instance.init()
  274. if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
  275. // Make server listening
  276. server.listen(port, hostname, async () => {
  277. if (cliOptions.plugins) {
  278. try {
  279. await PluginManager.Instance.rebuildNativePluginsIfNeeded()
  280. await PluginManager.Instance.registerPluginsAndThemes()
  281. } catch (err) {
  282. logger.error('Cannot register plugins and themes.', { err })
  283. }
  284. }
  285. ApplicationModel.updateNodeVersions()
  286. .catch(err => logger.error('Cannot update node versions.', { err }))
  287. logger.info('HTTP server listening on %s:%d', hostname, port)
  288. logger.info('Web server: %s', WEBSERVER.URL)
  289. Hooks.runAction('action:application.listening')
  290. if (cliOptions['benchmarkStartup']) process.exit(0)
  291. })
  292. process.on('exit', () => {
  293. JobQueue.Instance.terminate()
  294. .catch(err => logger.error('Cannot terminate job queue.', { err }))
  295. })
  296. process.on('SIGINT', () => process.exit(0))
  297. }