Gruntfile.coffee 17 KB

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