DockerRunner.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. /* eslint-disable
  2. camelcase,
  3. handle-callback-err,
  4. no-return-assign,
  5. no-unused-vars,
  6. */
  7. // TODO: This file was created by bulk-decaffeinate.
  8. // Fix any style issues and re-enable lint.
  9. /*
  10. * decaffeinate suggestions:
  11. * DS101: Remove unnecessary use of Array.from
  12. * DS102: Remove unnecessary code created because of implicit returns
  13. * DS103: Rewrite code to no longer use __guard__
  14. * DS205: Consider reworking code to avoid use of IIFEs
  15. * DS207: Consider shorter variations of null checks
  16. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  17. */
  18. let DockerRunner, oneHour
  19. const Settings = require('settings-sharelatex')
  20. const logger = require('logger-sharelatex')
  21. const Docker = require('dockerode')
  22. const dockerode = new Docker()
  23. const crypto = require('crypto')
  24. const async = require('async')
  25. const LockManager = require('./DockerLockManager')
  26. const fs = require('fs')
  27. const Path = require('path')
  28. const _ = require('lodash')
  29. logger.info('using docker runner')
  30. const usingSiblingContainers = () =>
  31. __guard__(
  32. Settings != null ? Settings.path : undefined,
  33. x => x.sandboxedCompilesHostDir
  34. ) != null
  35. let containerMonitorTimeout
  36. let containerMonitorInterval
  37. module.exports = DockerRunner = {
  38. ERR_NOT_DIRECTORY: new Error('not a directory'),
  39. ERR_TERMINATED: new Error('terminated'),
  40. ERR_EXITED: new Error('exited'),
  41. ERR_TIMED_OUT: new Error('container timed out'),
  42. run(
  43. project_id,
  44. command,
  45. directory,
  46. image,
  47. timeout,
  48. environment,
  49. compileGroup,
  50. callback
  51. ) {
  52. let name
  53. if (callback == null) {
  54. callback = function(error, output) {}
  55. }
  56. if (usingSiblingContainers()) {
  57. const _newPath = Settings.path.sandboxedCompilesHostDir
  58. logger.log(
  59. { path: _newPath },
  60. 'altering bind path for sibling containers'
  61. )
  62. // Server Pro, example:
  63. // '/var/lib/sharelatex/data/compiles/<project-id>'
  64. // ... becomes ...
  65. // '/opt/sharelatex_data/data/compiles/<project-id>'
  66. directory = Path.join(
  67. Settings.path.sandboxedCompilesHostDir,
  68. Path.basename(directory)
  69. )
  70. }
  71. const volumes = {}
  72. volumes[directory] = '/compile'
  73. command = Array.from(command).map(arg =>
  74. __guardMethod__(arg.toString(), 'replace', o =>
  75. o.replace('$COMPILE_DIR', '/compile')
  76. )
  77. )
  78. if (image == null) {
  79. ;({ image } = Settings.clsi.docker)
  80. }
  81. if (Settings.texliveImageNameOveride != null) {
  82. const img = image.split('/')
  83. image = `${Settings.texliveImageNameOveride}/${img[2]}`
  84. }
  85. const options = DockerRunner._getContainerOptions(
  86. command,
  87. image,
  88. volumes,
  89. timeout,
  90. environment,
  91. compileGroup
  92. )
  93. const fingerprint = DockerRunner._fingerprintContainer(options)
  94. options.name = name = `project-${project_id}-${fingerprint}`
  95. // logOptions = _.clone(options)
  96. // logOptions?.HostConfig?.SecurityOpt = "secomp used, removed in logging"
  97. logger.log({ project_id }, 'running docker container')
  98. DockerRunner._runAndWaitForContainer(options, volumes, timeout, function(
  99. error,
  100. output
  101. ) {
  102. if (error && error.statusCode === 500) {
  103. logger.log(
  104. { err: error, project_id },
  105. 'error running container so destroying and retrying'
  106. )
  107. return DockerRunner.destroyContainer(name, null, true, function(error) {
  108. if (error != null) {
  109. return callback(error)
  110. }
  111. return DockerRunner._runAndWaitForContainer(
  112. options,
  113. volumes,
  114. timeout,
  115. callback
  116. )
  117. })
  118. } else {
  119. return callback(error, output)
  120. }
  121. })
  122. return name
  123. }, // pass back the container name to allow it to be killed
  124. kill(container_id, callback) {
  125. if (callback == null) {
  126. callback = function(error) {}
  127. }
  128. logger.log({ container_id }, 'sending kill signal to container')
  129. const container = dockerode.getContainer(container_id)
  130. return container.kill(function(error) {
  131. if (
  132. error != null &&
  133. __guardMethod__(error != null ? error.message : undefined, 'match', o =>
  134. o.match(/Cannot kill container .* is not running/)
  135. )
  136. ) {
  137. logger.warn(
  138. { err: error, container_id },
  139. 'container not running, continuing'
  140. )
  141. error = null
  142. }
  143. if (error != null) {
  144. logger.error({ err: error, container_id }, 'error killing container')
  145. return callback(error)
  146. } else {
  147. return callback()
  148. }
  149. })
  150. },
  151. _runAndWaitForContainer(options, volumes, timeout, _callback) {
  152. if (_callback == null) {
  153. _callback = function(error, output) {}
  154. }
  155. const callback = function(...args) {
  156. _callback(...Array.from(args || []))
  157. // Only call the callback once
  158. return (_callback = function() {})
  159. }
  160. const { name } = options
  161. let streamEnded = false
  162. let containerReturned = false
  163. let output = {}
  164. const callbackIfFinished = function() {
  165. if (streamEnded && containerReturned) {
  166. return callback(null, output)
  167. }
  168. }
  169. const attachStreamHandler = function(error, _output) {
  170. if (error != null) {
  171. return callback(error)
  172. }
  173. output = _output
  174. streamEnded = true
  175. return callbackIfFinished()
  176. }
  177. return DockerRunner.startContainer(
  178. options,
  179. volumes,
  180. attachStreamHandler,
  181. function(error, containerId) {
  182. if (error != null) {
  183. return callback(error)
  184. }
  185. return DockerRunner.waitForContainer(name, timeout, function(
  186. error,
  187. exitCode
  188. ) {
  189. let err
  190. if (error != null) {
  191. return callback(error)
  192. }
  193. if (exitCode === 137) {
  194. // exit status from kill -9
  195. err = DockerRunner.ERR_TERMINATED
  196. err.terminated = true
  197. return callback(err)
  198. }
  199. if (exitCode === 1) {
  200. // exit status from chktex
  201. err = DockerRunner.ERR_EXITED
  202. err.code = exitCode
  203. return callback(err)
  204. }
  205. containerReturned = true
  206. __guard__(
  207. options != null ? options.HostConfig : undefined,
  208. x => (x.SecurityOpt = null)
  209. ) // small log line
  210. logger.log({ err, exitCode, options }, 'docker container has exited')
  211. return callbackIfFinished()
  212. })
  213. }
  214. )
  215. },
  216. _getContainerOptions(
  217. command,
  218. image,
  219. volumes,
  220. timeout,
  221. environment,
  222. compileGroup
  223. ) {
  224. let m, year
  225. let key, value, hostVol, dockerVol
  226. const timeoutInSeconds = timeout / 1000
  227. const dockerVolumes = {}
  228. for (hostVol in volumes) {
  229. dockerVol = volumes[hostVol]
  230. dockerVolumes[dockerVol] = {}
  231. if (volumes[hostVol].slice(-3).indexOf(':r') === -1) {
  232. volumes[hostVol] = `${dockerVol}:rw`
  233. }
  234. }
  235. // merge settings and environment parameter
  236. const env = {}
  237. for (const src of [Settings.clsi.docker.env, environment || {}]) {
  238. for (key in src) {
  239. value = src[key]
  240. env[key] = value
  241. }
  242. }
  243. // set the path based on the image year
  244. if ((m = image.match(/:([0-9]+)\.[0-9]+/))) {
  245. year = m[1]
  246. } else {
  247. year = '2014'
  248. }
  249. env.PATH = `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/texlive/${year}/bin/x86_64-linux/`
  250. const options = {
  251. Cmd: command,
  252. Image: image,
  253. Volumes: dockerVolumes,
  254. WorkingDir: '/compile',
  255. NetworkDisabled: true,
  256. Memory: 1024 * 1024 * 1024 * 1024, // 1 Gb
  257. User: Settings.clsi.docker.user,
  258. Env: (() => {
  259. const result = []
  260. for (key in env) {
  261. value = env[key]
  262. result.push(`${key}=${value}`)
  263. }
  264. return result
  265. })(), // convert the environment hash to an array
  266. HostConfig: {
  267. Binds: (() => {
  268. const result1 = []
  269. for (hostVol in volumes) {
  270. dockerVol = volumes[hostVol]
  271. result1.push(`${hostVol}:${dockerVol}`)
  272. }
  273. return result1
  274. })(),
  275. LogConfig: { Type: 'none', Config: {} },
  276. Ulimits: [
  277. {
  278. Name: 'cpu',
  279. Soft: timeoutInSeconds + 5,
  280. Hard: timeoutInSeconds + 10
  281. }
  282. ],
  283. CapDrop: 'ALL',
  284. SecurityOpt: ['no-new-privileges']
  285. }
  286. }
  287. if (
  288. (Settings.path != null ? Settings.path.synctexBinHostPath : undefined) !=
  289. null
  290. ) {
  291. options.HostConfig.Binds.push(
  292. `${Settings.path.synctexBinHostPath}:/opt/synctex:ro`
  293. )
  294. }
  295. if (Settings.clsi.docker.seccomp_profile != null) {
  296. options.HostConfig.SecurityOpt.push(
  297. `seccomp=${Settings.clsi.docker.seccomp_profile}`
  298. )
  299. }
  300. if (Settings.clsi.docker.runtime) {
  301. options.HostConfig.Runtime = Settings.clsi.docker.runtime
  302. }
  303. if (Settings.clsi.docker.Readonly) {
  304. options.HostConfig.ReadonlyRootfs = true
  305. options.HostConfig.Tmpfs = { '/tmp': 'rw,noexec,nosuid,size=65536k' }
  306. }
  307. // Allow per-compile group overriding of individual settings
  308. if (
  309. Settings.clsi.docker.compileGroupConfig &&
  310. Settings.clsi.docker.compileGroupConfig[compileGroup]
  311. ) {
  312. const override = Settings.clsi.docker.compileGroupConfig[compileGroup]
  313. let key
  314. for (key in override) {
  315. _.set(options, key, override[key])
  316. }
  317. }
  318. return options
  319. },
  320. _fingerprintContainer(containerOptions) {
  321. // Yay, Hashing!
  322. const json = JSON.stringify(containerOptions)
  323. return crypto
  324. .createHash('md5')
  325. .update(json)
  326. .digest('hex')
  327. },
  328. startContainer(options, volumes, attachStreamHandler, callback) {
  329. return LockManager.runWithLock(
  330. options.name,
  331. releaseLock =>
  332. // Check that volumes exist before starting the container.
  333. // When a container is started with volume pointing to a
  334. // non-existent directory then docker creates the directory but
  335. // with root ownership.
  336. DockerRunner._checkVolumes(options, volumes, function(err) {
  337. if (err != null) {
  338. return releaseLock(err)
  339. }
  340. return DockerRunner._startContainer(
  341. options,
  342. volumes,
  343. attachStreamHandler,
  344. releaseLock
  345. )
  346. }),
  347. callback
  348. )
  349. },
  350. // Check that volumes exist and are directories
  351. _checkVolumes(options, volumes, callback) {
  352. if (callback == null) {
  353. callback = function(error, containerName) {}
  354. }
  355. if (usingSiblingContainers()) {
  356. // Server Pro, with sibling-containers active, skip checks
  357. return callback(null)
  358. }
  359. const checkVolume = (path, cb) =>
  360. fs.stat(path, function(err, stats) {
  361. if (err != null) {
  362. return cb(err)
  363. }
  364. if (!(stats != null ? stats.isDirectory() : undefined)) {
  365. return cb(DockerRunner.ERR_NOT_DIRECTORY)
  366. }
  367. return cb()
  368. })
  369. const jobs = []
  370. for (const vol in volumes) {
  371. ;(vol => jobs.push(cb => checkVolume(vol, cb)))(vol)
  372. }
  373. return async.series(jobs, callback)
  374. },
  375. _startContainer(options, volumes, attachStreamHandler, callback) {
  376. if (callback == null) {
  377. callback = function(error, output) {}
  378. }
  379. callback = _.once(callback)
  380. const { name } = options
  381. logger.log({ container_name: name }, 'starting container')
  382. const container = dockerode.getContainer(name)
  383. const createAndStartContainer = () =>
  384. dockerode.createContainer(options, function(error, container) {
  385. if (error != null) {
  386. return callback(error)
  387. }
  388. return startExistingContainer()
  389. })
  390. var startExistingContainer = () =>
  391. DockerRunner.attachToContainer(
  392. options.name,
  393. attachStreamHandler,
  394. function(error) {
  395. if (error != null) {
  396. return callback(error)
  397. }
  398. return container.start(function(error) {
  399. if (
  400. error != null &&
  401. (error != null ? error.statusCode : undefined) !== 304
  402. ) {
  403. // already running
  404. return callback(error)
  405. } else {
  406. return callback()
  407. }
  408. })
  409. }
  410. )
  411. return container.inspect(function(error, stats) {
  412. if ((error != null ? error.statusCode : undefined) === 404) {
  413. return createAndStartContainer()
  414. } else if (error != null) {
  415. logger.err(
  416. { container_name: name, error },
  417. 'unable to inspect container to start'
  418. )
  419. return callback(error)
  420. } else {
  421. return startExistingContainer()
  422. }
  423. })
  424. },
  425. attachToContainer(containerId, attachStreamHandler, attachStartCallback) {
  426. const container = dockerode.getContainer(containerId)
  427. return container.attach({ stdout: 1, stderr: 1, stream: 1 }, function(
  428. error,
  429. stream
  430. ) {
  431. if (error != null) {
  432. logger.error(
  433. { err: error, container_id: containerId },
  434. 'error attaching to container'
  435. )
  436. return attachStartCallback(error)
  437. } else {
  438. attachStartCallback()
  439. }
  440. logger.log({ container_id: containerId }, 'attached to container')
  441. const MAX_OUTPUT = 1024 * 1024 // limit output to 1MB
  442. const createStringOutputStream = function(name) {
  443. return {
  444. data: '',
  445. overflowed: false,
  446. write(data) {
  447. if (this.overflowed) {
  448. return
  449. }
  450. if (this.data.length < MAX_OUTPUT) {
  451. return (this.data += data)
  452. } else {
  453. logger.error(
  454. {
  455. container_id: containerId,
  456. length: this.data.length,
  457. maxLen: MAX_OUTPUT
  458. },
  459. `${name} exceeds max size`
  460. )
  461. this.data += `(...truncated at ${MAX_OUTPUT} chars...)`
  462. return (this.overflowed = true)
  463. }
  464. }
  465. // kill container if too much output
  466. // docker.containers.kill(containerId, () ->)
  467. }
  468. }
  469. const stdout = createStringOutputStream('stdout')
  470. const stderr = createStringOutputStream('stderr')
  471. container.modem.demuxStream(stream, stdout, stderr)
  472. stream.on('error', err =>
  473. logger.error(
  474. { err, container_id: containerId },
  475. 'error reading from container stream'
  476. )
  477. )
  478. return stream.on('end', () =>
  479. attachStreamHandler(null, { stdout: stdout.data, stderr: stderr.data })
  480. )
  481. })
  482. },
  483. waitForContainer(containerId, timeout, _callback) {
  484. if (_callback == null) {
  485. _callback = function(error, exitCode) {}
  486. }
  487. const callback = function(...args) {
  488. _callback(...Array.from(args || []))
  489. // Only call the callback once
  490. return (_callback = function() {})
  491. }
  492. const container = dockerode.getContainer(containerId)
  493. let timedOut = false
  494. const timeoutId = setTimeout(function() {
  495. timedOut = true
  496. logger.log(
  497. { container_id: containerId },
  498. 'timeout reached, killing container'
  499. )
  500. return container.kill(function() {})
  501. }, timeout)
  502. logger.log({ container_id: containerId }, 'waiting for docker container')
  503. return container.wait(function(error, res) {
  504. if (error != null) {
  505. clearTimeout(timeoutId)
  506. logger.error(
  507. { err: error, container_id: containerId },
  508. 'error waiting for container'
  509. )
  510. return callback(error)
  511. }
  512. if (timedOut) {
  513. logger.log({ containerId }, 'docker container timed out')
  514. error = DockerRunner.ERR_TIMED_OUT
  515. error.timedout = true
  516. return callback(error)
  517. } else {
  518. clearTimeout(timeoutId)
  519. logger.log(
  520. { container_id: containerId, exitCode: res.StatusCode },
  521. 'docker container returned'
  522. )
  523. return callback(null, res.StatusCode)
  524. }
  525. })
  526. },
  527. destroyContainer(containerName, containerId, shouldForce, callback) {
  528. // We want the containerName for the lock and, ideally, the
  529. // containerId to delete. There is a bug in the docker.io module
  530. // where if you delete by name and there is an error, it throws an
  531. // async exception, but if you delete by id it just does a normal
  532. // error callback. We fall back to deleting by name if no id is
  533. // supplied.
  534. if (callback == null) {
  535. callback = function(error) {}
  536. }
  537. return LockManager.runWithLock(
  538. containerName,
  539. releaseLock =>
  540. DockerRunner._destroyContainer(
  541. containerId || containerName,
  542. shouldForce,
  543. releaseLock
  544. ),
  545. callback
  546. )
  547. },
  548. _destroyContainer(containerId, shouldForce, callback) {
  549. if (callback == null) {
  550. callback = function(error) {}
  551. }
  552. logger.log({ container_id: containerId }, 'destroying docker container')
  553. const container = dockerode.getContainer(containerId)
  554. return container.remove({ force: shouldForce === true }, function(error) {
  555. if (
  556. error != null &&
  557. (error != null ? error.statusCode : undefined) === 404
  558. ) {
  559. logger.warn(
  560. { err: error, container_id: containerId },
  561. 'container not found, continuing'
  562. )
  563. error = null
  564. }
  565. if (error != null) {
  566. logger.error(
  567. { err: error, container_id: containerId },
  568. 'error destroying container'
  569. )
  570. } else {
  571. logger.log({ container_id: containerId }, 'destroyed container')
  572. }
  573. return callback(error)
  574. })
  575. },
  576. // handle expiry of docker containers
  577. MAX_CONTAINER_AGE:
  578. Settings.clsi.docker.maxContainerAge || (oneHour = 60 * 60 * 1000),
  579. examineOldContainer(container, callback) {
  580. if (callback == null) {
  581. callback = function(error, name, id, ttl) {}
  582. }
  583. const name =
  584. container.Name ||
  585. (container.Names != null ? container.Names[0] : undefined)
  586. const created = container.Created * 1000 // creation time is returned in seconds
  587. const now = Date.now()
  588. const age = now - created
  589. const maxAge = DockerRunner.MAX_CONTAINER_AGE
  590. const ttl = maxAge - age
  591. logger.log(
  592. { containerName: name, created, now, age, maxAge, ttl },
  593. 'checking whether to destroy container'
  594. )
  595. return callback(null, name, container.Id, ttl)
  596. },
  597. destroyOldContainers(callback) {
  598. if (callback == null) {
  599. callback = function(error) {}
  600. }
  601. return dockerode.listContainers({ all: true }, function(error, containers) {
  602. if (error != null) {
  603. return callback(error)
  604. }
  605. const jobs = []
  606. for (const container of Array.from(containers || [])) {
  607. ;(container =>
  608. DockerRunner.examineOldContainer(container, function(
  609. err,
  610. name,
  611. id,
  612. ttl
  613. ) {
  614. if (name.slice(0, 9) === '/project-' && ttl <= 0) {
  615. // strip the / prefix
  616. // the LockManager uses the plain container name
  617. name = name.slice(1)
  618. return jobs.push(cb =>
  619. DockerRunner.destroyContainer(name, id, false, () => cb())
  620. )
  621. }
  622. }))(container)
  623. }
  624. // Ignore errors because some containers get stuck but
  625. // will be destroyed next time
  626. return async.series(jobs, callback)
  627. })
  628. },
  629. startContainerMonitor() {
  630. logger.log(
  631. { maxAge: DockerRunner.MAX_CONTAINER_AGE },
  632. 'starting container expiry'
  633. )
  634. // guarantee only one monitor is running
  635. DockerRunner.stopContainerMonitor()
  636. // randomise the start time
  637. const randomDelay = Math.floor(Math.random() * 5 * 60 * 1000)
  638. containerMonitorTimeout = setTimeout(() => {
  639. containerMonitorInterval = setInterval(
  640. () => DockerRunner.destroyOldContainers(),
  641. (oneHour = 60 * 60 * 1000)
  642. )
  643. }, randomDelay)
  644. },
  645. stopContainerMonitor() {
  646. if (containerMonitorTimeout) {
  647. clearTimeout(containerMonitorTimeout)
  648. containerMonitorTimeout = undefined
  649. }
  650. if (containerMonitorInterval) {
  651. clearInterval(containerMonitorTimeout)
  652. containerMonitorTimeout = undefined
  653. }
  654. }
  655. }
  656. DockerRunner.startContainerMonitor()
  657. function __guard__(value, transform) {
  658. return typeof value !== 'undefined' && value !== null
  659. ? transform(value)
  660. : undefined
  661. }
  662. function __guardMethod__(obj, methodName, transform) {
  663. if (
  664. typeof obj !== 'undefined' &&
  665. obj !== null &&
  666. typeof obj[methodName] === 'function'
  667. ) {
  668. return transform(obj, methodName)
  669. } else {
  670. return undefined
  671. }
  672. }