DockerRunner.js 21 KB

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