Gruntfile.coffee 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. fs = require "fs"
  2. spawn = require("child_process").spawn
  3. exec = require("child_process").exec
  4. rimraf = require "rimraf"
  5. Path = require "path"
  6. semver = require "semver"
  7. knox = require "knox"
  8. crypto = require "crypto"
  9. async = require "async"
  10. SERVICES = [{
  11. name: "web"
  12. repo: "https://github.com/sharelatex/web-sharelatex.git"
  13. version: "master"
  14. }, {
  15. name: "real-time"
  16. repo: "https://github.com/sharelatex/real-time-sharelatex.git"
  17. version: "master"
  18. }, {
  19. name: "document-updater"
  20. repo: "https://github.com/sharelatex/document-updater-sharelatex.git"
  21. version: "master"
  22. }, {
  23. name: "clsi"
  24. repo: "https://github.com/sharelatex/clsi-sharelatex.git"
  25. version: "master"
  26. }, {
  27. name: "filestore"
  28. repo: "https://github.com/sharelatex/filestore-sharelatex.git"
  29. version: "master"
  30. }, {
  31. name: "track-changes"
  32. repo: "https://github.com/sharelatex/track-changes-sharelatex.git"
  33. version: "master"
  34. }, {
  35. name: "docstore"
  36. repo: "https://github.com/sharelatex/docstore-sharelatex.git"
  37. version: "master"
  38. }, {
  39. name: "chat"
  40. repo: "https://github.com/sharelatex/chat-sharelatex.git"
  41. version: "master"
  42. }, {
  43. name: "tags"
  44. repo: "https://github.com/sharelatex/tags-sharelatex.git"
  45. version: "master"
  46. }, {
  47. name: "spelling"
  48. repo: "https://github.com/sharelatex/spelling-sharelatex.git"
  49. version: "master"
  50. }]
  51. module.exports = (grunt) ->
  52. grunt.loadNpmTasks 'grunt-bunyan'
  53. grunt.loadNpmTasks 'grunt-execute'
  54. grunt.loadNpmTasks 'grunt-available-tasks'
  55. grunt.loadNpmTasks 'grunt-concurrent'
  56. grunt.loadNpmTasks "grunt-contrib-coffee"
  57. execute = {}
  58. for service in SERVICES
  59. execute[service.name] =
  60. src: "#{service.name}/app.js"
  61. grunt.initConfig
  62. execute: execute
  63. concurrent:
  64. all:
  65. tasks: ("run:#{service.name}" for service in SERVICES)
  66. options:
  67. limit: SERVICES.length
  68. logConcurrentOutput: true
  69. coffee:
  70. migrate:
  71. expand: true,
  72. flatten: false,
  73. cwd: './',
  74. src: ['./migrations/*.coffee'],
  75. dest: './',
  76. ext: '.js'
  77. options:
  78. bare:true
  79. availabletasks:
  80. tasks:
  81. options:
  82. filter: 'exclude',
  83. tasks: [
  84. 'concurrent'
  85. 'execute'
  86. 'bunyan'
  87. 'availabletasks'
  88. ]
  89. groups:
  90. "Run tasks": [
  91. "run"
  92. "run:all"
  93. "default"
  94. ].concat ("run:#{service.name}" for service in SERVICES)
  95. "Misc": [
  96. "help"
  97. ]
  98. "Install tasks": ("install:#{service.name}" for service in SERVICES).concat(["install:all", "install", "install:dirs", "install:config"])
  99. "Update tasks": ("update:#{service.name}" for service in SERVICES).concat(["update:all", "update"])
  100. "Config tasks": ["install:config"]
  101. "Checks": ["check", "check:redis", "check:latexmk", "check:s3", "check:make"]
  102. for service in SERVICES
  103. do (service) ->
  104. grunt.registerTask "install:#{service.name}", "Download and set up the #{service.name} service", () ->
  105. done = @async()
  106. Helpers.installService(service, done)
  107. grunt.registerTask "update:#{service.name}", "Checkout and update the #{service.name} service", () ->
  108. done = @async()
  109. Helpers.updateService(service, done)
  110. grunt.registerTask "run:#{service.name}", "Run the ShareLaTeX #{service.name} service", ["bunyan", "execute:#{service.name}"]
  111. grunt.registerTask "release:#{service.name}", "Create a new release version of #{service.name} (specify with --release option)", () ->
  112. done = @async()
  113. Helpers.createNewRelease(service, grunt.option("release"), done)
  114. grunt.registerTask 'install:config', "Copy the example config into the real config", () ->
  115. Helpers.installConfig @async()
  116. grunt.registerTask 'install:dirs', "Copy the example config into the real config", () ->
  117. Helpers.createDataDirs @async()
  118. grunt.registerTask 'install:all', "Download and set up all ShareLaTeX services",
  119. ["check:make"].concat(
  120. ("install:#{service.name}" for service in SERVICES)
  121. ).concat(["install:config", "install:dirs"])
  122. grunt.registerTask 'install', 'install:all'
  123. grunt.registerTask 'update:all', "Checkout and update all ShareLaTeX services",
  124. ["check:make"].concat(
  125. ("update:#{service.name}" for service in SERVICES)
  126. )
  127. grunt.registerTask 'update', 'update:all'
  128. grunt.registerTask 'run', "Run all of the sharelatex processes", ['concurrent:all']
  129. grunt.registerTask 'run:all', 'run'
  130. grunt.registerTask 'help', 'Display this help list', 'availabletasks'
  131. grunt.registerTask 'default', 'run'
  132. grunt.registerTask "check:redis", "Check that redis is installed and running", () ->
  133. Helpers.checkRedis @async()
  134. grunt.registerTask "check:latexmk", "Check that latexmk is installed", () ->
  135. Helpers.checkLatexmk @async()
  136. grunt.registerTask "check:s3", "Check that Amazon S3 credentials are configured", () ->
  137. Helpers.checkS3 @async()
  138. grunt.registerTask "check:fs", "Check that local filesystem options are configured", () ->
  139. Helpers.checkFS @async()
  140. grunt.registerTask "check:aspell", "Check that aspell is installed", () ->
  141. Helpers.checkAspell @async()
  142. grunt.registerTask "check:make", "Check that make is installed", () ->
  143. Helpers.checkMake @async()
  144. grunt.registerTask "check", "Check that you have the required dependencies installed", ["check:redis", "check:latexmk", "check:s3", "check:fs", "check:aspell"]
  145. grunt.registerTask "build:deb", "Build an installable .deb file from the current directory", () ->
  146. Helpers.buildDeb @async()
  147. grunt.registerTask "build:upstart_scripts", "Create upstart scripts for each service", () ->
  148. Helpers.buildUpstartScripts()
  149. grunt.registerTask 'migrate', 'run migrations', ['coffee:migrate']
  150. Helpers =
  151. installService: (service, callback = (error) ->) ->
  152. Helpers.cloneGitRepo service, (error) ->
  153. return callback(error) if error?
  154. Helpers.installNpmModules service, (error) ->
  155. return callback(error) if error?
  156. Helpers.rebuildNpmModules service, (error) ->
  157. return callback(error) if error?
  158. Helpers.runGruntInstall service, (error) ->
  159. return callback(error) if error?
  160. callback()
  161. updateService: (service, callback = (error) ->) ->
  162. Helpers.updateGitRepo service, (error) ->
  163. return callback(error) if error?
  164. Helpers.installNpmModules service, (error) ->
  165. return callback(error) if error?
  166. Helpers.rebuildNpmModules service, (error) ->
  167. return callback(error) if error?
  168. Helpers.runGruntInstall service, (error) ->
  169. return callback(error) if error?
  170. callback()
  171. cloneGitRepo: (service, callback = (error) ->) ->
  172. repo_src = service.repo
  173. dir = service.name
  174. if !fs.existsSync(dir)
  175. proc = spawn "git", [
  176. "clone",
  177. "-b", service.version,
  178. repo_src,
  179. dir
  180. ], stdio: "inherit"
  181. proc.on "close", () ->
  182. callback()
  183. else
  184. console.log "#{dir} already installed, skipping."
  185. callback()
  186. updateGitRepo: (service, callback = (error) ->) ->
  187. dir = service.name
  188. proc = spawn "git", ["checkout", service.version], cwd: dir, stdio: "inherit"
  189. proc.on "close", () ->
  190. proc = spawn "git", ["pull"], cwd: dir, stdio: "inherit"
  191. proc.on "close", () ->
  192. callback()
  193. createNewRelease: (service, version, callback = (error) ->) ->
  194. dir = service.name
  195. proc = spawn "sed", [
  196. "-i", "",
  197. "s/\"version\".*$/\"version\": \"#{version}\",/g",
  198. "package.json"
  199. ], cwd: dir, stdio: "inherit"
  200. proc.on "close", () ->
  201. proc = spawn "git", ["commit", "-a", "-m", "Release version #{version}"], cwd: dir, stdio: "inherit"
  202. proc.on "close", () ->
  203. proc = spawn "git", ["tag", "v#{version}"], cwd: dir, stdio: "inherit"
  204. proc.on "close", () ->
  205. proc = spawn "git", ["push"], cwd: dir, stdio: "inherit"
  206. proc.on "close", () ->
  207. proc = spawn "git", ["push", "--tags"], cwd: dir, stdio: "inherit"
  208. proc.on "close", () ->
  209. callback()
  210. installNpmModules: (service, callback = (error) ->) ->
  211. dir = service.name
  212. proc = spawn "npm", ["install"], stdio: "inherit", cwd: dir
  213. proc.on "close", () ->
  214. callback()
  215. # work around for https://github.com/npm/npm/issues/5400
  216. # where binary modules are not built due to bug in npm
  217. rebuildNpmModules: (service, callback = (error) ->) ->
  218. dir = service.name
  219. proc = spawn "npm", ["rebuild"], stdio: "inherit", cwd: dir
  220. proc.on "close", () ->
  221. callback()
  222. createDataDirs: (callback = (error) ->) ->
  223. DIRS = [
  224. "tmp/dumpFolder"
  225. "tmp/uploads"
  226. "data/user_files"
  227. "data/compiles"
  228. "data/cache"
  229. ]
  230. jobs = []
  231. for dir in DIRS
  232. do (dir) ->
  233. jobs.push (callback) ->
  234. path = Path.join(__dirname, dir)
  235. grunt.log.writeln "Ensuring '#{path}' exists"
  236. exec "mkdir -p #{path}", callback
  237. async.series jobs, callback
  238. installConfig: (callback = (error) ->) ->
  239. src = "config/settings.development.coffee.example"
  240. dest = "config/settings.development.coffee"
  241. if !fs.existsSync(dest)
  242. grunt.log.writeln "Creating config at #{dest}"
  243. config = fs.readFileSync(src).toString()
  244. config = config.replace /CRYPTO_RANDOM/g, () ->
  245. crypto.randomBytes(64).toString("hex")
  246. fs.writeFileSync dest, config
  247. callback()
  248. else
  249. grunt.log.writeln "Config file already exists. Skipping."
  250. callback()
  251. runGruntInstall: (service, callback = (error) ->) ->
  252. dir = service.name
  253. proc = spawn "grunt", ["install"], stdio: "inherit", cwd: dir
  254. proc.on "close", () ->
  255. callback()
  256. checkRedis: (callback = (error) ->) ->
  257. grunt.log.write "Checking Redis is running... "
  258. exec "redis-cli info", (error, stdout, stderr) ->
  259. if error? and error.message.match("Could not connect")
  260. grunt.log.error "FAIL. Redis is not running"
  261. return callback(error)
  262. else if error?
  263. return callback(error)
  264. else
  265. m = stdout.match(/redis_version:(.*)/)
  266. if !m?
  267. grunt.log.error "FAIL."
  268. grunt.log.error "Unknown redis version"
  269. error = new Error("Unknown redis version")
  270. else
  271. version = m[1]
  272. if semver.gte(version, "2.6.12")
  273. grunt.log.writeln "OK."
  274. grunt.log.writeln "Running Redis version #{version}"
  275. else
  276. grunt.log.error "FAIL."
  277. grunt.log.error "Redis version is too old (#{version}). Must be 2.6.12 or greater."
  278. error = new Error("Redis version is too old (#{version}). Must be 2.6.12 or greater.")
  279. callback(error)
  280. checkLatexmk: (callback = (error) ->) ->
  281. grunt.log.write "Checking latexmk is installed... "
  282. exec "latexmk --version", (error, stdout, stderr) ->
  283. if error? and error.message.match("not found")
  284. grunt.log.error "FAIL."
  285. grunt.log.errorlns """
  286. Either latexmk is not installed or is not in your PATH.
  287. latexmk comes with TexLive 2013, and must be a version from 2013 or later.
  288. If you have already have TeXLive installed, then make sure it is
  289. included in your PATH (example for 64-bit linux):
  290. export PATH=$PATH:/usr/local/texlive/2014/bin/x86_64-linux/
  291. This is a not a fatal error, but compiling will not work without latexmk.
  292. """
  293. return callback(error)
  294. else if error?
  295. return callback(error)
  296. else
  297. m = stdout.match(/Version (.*)/)
  298. if !m?
  299. grunt.log.error "FAIL."
  300. grunt.log.error "Unknown latexmk version"
  301. error = new Error("Unknown latexmk version")
  302. else
  303. version = m[1]
  304. if semver.gte(version + ".0", "4.39.0")
  305. grunt.log.writeln "OK."
  306. grunt.log.writeln "Running latexmk version #{version}"
  307. else
  308. grunt.log.error "FAIL."
  309. grunt.log.errorlns """
  310. latexmk version is too old (#{version}). Must be 4.39 or greater.
  311. This is a not a fatal error, but compiling will not work without latexmk
  312. """
  313. error = new Error("latexmk is too old")
  314. callback(error)
  315. checkAspell: (callback = (error) ->) ->
  316. grunt.log.write "Checking aspell is installed... "
  317. exec "aspell dump dicts", (error, stdout, stderr) ->
  318. if error? and error.message.match("not found")
  319. grunt.log.error "FAIL."
  320. grunt.log.errorlns """
  321. Either aspell is not installed or is not in your PATH.
  322. On Ubuntu you can install aspell with:
  323. sudo apt-get install aspell
  324. Or on a mac:
  325. brew install aspell
  326. This is not a fatal error, but the spell-checker will not work without aspell
  327. """
  328. return callback(error)
  329. else if error?
  330. return callback(error)
  331. else
  332. grunt.log.writeln "OK."
  333. grunt.log.writeln "The following spell check dictionaries are available:"
  334. grunt.log.write stdout
  335. callback()
  336. callback(error)
  337. checkS3: (callback = (error) ->) ->
  338. Settings = require "settings-sharelatex"
  339. if Settings.filestore.backend==""
  340. grunt.log.writeln "No backend specified. Assuming Amazon S3"
  341. Settings.filestore.backend = "s3"
  342. if Settings.filestore.backend=="s3"
  343. grunt.log.write "Checking S3 credentials... "
  344. try
  345. client = knox.createClient({
  346. key: Settings.filestore.s3.key
  347. secret: Settings.filestore.s3.secret
  348. bucket: Settings.filestore.stores.user_files
  349. })
  350. catch e
  351. grunt.log.error "FAIL."
  352. grunt.log.errorlns """
  353. Please configure your Amazon S3 credentials in config/settings.development.coffee
  354. Amazon S3 (Simple Storage Service) is a cloud storage service provided by
  355. Amazon. ShareLaTeX uses S3 for storing binary files like images. You can
  356. sign up for an account and find out more at:
  357. http://aws.amazon.com/s3/
  358. """
  359. return callback()
  360. client.getFile "does-not-exist", (error, response) ->
  361. unless response? and response.statusCode == 404
  362. grunt.log.error "FAIL."
  363. grunt.log.errorlns """
  364. Could not connect to Amazon S3. Please check your credentials.
  365. """
  366. else
  367. grunt.log.writeln "OK."
  368. callback()
  369. else
  370. grunt.log.writeln "Filestore other than S3 configured. Not checking S3."
  371. callback()
  372. checkFS: (callback = (error) ->) ->
  373. Settings = require "settings-sharelatex"
  374. if Settings.filestore.backend=="fs"
  375. grunt.log.write "Checking FS configuration... "
  376. fs = require("fs")
  377. fs.exists Settings.filestore.stores.user_files, (exists) ->
  378. if exists
  379. grunt.log.writeln "OK."
  380. else
  381. grunt.log.error "FAIL."
  382. grunt.log.errorlns """
  383. Could not find directory "#{Settings.filestore.stores.user_files}".
  384. Please check your configuration.
  385. """
  386. callback()
  387. else
  388. grunt.log.writeln "Filestore other than FS configured. Not checking FS."
  389. callback()
  390. checkMake: (callback = (error) ->) ->
  391. grunt.log.write "Checking make is installed... "
  392. exec "make --version", (error, stdout, stderr) ->
  393. if error? and error.message.match("not found")
  394. grunt.log.error "FAIL."
  395. grunt.log.errorlns """
  396. Either make is not installed or is not in your path.
  397. On Ubuntu you can install make with:
  398. sudo apt-get install build-essential
  399. """
  400. return callback(error)
  401. else if error?
  402. return callback(error)
  403. else
  404. grunt.log.write "OK."
  405. return callback()
  406. buildUpstartScripts: () ->
  407. template = fs.readFileSync("package/upstart/sharelatex-template").toString()
  408. for service in SERVICES
  409. fs.writeFileSync "package/upstart/sharelatex-#{service.name}", template.replace(/__SERVICE__/g, service.name)
  410. buildPackageSettingsFile: () ->
  411. config = fs.readFileSync("config/settings.development.coffee.example").toString()
  412. config = config.replace /DATA_DIR.*/, "DATA_DIR = '/var/lib/sharelatex/data'"
  413. config = config.replace /TMP_DIR.*/, "TMP_DIR = '/var/lib/sharelatex/tmp'"
  414. fs.writeFileSync "package/config/settings.coffee", config
  415. buildDeb: (callback = (error) ->) ->
  416. command = ["-s", "dir", "-t", "deb", "-n", "sharelatex", "-v", "0.0.1", "--verbose"]
  417. command.push(
  418. "--maintainer", "ShareLaTeX <team@sharelatex.com>"
  419. "--config-files", "/etc/sharelatex/settings.coffee"
  420. "--config-files", "/etc/nginx/conf.d/sharelatex.conf"
  421. "--directories", "/var/lib/sharelatex"
  422. "--directories", "/var/log/sharelatex"
  423. )
  424. command.push(
  425. "--depends", "redis-server > 2.6.12"
  426. "--depends", "mongodb-org > 2.4.0"
  427. "--depends", "nodejs > 0.10.0"
  428. )
  429. @buildPackageSettingsFile()
  430. @buildUpstartScripts()
  431. for service in SERVICES
  432. command.push(
  433. "--deb-upstart", "package/upstart/sharelatex-#{service.name}"
  434. )
  435. after_install_script = """
  436. #!/bin/sh
  437. # Create random secret keys (twice, once for http auth pass, once for cookie secret).
  438. sed -i "0,/CRYPTO_RANDOM/s/CRYPTO_RANDOM/$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 64 | head -n 1)/" /etc/sharelatex/settings.coffee
  439. sed -i "0,/CRYPTO_RANDOM/s/CRYPTO_RANDOM/$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 64 | head -n 1)/" /etc/sharelatex/settings.coffee
  440. sudo adduser --system --group --home /var/www/sharelatex --no-create-home sharelatex
  441. mkdir -p /var/log/sharelatex
  442. chown sharelatex:sharelatex /var/log/sharelatex
  443. mkdir -p /var/lib/sharelatex
  444. """
  445. for dir in ["data/user_files", "tmp/uploads", "data/compiles", "data/cache", "tmp/dumpFolder"]
  446. after_install_script += """
  447. mkdir -p /var/lib/sharelatex/#{dir}
  448. """
  449. after_install_script += """
  450. chown -R sharelatex:sharelatex /var/lib/sharelatex
  451. """
  452. for service in SERVICES
  453. after_install_script += "service sharelatex-#{service.name} restart\n"
  454. fs.writeFileSync "package/scripts/after_install.sh", after_install_script
  455. command.push("--after-install", "package/scripts/after_install.sh")
  456. command.push("--exclude", "**/.git")
  457. command.push("--exclude", "**/node_modules/grunt-*")
  458. for path in ["filestore/user_files", "filestore/uploads", "clsi/cache", "clsi/compiles"]
  459. command.push "--exclude", path
  460. for service in SERVICES
  461. command.push "#{service.name}=/var/www/sharelatex/"
  462. command.push(
  463. "package/config/settings.coffee=/etc/sharelatex/settings.coffee"
  464. "package/nginx/sharelatex=/etc/nginx/conf.d/sharelatex.conf"
  465. )
  466. console.log "fpm " + command.join(" ")
  467. proc = spawn "fpm", command, stdio: "inherit"
  468. proc.on "close", (code) ->
  469. if code != 0
  470. callback(new Error("exit code: #{code}"))
  471. else
  472. callback()