Gruntfile.coffee 17 KB

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