DockerRunner.js 17 KB

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