DockerRunner.js 20 KB

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