DockerRunner.js 17 KB

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