db.js 6.6 KB

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