Gruntfile.coffee 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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: (dir, callback = (error) ->) ->
  225. proc = spawn "grunt", ["install"], stdio: "inherit", cwd: dir
  226. proc.on "close", () ->
  227. callback()
  228. checkRedis: (callback = (error) ->) ->
  229. grunt.log.write "Checking Redis is running... "
  230. exec "redis-cli info", (error, stdout, stderr) ->
  231. if error? and error.message.match("Could not connect")
  232. grunt.log.error "FAIL. Redis is not running"
  233. return callback(error)
  234. else if error?
  235. return callback(error)
  236. else
  237. m = stdout.match(/redis_version:(.*)/)
  238. if !m?
  239. grunt.log.error "FAIL."
  240. grunt.log.error "Unknown redis version"
  241. error = new Error("Unknown redis version")
  242. else
  243. version = m[1]
  244. if semver.gte(version, "2.6.12")
  245. grunt.log.writeln "OK."
  246. grunt.log.writeln "Running Redis version #{version}"
  247. else
  248. grunt.log.error "FAIL."
  249. grunt.log.error "Redis version is too old (#{version}). Must be 2.6.12 or greater."
  250. error = new Error("Redis version is too old (#{version}). Must be 2.6.12 or greater.")
  251. callback(error)
  252. checkLatexmk: (callback = (error) ->) ->
  253. grunt.log.write "Checking latexmk is installed... "
  254. exec "latexmk --version", (error, stdout, stderr) ->
  255. if error? and error.message.match("not found")
  256. grunt.log.error "FAIL."
  257. grunt.log.errorlns """
  258. Either latexmk is not installed or is not in your PATH.
  259. latexmk comes with TexLive 2013, and must be a version from 2013 or later.
  260. If you have already have TeXLive installed, then make sure it is
  261. included in your PATH (example for 64-bit linux):
  262. export PATH=$PATH:/usr/local/texlive/2014/bin/x86_64-linux/
  263. This is a not a fatal error, but compiling will not work without latexmk.
  264. """
  265. return callback(error)
  266. else if error?
  267. return callback(error)
  268. else
  269. m = stdout.match(/Version (.*)/)
  270. if !m?
  271. grunt.log.error "FAIL."
  272. grunt.log.error "Unknown latexmk version"
  273. error = new Error("Unknown latexmk version")
  274. else
  275. version = m[1]
  276. if semver.gte(version + ".0", "4.39.0")
  277. grunt.log.writeln "OK."
  278. grunt.log.writeln "Running latexmk version #{version}"
  279. else
  280. grunt.log.error "FAIL."
  281. grunt.log.errorlns """
  282. latexmk version is too old (#{version}). Must be 4.39 or greater.
  283. This is a not a fatal error, but compiling will not work without latexmk
  284. """
  285. error = new Error("latexmk is too old")
  286. callback(error)
  287. checkAspell: (callback = (error) ->) ->
  288. grunt.log.write "Checking aspell is installed... "
  289. exec "aspell dump dicts", (error, stdout, stderr) ->
  290. if error? and error.message.match("not found")
  291. grunt.log.error "FAIL."
  292. grunt.log.errorlns """
  293. Either aspell is not installed or is not in your PATH.
  294. On Ubuntu you can install aspell with:
  295. sudo apt-get install aspell
  296. Or on a mac:
  297. brew install aspell
  298. This is not a fatal error, but the spell-checker will not work without aspell
  299. """
  300. return callback(error)
  301. else if error?
  302. return callback(error)
  303. else
  304. grunt.log.writeln "OK."
  305. grunt.log.writeln "The following spell check dictionaries are available:"
  306. grunt.log.write stdout
  307. callback()
  308. callback(error)
  309. checkS3: (callback = (error) ->) ->
  310. Settings = require "settings-sharelatex"
  311. if Settings.filestore.backend==""
  312. grunt.log.writeln "No backend specified. Assuming Amazon S3"
  313. Settings.filestore.backend = "s3"
  314. if Settings.filestore.backend=="s3"
  315. grunt.log.write "Checking S3 credentials... "
  316. try
  317. client = knox.createClient({
  318. key: Settings.filestore.s3.key
  319. secret: Settings.filestore.s3.secret
  320. bucket: Settings.filestore.stores.user_files
  321. })
  322. catch e
  323. grunt.log.error "FAIL."
  324. grunt.log.errorlns """
  325. Please configure your Amazon S3 credentials in config/settings.development.coffee
  326. Amazon S3 (Simple Storage Service) is a cloud storage service provided by
  327. Amazon. ShareLaTeX uses S3 for storing binary files like images. You can
  328. sign up for an account and find out more at:
  329. http://aws.amazon.com/s3/
  330. """
  331. return callback()
  332. client.getFile "does-not-exist", (error, response) ->
  333. unless response? and response.statusCode == 404
  334. grunt.log.error "FAIL."
  335. grunt.log.errorlns """
  336. Could not connect to Amazon S3. Please check your credentials.
  337. """
  338. else
  339. grunt.log.writeln "OK."
  340. callback()
  341. else
  342. grunt.log.writeln "Filestore other than S3 configured. Not checking S3."
  343. callback()
  344. checkFS: (callback = (error) ->) ->
  345. Settings = require "settings-sharelatex"
  346. if Settings.filestore.backend=="fs"
  347. grunt.log.write "Checking FS configuration... "
  348. fs = require("fs")
  349. fs.exists Settings.filestore.stores.user_files, (exists) ->
  350. if exists
  351. grunt.log.writeln "OK."
  352. else
  353. grunt.log.error "FAIL."
  354. grunt.log.errorlns """
  355. Could not find directory "#{Settings.filestore.stores.user_files}".
  356. Please check your configuration.
  357. """
  358. callback()
  359. else
  360. grunt.log.writeln "Filestore other than FS configured. Not checking FS."
  361. callback()
  362. checkMake: (callback = (error) ->) ->
  363. grunt.log.write "Checking make is installed... "
  364. exec "make --version", (error, stdout, stderr) ->
  365. if error? and error.message.match("not found")
  366. grunt.log.error "FAIL."
  367. grunt.log.errorlns """
  368. Either make is not installed or is not in your path.
  369. On Ubuntu you can install make with:
  370. sudo apt-get install build-essential
  371. """
  372. return callback(error)
  373. else if error?
  374. return callback(error)
  375. else
  376. grunt.log.write "OK."
  377. return callback()
  378. buildUpstartScripts: () ->
  379. template = fs.readFileSync("package/upstart/sharelatex-template").toString()
  380. for service in SERVICES
  381. fs.writeFileSync "package/upstart/sharelatex-#{service.name}", template.replace(/__SERVICE__/g, service.name)
  382. buildPackageSettingsFile: () ->
  383. config = fs.readFileSync("config/settings.development.coffee.example").toString()
  384. config = config.replace /DATA_DIR.*/, "DATA_DIR = '/var/lib/sharelatex/data'"
  385. config = config.replace /TMP_DIR.*/, "TMP_DIR = '/var/lib/sharelatex/tmp'"
  386. fs.writeFileSync "package/config/settings.coffee", config
  387. buildDeb: (callback = (error) ->) ->
  388. command = ["-s", "dir", "-t", "deb", "-n", "sharelatex", "-v", "0.0.1", "--verbose"]
  389. command.push(
  390. "--maintainer", "ShareLaTeX <team@sharelatex.com>"
  391. "--config-files", "/etc/sharelatex/settings.coffee"
  392. "--config-files", "/etc/nginx/conf.d/sharelatex.conf"
  393. "--directories", "/var/lib/sharelatex"
  394. "--directories", "/var/log/sharelatex"
  395. )
  396. command.push(
  397. "--depends", "redis-server > 2.6.12"
  398. "--depends", "mongodb-org > 2.4.0"
  399. "--depends", "nodejs > 0.10.0"
  400. )
  401. @buildPackageSettingsFile()
  402. @buildUpstartScripts()
  403. for service in SERVICES
  404. command.push(
  405. "--deb-upstart", "package/upstart/sharelatex-#{service.name}"
  406. )
  407. after_install_script = """
  408. #!/bin/sh
  409. # Create random secret keys (twice, once for http auth pass, once for cookie secret).
  410. 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
  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. sudo adduser --system --group --home /var/www/sharelatex --no-create-home sharelatex
  413. mkdir -p /var/log/sharelatex
  414. chown sharelatex:sharelatex /var/log/sharelatex
  415. mkdir -p /var/lib/sharelatex
  416. """
  417. for dir in ["data/user_files", "tmp/uploads", "data/compiles", "data/cache", "tmp/dumpFolder"]
  418. after_install_script += """
  419. mkdir -p /var/lib/sharelatex/#{dir}
  420. """
  421. after_install_script += """
  422. chown -R sharelatex:sharelatex /var/lib/sharelatex
  423. """
  424. for service in SERVICES
  425. after_install_script += "service sharelatex-#{service.name} restart\n"
  426. fs.writeFileSync "package/scripts/after_install.sh", after_install_script
  427. command.push("--after-install", "package/scripts/after_install.sh")
  428. command.push("--exclude", "**/.git")
  429. command.push("--exclude", "**/node_modules/grunt-*")
  430. for path in ["filestore/user_files", "filestore/uploads", "clsi/cache", "clsi/compiles"]
  431. command.push "--exclude", path
  432. for service in SERVICES
  433. command.push "#{service.name}=/var/www/sharelatex/"
  434. command.push(
  435. "package/config/settings.coffee=/etc/sharelatex/settings.coffee"
  436. "package/nginx/sharelatex=/etc/nginx/conf.d/sharelatex.conf"
  437. )
  438. console.log "fpm " + command.join(" ")
  439. proc = spawn "fpm", command, stdio: "inherit"
  440. proc.on "close", (code) ->
  441. if code != 0
  442. callback(new Error("exit code: #{code}"))
  443. else
  444. callback()