DockerRunner.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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(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. DockerRunner._startContainer(
  282. options,
  283. volumes,
  284. attachStreamHandler,
  285. releaseLock
  286. ),
  287. callback
  288. )
  289. },
  290. // Check that volumes exist and are directories
  291. _startContainer(options, volumes, attachStreamHandler, callback) {
  292. callback = _.once(callback)
  293. const { name } = options
  294. logger.debug({ containerName: name }, 'starting container')
  295. const container = dockerode.getContainer(name)
  296. function createAndStartContainer() {
  297. dockerode.createContainer(options, (error, container) => {
  298. if (error != null) {
  299. return callback(error)
  300. }
  301. startExistingContainer()
  302. })
  303. }
  304. function startExistingContainer() {
  305. DockerRunner.attachToContainer(
  306. options.name,
  307. attachStreamHandler,
  308. error => {
  309. if (error != null) {
  310. return callback(error)
  311. }
  312. container.start(error => {
  313. if (error != null && error.statusCode !== 304) {
  314. callback(error)
  315. } else {
  316. // already running
  317. callback()
  318. }
  319. })
  320. }
  321. )
  322. }
  323. container.inspect((error, stats) => {
  324. if (error != null && error.statusCode === 404) {
  325. createAndStartContainer()
  326. } else if (error != null) {
  327. logger.err(
  328. { containerName: name, error },
  329. 'unable to inspect container to start'
  330. )
  331. callback(error)
  332. } else {
  333. startExistingContainer()
  334. }
  335. })
  336. },
  337. attachToContainer(containerId, attachStreamHandler, attachStartCallback) {
  338. const container = dockerode.getContainer(containerId)
  339. container.attach({ stdout: 1, stderr: 1, stream: 1 }, (error, stream) => {
  340. if (error != null) {
  341. logger.error(
  342. { err: error, containerId },
  343. 'error attaching to container'
  344. )
  345. return attachStartCallback(error)
  346. } else {
  347. attachStartCallback()
  348. }
  349. logger.debug({ containerId }, 'attached to container')
  350. const MAX_OUTPUT = 1024 * 1024 * 2 // limit output to 2MB
  351. function createStringOutputStream(name) {
  352. return {
  353. data: '',
  354. overflowed: false,
  355. write(data) {
  356. if (this.overflowed) {
  357. return
  358. }
  359. if (this.data.length < MAX_OUTPUT) {
  360. this.data += data
  361. } else {
  362. logger.info(
  363. {
  364. containerId,
  365. length: this.data.length,
  366. maxLen: MAX_OUTPUT,
  367. },
  368. `${name} exceeds max size`
  369. )
  370. this.data += `(...truncated at ${MAX_OUTPUT} chars...)`
  371. this.overflowed = true
  372. }
  373. },
  374. // kill container if too much output
  375. // docker.containers.kill(containerId, () ->)
  376. }
  377. }
  378. const stdout = createStringOutputStream('stdout')
  379. const stderr = createStringOutputStream('stderr')
  380. container.modem.demuxStream(stream, stdout, stderr)
  381. stream.on('error', err =>
  382. logger.error(
  383. { err, containerId },
  384. 'error reading from container stream'
  385. )
  386. )
  387. stream.on('end', () =>
  388. attachStreamHandler(null, { stdout: stdout.data, stderr: stderr.data })
  389. )
  390. })
  391. },
  392. waitForContainer(containerId, timeout, _callback) {
  393. const callback = _.once(_callback)
  394. const container = dockerode.getContainer(containerId)
  395. let timedOut = false
  396. const timeoutId = setTimeout(() => {
  397. timedOut = true
  398. logger.debug({ containerId }, 'timeout reached, killing container')
  399. container.kill(err => {
  400. logger.warn({ err, containerId }, 'failed to kill container')
  401. })
  402. }, timeout)
  403. logger.debug({ containerId }, 'waiting for docker container')
  404. container.wait((error, res) => {
  405. if (error != null) {
  406. clearTimeout(timeoutId)
  407. logger.warn({ err: error, containerId }, 'error waiting for container')
  408. return callback(error)
  409. }
  410. if (timedOut) {
  411. logger.debug({ containerId }, 'docker container timed out')
  412. error = new Error('container timed out')
  413. error.timedout = true
  414. callback(error)
  415. } else {
  416. clearTimeout(timeoutId)
  417. logger.debug(
  418. { containerId, exitCode: res.StatusCode },
  419. 'docker container returned'
  420. )
  421. callback(null, res.StatusCode)
  422. }
  423. })
  424. },
  425. destroyContainer(containerName, containerId, shouldForce, callback) {
  426. // We want the containerName for the lock and, ideally, the
  427. // containerId to delete. There is a bug in the docker.io module
  428. // where if you delete by name and there is an error, it throws an
  429. // async exception, but if you delete by id it just does a normal
  430. // error callback. We fall back to deleting by name if no id is
  431. // supplied.
  432. LockManager.runWithLock(
  433. containerName,
  434. releaseLock =>
  435. DockerRunner._destroyContainer(
  436. containerId || containerName,
  437. shouldForce,
  438. releaseLock
  439. ),
  440. callback
  441. )
  442. },
  443. _destroyContainer(containerId, shouldForce, callback) {
  444. logger.debug({ containerId }, 'destroying docker container')
  445. const container = dockerode.getContainer(containerId)
  446. container.remove({ force: shouldForce === true, v: true }, error => {
  447. if (error != null && error.statusCode === 404) {
  448. logger.warn(
  449. { err: error, containerId },
  450. 'container not found, continuing'
  451. )
  452. error = null
  453. }
  454. if (error != null) {
  455. logger.error({ err: error, containerId }, 'error destroying container')
  456. } else {
  457. logger.debug({ containerId }, 'destroyed container')
  458. }
  459. callback(error)
  460. })
  461. },
  462. // handle expiry of docker containers
  463. MAX_CONTAINER_AGE: Settings.clsi.docker.maxContainerAge || ONE_HOUR_IN_MS,
  464. examineOldContainer(container, callback) {
  465. const name = container.Name || (container.Names && container.Names[0])
  466. const created = container.Created * 1000 // creation time is returned in seconds
  467. const now = Date.now()
  468. const age = now - created
  469. const maxAge = DockerRunner.MAX_CONTAINER_AGE
  470. const ttl = maxAge - age
  471. logger.debug(
  472. { containerName: name, created, now, age, maxAge, ttl },
  473. 'checking whether to destroy container'
  474. )
  475. return { name, id: container.Id, ttl }
  476. },
  477. destroyOldContainers(callback) {
  478. dockerode.listContainers({ all: true }, (error, containers) => {
  479. if (error != null) {
  480. return callback(error)
  481. }
  482. const jobs = []
  483. for (const container of containers) {
  484. const { name, id, ttl } = DockerRunner.examineOldContainer(container)
  485. if (name.slice(0, 9) === '/project-' && ttl <= 0) {
  486. // strip the / prefix
  487. // the LockManager uses the plain container name
  488. const plainName = name.slice(1)
  489. jobs.push(cb =>
  490. DockerRunner.destroyContainer(plainName, id, false, () => cb())
  491. )
  492. }
  493. }
  494. // Ignore errors because some containers get stuck but
  495. // will be destroyed next time
  496. async.series(jobs, callback)
  497. })
  498. },
  499. startContainerMonitor() {
  500. logger.debug(
  501. { maxAge: DockerRunner.MAX_CONTAINER_AGE },
  502. 'starting container expiry'
  503. )
  504. // guarantee only one monitor is running
  505. DockerRunner.stopContainerMonitor()
  506. // randomise the start time
  507. const randomDelay = Math.floor(Math.random() * 5 * 60 * 1000)
  508. containerMonitorTimeout = setTimeout(() => {
  509. containerMonitorInterval = setInterval(
  510. () =>
  511. DockerRunner.destroyOldContainers(err => {
  512. if (err) {
  513. logger.error({ err }, 'failed to destroy old containers')
  514. }
  515. }),
  516. ONE_HOUR_IN_MS
  517. )
  518. }, randomDelay)
  519. },
  520. stopContainerMonitor() {
  521. if (containerMonitorTimeout) {
  522. clearTimeout(containerMonitorTimeout)
  523. containerMonitorTimeout = undefined
  524. }
  525. if (containerMonitorInterval) {
  526. clearInterval(containerMonitorInterval)
  527. containerMonitorInterval = undefined
  528. }
  529. },
  530. canRunSyncTeXInOutputDir() {
  531. return Boolean(Settings.path.sandboxedCompilesHostDirOutput)
  532. },
  533. }
  534. DockerRunner.startContainerMonitor()
  535. module.exports = DockerRunner
  536. module.exports.promises = {
  537. run: promisify(DockerRunner.run),
  538. kill: promisify(DockerRunner.kill),
  539. }