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.

258 lines
9.6 KiB

  1. 'use strict'
  2. // =====================================================
  3. // Wiki.js
  4. // Installation Script
  5. // =====================================================
  6. const Promise = require('bluebird')
  7. const _ = require('lodash')
  8. const colors = require('colors/safe')
  9. const exec = require('execa')
  10. const fs = Promise.promisifyAll(require('fs-extra'))
  11. const https = require('follow-redirects').https
  12. const inquirer = require('inquirer')
  13. const os = require('os')
  14. const path = require('path')
  15. const pm2 = Promise.promisifyAll(require('pm2'))
  16. const tar = require('tar')
  17. const zlib = require('zlib')
  18. const installDir = path.resolve(__dirname, '../..')
  19. const isContainerBased = (process.env.WIKI_JS_HEROKU || process.env.WIKI_JS_DOCKER)
  20. let installMode = 'new'
  21. // =====================================================
  22. // INSTALLATION TASKS
  23. // =====================================================
  24. const tasks = {
  25. /**
  26. * Stop and delete existing instances
  27. */
  28. stopAndDeleteInstances() {
  29. ora.text = 'Looking for running instances...'
  30. return pm2.connectAsync().then(() => {
  31. return pm2.describeAsync('wiki').then(() => {
  32. ora.text = 'Stopping and deleting process from pm2...'
  33. return pm2.deleteAsync('wiki')
  34. }).catch(err => { // eslint-disable-line handle-callback-err
  35. return true
  36. }).finally(() => {
  37. pm2.disconnect()
  38. })
  39. }).catch(err => { // eslint-disable-line handle-callback-err
  40. return true
  41. })
  42. },
  43. /**
  44. * Check for sufficient memory
  45. */
  46. checkRequirements() {
  47. ora.text = 'Checking system requirements...'
  48. if (os.totalmem() < 1000 * 1000 * 768) {
  49. return Promise.reject(new Error('Not enough memory to install dependencies. Minimum is 768 MB.'))
  50. } else {
  51. return Promise.resolve(true)
  52. }
  53. },
  54. /**
  55. * Install via local tarball if present
  56. */
  57. installFromLocal() {
  58. let hasTarball = true
  59. let tbPath = path.join(installDir, 'wiki-js.tar.gz')
  60. return fs.accessAsync(tbPath)
  61. .catch(err => { // eslint-disable-line handle-callback-err
  62. hasTarball = false
  63. }).then(() => {
  64. if (hasTarball) {
  65. ora.text = 'Local tarball found. Extracting...'
  66. return new Promise((resolve, reject) => {
  67. fs.createReadStream(tbPath).pipe(zlib.createGunzip())
  68. .pipe(tar.extract({ cwd: installDir }))
  69. .on('error', err => reject(err))
  70. .on('end', () => {
  71. ora.text = 'Tarball extracted successfully.'
  72. resolve(true)
  73. })
  74. })
  75. } else {
  76. return false
  77. }
  78. })
  79. },
  80. /**
  81. * Install from GitHub release download
  82. */
  83. installFromRemote() {
  84. // Fetch version from npm package
  85. return fs.readJsonAsync('package.json').then((packageObj) => {
  86. let versionGet = _.chain(packageObj.version).split('.').take(4).join('.')
  87. let remoteURL = _.replace('https://github.com/Requarks/wiki/releases/download/v{0}/wiki-js.tar.gz', '{0}', versionGet)
  88. return new Promise((resolve, reject) => {
  89. // Fetch tarball
  90. ora.text = 'Looking for latest release...'
  91. https.get(remoteURL, resp => {
  92. if (resp.statusCode !== 200) {
  93. return reject(new Error('Remote file not found'))
  94. }
  95. ora.text = 'Remote wiki.js tarball found. Downloading...'
  96. isContainerBased && console.info('>> Extracting to ' + installDir)
  97. // Extract tarball
  98. resp.pipe(zlib.createGunzip())
  99. .pipe(tar.extract({ cwd: installDir }))
  100. .on('error', err => reject(err))
  101. .on('end', () => {
  102. ora.text = 'Tarball extracted successfully.'
  103. resolve(true)
  104. })
  105. })
  106. })
  107. })
  108. },
  109. /**
  110. * Create default config.yml file if new installation
  111. */
  112. ensureConfigFile() {
  113. return fs.accessAsync(path.join(installDir, 'config.yml')).then(() => {
  114. // Is Upgrade
  115. ora.text = 'Existing config.yml found. Upgrade mode.'
  116. installMode = 'upgrade'
  117. return true
  118. }).catch(err => {
  119. // Is New Install
  120. if (err.code === 'ENOENT') {
  121. ora.text = 'First-time install, creating a new config.yml...'
  122. installMode = 'new'
  123. let sourceConfigFile = path.join(installDir, 'config.sample.yml')
  124. if (process.env.WIKI_JS_HEROKU || process.env.WIKI_JS_DOCKER) {
  125. sourceConfigFile = path.join(__dirname, 'configs/config.passive.yml')
  126. }
  127. return fs.copyAsync(sourceConfigFile, path.join(installDir, 'config.yml'))
  128. } else {
  129. return err
  130. }
  131. })
  132. },
  133. /**
  134. * Install npm dependencies
  135. */
  136. installDependencies() {
  137. ora.text = 'Installing Wiki.js npm dependencies...'
  138. return exec.stdout('npm', ['install', '--only=production', '--no-optional'], {
  139. cwd: installDir
  140. }).then(results => {
  141. ora.text = 'Wiki.js npm dependencies installed successfully.'
  142. return true
  143. })
  144. },
  145. startConfigurationWizard() {
  146. ora.succeed('Installation succeeded.')
  147. if (process.env.WIKI_JS_HEROKU) {
  148. console.info('> Wiki.js has been installed and is configured to use Heroku configuration.')
  149. return true
  150. } else if (process.env.WIKI_JS_DOCKER) {
  151. console.info('Docker environment detected. Skipping setup wizard auto-start.')
  152. return true
  153. } else if (process.stdout.isTTY) {
  154. if (installMode === 'upgrade') {
  155. console.info(colors.yellow('\n!!! IMPORTANT !!!'))
  156. console.info(colors.yellow('Running the configuration wizard is optional but recommended after an upgrade to ensure your config file is using the latest available settings.'))
  157. console.info(colors.yellow('Note that the contents of your config file will be displayed during the configuration wizard. It is therefor highly recommended to run the wizard on a non-publicly accessible port or skip this step completely.\n'))
  158. }
  159. inquirer.prompt([{
  160. type: 'list',
  161. name: 'action',
  162. message: 'Continue with configuration wizard?',
  163. default: 'default',
  164. choices: [
  165. { name: 'Yes, run configuration wizard on port 3000 (recommended)', value: 'default', short: 'Yes' },
  166. { name: 'Yes, run configuration wizard on a custom port...', value: 'custom', short: 'Yes' },
  167. { name: 'No, I\'ll configure the config file manually', value: 'exit', short: 'No' }
  168. ]
  169. }, {
  170. type: 'input',
  171. name: 'customport',
  172. message: 'Custom port to use:',
  173. default: 3000,
  174. validate: (val) => {
  175. val = _.toNumber(val)
  176. return (_.isNumber(val) && val > 0) ? true : 'Invalid Port!'
  177. },
  178. when: (ans) => {
  179. return ans.action === 'custom'
  180. }
  181. }]).then((ans) => {
  182. switch (ans.action) {
  183. case 'default':
  184. console.info(colors.bold.cyan('> Browse to http://your-server:3000/ to configure your wiki! (Replaced your-server with the hostname or IP of your server!)'))
  185. ora = require('ora')({ text: 'I\'ll wait until you\'re done ;)', color: 'yellow', spinner: 'pong' }).start()
  186. return exec.stdout('node', ['wiki', 'configure'], {
  187. cwd: installDir
  188. })
  189. case 'custom':
  190. console.info(colors.bold.cyan('> Browse to http://your-server:' + ans.customport + '/ to configure your wiki! (Replaced your-server with the hostname or IP of your server!)'))
  191. ora = require('ora')({ text: 'I\'ll wait until you\'re done ;)', color: 'yellow', spinner: 'pong' }).start()
  192. return exec.stdout('node', ['wiki', 'configure', ans.customport], {
  193. cwd: installDir
  194. })
  195. default:
  196. console.info(colors.bold.cyan('\n> You can run the configuration wizard using command:') + colors.bold.white(' node wiki configure') + colors.bold.cyan('.\n> Then start Wiki.js using command: ') + colors.bold.white('node wiki start'))
  197. return Promise.delay(7000).then(() => {
  198. process.exit(0)
  199. })
  200. }
  201. }).then(() => {
  202. ora.succeed(colors.bold.green('Wiki.js has been configured successfully. It is now starting up and should be accessible very soon!'))
  203. return Promise.delay(3000).then(() => {
  204. console.info('npm is finishing... please wait...')
  205. })
  206. })
  207. } else {
  208. console.info(colors.cyan('[WARNING] Non-interactive terminal detected. You must manually start the configuration wizard using the command: node wiki configure'))
  209. }
  210. }
  211. }
  212. // =====================================================
  213. // INSTALL SEQUENCE
  214. // =====================================================
  215. if (!isContainerBased) {
  216. console.info(colors.yellow(
  217. ' __ __ _ _ _ _ \n' +
  218. '/ / /\\ \\ (_) | _(_) (_)___ \n' +
  219. '\\ \\/ \\/ / | |/ / | | / __| \n' +
  220. ' \\ /\\ /| | <| |_ | \\__ \\ \n' +
  221. ' \\/ \\/ |_|_|\\_\\_(_)/ |___/ \n' +
  222. ' |__/\n'))
  223. } else {
  224. console.info('> WIKI.JS [Installing...]')
  225. }
  226. let ora = require('ora')({ text: 'Initializing...', spinner: 'dots12' }).start()
  227. Promise.join(
  228. tasks.stopAndDeleteInstances(),
  229. tasks.checkRequirements()
  230. ).then(() => {
  231. isContainerBased && console.info('>> Fetching tarball...')
  232. return tasks.installFromLocal().then(succeeded => {
  233. return (!succeeded) ? tasks.installFromRemote() : true
  234. })
  235. }).then(() => {
  236. isContainerBased && console.info('>> Creating config file...')
  237. return tasks.ensureConfigFile()
  238. }).then(() => {
  239. isContainerBased && console.info('>> Installing dependencies...')
  240. return tasks.installDependencies()
  241. }).then(() => {
  242. return tasks.startConfigurationWizard()
  243. }).catch(err => {
  244. isContainerBased && console.error(err)
  245. ora.fail(err)
  246. })