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.

260 lines
9.7 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) {
  125. sourceConfigFile = path.join(__dirname, 'configs/config.heroku.yml')
  126. } else if (process.env.WIKI_JS_DOCKER) {
  127. sourceConfigFile = path.join(__dirname, 'configs/config.docker.yml')
  128. }
  129. return fs.copyAsync(sourceConfigFile, path.join(installDir, 'config.yml'))
  130. } else {
  131. return err
  132. }
  133. })
  134. },
  135. /**
  136. * Install npm dependencies
  137. */
  138. installDependencies() {
  139. ora.text = 'Installing Wiki.js npm dependencies...'
  140. return exec.stdout('npm', ['install', '--only=production', '--no-optional'], {
  141. cwd: installDir
  142. }).then(results => {
  143. ora.text = 'Wiki.js npm dependencies installed successfully.'
  144. return true
  145. })
  146. },
  147. startConfigurationWizard() {
  148. ora.succeed('Installation succeeded.')
  149. if (process.env.WIKI_JS_HEROKU) {
  150. console.info('> Wiki.js has been installed and is configured to use Heroku configuration.')
  151. return true
  152. } else if (process.env.WIKI_JS_DOCKER) {
  153. console.info('Docker environment detected. Skipping setup wizard auto-start.')
  154. return true
  155. } else if (process.stdout.isTTY) {
  156. if (installMode === 'upgrade') {
  157. console.info(colors.yellow('\n!!! IMPORTANT !!!'))
  158. 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.'))
  159. 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'))
  160. }
  161. inquirer.prompt([{
  162. type: 'list',
  163. name: 'action',
  164. message: 'Continue with configuration wizard?',
  165. default: 'default',
  166. choices: [
  167. { name: 'Yes, run configuration wizard on port 3000 (recommended)', value: 'default', short: 'Yes' },
  168. { name: 'Yes, run configuration wizard on a custom port...', value: 'custom', short: 'Yes' },
  169. { name: 'No, I\'ll configure the config file manually', value: 'exit', short: 'No' }
  170. ]
  171. }, {
  172. type: 'input',
  173. name: 'customport',
  174. message: 'Custom port to use:',
  175. default: 3000,
  176. validate: (val) => {
  177. val = _.toNumber(val)
  178. return (_.isNumber(val) && val > 0) ? true : 'Invalid Port!'
  179. },
  180. when: (ans) => {
  181. return ans.action === 'custom'
  182. }
  183. }]).then((ans) => {
  184. switch (ans.action) {
  185. case 'default':
  186. 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!)'))
  187. ora = require('ora')({ text: 'I\'ll wait until you\'re done ;)', color: 'yellow', spinner: 'pong' }).start()
  188. return exec.stdout('node', ['wiki', 'configure'], {
  189. cwd: installDir
  190. })
  191. case 'custom':
  192. 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!)'))
  193. ora = require('ora')({ text: 'I\'ll wait until you\'re done ;)', color: 'yellow', spinner: 'pong' }).start()
  194. return exec.stdout('node', ['wiki', 'configure', ans.customport], {
  195. cwd: installDir
  196. })
  197. default:
  198. 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'))
  199. return Promise.delay(7000).then(() => {
  200. process.exit(0)
  201. })
  202. }
  203. }).then(() => {
  204. ora.succeed(colors.bold.green('Wiki.js has been configured successfully. It is now starting up and should be accessible very soon!'))
  205. return Promise.delay(3000).then(() => {
  206. console.info('npm is finishing... please wait...')
  207. })
  208. })
  209. } else {
  210. console.info(colors.cyan('[WARNING] Non-interactive terminal detected. You must manually start the configuration wizard using the command: node wiki configure'))
  211. }
  212. }
  213. }
  214. // =====================================================
  215. // INSTALL SEQUENCE
  216. // =====================================================
  217. if (!isContainerBased) {
  218. console.info(colors.yellow(
  219. ' __ __ _ _ _ _ \n' +
  220. '/ / /\\ \\ (_) | _(_) (_)___ \n' +
  221. '\\ \\/ \\/ / | |/ / | | / __| \n' +
  222. ' \\ /\\ /| | <| |_ | \\__ \\ \n' +
  223. ' \\/ \\/ |_|_|\\_\\_(_)/ |___/ \n' +
  224. ' |__/\n'))
  225. } else {
  226. console.info('> WIKI.JS [Installing...]')
  227. }
  228. let ora = require('ora')({ text: 'Initializing...', spinner: 'dots12' }).start()
  229. Promise.join(
  230. tasks.stopAndDeleteInstances(),
  231. tasks.checkRequirements()
  232. ).then(() => {
  233. isContainerBased && console.info('>> Fetching tarball...')
  234. return tasks.installFromLocal().then(succeeded => {
  235. return (!succeeded) ? tasks.installFromRemote() : true
  236. })
  237. }).then(() => {
  238. isContainerBased && console.info('>> Creating config file...')
  239. return tasks.ensureConfigFile()
  240. }).then(() => {
  241. isContainerBased && console.info('>> Installing dependencies...')
  242. return tasks.installDependencies()
  243. }).then(() => {
  244. return tasks.startConfigurationWizard()
  245. }).catch(err => {
  246. isContainerBased && console.error(err)
  247. ora.fail(err)
  248. })