db.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. const _ = require('lodash')
  2. const autoload = require('auto-load')
  3. const path = require('path')
  4. const Knex = require('knex')
  5. const fs = require('fs')
  6. const Objection = require('objection')
  7. const migrationSource = require('../db/migrator-source')
  8. const migrateFromLegacy = require('../db/legacy')
  9. const { setTimeout } = require('timers/promises')
  10. /**
  11. * ORM DB module
  12. */
  13. module.exports = {
  14. Objection,
  15. knex: null,
  16. listener: null,
  17. config: null,
  18. /**
  19. * Initialize DB
  20. */
  21. init() {
  22. let self = this
  23. WIKI.logger.info('Checking DB configuration...')
  24. // Fetch DB Config
  25. this.config = (!_.isEmpty(process.env.DATABASE_URL)) ? process.env.DATABASE_URL : {
  26. host: WIKI.config.db.host.toString(),
  27. user: WIKI.config.db.user.toString(),
  28. password: WIKI.config.db.pass.toString(),
  29. database: WIKI.config.db.db.toString(),
  30. port: WIKI.config.db.port
  31. }
  32. // Handle SSL Options
  33. let dbUseSSL = (WIKI.config.db.ssl === true || WIKI.config.db.ssl === 'true' || WIKI.config.db.ssl === 1 || WIKI.config.db.ssl === '1')
  34. let sslOptions = null
  35. if (dbUseSSL && _.isPlainObject(this.config) && _.get(WIKI.config.db, 'sslOptions.auto', null) === false) {
  36. sslOptions = WIKI.config.db.sslOptions
  37. sslOptions.rejectUnauthorized = sslOptions.rejectUnauthorized !== false
  38. if (sslOptions.ca && sslOptions.ca.indexOf('-----') !== 0) {
  39. sslOptions.ca = fs.readFileSync(path.resolve(WIKI.ROOTPATH, sslOptions.ca))
  40. }
  41. if (sslOptions.cert) {
  42. sslOptions.cert = fs.readFileSync(path.resolve(WIKI.ROOTPATH, sslOptions.cert))
  43. }
  44. if (sslOptions.key) {
  45. sslOptions.key = fs.readFileSync(path.resolve(WIKI.ROOTPATH, sslOptions.key))
  46. }
  47. if (sslOptions.pfx) {
  48. sslOptions.pfx = fs.readFileSync(path.resolve(WIKI.ROOTPATH, sslOptions.pfx))
  49. }
  50. } else {
  51. sslOptions = true
  52. }
  53. // Handle inline SSL CA Certificate mode
  54. if (!_.isEmpty(process.env.DB_SSL_CA)) {
  55. const chunks = []
  56. for (let i = 0, charsLength = process.env.DB_SSL_CA.length; i < charsLength; i += 64) {
  57. chunks.push(process.env.DB_SSL_CA.substring(i, i + 64))
  58. }
  59. dbUseSSL = true
  60. sslOptions = {
  61. rejectUnauthorized: true,
  62. ca: '-----BEGIN CERTIFICATE-----\n' + chunks.join('\n') + '\n-----END CERTIFICATE-----\n'
  63. }
  64. }
  65. if (dbUseSSL && _.isPlainObject(this.config)) {
  66. this.config.ssl = (sslOptions === true) ? { rejectUnauthorized: true } : sslOptions
  67. }
  68. // Initialize Knex
  69. this.knex = Knex({
  70. client: 'pg',
  71. useNullAsDefault: true,
  72. asyncStackTraces: WIKI.IS_DEBUG,
  73. connection: this.config,
  74. searchPath: [WIKI.config.db.schemas.wiki],
  75. pool: {
  76. ...WIKI.config.pool,
  77. async afterCreate(conn, done) {
  78. // -> Set Connection App Name
  79. await conn.query(`set application_name = 'Wiki.js'`)
  80. done()
  81. }
  82. },
  83. debug: WIKI.IS_DEBUG
  84. })
  85. Objection.Model.knex(this.knex)
  86. // Load DB Models
  87. WIKI.logger.info('Loading DB models...')
  88. const models = autoload(path.join(WIKI.SERVERPATH, 'models'))
  89. // Set init tasks
  90. let conAttempts = 0
  91. let initTasks = {
  92. // -> Attempt initial connection
  93. async connect () {
  94. try {
  95. WIKI.logger.info('Connecting to database...')
  96. await self.knex.raw('SELECT 1 + 1;')
  97. WIKI.logger.info('Database Connection Successful [ OK ]')
  98. } catch (err) {
  99. if (conAttempts < 10) {
  100. if (err.code) {
  101. WIKI.logger.error(`Database Connection Error: ${err.code} ${err.address}:${err.port}`)
  102. } else {
  103. WIKI.logger.error(`Database Connection Error: ${err.message}`)
  104. }
  105. WIKI.logger.warn(`Will retry in 3 seconds... [Attempt ${++conAttempts} of 10]`)
  106. await setTimeout(3000)
  107. await initTasks.connect()
  108. } else {
  109. throw err
  110. }
  111. }
  112. },
  113. // -> Migrate DB Schemas
  114. async syncSchemas () {
  115. WIKI.logger.info('Ensuring DB schema exists...')
  116. await self.knex.raw(`CREATE SCHEMA IF NOT EXISTS ${WIKI.config.db.schemas.wiki}`)
  117. WIKI.logger.info('Ensuring DB migrations have been applied...')
  118. return self.knex.migrate.latest({
  119. tableName: 'migrations',
  120. migrationSource,
  121. schemaName: WIKI.config.db.schemas.wiki
  122. })
  123. },
  124. // -> Migrate DB Schemas from 2.x
  125. async migrateFromLegacy () {
  126. return migrateFromLegacy.migrate(self.knex)
  127. }
  128. }
  129. // Perform init tasks
  130. this.onReady = (async () => {
  131. await initTasks.connect()
  132. await initTasks.migrateFromLegacy()
  133. await initTasks.syncSchemas()
  134. })()
  135. return {
  136. ...this,
  137. ...models
  138. }
  139. },
  140. /**
  141. * Subscribe to database LISTEN / NOTIFY for multi-instances events
  142. */
  143. async subscribeToNotifications () {
  144. const PGPubSub = require('pg-pubsub')
  145. this.listener = new PGPubSub(this.knex.client.connectionSettings, {
  146. log (ev) {
  147. WIKI.logger.debug(ev)
  148. }
  149. })
  150. // -> Outbound events handling
  151. this.listener.addChannel('wiki', payload => {
  152. if (_.has(payload, 'event') && payload.source !== WIKI.INSTANCE_ID) {
  153. WIKI.logger.info(`Received event ${payload.event} from instance ${payload.source}: [ OK ]`)
  154. WIKI.events.inbound.emit(payload.event, payload.value)
  155. }
  156. })
  157. WIKI.events.outbound.onAny(this.notifyViaDB)
  158. // -> Listen to inbound events
  159. WIKI.auth.subscribeToEvents()
  160. WIKI.configSvc.subscribeToEvents()
  161. WIKI.db.pages.subscribeToEvents()
  162. WIKI.logger.info(`PG PubSub Listener initialized successfully: [ OK ]`)
  163. },
  164. /**
  165. * Unsubscribe from database LISTEN / NOTIFY
  166. */
  167. async unsubscribeToNotifications () {
  168. if (this.listener) {
  169. WIKI.events.outbound.offAny(this.notifyViaDB)
  170. WIKI.events.inbound.removeAllListeners()
  171. this.listener.close()
  172. }
  173. },
  174. /**
  175. * Publish event via database NOTIFY
  176. *
  177. * @param {string} event Event fired
  178. * @param {object} value Payload of the event
  179. */
  180. notifyViaDB (event, value) {
  181. WIKI.db.listener.publish('wiki', {
  182. source: WIKI.INSTANCE_ID,
  183. event,
  184. value
  185. })
  186. }
  187. }