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.

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