You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

269 lines
7.6 KiB

  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 migrateFromBeta = require('../db/beta')
  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. * @return {Object} DB instance
  22. */
  23. init() {
  24. let self = this
  25. // Fetch DB Config
  26. let dbClient = null
  27. let dbConfig = (!_.isEmpty(process.env.DATABASE_URL)) ? process.env.DATABASE_URL : {
  28. host: WIKI.config.db.host.toString(),
  29. user: WIKI.config.db.user.toString(),
  30. password: WIKI.config.db.pass.toString(),
  31. database: WIKI.config.db.db.toString(),
  32. port: WIKI.config.db.port
  33. }
  34. // Handle SSL Options
  35. let dbUseSSL = (WIKI.config.db.ssl === true || WIKI.config.db.ssl === 'true' || WIKI.config.db.ssl === 1 || WIKI.config.db.ssl === '1')
  36. let sslOptions = null
  37. if (dbUseSSL && _.isPlainObject(dbConfig) && _.get(WIKI.config.db, 'sslOptions.auto', null) === false) {
  38. sslOptions = WIKI.config.db.sslOptions
  39. // eslint-disable-next-line no-unneeded-ternary
  40. sslOptions.rejectUnauthorized = sslOptions.rejectUnauthorized === false ? false : true
  41. if (sslOptions.ca && sslOptions.ca.indexOf('-----') !== 0) {
  42. sslOptions.ca = fs.readFileSync(path.resolve(WIKI.ROOTPATH, sslOptions.ca))
  43. }
  44. if (sslOptions.cert) {
  45. sslOptions.cert = fs.readFileSync(path.resolve(WIKI.ROOTPATH, sslOptions.cert))
  46. }
  47. if (sslOptions.key) {
  48. sslOptions.key = fs.readFileSync(path.resolve(WIKI.ROOTPATH, sslOptions.key))
  49. }
  50. if (sslOptions.pfx) {
  51. sslOptions.pfx = fs.readFileSync(path.resolve(WIKI.ROOTPATH, sslOptions.pfx))
  52. }
  53. } else {
  54. sslOptions = true
  55. }
  56. // Handle inline SSL CA Certificate mode
  57. if (!_.isEmpty(process.env.DB_SSL_CA)) {
  58. const chunks = []
  59. for (let i = 0, charsLength = process.env.DB_SSL_CA.length; i < charsLength; i += 64) {
  60. chunks.push(process.env.DB_SSL_CA.substring(i, i + 64))
  61. }
  62. dbUseSSL = true
  63. sslOptions = {
  64. rejectUnauthorized: true,
  65. ca: '-----BEGIN CERTIFICATE-----\n' + chunks.join('\n') + '\n-----END CERTIFICATE-----\n'
  66. }
  67. }
  68. // Engine-specific config
  69. switch (WIKI.config.db.type) {
  70. case 'postgres':
  71. dbClient = 'pg'
  72. if (dbUseSSL && _.isPlainObject(dbConfig)) {
  73. dbConfig.ssl = (sslOptions === true) ? { rejectUnauthorized: true } : sslOptions
  74. }
  75. break
  76. case 'mariadb':
  77. case 'mysql':
  78. dbClient = 'mysql2'
  79. if (dbUseSSL && _.isPlainObject(dbConfig)) {
  80. dbConfig.ssl = sslOptions
  81. }
  82. // Fix mysql boolean handling...
  83. dbConfig.typeCast = (field, next) => {
  84. if (field.type === 'TINY' && field.length === 1) {
  85. let value = field.string()
  86. return value ? (value === '1') : null
  87. }
  88. return next()
  89. }
  90. break
  91. case 'mssql':
  92. dbClient = 'mssql'
  93. if (_.isPlainObject(dbConfig)) {
  94. dbConfig.appName = 'Wiki.js'
  95. if (dbUseSSL) {
  96. dbConfig.encrypt = true
  97. }
  98. }
  99. break
  100. case 'sqlite':
  101. dbClient = 'sqlite3'
  102. dbConfig = { filename: WIKI.config.db.storage }
  103. break
  104. default:
  105. WIKI.logger.error('Invalid DB Type')
  106. process.exit(1)
  107. }
  108. // Initialize Knex
  109. this.knex = Knex({
  110. client: dbClient,
  111. useNullAsDefault: true,
  112. asyncStackTraces: WIKI.IS_DEBUG,
  113. connection: dbConfig,
  114. pool: {
  115. ...WIKI.config.pool,
  116. async afterCreate(conn, done) {
  117. // -> Set Connection App Name
  118. switch (WIKI.config.db.type) {
  119. case 'postgres':
  120. await conn.query(`set application_name = 'Wiki.js'`)
  121. done()
  122. break
  123. default:
  124. done()
  125. break
  126. }
  127. }
  128. },
  129. debug: WIKI.IS_DEBUG
  130. })
  131. Objection.Model.knex(this.knex)
  132. // Load DB Models
  133. const models = autoload(path.join(WIKI.SERVERPATH, 'models'))
  134. // Set init tasks
  135. let conAttempts = 0
  136. let initTasks = {
  137. // -> Attempt initial connection
  138. async connect () {
  139. try {
  140. WIKI.logger.info('Connecting to database...')
  141. await self.knex.raw('SELECT 1 + 1;')
  142. WIKI.logger.info('Database Connection Successful [ OK ]')
  143. } catch (err) {
  144. if (conAttempts < 10) {
  145. if (err.code) {
  146. WIKI.logger.error(`Database Connection Error: ${err.code} ${err.address}:${err.port}`)
  147. } else {
  148. WIKI.logger.error(`Database Connection Error: ${err.message}`)
  149. }
  150. WIKI.logger.warn(`Will retry in 3 seconds... [Attempt ${++conAttempts} of 10]`)
  151. await new Promise(resolve => setTimeout(resolve, 3000))
  152. await initTasks.connect()
  153. } else {
  154. throw err
  155. }
  156. }
  157. },
  158. // -> Migrate DB Schemas
  159. async syncSchemas () {
  160. return self.knex.migrate.latest({
  161. tableName: 'migrations',
  162. migrationSource
  163. })
  164. },
  165. // -> Migrate DB Schemas from beta
  166. async migrateFromBeta () {
  167. return migrateFromBeta.migrate(self.knex)
  168. }
  169. }
  170. let initTasksQueue = (WIKI.IS_MASTER) ? [
  171. initTasks.connect,
  172. initTasks.migrateFromBeta,
  173. initTasks.syncSchemas
  174. ] : [
  175. () => { return Promise.resolve() }
  176. ]
  177. // Perform init tasks
  178. WIKI.logger.info(`Using database driver ${dbClient} for ${WIKI.config.db.type} [ OK ]`)
  179. this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
  180. return {
  181. ...this,
  182. ...models
  183. }
  184. },
  185. /**
  186. * Subscribe to database LISTEN / NOTIFY for multi-instances events
  187. */
  188. async subscribeToNotifications () {
  189. const useHA = (WIKI.config.ha === true || WIKI.config.ha === 'true' || WIKI.config.ha === 1 || WIKI.config.ha === '1')
  190. if (!useHA) {
  191. return
  192. } else if (WIKI.config.db.type !== 'postgres') {
  193. WIKI.logger.warn(`Database engine doesn't support pub/sub. Will not handle concurrent instances: [ DISABLED ]`)
  194. return
  195. }
  196. const PGPubSub = require('pg-pubsub')
  197. this.listener = new PGPubSub(this.knex.client.connectionSettings, {
  198. log (ev) {
  199. WIKI.logger.debug(ev)
  200. }
  201. })
  202. // -> Outbound events handling
  203. this.listener.addChannel('wiki', payload => {
  204. if (_.has(payload, 'event') && payload.source !== WIKI.INSTANCE_ID) {
  205. WIKI.logger.info(`Received event ${payload.event} from instance ${payload.source}: [ OK ]`)
  206. WIKI.events.inbound.emit(payload.event, payload.value)
  207. }
  208. })
  209. WIKI.events.outbound.onAny(this.notifyViaDB)
  210. // -> Listen to inbound events
  211. WIKI.auth.subscribeToEvents()
  212. WIKI.configSvc.subscribeToEvents()
  213. WIKI.models.pages.subscribeToEvents()
  214. WIKI.logger.info(`High-Availability Listener initialized successfully: [ OK ]`)
  215. },
  216. /**
  217. * Unsubscribe from database LISTEN / NOTIFY
  218. */
  219. async unsubscribeToNotifications () {
  220. if (this.listener) {
  221. WIKI.events.outbound.offAny(this.notifyViaDB)
  222. WIKI.events.inbound.removeAllListeners()
  223. this.listener.close()
  224. }
  225. },
  226. /**
  227. * Publish event via database NOTIFY
  228. *
  229. * @param {string} event Event fired
  230. * @param {object} value Payload of the event
  231. */
  232. notifyViaDB (event, value) {
  233. WIKI.models.listener.publish('wiki', {
  234. source: WIKI.INSTANCE_ID,
  235. event,
  236. value
  237. })
  238. }
  239. }