db.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. const _ = require('lodash')
  2. const autoload = require('auto-load')
  3. const path = require('path')
  4. const Promise = require('bluebird')
  5. const Knex = require('knex')
  6. const fs = require('fs')
  7. const Objection = require('objection')
  8. const migrationSource = require('../db/migrator-source')
  9. const migrateFromLegacy = require('../db/legacy')
  10. /* global WIKI */
  11. /**
  12. * ORM DB module
  13. */
  14. module.exports = {
  15. Objection,
  16. knex: null,
  17. listener: null,
  18. /**
  19. * Initialize DB
  20. */
  21. init() {
  22. let self = this
  23. WIKI.logger.info('Checking DB configuration...')
  24. // Fetch DB Config
  25. const dbConfig = (!_.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(dbConfig) && _.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(dbConfig)) {
  66. dbConfig.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: dbConfig,
  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 new Promise(resolve => setTimeout(resolve, 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. let initTasksQueue = (WIKI.IS_MASTER) ? [
  130. initTasks.connect,
  131. initTasks.migrateFromLegacy,
  132. initTasks.syncSchemas
  133. ] : [
  134. () => { return Promise.resolve() }
  135. ]
  136. // Perform init tasks
  137. this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
  138. return {
  139. ...this,
  140. ...models
  141. }
  142. },
  143. /**
  144. * Subscribe to database LISTEN / NOTIFY for multi-instances events
  145. */
  146. async subscribeToNotifications () {
  147. const PGPubSub = require('pg-pubsub')
  148. this.listener = new PGPubSub(this.knex.client.connectionSettings, {
  149. log (ev) {
  150. WIKI.logger.debug(ev)
  151. }
  152. })
  153. // -> Outbound events handling
  154. this.listener.addChannel('wiki', payload => {
  155. if (_.has(payload, 'event') && payload.source !== WIKI.INSTANCE_ID) {
  156. WIKI.logger.info(`Received event ${payload.event} from instance ${payload.source}: [ OK ]`)
  157. WIKI.events.inbound.emit(payload.event, payload.value)
  158. }
  159. })
  160. WIKI.events.outbound.onAny(this.notifyViaDB)
  161. // -> Listen to inbound events
  162. WIKI.auth.subscribeToEvents()
  163. WIKI.configSvc.subscribeToEvents()
  164. WIKI.models.pages.subscribeToEvents()
  165. WIKI.logger.info(`PG PubSub Listener initialized successfully: [ OK ]`)
  166. },
  167. /**
  168. * Unsubscribe from database LISTEN / NOTIFY
  169. */
  170. async unsubscribeToNotifications () {
  171. if (this.listener) {
  172. WIKI.events.outbound.offAny(this.notifyViaDB)
  173. WIKI.events.inbound.removeAllListeners()
  174. this.listener.close()
  175. }
  176. },
  177. /**
  178. * Publish event via database NOTIFY
  179. *
  180. * @param {string} event Event fired
  181. * @param {object} value Payload of the event
  182. */
  183. notifyViaDB (event, value) {
  184. WIKI.models.listener.publish('wiki', {
  185. source: WIKI.INSTANCE_ID,
  186. event,
  187. value
  188. })
  189. }
  190. }