DockerRunner.js 17 KB

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