DockerRunner.coffee 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. Settings = require "settings-sharelatex"
  2. logger = require "logger-sharelatex"
  3. Docker = require("dockerode")
  4. dockerode = new Docker()
  5. crypto = require "crypto"
  6. async = require "async"
  7. LockManager = require "./DockerLockManager"
  8. fs = require "fs"
  9. Path = require 'path'
  10. _ = require "underscore"
  11. logger.info "using docker runner"
  12. usingSiblingContainers = () ->
  13. Settings?.path?.sandboxedCompilesHostDir?
  14. module.exports = DockerRunner =
  15. ERR_NOT_DIRECTORY: new Error("not a directory")
  16. ERR_TERMINATED: new Error("terminated")
  17. ERR_EXITED: new Error("exited")
  18. ERR_TIMED_OUT: new Error("container timed out")
  19. run: (project_id, command, directory, image, timeout, environment, callback = (error, output) ->) ->
  20. if usingSiblingContainers()
  21. _newPath = Settings.path.sandboxedCompilesHostDir
  22. logger.log {path: _newPath}, "altering bind path for sibling containers"
  23. # Server Pro, example:
  24. # '/var/lib/sharelatex/data/compiles/<project-id>'
  25. # ... becomes ...
  26. # '/opt/sharelatex_data/data/compiles/<project-id>'
  27. directory = Path.join(Settings.path.sandboxedCompilesHostDir, Path.basename(directory))
  28. volumes = {}
  29. volumes[directory] = "/compile"
  30. command = (arg.toString().replace?('$COMPILE_DIR', "/compile") for arg in command)
  31. if !image?
  32. image = Settings.clsi.docker.image
  33. if Settings.texliveImageNameOveride?
  34. img = image.split("/")
  35. image = "#{Settings.texliveImageNameOveride}/#{img[2]}"
  36. options = DockerRunner._getContainerOptions(command, image, volumes, timeout, environment)
  37. fingerprint = DockerRunner._fingerprintContainer(options)
  38. options.name = name = "project-#{project_id}-#{fingerprint}"
  39. # logOptions = _.clone(options)
  40. # logOptions?.HostConfig?.SecurityOpt = "secomp used, removed in logging"
  41. logger.log project_id: project_id, "running docker container"
  42. DockerRunner._runAndWaitForContainer options, volumes, timeout, (error, output) ->
  43. if error?.message?.match("HTTP code is 500")
  44. logger.log err: error, project_id: project_id, "error running container so destroying and retrying"
  45. DockerRunner.destroyContainer name, null, true, (error) ->
  46. return callback(error) if error?
  47. DockerRunner._runAndWaitForContainer options, volumes, timeout, callback
  48. else
  49. callback(error, output)
  50. return name # pass back the container name to allow it to be killed
  51. kill: (container_id, callback = (error) ->) ->
  52. logger.log container_id: container_id, "sending kill signal to container"
  53. container = dockerode.getContainer(container_id)
  54. container.kill (error) ->
  55. if error? and error?.message?.match?(/Cannot kill container .* is not running/)
  56. logger.warn err: error, container_id: container_id, "container not running, continuing"
  57. error = null
  58. if error?
  59. logger.error err: error, container_id: container_id, "error killing container"
  60. return callback(error)
  61. else
  62. callback()
  63. _runAndWaitForContainer: (options, volumes, timeout, _callback = (error, output) ->) ->
  64. callback = (args...) ->
  65. _callback(args...)
  66. # Only call the callback once
  67. _callback = () ->
  68. name = options.name
  69. streamEnded = false
  70. containerReturned = false
  71. output = {}
  72. callbackIfFinished = () ->
  73. if streamEnded and containerReturned
  74. callback(null, output)
  75. attachStreamHandler = (error, _output) ->
  76. return callback(error) if error?
  77. output = _output
  78. streamEnded = true
  79. callbackIfFinished()
  80. DockerRunner.startContainer options, volumes, attachStreamHandler, (error, containerId) ->
  81. return callback(error) if error?
  82. DockerRunner.waitForContainer name, timeout, (error, exitCode) ->
  83. return callback(error) if error?
  84. if exitCode is 137 # exit status from kill -9
  85. err = DockerRunner.ERR_TERMINATED
  86. err.terminated = true
  87. return callback(err)
  88. if exitCode is 1 # exit status from chktex
  89. err = DockerRunner.ERR_EXITED
  90. err.code = exitCode
  91. return callback(err)
  92. containerReturned = true
  93. options?.HostConfig?.SecurityOpt = null #small log line
  94. logger.log err:err, exitCode:exitCode, options:options, "docker container has exited"
  95. callbackIfFinished()
  96. _getContainerOptions: (command, image, volumes, timeout, environment) ->
  97. timeoutInSeconds = timeout / 1000
  98. dockerVolumes = {}
  99. for hostVol, dockerVol of volumes
  100. dockerVolumes[dockerVol] = {}
  101. if volumes[hostVol].slice(-3).indexOf(":r") == -1
  102. volumes[hostVol] = "#{dockerVol}:rw"
  103. # merge settings and environment parameter
  104. env = {}
  105. for src in [Settings.clsi.docker.env, environment or {}]
  106. env[key] = value for key, value of src
  107. # set the path based on the image year
  108. if m = image.match /:([0-9]+)\.[0-9]+/
  109. year = m[1]
  110. else
  111. year = "2014"
  112. env['PATH'] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/texlive/#{year}/bin/x86_64-linux/"
  113. options =
  114. "Cmd" : command,
  115. "Image" : image
  116. "Volumes" : dockerVolumes
  117. "WorkingDir" : "/compile"
  118. "NetworkDisabled" : true
  119. "Memory" : 1024 * 1024 * 1024 * 1024 # 1 Gb
  120. "User" : Settings.clsi.docker.user
  121. "Env" : ("#{key}=#{value}" for key, value of env) # convert the environment hash to an array
  122. "HostConfig" :
  123. "Binds": ("#{hostVol}:#{dockerVol}" for hostVol, dockerVol of volumes)
  124. "LogConfig": {"Type": "none", "Config": {}}
  125. "Ulimits": [{'Name': 'cpu', 'Soft': timeoutInSeconds+5, 'Hard': timeoutInSeconds+10}]
  126. "CapDrop": "ALL"
  127. "SecurityOpt": ["no-new-privileges"]
  128. if Settings.path?.synctexBinHostPath?
  129. options["HostConfig"]["Binds"].push("#{Settings.path.synctexBinHostPath}:/opt/synctex:ro")
  130. if Settings.clsi.docker.seccomp_profile?
  131. options.HostConfig.SecurityOpt.push "seccomp=#{Settings.clsi.docker.seccomp_profile}"
  132. return options
  133. _fingerprintContainer: (containerOptions) ->
  134. # Yay, Hashing!
  135. json = JSON.stringify(containerOptions)
  136. return crypto.createHash("md5").update(json).digest("hex")
  137. startContainer: (options, volumes, attachStreamHandler, callback) ->
  138. LockManager.runWithLock options.name, (releaseLock) ->
  139. # Check that volumes exist before starting the container.
  140. # When a container is started with volume pointing to a
  141. # non-existent directory then docker creates the directory but
  142. # with root ownership.
  143. DockerRunner._checkVolumes options, volumes, (err) ->
  144. return releaseLock(err) if err?
  145. DockerRunner._startContainer options, volumes, attachStreamHandler, releaseLock
  146. , callback
  147. # Check that volumes exist and are directories
  148. _checkVolumes: (options, volumes, callback = (error, containerName) ->) ->
  149. if usingSiblingContainers()
  150. # Server Pro, with sibling-containers active, skip checks
  151. return callback(null)
  152. checkVolume = (path, cb) ->
  153. fs.stat path, (err, stats) ->
  154. return cb(err) if err?
  155. return cb(DockerRunner.ERR_NOT_DIRECTORY) if not stats?.isDirectory()
  156. cb()
  157. jobs = []
  158. for vol of volumes
  159. do (vol) ->
  160. jobs.push (cb) -> checkVolume(vol, cb)
  161. async.series jobs, callback
  162. _startContainer: (options, volumes, attachStreamHandler, callback = ((error, output) ->)) ->
  163. callback = _.once(callback)
  164. name = options.name
  165. logger.log {container_name: name}, "starting container"
  166. container = dockerode.getContainer(name)
  167. createAndStartContainer = ->
  168. dockerode.createContainer options, (error, container) ->
  169. return callback(error) if error?
  170. startExistingContainer()
  171. startExistingContainer = ->
  172. DockerRunner.attachToContainer options.name, attachStreamHandler, (error)->
  173. return callback(error) if error?
  174. container.start (error) ->
  175. if error? and error?.statusCode != 304 #already running
  176. return callback(error)
  177. else
  178. callback()
  179. container.inspect (error, stats)->
  180. if error?.statusCode == 404
  181. createAndStartContainer()
  182. else if error?
  183. logger.err {container_name: name, error:error}, "unable to inspect container to start"
  184. return callback(error)
  185. else
  186. startExistingContainer()
  187. attachToContainer: (containerId, attachStreamHandler, attachStartCallback) ->
  188. container = dockerode.getContainer(containerId)
  189. container.attach {stdout: 1, stderr: 1, stream: 1}, (error, stream) ->
  190. if error?
  191. logger.error err: error, container_id: containerId, "error attaching to container"
  192. return attachStartCallback(error)
  193. else
  194. attachStartCallback()
  195. logger.log container_id: containerId, "attached to container"
  196. MAX_OUTPUT = 1024 * 1024 # limit output to 1MB
  197. createStringOutputStream = (name) ->
  198. return {
  199. data: ""
  200. overflowed: false
  201. write: (data) ->
  202. return if @overflowed
  203. if @data.length < MAX_OUTPUT
  204. @data += data
  205. else
  206. logger.error container_id: containerId, length: @data.length, maxLen: MAX_OUTPUT, "#{name} exceeds max size"
  207. @data += "(...truncated at #{MAX_OUTPUT} chars...)"
  208. @overflowed = true
  209. # kill container if too much output
  210. # docker.containers.kill(containerId, () ->)
  211. }
  212. stdout = createStringOutputStream "stdout"
  213. stderr = createStringOutputStream "stderr"
  214. container.modem.demuxStream(stream, stdout, stderr)
  215. stream.on "error", (err) ->
  216. logger.error err: err, container_id: containerId, "error reading from container stream"
  217. stream.on "end", () ->
  218. attachStreamHandler null, {stdout: stdout.data, stderr: stderr.data}
  219. waitForContainer: (containerId, timeout, _callback = (error, exitCode) ->) ->
  220. callback = (args...) ->
  221. _callback(args...)
  222. # Only call the callback once
  223. _callback = () ->
  224. container = dockerode.getContainer(containerId)
  225. timedOut = false
  226. timeoutId = setTimeout () ->
  227. timedOut = true
  228. logger.log container_id: containerId, "timeout reached, killing container"
  229. container.kill(() ->)
  230. , timeout
  231. logger.log container_id: containerId, "waiting for docker container"
  232. container.wait (error, res) ->
  233. if error?
  234. clearTimeout timeoutId
  235. logger.error err: error, container_id: containerId, "error waiting for container"
  236. return callback(error)
  237. if timedOut
  238. logger.log containerId: containerId, "docker container timed out"
  239. error = DockerRunner.ERR_TIMED_OUT
  240. error.timedout = true
  241. callback error
  242. else
  243. clearTimeout timeoutId
  244. logger.log container_id: containerId, exitCode: res.StatusCode, "docker container returned"
  245. callback null, res.StatusCode
  246. destroyContainer: (containerName, containerId, shouldForce, callback = (error) ->) ->
  247. # We want the containerName for the lock and, ideally, the
  248. # containerId to delete. There is a bug in the docker.io module
  249. # where if you delete by name and there is an error, it throws an
  250. # async exception, but if you delete by id it just does a normal
  251. # error callback. We fall back to deleting by name if no id is
  252. # supplied.
  253. LockManager.runWithLock containerName, (releaseLock) ->
  254. DockerRunner._destroyContainer containerId or containerName, shouldForce, releaseLock
  255. , callback
  256. _destroyContainer: (containerId, shouldForce, callback = (error) ->) ->
  257. logger.log container_id: containerId, "destroying docker container"
  258. container = dockerode.getContainer(containerId)
  259. container.remove {force: shouldForce == true}, (error) ->
  260. if error? and error?.statusCode == 404
  261. logger.warn err: error, container_id: containerId, "container not found, continuing"
  262. error = null
  263. if error?
  264. logger.error err: error, container_id: containerId, "error destroying container"
  265. else
  266. logger.log container_id: containerId, "destroyed container"
  267. callback(error)
  268. # handle expiry of docker containers
  269. MAX_CONTAINER_AGE: Settings.clsi.docker.maxContainerAge or oneHour = 60 * 60 * 1000
  270. examineOldContainer: (container, callback = (error, name, id, ttl)->) ->
  271. name = container.Name or container.Names?[0]
  272. created = container.Created * 1000 # creation time is returned in seconds
  273. now = Date.now()
  274. age = now - created
  275. maxAge = DockerRunner.MAX_CONTAINER_AGE
  276. ttl = maxAge - age
  277. logger.log {containerName: name, created: created, now: now, age: age, maxAge: maxAge, ttl: ttl}, "checking whether to destroy container"
  278. callback(null, name, container.Id, ttl)
  279. destroyOldContainers: (callback = (error) ->) ->
  280. dockerode.listContainers all: true, (error, containers) ->
  281. return callback(error) if error?
  282. jobs = []
  283. for container in containers or []
  284. do (container) ->
  285. DockerRunner.examineOldContainer container, (err, name, id, ttl) ->
  286. if name.slice(0, 9) == '/project-' && ttl <= 0
  287. jobs.push (cb) ->
  288. DockerRunner.destroyContainer name, id, false, () -> cb()
  289. # Ignore errors because some containers get stuck but
  290. # will be destroyed next time
  291. async.series jobs, callback
  292. startContainerMonitor: () ->
  293. logger.log {maxAge: DockerRunner.MAX_CONTAINER_AGE}, "starting container expiry"
  294. # randomise the start time
  295. randomDelay = Math.floor(Math.random() * 5 * 60 * 1000)
  296. setTimeout () ->
  297. setInterval () ->
  298. DockerRunner.destroyOldContainers()
  299. , oneHour = 60 * 60 * 1000
  300. , randomDelay
  301. DockerRunner.startContainerMonitor()