DockerRunnerTests.coffee 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. SandboxedModule = require('sandboxed-module')
  2. sinon = require('sinon')
  3. require('chai').should()
  4. expect = require('chai').expect
  5. require "coffee-script"
  6. modulePath = require('path').join __dirname, '../../../app/coffee/DockerRunner'
  7. Path = require "path"
  8. describe "DockerRunner", ->
  9. beforeEach ->
  10. @container = container = {}
  11. @DockerRunner = SandboxedModule.require modulePath, requires:
  12. "settings-sharelatex": @Settings =
  13. clsi: docker: {}
  14. path: {}
  15. "logger-sharelatex": @logger = {
  16. log: sinon.stub(),
  17. error: sinon.stub(),
  18. info: sinon.stub(),
  19. warn: sinon.stub()
  20. }
  21. "dockerode": class Docker
  22. getContainer: sinon.stub().returns(container)
  23. createContainer: sinon.stub().yields(null, container)
  24. listContainers: sinon.stub()
  25. "fs": @fs = { stat: sinon.stub().yields(null,{isDirectory:()->true}) }
  26. "./Metrics":
  27. Timer: class Timer
  28. done: () ->
  29. "./LockManager":
  30. runWithLock: (key, runner, callback) -> runner(callback)
  31. @Docker = Docker
  32. @getContainer = Docker::getContainer
  33. @createContainer = Docker::createContainer
  34. @listContainers = Docker::listContainers
  35. @directory = "/local/compile/directory"
  36. @mainFile = "main-file.tex"
  37. @compiler = "pdflatex"
  38. @image = "example.com/sharelatex/image:2016.2"
  39. @env = {}
  40. @callback = sinon.stub()
  41. @project_id = "project-id-123"
  42. @volumes =
  43. "/local/compile/directory": "/compile"
  44. @Settings.clsi.docker.image = @defaultImage = "default-image"
  45. @Settings.clsi.docker.env = PATH: "mock-path"
  46. describe "run", ->
  47. beforeEach (done)->
  48. @DockerRunner._getContainerOptions = sinon.stub().returns(@options = {mockoptions: "foo"})
  49. @DockerRunner._fingerprintContainer = sinon.stub().returns(@fingerprint = "fingerprint")
  50. @name = "project-#{@project_id}-#{@fingerprint}"
  51. @command = ["mock", "command", "--outdir=$COMPILE_DIR"]
  52. @command_with_dir = ["mock", "command", "--outdir=/compile"]
  53. @timeout = 42000
  54. done()
  55. describe "successfully", ->
  56. beforeEach (done)->
  57. @DockerRunner._runAndWaitForContainer = sinon.stub().callsArgWith(3, null, @output = "mock-output")
  58. @DockerRunner.run @project_id, @command, @directory, @image, @timeout, @env, (err, output)=>
  59. @callback(err, output)
  60. done()
  61. it "should generate the options for the container", ->
  62. @DockerRunner._getContainerOptions
  63. .calledWith(@command_with_dir, @image, @volumes, @timeout)
  64. .should.equal true
  65. it "should generate the fingerprint from the returned options", ->
  66. @DockerRunner._fingerprintContainer
  67. .calledWith(@options)
  68. .should.equal true
  69. it "should do the run", ->
  70. @DockerRunner._runAndWaitForContainer
  71. .calledWith(@options, @volumes, @timeout)
  72. .should.equal true
  73. it "should call the callback", ->
  74. @callback.calledWith(null, @output).should.equal true
  75. describe 'when path.sandboxedCompilesHostDir is set', ->
  76. beforeEach ->
  77. @Settings.path.sandboxedCompilesHostDir = '/some/host/dir/compiles'
  78. @directory = '/var/lib/sharelatex/data/compiles/xyz'
  79. @DockerRunner._runAndWaitForContainer = sinon.stub().callsArgWith(3, null, @output = "mock-output")
  80. @DockerRunner.run @project_id, @command, @directory, @image, @timeout, @env, @callback
  81. it 'should re-write the bind directory', ->
  82. volumes = @DockerRunner._runAndWaitForContainer.lastCall.args[1]
  83. expect(volumes).to.deep.equal {
  84. '/some/host/dir/compiles/xyz': '/compile'
  85. }
  86. it "should call the callback", ->
  87. @callback.calledWith(null, @output).should.equal true
  88. describe "when the run throws an error", ->
  89. beforeEach ->
  90. firstTime = true
  91. @output = "mock-output"
  92. @DockerRunner._runAndWaitForContainer = (options, volumes, timeout, callback = (error, output)->) =>
  93. if firstTime
  94. firstTime = false
  95. callback new Error("HTTP code is 500 which indicates error: server error")
  96. else
  97. callback(null, @output)
  98. sinon.spy @DockerRunner, "_runAndWaitForContainer"
  99. @DockerRunner.destroyContainer = sinon.stub().callsArg(3)
  100. @DockerRunner.run @project_id, @command, @directory, @image, @timeout, @env, @callback
  101. it "should do the run twice", ->
  102. @DockerRunner._runAndWaitForContainer
  103. .calledTwice.should.equal true
  104. it "should destroy the container in between", ->
  105. @DockerRunner.destroyContainer
  106. .calledWith(@name, null)
  107. .should.equal true
  108. it "should call the callback", ->
  109. @callback.calledWith(null, @output).should.equal true
  110. describe "with no image", ->
  111. beforeEach ->
  112. @DockerRunner._runAndWaitForContainer = sinon.stub().callsArgWith(3, null, @output = "mock-output")
  113. @DockerRunner.run @project_id, @command, @directory, null, @timeout, @env, @callback
  114. it "should use the default image", ->
  115. @DockerRunner._getContainerOptions
  116. .calledWith(@command_with_dir, @defaultImage, @volumes, @timeout)
  117. .should.equal true
  118. describe "with image override", ->
  119. beforeEach ->
  120. @Settings.texliveImageNameOveride = "overrideimage.com/something"
  121. @DockerRunner._runAndWaitForContainer = sinon.stub().callsArgWith(3, null, @output = "mock-output")
  122. @DockerRunner.run @project_id, @command, @directory, @image, @timeout, @env, @callback
  123. it "should use the override and keep the tag", ->
  124. image = @DockerRunner._getContainerOptions.args[0][1]
  125. image.should.equal "overrideimage.com/something/image:2016.2"
  126. describe "_runAndWaitForContainer", ->
  127. beforeEach ->
  128. @options = {mockoptions: "foo", name: @name = "mock-name"}
  129. @DockerRunner.startContainer = (options, volumes, attachStreamHandler, callback) =>
  130. attachStreamHandler(null, @output = "mock-output")
  131. callback(null, @containerId = "container-id")
  132. sinon.spy @DockerRunner, "startContainer"
  133. @DockerRunner.waitForContainer = sinon.stub().callsArgWith(2, null, @exitCode = 42)
  134. @DockerRunner._runAndWaitForContainer @options, @volumes, @timeout, @callback
  135. it "should create/start the container", ->
  136. @DockerRunner.startContainer
  137. .calledWith(@options, @volumes)
  138. .should.equal true
  139. it "should wait for the container to finish", ->
  140. @DockerRunner.waitForContainer
  141. .calledWith(@name, @timeout)
  142. .should.equal true
  143. it "should call the callback with the output", ->
  144. @callback.calledWith(null, @output).should.equal true
  145. describe "startContainer", ->
  146. beforeEach ->
  147. @attachStreamHandler = sinon.stub()
  148. @attachStreamHandler.cock = true
  149. @options = {mockoptions: "foo", name: "mock-name"}
  150. @container.inspect = sinon.stub().callsArgWith(0)
  151. @DockerRunner.attachToContainer = (containerId, attachStreamHandler, cb)=>
  152. attachStreamHandler()
  153. cb()
  154. sinon.spy @DockerRunner, "attachToContainer"
  155. describe "when the container exists", ->
  156. beforeEach ->
  157. @container.inspect = sinon.stub().callsArgWith(0)
  158. @container.start = sinon.stub().yields()
  159. @DockerRunner.startContainer @options, @volumes, @callback, ->
  160. it "should start the container with the given name", ->
  161. @getContainer
  162. .calledWith(@options.name)
  163. .should.equal true
  164. @container.start
  165. .called
  166. .should.equal true
  167. it "should not try to create the container", ->
  168. @createContainer.called.should.equal false
  169. it "should attach to the container", ->
  170. @DockerRunner.attachToContainer.called.should.equal true
  171. it "should call the callback", ->
  172. @callback.called.should.equal true
  173. it "should attach before the container starts", ->
  174. sinon.assert.callOrder(@DockerRunner.attachToContainer, @container.start)
  175. describe "when the container does not exist", ->
  176. beforeEach ()->
  177. exists = false
  178. @container.start = sinon.stub().yields()
  179. @container.inspect = sinon.stub().callsArgWith(0, {statusCode:404})
  180. @DockerRunner.startContainer @options, @volumes, @attachStreamHandler, @callback
  181. it "should create the container", ->
  182. @createContainer
  183. .calledWith(@options)
  184. .should.equal true
  185. it "should call the callback and stream handler", ->
  186. @attachStreamHandler.called.should.equal true
  187. @callback.called.should.equal true
  188. it "should attach to the container", ->
  189. @DockerRunner.attachToContainer.called.should.equal true
  190. it "should attach before the container starts", ->
  191. sinon.assert.callOrder(@DockerRunner.attachToContainer, @container.start)
  192. describe "when the container is already running", ->
  193. beforeEach ->
  194. error = new Error("HTTP code is 304 which indicates error: server error - start: Cannot start container #{@name}: The container MOCKID is already running.")
  195. error.statusCode = 304
  196. @container.start = sinon.stub().yields(error)
  197. @container.inspect = sinon.stub().callsArgWith(0)
  198. @DockerRunner.startContainer @options, @volumes, @attachStreamHandler, @callback
  199. it "should not try to create the container", ->
  200. @createContainer.called.should.equal false
  201. it "should call the callback and stream handler without an error", ->
  202. @attachStreamHandler.called.should.equal true
  203. @callback.called.should.equal true
  204. describe "when a volume does not exist", ->
  205. beforeEach ()->
  206. @fs.stat = sinon.stub().yields(new Error("no such path"))
  207. @DockerRunner.startContainer @options, @volumes, @attachStreamHandler, @callback
  208. it "should not try to create the container", ->
  209. @createContainer.called.should.equal false
  210. it "should call the callback with an error", ->
  211. @callback.calledWith(new Error()).should.equal true
  212. describe "when a volume exists but is not a directory", ->
  213. beforeEach ->
  214. @fs.stat = sinon.stub().yields(null, {isDirectory: () -> return false})
  215. @DockerRunner.startContainer @options, @volumes, @attachStreamHandler, @callback
  216. it "should not try to create the container", ->
  217. @createContainer.called.should.equal false
  218. it "should call the callback with an error", ->
  219. @callback.calledWith(new Error()).should.equal true
  220. describe "when a volume does not exist, but sibling-containers are used", ->
  221. beforeEach ->
  222. @fs.stat = sinon.stub().yields(new Error("no such path"))
  223. @Settings.path.sandboxedCompilesHostDir = '/some/path'
  224. @container.start = sinon.stub().yields()
  225. @DockerRunner.startContainer @options, @volumes, @callback
  226. afterEach ->
  227. delete @Settings.path.sandboxedCompilesHostDir
  228. it "should start the container with the given name", ->
  229. @getContainer
  230. .calledWith(@options.name)
  231. .should.equal true
  232. @container.start
  233. .called
  234. .should.equal true
  235. it "should not try to create the container", ->
  236. @createContainer.called.should.equal false
  237. it "should call the callback", ->
  238. @callback.called.should.equal true
  239. @callback.calledWith(new Error()).should.equal false
  240. describe "when the container tries to be created, but already has been (race condition)", ->
  241. describe "waitForContainer", ->
  242. beforeEach ->
  243. @containerId = "container-id"
  244. @timeout = 5000
  245. @container.wait = sinon.stub().yields(null, StatusCode: @statusCode = 42)
  246. @container.kill = sinon.stub().yields()
  247. describe "when the container returns in time", ->
  248. beforeEach ->
  249. @DockerRunner.waitForContainer @containerId, @timeout, @callback
  250. it "should wait for the container", ->
  251. @getContainer
  252. .calledWith(@containerId)
  253. .should.equal true
  254. @container.wait
  255. .called
  256. .should.equal true
  257. it "should call the callback with the exit", ->
  258. @callback
  259. .calledWith(null, @statusCode)
  260. .should.equal true
  261. describe "when the container does not return before the timeout", ->
  262. beforeEach (done) ->
  263. @container.wait = (callback = (error, exitCode) ->) ->
  264. setTimeout () ->
  265. callback(null, StatusCode: 42)
  266. , 100
  267. @timeout = 5
  268. @DockerRunner.waitForContainer @containerId, @timeout, (args...) =>
  269. @callback(args...)
  270. done()
  271. it "should call kill on the container", ->
  272. @getContainer
  273. .calledWith(@containerId)
  274. .should.equal true
  275. @container.kill
  276. .called
  277. .should.equal true
  278. it "should call the callback with an error", ->
  279. error = new Error("container timed out")
  280. error.timedout = true
  281. @callback
  282. .calledWith(error)
  283. .should.equal true
  284. describe "destroyOldContainers", ->
  285. beforeEach (done) ->
  286. oneHourInSeconds = 60 * 60
  287. oneHourInMilliseconds = oneHourInSeconds * 1000
  288. nowInSeconds = Date.now()/1000
  289. @containers = [{
  290. Name: "/project-old-container-name"
  291. Id: "old-container-id"
  292. Created: nowInSeconds - oneHourInSeconds - 100
  293. }, {
  294. Name: "/project-new-container-name"
  295. Id: "new-container-id"
  296. Created: nowInSeconds - oneHourInSeconds + 100
  297. }, {
  298. Name: "/totally-not-a-project-container"
  299. Id: "some-random-id"
  300. Created: nowInSeconds - (2 * oneHourInSeconds )
  301. }]
  302. @DockerRunner.MAX_CONTAINER_AGE = oneHourInMilliseconds
  303. @listContainers.callsArgWith(1, null, @containers)
  304. @DockerRunner.destroyContainer = sinon.stub().callsArg(3)
  305. @DockerRunner.destroyOldContainers (error) =>
  306. @callback(error)
  307. done()
  308. it "should list all containers", ->
  309. @listContainers
  310. .calledWith(all: true)
  311. .should.equal true
  312. it "should destroy old containers", ->
  313. @DockerRunner.destroyContainer
  314. .callCount
  315. .should.equal 1
  316. @DockerRunner.destroyContainer
  317. .calledWith("/project-old-container-name", "old-container-id")
  318. .should.equal true
  319. it "should not destroy new containers", ->
  320. @DockerRunner.destroyContainer
  321. .calledWith("/project-new-container-name", "new-container-id")
  322. .should.equal false
  323. it "should not destroy non-project containers", ->
  324. @DockerRunner.destroyContainer
  325. .calledWith("/totally-not-a-project-container", "some-random-id")
  326. .should.equal false
  327. it "should callback the callback", ->
  328. @callback.called.should.equal true
  329. describe '_destroyContainer', ->
  330. beforeEach ->
  331. @containerId = 'some_id'
  332. @fakeContainer =
  333. remove: sinon.stub().callsArgWith(1, null)
  334. @Docker::getContainer = sinon.stub().returns(@fakeContainer)
  335. it 'should get the container', (done) ->
  336. @DockerRunner._destroyContainer @containerId, false, (err) =>
  337. @Docker::getContainer.callCount.should.equal 1
  338. @Docker::getContainer.calledWith(@containerId).should.equal true
  339. done()
  340. it 'should try to force-destroy the container when shouldForce=true', (done) ->
  341. @DockerRunner._destroyContainer @containerId, true, (err) =>
  342. @fakeContainer.remove.callCount.should.equal 1
  343. @fakeContainer.remove.calledWith({force: true}).should.equal true
  344. done()
  345. it 'should not try to force-destroy the container when shouldForce=false', (done) ->
  346. @DockerRunner._destroyContainer @containerId, false, (err) =>
  347. @fakeContainer.remove.callCount.should.equal 1
  348. @fakeContainer.remove.calledWith({force: false}).should.equal true
  349. done()
  350. it 'should not produce an error', (done) ->
  351. @DockerRunner._destroyContainer @containerId, false, (err) =>
  352. expect(err).to.equal null
  353. done()
  354. describe 'when the container is already gone', ->
  355. beforeEach ->
  356. @fakeError = new Error('woops')
  357. @fakeError.statusCode = 404
  358. @fakeContainer =
  359. remove: sinon.stub().callsArgWith(1, @fakeError)
  360. @Docker::getContainer = sinon.stub().returns(@fakeContainer)
  361. it 'should not produce an error', (done) ->
  362. @DockerRunner._destroyContainer @containerId, false, (err) =>
  363. expect(err).to.equal null
  364. done()
  365. describe 'when container.destroy produces an error', (done) ->
  366. beforeEach ->
  367. @fakeError = new Error('woops')
  368. @fakeError.statusCode = 500
  369. @fakeContainer =
  370. remove: sinon.stub().callsArgWith(1, @fakeError)
  371. @Docker::getContainer = sinon.stub().returns(@fakeContainer)
  372. it 'should produce an error', (done) ->
  373. @DockerRunner._destroyContainer @containerId, false, (err) =>
  374. expect(err).to.not.equal null
  375. expect(err).to.equal @fakeError
  376. done()
  377. describe 'kill', ->
  378. beforeEach ->
  379. @containerId = 'some_id'
  380. @fakeContainer =
  381. kill: sinon.stub().callsArgWith(0, null)
  382. @Docker::getContainer = sinon.stub().returns(@fakeContainer)
  383. it 'should get the container', (done) ->
  384. @DockerRunner.kill @containerId, (err) =>
  385. @Docker::getContainer.callCount.should.equal 1
  386. @Docker::getContainer.calledWith(@containerId).should.equal true
  387. done()
  388. it 'should try to force-destroy the container', (done) ->
  389. @DockerRunner.kill @containerId, (err) =>
  390. @fakeContainer.kill.callCount.should.equal 1
  391. done()
  392. it 'should not produce an error', (done) ->
  393. @DockerRunner.kill @containerId, (err) =>
  394. expect(err).to.equal undefined
  395. done()
  396. describe 'when the container is not actually running', ->
  397. beforeEach ->
  398. @fakeError = new Error('woops')
  399. @fakeError.statusCode = 500
  400. @fakeError.message = 'Cannot kill container <whatever> is not running'
  401. @fakeContainer =
  402. kill: sinon.stub().callsArgWith(0, @fakeError)
  403. @Docker::getContainer = sinon.stub().returns(@fakeContainer)
  404. it 'should not produce an error', (done) ->
  405. @DockerRunner.kill @containerId, (err) =>
  406. expect(err).to.equal undefined
  407. done()
  408. describe 'when container.kill produces a legitimate error', (done) ->
  409. beforeEach ->
  410. @fakeError = new Error('woops')
  411. @fakeError.statusCode = 500
  412. @fakeError.message = 'Totally legitimate reason to throw an error'
  413. @fakeContainer =
  414. kill: sinon.stub().callsArgWith(0, @fakeError)
  415. @Docker::getContainer = sinon.stub().returns(@fakeContainer)
  416. it 'should produce an error', (done) ->
  417. @DockerRunner.kill @containerId, (err) =>
  418. expect(err).to.not.equal undefined
  419. expect(err).to.equal @fakeError
  420. done()