Gruntfile.coffee 17 KB

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