DockerRunner.js 18 KB

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