DockerRunner.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. const { promisify } = require('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('crypto')
  7. const async = require('async')
  8. const LockManager = require('./DockerLockManager')
  9. const fs = require('fs')
  10. const Path = require('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/sharelatex/data/compiles/<project-id>'
  42. // ... becomes ...
  43. // '/opt/sharelatex_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. const options = DockerRunner._getContainerOptions(
  67. command,
  68. image,
  69. volumes,
  70. timeout,
  71. environment,
  72. compileGroup
  73. )
  74. const fingerprint = DockerRunner._fingerprintContainer(options)
  75. const name = `project-${projectId}-${fingerprint}`
  76. options.name = name
  77. // logOptions = _.clone(options)
  78. // logOptions?.HostConfig?.SecurityOpt = "secomp used, removed in logging"
  79. logger.debug({ projectId }, 'running docker container')
  80. DockerRunner._runAndWaitForContainer(
  81. options,
  82. volumes,
  83. timeout,
  84. (error, output) => {
  85. if (error && error.statusCode === 500) {
  86. logger.debug(
  87. { err: error, projectId },
  88. 'error running container so destroying and retrying'
  89. )
  90. DockerRunner.destroyContainer(name, null, true, error => {
  91. if (error != null) {
  92. return callback(error)
  93. }
  94. DockerRunner._runAndWaitForContainer(
  95. options,
  96. volumes,
  97. timeout,
  98. callback
  99. )
  100. })
  101. } else {
  102. callback(error, output)
  103. }
  104. }
  105. )
  106. // pass back the container name to allow it to be killed
  107. return name
  108. },
  109. kill(containerId, callback) {
  110. logger.debug({ containerId }, 'sending kill signal to container')
  111. const container = dockerode.getContainer(containerId)
  112. container.kill(error => {
  113. if (
  114. error != null &&
  115. error.message != null &&
  116. error.message.match(/Cannot kill container .* is not running/)
  117. ) {
  118. logger.warn(
  119. { err: error, containerId },
  120. 'container not running, continuing'
  121. )
  122. error = null
  123. }
  124. if (error != null) {
  125. logger.error({ err: error, containerId }, 'error killing container')
  126. callback(error)
  127. } else {
  128. callback()
  129. }
  130. })
  131. },
  132. _runAndWaitForContainer(options, volumes, timeout, _callback) {
  133. const callback = _.once(_callback)
  134. const { name } = options
  135. let streamEnded = false
  136. let containerReturned = false
  137. let output = {}
  138. function callbackIfFinished() {
  139. if (streamEnded && containerReturned) {
  140. callback(null, output)
  141. }
  142. }
  143. function attachStreamHandler(error, _output) {
  144. if (error != null) {
  145. return callback(error)
  146. }
  147. output = _output
  148. streamEnded = true
  149. callbackIfFinished()
  150. }
  151. DockerRunner.startContainer(
  152. options,
  153. volumes,
  154. attachStreamHandler,
  155. (error, containerId) => {
  156. if (error != null) {
  157. return callback(error)
  158. }
  159. DockerRunner.waitForContainer(name, timeout, (error, exitCode) => {
  160. if (error != null) {
  161. return callback(error)
  162. }
  163. if (exitCode === 137) {
  164. // exit status from kill -9
  165. const err = new Error('terminated')
  166. err.terminated = true
  167. return callback(err)
  168. }
  169. if (exitCode === 1) {
  170. // exit status from chktex
  171. const err = new Error('exited')
  172. err.code = exitCode
  173. return callback(err)
  174. }
  175. containerReturned = true
  176. if (options != null && options.HostConfig != null) {
  177. options.HostConfig.SecurityOpt = null
  178. }
  179. logger.debug({ exitCode, options }, 'docker container has exited')
  180. callbackIfFinished()
  181. })
  182. }
  183. )
  184. },
  185. _getContainerOptions(
  186. command,
  187. image,
  188. volumes,
  189. timeout,
  190. environment,
  191. compileGroup
  192. ) {
  193. const timeoutInSeconds = timeout / 1000
  194. const dockerVolumes = {}
  195. for (const hostVol in volumes) {
  196. const dockerVol = volumes[hostVol]
  197. dockerVolumes[dockerVol] = {}
  198. if (volumes[hostVol].slice(-3).indexOf(':r') === -1) {
  199. volumes[hostVol] = `${dockerVol}:rw`
  200. }
  201. }
  202. // merge settings and environment parameter
  203. const env = {}
  204. for (const src of [Settings.clsi.docker.env, environment || {}]) {
  205. for (const key in src) {
  206. const value = src[key]
  207. env[key] = value
  208. }
  209. }
  210. // set the path based on the image year
  211. const match = image.match(/:([0-9]+)\.[0-9]+/)
  212. const year = match ? match[1] : '2014'
  213. env.PATH = `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/texlive/${year}/bin/x86_64-linux/`
  214. const options = {
  215. Cmd: command,
  216. Image: image,
  217. Volumes: dockerVolumes,
  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. // Check that volumes exist before starting the container.
  279. // When a container is started with volume pointing to a
  280. // non-existent directory then docker creates the directory but
  281. // with root ownership.
  282. DockerRunner._checkVolumes(options, volumes, err => {
  283. if (err != null) {
  284. return releaseLock(err)
  285. }
  286. DockerRunner._startContainer(
  287. options,
  288. volumes,
  289. attachStreamHandler,
  290. releaseLock
  291. )
  292. }),
  293. callback
  294. )
  295. },
  296. // Check that volumes exist and are directories
  297. _checkVolumes(options, volumes, callback) {
  298. if (usingSiblingContainers()) {
  299. // Server Pro, with sibling-containers active, skip checks
  300. return callback(null)
  301. }
  302. const checkVolume = (path, cb) =>
  303. fs.stat(path, (err, stats) => {
  304. if (err != null) {
  305. return cb(err)
  306. }
  307. if (!stats.isDirectory()) {
  308. return cb(new Error('not a directory'))
  309. }
  310. cb()
  311. })
  312. const jobs = []
  313. for (const vol in volumes) {
  314. jobs.push(cb => checkVolume(vol, cb))
  315. }
  316. async.series(jobs, callback)
  317. },
  318. _startContainer(options, volumes, attachStreamHandler, callback) {
  319. callback = _.once(callback)
  320. const { name } = options
  321. logger.debug({ containerName: name }, 'starting container')
  322. const container = dockerode.getContainer(name)
  323. function createAndStartContainer() {
  324. dockerode.createContainer(options, (error, container) => {
  325. if (error != null) {
  326. return callback(error)
  327. }
  328. startExistingContainer()
  329. })
  330. }
  331. function startExistingContainer() {
  332. DockerRunner.attachToContainer(
  333. options.name,
  334. attachStreamHandler,
  335. error => {
  336. if (error != null) {
  337. return callback(error)
  338. }
  339. container.start(error => {
  340. if (error != null && error.statusCode !== 304) {
  341. callback(error)
  342. } else {
  343. // already running
  344. callback()
  345. }
  346. })
  347. }
  348. )
  349. }
  350. container.inspect((error, stats) => {
  351. if (error != null && error.statusCode === 404) {
  352. createAndStartContainer()
  353. } else if (error != null) {
  354. logger.err(
  355. { containerName: name, error },
  356. 'unable to inspect container to start'
  357. )
  358. callback(error)
  359. } else {
  360. startExistingContainer()
  361. }
  362. })
  363. },
  364. attachToContainer(containerId, attachStreamHandler, attachStartCallback) {
  365. const container = dockerode.getContainer(containerId)
  366. container.attach({ stdout: 1, stderr: 1, stream: 1 }, (error, stream) => {
  367. if (error != null) {
  368. logger.error(
  369. { err: error, containerId },
  370. 'error attaching to container'
  371. )
  372. return attachStartCallback(error)
  373. } else {
  374. attachStartCallback()
  375. }
  376. logger.debug({ containerId }, 'attached to container')
  377. const MAX_OUTPUT = 1024 * 1024 * 2 // limit output to 2MB
  378. function createStringOutputStream(name) {
  379. return {
  380. data: '',
  381. overflowed: false,
  382. write(data) {
  383. if (this.overflowed) {
  384. return
  385. }
  386. if (this.data.length < MAX_OUTPUT) {
  387. this.data += data
  388. } else {
  389. logger.info(
  390. {
  391. containerId,
  392. length: this.data.length,
  393. maxLen: MAX_OUTPUT,
  394. },
  395. `${name} exceeds max size`
  396. )
  397. this.data += `(...truncated at ${MAX_OUTPUT} chars...)`
  398. this.overflowed = true
  399. }
  400. },
  401. // kill container if too much output
  402. // docker.containers.kill(containerId, () ->)
  403. }
  404. }
  405. const stdout = createStringOutputStream('stdout')
  406. const stderr = createStringOutputStream('stderr')
  407. container.modem.demuxStream(stream, stdout, stderr)
  408. stream.on('error', err =>
  409. logger.error(
  410. { err, containerId },
  411. 'error reading from container stream'
  412. )
  413. )
  414. stream.on('end', () =>
  415. attachStreamHandler(null, { stdout: stdout.data, stderr: stderr.data })
  416. )
  417. })
  418. },
  419. waitForContainer(containerId, timeout, _callback) {
  420. const callback = _.once(_callback)
  421. const container = dockerode.getContainer(containerId)
  422. let timedOut = false
  423. const timeoutId = setTimeout(() => {
  424. timedOut = true
  425. logger.debug({ containerId }, 'timeout reached, killing container')
  426. container.kill(err => {
  427. logger.warn({ err, containerId }, 'failed to kill container')
  428. })
  429. }, timeout)
  430. logger.debug({ containerId }, 'waiting for docker container')
  431. container.wait((error, res) => {
  432. if (error != null) {
  433. clearTimeout(timeoutId)
  434. logger.warn({ err: error, containerId }, 'error waiting for container')
  435. return callback(error)
  436. }
  437. if (timedOut) {
  438. logger.debug({ containerId }, 'docker container timed out')
  439. error = new Error('container timed out')
  440. error.timedout = true
  441. callback(error)
  442. } else {
  443. clearTimeout(timeoutId)
  444. logger.debug(
  445. { containerId, exitCode: res.StatusCode },
  446. 'docker container returned'
  447. )
  448. callback(null, res.StatusCode)
  449. }
  450. })
  451. },
  452. destroyContainer(containerName, containerId, shouldForce, callback) {
  453. // We want the containerName for the lock and, ideally, the
  454. // containerId to delete. There is a bug in the docker.io module
  455. // where if you delete by name and there is an error, it throws an
  456. // async exception, but if you delete by id it just does a normal
  457. // error callback. We fall back to deleting by name if no id is
  458. // supplied.
  459. LockManager.runWithLock(
  460. containerName,
  461. releaseLock =>
  462. DockerRunner._destroyContainer(
  463. containerId || containerName,
  464. shouldForce,
  465. releaseLock
  466. ),
  467. callback
  468. )
  469. },
  470. _destroyContainer(containerId, shouldForce, callback) {
  471. logger.debug({ containerId }, 'destroying docker container')
  472. const container = dockerode.getContainer(containerId)
  473. container.remove({ force: shouldForce === true, v: true }, error => {
  474. if (error != null && error.statusCode === 404) {
  475. logger.warn(
  476. { err: error, containerId },
  477. 'container not found, continuing'
  478. )
  479. error = null
  480. }
  481. if (error != null) {
  482. logger.error({ err: error, containerId }, 'error destroying container')
  483. } else {
  484. logger.debug({ containerId }, 'destroyed container')
  485. }
  486. callback(error)
  487. })
  488. },
  489. // handle expiry of docker containers
  490. MAX_CONTAINER_AGE: Settings.clsi.docker.maxContainerAge || ONE_HOUR_IN_MS,
  491. examineOldContainer(container, callback) {
  492. const name = container.Name || (container.Names && container.Names[0])
  493. const created = container.Created * 1000 // creation time is returned in seconds
  494. const now = Date.now()
  495. const age = now - created
  496. const maxAge = DockerRunner.MAX_CONTAINER_AGE
  497. const ttl = maxAge - age
  498. logger.debug(
  499. { containerName: name, created, now, age, maxAge, ttl },
  500. 'checking whether to destroy container'
  501. )
  502. return { name, id: container.Id, ttl }
  503. },
  504. destroyOldContainers(callback) {
  505. dockerode.listContainers({ all: true }, (error, containers) => {
  506. if (error != null) {
  507. return callback(error)
  508. }
  509. const jobs = []
  510. for (const container of containers) {
  511. const { name, id, ttl } = DockerRunner.examineOldContainer(container)
  512. if (name.slice(0, 9) === '/project-' && ttl <= 0) {
  513. // strip the / prefix
  514. // the LockManager uses the plain container name
  515. const plainName = name.slice(1)
  516. jobs.push(cb =>
  517. DockerRunner.destroyContainer(plainName, id, false, () => cb())
  518. )
  519. }
  520. }
  521. // Ignore errors because some containers get stuck but
  522. // will be destroyed next time
  523. async.series(jobs, callback)
  524. })
  525. },
  526. startContainerMonitor() {
  527. logger.debug(
  528. { maxAge: DockerRunner.MAX_CONTAINER_AGE },
  529. 'starting container expiry'
  530. )
  531. // guarantee only one monitor is running
  532. DockerRunner.stopContainerMonitor()
  533. // randomise the start time
  534. const randomDelay = Math.floor(Math.random() * 5 * 60 * 1000)
  535. containerMonitorTimeout = setTimeout(() => {
  536. containerMonitorInterval = setInterval(
  537. () =>
  538. DockerRunner.destroyOldContainers(err => {
  539. if (err) {
  540. logger.error({ err }, 'failed to destroy old containers')
  541. }
  542. }),
  543. ONE_HOUR_IN_MS
  544. )
  545. }, randomDelay)
  546. },
  547. stopContainerMonitor() {
  548. if (containerMonitorTimeout) {
  549. clearTimeout(containerMonitorTimeout)
  550. containerMonitorTimeout = undefined
  551. }
  552. if (containerMonitorInterval) {
  553. clearInterval(containerMonitorInterval)
  554. containerMonitorInterval = undefined
  555. }
  556. },
  557. }
  558. DockerRunner.startContainerMonitor()
  559. module.exports = DockerRunner
  560. module.exports.promises = {
  561. run: promisify(DockerRunner.run),
  562. kill: promisify(DockerRunner.kill),
  563. }