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.

278 lines
7.9 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. case 'mysql':
  127. await conn.promise().query(`set autocommit = 1`)
  128. done()
  129. break
  130. default:
  131. done()
  132. break
  133. }
  134. }
  135. },
  136. debug: WIKI.IS_DEBUG
  137. })
  138. Objection.Model.knex(this.knex)
  139. // Load DB Models
  140. const models = autoload(path.join(WIKI.SERVERPATH, 'models'))
  141. // Set init tasks
  142. let conAttempts = 0
  143. let initTasks = {
  144. // -> Attempt initial connection
  145. async connect () {
  146. try {
  147. WIKI.logger.info('Connecting to database...')
  148. await self.knex.raw('SELECT 1 + 1;')
  149. WIKI.logger.info('Database Connection Successful [ OK ]')
  150. } catch (err) {
  151. if (conAttempts < 10) {
  152. if (err.code) {
  153. WIKI.logger.error(`Database Connection Error: ${err.code} ${err.address}:${err.port}`)
  154. } else {
  155. WIKI.logger.error(`Database Connection Error: ${err.message}`)
  156. }
  157. WIKI.logger.warn(`Will retry in 3 seconds... [Attempt ${++conAttempts} of 10]`)
  158. await new Promise(resolve => setTimeout(resolve, 3000))
  159. await initTasks.connect()
  160. } else {
  161. throw err
  162. }
  163. }
  164. },
  165. // -> Migrate DB Schemas
  166. async syncSchemas () {
  167. return self.knex.migrate.latest({
  168. tableName: 'migrations',
  169. migrationSource
  170. })
  171. },
  172. // -> Migrate DB Schemas from beta
  173. async migrateFromBeta () {
  174. return migrateFromBeta.migrate(self.knex)
  175. }
  176. }
  177. let initTasksQueue = (WIKI.IS_MASTER) ? [
  178. initTasks.connect,
  179. initTasks.migrateFromBeta,
  180. initTasks.syncSchemas
  181. ] : [
  182. () => { return Promise.resolve() }
  183. ]
  184. // Perform init tasks
  185. WIKI.logger.info(`Using database driver ${dbClient} for ${WIKI.config.db.type} [ OK ]`)
  186. this.onReady = Promise.each(initTasksQueue, t => t()).return(true)
  187. return {
  188. ...this,
  189. ...models
  190. }
  191. },
  192. /**
  193. * Subscribe to database LISTEN / NOTIFY for multi-instances events
  194. */
  195. async subscribeToNotifications () {
  196. const useHA = (WIKI.config.ha === true || WIKI.config.ha === 'true' || WIKI.config.ha === 1 || WIKI.config.ha === '1')
  197. if (!useHA) {
  198. return
  199. } else if (WIKI.config.db.type !== 'postgres') {
  200. WIKI.logger.warn(`Database engine doesn't support pub/sub. Will not handle concurrent instances: [ DISABLED ]`)
  201. return
  202. }
  203. const PGPubSub = require('pg-pubsub')
  204. this.listener = new PGPubSub(this.knex.client.connectionSettings, {
  205. log (ev) {
  206. WIKI.logger.debug(ev)
  207. }
  208. })
  209. // -> Outbound events handling
  210. this.listener.addChannel('wiki', payload => {
  211. if (_.has(payload, 'event') && payload.source !== WIKI.INSTANCE_ID) {
  212. WIKI.logger.info(`Received event ${payload.event} from instance ${payload.source}: [ OK ]`)
  213. WIKI.events.inbound.emit(payload.event, payload.value)
  214. }
  215. })
  216. WIKI.events.outbound.onAny(this.notifyViaDB)
  217. // -> Listen to inbound events
  218. WIKI.auth.subscribeToEvents()
  219. WIKI.configSvc.subscribeToEvents()
  220. WIKI.models.pages.subscribeToEvents()
  221. WIKI.logger.info(`High-Availability Listener initialized successfully: [ OK ]`)
  222. },
  223. /**
  224. * Unsubscribe from database LISTEN / NOTIFY
  225. */
  226. async unsubscribeToNotifications () {
  227. if (this.listener) {
  228. WIKI.events.outbound.offAny(this.notifyViaDB)
  229. WIKI.events.inbound.removeAllListeners()
  230. this.listener.close()
  231. }
  232. },
  233. /**
  234. * Publish event via database NOTIFY
  235. *
  236. * @param {string} event Event fired
  237. * @param {object} value Payload of the event
  238. */
  239. notifyViaDB (event, value) {
  240. WIKI.models.listener.publish('wiki', {
  241. source: WIKI.INSTANCE_ID,
  242. event,
  243. value
  244. })
  245. }
  246. }