DockerRunner.js 20 KB

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