17774: Ignore addition of zero/default values to mounts when frozen.
[arvados.git] / services / api / test / unit / container_request_test.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'test_helper'
6 require 'helpers/container_test_helper'
7 require 'helpers/docker_migration_helper'
8 require 'arvados/collection'
9
10 class ContainerRequestTest < ActiveSupport::TestCase
11   include DockerMigrationHelper
12   include DbCurrentTime
13   include ContainerTestHelper
14
15   def with_container_auth(ctr)
16     auth_was = Thread.current[:api_client_authorization]
17     Thread.current[:api_client_authorization] = ApiClientAuthorization.find_by_uuid(ctr.auth_uuid)
18     begin
19       yield
20     ensure
21       Thread.current[:api_client_authorization] = auth_was
22     end
23   end
24
25   def lock_and_run(ctr)
26       act_as_system_user do
27         ctr.update_attributes!(state: Container::Locked)
28         ctr.update_attributes!(state: Container::Running)
29       end
30   end
31
32   def create_minimal_req! attrs={}
33     defaults = {
34       command: ["echo", "foo"],
35       container_image: links(:docker_image_collection_tag).name,
36       cwd: "/tmp",
37       environment: {},
38       mounts: {"/out" => {"kind" => "tmp", "capacity" => 1000000}},
39       output_path: "/out",
40       runtime_constraints: {"vcpus" => 1, "ram" => 2},
41       name: "foo",
42       description: "bar",
43     }
44     cr = ContainerRequest.create!(defaults.merge(attrs))
45     cr.reload
46     return cr
47   end
48
49   def check_bogus_states cr
50     [nil, "Flubber"].each do |state|
51       assert_raises(ActiveRecord::RecordInvalid) do
52         cr.state = state
53         cr.save!
54       end
55       cr.reload
56     end
57   end
58
59   test "Container request create" do
60     set_user_from_auth :active
61     cr = create_minimal_req!
62
63     assert_nil cr.container_uuid
64     assert_equal 0, cr.priority
65
66     check_bogus_states cr
67
68     # Ensure we can modify all attributes
69     cr.command = ["echo", "foo3"]
70     cr.container_image = "img3"
71     cr.cwd = "/tmp3"
72     cr.environment = {"BUP" => "BOP"}
73     cr.mounts = {"BAR" => {"kind" => "BAZ"}}
74     cr.output_path = "/tmp4"
75     cr.priority = 2
76     cr.runtime_constraints = {"vcpus" => 4}
77     cr.name = "foo3"
78     cr.description = "bar3"
79     cr.save!
80
81     assert_nil cr.container_uuid
82   end
83
84   [
85     {"runtime_constraints" => {"vcpus" => 1}},
86     {"runtime_constraints" => {"vcpus" => 1, "ram" => nil}},
87     {"runtime_constraints" => {"vcpus" => 0, "ram" => 123}},
88     {"runtime_constraints" => {"vcpus" => "1", "ram" => "123"}},
89     {"mounts" => {"FOO" => "BAR"}},
90     {"mounts" => {"FOO" => {}}},
91     {"mounts" => {"FOO" => {"kind" => "tmp", "capacity" => 42.222}}},
92     {"command" => ["echo", 55]},
93     {"environment" => {"FOO" => 55}}
94   ].each do |value|
95     test "Create with invalid #{value}" do
96       set_user_from_auth :active
97       assert_raises(ActiveRecord::RecordInvalid) do
98         cr = create_minimal_req!({state: "Committed",
99                priority: 1}.merge(value))
100         cr.save!
101       end
102     end
103
104     test "Update with invalid #{value}" do
105       set_user_from_auth :active
106       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
107       cr.save!
108       assert_raises(ActiveRecord::RecordInvalid) do
109         cr = ContainerRequest.find_by_uuid cr.uuid
110         cr.update_attributes!({state: "Committed",
111                                priority: 1}.merge(value))
112       end
113     end
114   end
115
116   test "Update from fixture" do
117     set_user_from_auth :active
118     cr = ContainerRequest.find_by_uuid(container_requests(:running).uuid)
119     cr.update_attributes!(description: "New description")
120     assert_equal "New description", cr.description
121   end
122
123   test "Update with valid runtime constraints" do
124       set_user_from_auth :active
125       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
126       cr.save!
127       cr = ContainerRequest.find_by_uuid cr.uuid
128       cr.update_attributes!(state: "Committed",
129                             runtime_constraints: {"vcpus" => 1, "ram" => 23})
130       assert_not_nil cr.container_uuid
131   end
132
133   test "Container request priority must be non-nil" do
134     set_user_from_auth :active
135     cr = create_minimal_req!
136     cr.priority = nil
137     cr.state = "Committed"
138     assert_raises(ActiveRecord::RecordInvalid) do
139       cr.save!
140     end
141   end
142
143   test "Container request commit" do
144     set_user_from_auth :active
145     cr = create_minimal_req!(runtime_constraints: {"vcpus" => 2, "ram" => 30})
146
147     assert_nil cr.container_uuid
148
149     cr.reload
150     cr.state = "Committed"
151     cr.priority = 1
152     cr.save!
153
154     cr.reload
155
156     assert ({"vcpus" => 2, "ram" => 30}.to_a - cr.runtime_constraints.to_a).empty?
157
158     assert_not_nil cr.container_uuid
159     c = Container.find_by_uuid cr.container_uuid
160     assert_not_nil c
161     assert_equal ["echo", "foo"], c.command
162     assert_equal collections(:docker_image).portable_data_hash, c.container_image
163     assert_equal "/tmp", c.cwd
164     assert_equal({}, c.environment)
165     assert_equal({"/out" => {"kind"=>"tmp", "capacity"=>1000000}}, c.mounts)
166     assert_equal "/out", c.output_path
167     assert ({"keep_cache_ram"=>268435456, "vcpus" => 2, "ram" => 30}.to_a - c.runtime_constraints.to_a).empty?
168     assert_operator 0, :<, c.priority
169
170     assert_raises(ActiveRecord::RecordInvalid) do
171       cr.priority = nil
172       cr.save!
173     end
174
175     cr.priority = 0
176     cr.save!
177
178     cr.reload
179     c.reload
180     assert_equal 0, cr.priority
181     assert_equal 0, c.priority
182   end
183
184   test "Independent container requests" do
185     set_user_from_auth :active
186     cr1 = create_minimal_req!(command: ["foo", "1"], priority: 5, state: "Committed")
187     cr2 = create_minimal_req!(command: ["foo", "2"], priority: 10, state: "Committed")
188
189     c1 = Container.find_by_uuid cr1.container_uuid
190     assert_operator 0, :<, c1.priority
191
192     c2 = Container.find_by_uuid cr2.container_uuid
193     assert_operator c1.priority, :<, c2.priority
194     c2priority_was = c2.priority
195
196     cr1.update_attributes!(priority: 0)
197
198     c1.reload
199     assert_equal 0, c1.priority
200
201     c2.reload
202     assert_equal c2priority_was, c2.priority
203   end
204
205   test "Request is finalized when its container is cancelled" do
206     set_user_from_auth :active
207     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 1)
208     assert_equal users(:active).uuid, cr.modified_by_user_uuid
209
210     act_as_system_user do
211       Container.find_by_uuid(cr.container_uuid).
212         update_attributes!(state: Container::Cancelled)
213     end
214
215     cr.reload
216     assert_equal "Final", cr.state
217     assert_equal users(:active).uuid, cr.modified_by_user_uuid
218   end
219
220   test "Request is finalized when its container is completed" do
221     set_user_from_auth :active
222     project = groups(:private)
223     cr = create_minimal_req!(owner_uuid: project.uuid,
224                              priority: 1,
225                              state: "Committed")
226     assert_equal users(:active).uuid, cr.modified_by_user_uuid
227
228     c = act_as_system_user do
229       c = Container.find_by_uuid(cr.container_uuid)
230       c.update_attributes!(state: Container::Locked)
231       c.update_attributes!(state: Container::Running)
232       c
233     end
234
235     cr.reload
236     assert_equal "Committed", cr.state
237
238     output_pdh = '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
239     log_pdh = 'fa7aeb5140e2848d39b416daeef4ffc5+45'
240     act_as_system_user do
241       c.update_attributes!(state: Container::Complete,
242                            output: output_pdh,
243                            log: log_pdh)
244     end
245
246     cr.reload
247     assert_equal "Final", cr.state
248     assert_equal users(:active).uuid, cr.modified_by_user_uuid
249
250     assert_not_nil cr.output_uuid
251     assert_not_nil cr.log_uuid
252     output = Collection.find_by_uuid cr.output_uuid
253     assert_equal output_pdh, output.portable_data_hash
254     assert_equal output.owner_uuid, project.uuid, "Container output should be copied to #{project.uuid}"
255     assert_not_nil output.modified_at
256
257     log = Collection.find_by_uuid cr.log_uuid
258     assert_equal log.manifest_text, ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
259 ./log\\040for\\040container\\040#{cr.container_uuid} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n"
260
261     assert_equal log.owner_uuid, project.uuid, "Container log should be copied to #{project.uuid}"
262   end
263
264   # This tests bug report #16144
265   test "Request is finalized when its container is completed even when log & output don't exist" do
266     set_user_from_auth :active
267     project = groups(:private)
268     cr = create_minimal_req!(owner_uuid: project.uuid,
269                              priority: 1,
270                              state: "Committed")
271     assert_equal users(:active).uuid, cr.modified_by_user_uuid
272
273     output_pdh = '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
274     log_pdh = 'fa7aeb5140e2848d39b416daeef4ffc5+45'
275
276     c = act_as_system_user do
277       c = Container.find_by_uuid(cr.container_uuid)
278       c.update_attributes!(state: Container::Locked)
279       c.update_attributes!(state: Container::Running,
280                            output: output_pdh,
281                            log: log_pdh)
282       c
283     end
284
285     cr.reload
286     assert_equal "Committed", cr.state
287
288     act_as_system_user do
289       Collection.where(portable_data_hash: output_pdh).delete_all
290       Collection.where(portable_data_hash: log_pdh).delete_all
291       c.update_attributes!(state: Container::Complete)
292     end
293
294     cr.reload
295     assert_equal "Final", cr.state
296   end
297
298   # This tests bug report #16144
299   test "Can destroy CR even if its container doesn't exist" do
300     set_user_from_auth :active
301     project = groups(:private)
302     cr = create_minimal_req!(owner_uuid: project.uuid,
303                              priority: 1,
304                              state: "Committed")
305     assert_equal users(:active).uuid, cr.modified_by_user_uuid
306
307     c = act_as_system_user do
308       c = Container.find_by_uuid(cr.container_uuid)
309       c.update_attributes!(state: Container::Locked)
310       c.update_attributes!(state: Container::Running)
311       c
312     end
313
314     cr.reload
315     assert_equal "Committed", cr.state
316
317     cr_uuid = cr.uuid
318     act_as_system_user do
319       Container.find_by_uuid(cr.container_uuid).destroy
320       cr.destroy
321     end
322     assert_nil ContainerRequest.find_by_uuid(cr_uuid)
323   end
324
325   test "Container makes container request, then is cancelled" do
326     set_user_from_auth :active
327     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 1)
328
329     c = Container.find_by_uuid cr.container_uuid
330     assert_operator 0, :<, c.priority
331     lock_and_run(c)
332
333     cr2 = with_container_auth(c) do
334       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
335     end
336     assert_not_nil cr2.requesting_container_uuid
337     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
338
339     c2 = Container.find_by_uuid cr2.container_uuid
340     assert_operator 0, :<, c2.priority
341
342     act_as_system_user do
343       c.state = "Cancelled"
344       c.save!
345     end
346
347     cr.reload
348     assert_equal "Final", cr.state
349
350     cr2.reload
351     assert_equal 0, cr2.priority
352     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
353
354     c2.reload
355     assert_equal 0, c2.priority
356   end
357
358   test "child container priority follows same ordering as corresponding top-level ancestors" do
359     findctr = lambda { |cr| Container.find_by_uuid(cr.container_uuid) }
360
361     set_user_from_auth :active
362
363     toplevel_crs = [
364       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "0"}),
365       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "1"}),
366       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "2"}),
367     ]
368     parents = toplevel_crs.map(&findctr)
369
370     children = parents.map do |parent|
371       lock_and_run(parent)
372       with_container_auth(parent) do
373         create_minimal_req!(state: "Committed",
374                             priority: 1,
375                             environment: {"child" => parent.environment["workflow"]})
376       end
377     end.map(&findctr)
378
379     grandchildren = children.reverse.map do |child|
380       lock_and_run(child)
381       with_container_auth(child) do
382         create_minimal_req!(state: "Committed",
383                             priority: 1,
384                             environment: {"grandchild" => child.environment["child"]})
385       end
386     end.reverse.map(&findctr)
387
388     shared_grandchildren = children.map do |child|
389       with_container_auth(child) do
390         create_minimal_req!(state: "Committed",
391                             priority: 1,
392                             environment: {"grandchild" => "shared"})
393       end
394     end.map(&findctr)
395
396     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[1].uuid
397     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[2].uuid
398     shared_grandchild = shared_grandchildren[0]
399
400     set_user_from_auth :active
401
402     # parents should be prioritized by submit time.
403     assert_operator parents[0].priority, :>, parents[1].priority
404     assert_operator parents[1].priority, :>, parents[2].priority
405
406     # children should be prioritized in same order as their respective
407     # parents.
408     assert_operator children[0].priority, :>, children[1].priority
409     assert_operator children[1].priority, :>, children[2].priority
410
411     # grandchildren should also be prioritized in the same order,
412     # despite having been submitted in the opposite order.
413     assert_operator grandchildren[0].priority, :>, grandchildren[1].priority
414     assert_operator grandchildren[1].priority, :>, grandchildren[2].priority
415
416     # shared grandchild container should be prioritized above
417     # everything that isn't needed by parents[0], but not above
418     # earlier-submitted descendants of parents[0]
419     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
420     assert_operator shared_grandchild.priority, :>, children[1].priority
421     assert_operator shared_grandchild.priority, :>, parents[1].priority
422     assert_operator shared_grandchild.priority, :<=, grandchildren[0].priority
423     assert_operator shared_grandchild.priority, :<=, children[0].priority
424     assert_operator shared_grandchild.priority, :<=, parents[0].priority
425
426     # increasing priority of the most recent toplevel container should
427     # reprioritize all of its descendants (including the shared
428     # grandchild) above everything else.
429     toplevel_crs[2].update_attributes!(priority: 72)
430     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
431     assert_operator shared_grandchild.priority, :>, grandchildren[0].priority
432     assert_operator shared_grandchild.priority, :>, children[0].priority
433     assert_operator shared_grandchild.priority, :>, parents[0].priority
434     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
435     assert_operator shared_grandchild.priority, :>, children[1].priority
436     assert_operator shared_grandchild.priority, :>, parents[1].priority
437     # ...but the shared container should not have higher priority than
438     # the earlier-submitted descendants of the high-priority workflow.
439     assert_operator shared_grandchild.priority, :<=, grandchildren[2].priority
440     assert_operator shared_grandchild.priority, :<=, children[2].priority
441     assert_operator shared_grandchild.priority, :<=, parents[2].priority
442   end
443
444   [
445     ['running_container_auth', 'zzzzz-dz642-runningcontainr', 501],
446     ['active_no_prefs', nil, 0]
447   ].each do |token, expected, expected_priority|
448     test "create as #{token} and expect requesting_container_uuid to be #{expected}" do
449       set_user_from_auth token
450       cr = ContainerRequest.create(container_image: "img", output_path: "/tmp", command: ["echo", "foo"])
451       assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
452       assert_equal expected, cr.requesting_container_uuid
453       assert_equal expected_priority, cr.priority
454     end
455   end
456
457   test "create as container_runtime_token and expect requesting_container_uuid to be zzzzz-dz642-20isqbkl8xwnsao" do
458     set_user_from_auth :container_runtime_token
459     Thread.current[:token] = "#{Thread.current[:token]}/zzzzz-dz642-20isqbkl8xwnsao"
460     cr = ContainerRequest.create(container_image: "img", output_path: "/tmp", command: ["echo", "foo"])
461     assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
462     assert_equal 'zzzzz-dz642-20isqbkl8xwnsao', cr.requesting_container_uuid
463     assert_equal 1, cr.priority
464   end
465
466   [[{"vcpus" => [2, nil]},
467     lambda { |resolved| resolved["vcpus"] == 2 }],
468    [{"vcpus" => [3, 7]},
469     lambda { |resolved| resolved["vcpus"] == 3 }],
470    [{"vcpus" => 4},
471     lambda { |resolved| resolved["vcpus"] == 4 }],
472    [{"ram" => [1000000000, 2000000000]},
473     lambda { |resolved| resolved["ram"] == 1000000000 }],
474    [{"ram" => [1234234234]},
475     lambda { |resolved| resolved["ram"] == 1234234234 }],
476   ].each do |rc, okfunc|
477     test "resolve runtime constraint range #{rc} to values" do
478       resolved = Container.resolve_runtime_constraints(rc)
479       assert(okfunc.call(resolved),
480              "container runtime_constraints was #{resolved.inspect}")
481     end
482   end
483
484   [[{"/out" => {
485         "kind" => "collection",
486         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
487         "path" => "/foo"}},
488     lambda do |resolved|
489       resolved["/out"] == {
490         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
491         "kind" => "collection",
492         "path" => "/foo",
493       }
494     end],
495    [{"/out" => {
496         "kind" => "collection",
497         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
498         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
499         "path" => "/foo"}},
500     lambda do |resolved|
501       resolved["/out"] == {
502         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
503         "kind" => "collection",
504         "path" => "/foo",
505       }
506     end],
507    [{"/out" => {
508       "kind" => "collection",
509       "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
510       "path" => "/foo"}},
511     lambda do |resolved|
512       resolved["/out"] == {
513         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
514         "kind" => "collection",
515         "path" => "/foo",
516       }
517     end],
518     # Empty collection
519     [{"/out" => {
520       "kind" => "collection",
521       "path" => "/foo"}},
522     lambda do |resolved|
523       resolved["/out"] == {
524         "kind" => "collection",
525         "path" => "/foo",
526       }
527     end],
528   ].each do |mounts, okfunc|
529     test "resolve mounts #{mounts.inspect} to values" do
530       set_user_from_auth :active
531       resolved = Container.resolve_mounts(mounts)
532       assert(okfunc.call(resolved),
533              "Container.resolve_mounts returned #{resolved.inspect}")
534     end
535   end
536
537   test 'mount unreadable collection' do
538     set_user_from_auth :spectator
539     m = {
540       "/foo" => {
541         "kind" => "collection",
542         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
543         "path" => "/foo",
544       },
545     }
546     assert_raises(ArvadosModel::UnresolvableContainerError) do
547       Container.resolve_mounts(m)
548     end
549   end
550
551   test 'mount collection with mismatched UUID and PDH' do
552     set_user_from_auth :active
553     m = {
554       "/foo" => {
555         "kind" => "collection",
556         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
557         "portable_data_hash" => "fa7aeb5140e2848d39b416daeef4ffc5+45",
558         "path" => "/foo",
559       },
560     }
561     resolved_mounts = Container.resolve_mounts(m)
562     assert_equal m['portable_data_hash'], resolved_mounts['portable_data_hash']
563   end
564
565   ['arvados/apitestfixture:latest',
566    'arvados/apitestfixture',
567    'd8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678',
568   ].each do |tag|
569     test "Container.resolve_container_image(#{tag.inspect})" do
570       set_user_from_auth :active
571       resolved = Container.resolve_container_image(tag)
572       assert_equal resolved, collections(:docker_image).portable_data_hash
573     end
574   end
575
576   test "Container.resolve_container_image(pdh)" do
577     set_user_from_auth :active
578     [[:docker_image, 'v1'], [:docker_image_1_12, 'v2']].each do |coll, ver|
579       Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({ver=>{}})
580       pdh = collections(coll).portable_data_hash
581       resolved = Container.resolve_container_image(pdh)
582       assert_equal resolved, pdh
583     end
584   end
585
586   ['acbd18db4cc2f85cedef654fccc4a4d8+3',
587    'ENOEXIST',
588    'arvados/apitestfixture:ENOEXIST',
589   ].each do |img|
590     test "container_image_for_container(#{img.inspect}) => 422" do
591       set_user_from_auth :active
592       assert_raises(ArvadosModel::UnresolvableContainerError) do
593         Container.resolve_container_image(img)
594       end
595     end
596   end
597
598   test "allow unrecognized container when there are remote_hosts" do
599     set_user_from_auth :active
600     Rails.configuration.RemoteClusters = Rails.configuration.RemoteClusters.merge({foooo: ActiveSupport::InheritableOptions.new({Host: "bar.com"})})
601     Container.resolve_container_image('acbd18db4cc2f85cedef654fccc4a4d8+3')
602   end
603
604   test "migrated docker image" do
605     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v2'=>{}})
606     add_docker19_migration_link
607
608     # Test that it returns only v2 images even though request is for v1 image.
609
610     set_user_from_auth :active
611     cr = create_minimal_req!(command: ["true", "1"],
612                              container_image: collections(:docker_image).portable_data_hash)
613     assert_equal(Container.resolve_container_image(cr.container_image),
614                  collections(:docker_image_1_12).portable_data_hash)
615
616     cr = create_minimal_req!(command: ["true", "2"],
617                              container_image: links(:docker_image_collection_tag).name)
618     assert_equal(Container.resolve_container_image(cr.container_image),
619                  collections(:docker_image_1_12).portable_data_hash)
620   end
621
622   test "use unmigrated docker image" do
623     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v1'=>{}})
624     add_docker19_migration_link
625
626     # Test that it returns only supported v1 images even though there is a
627     # migration link.
628
629     set_user_from_auth :active
630     cr = create_minimal_req!(command: ["true", "1"],
631                              container_image: collections(:docker_image).portable_data_hash)
632     assert_equal(Container.resolve_container_image(cr.container_image),
633                  collections(:docker_image).portable_data_hash)
634
635     cr = create_minimal_req!(command: ["true", "2"],
636                              container_image: links(:docker_image_collection_tag).name)
637     assert_equal(Container.resolve_container_image(cr.container_image),
638                  collections(:docker_image).portable_data_hash)
639   end
640
641   test "incompatible docker image v1" do
642     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v1'=>{}})
643     add_docker19_migration_link
644
645     # Don't return unsupported v2 image even if we ask for it directly.
646     set_user_from_auth :active
647     cr = create_minimal_req!(command: ["true", "1"],
648                              container_image: collections(:docker_image_1_12).portable_data_hash)
649     assert_raises(ArvadosModel::UnresolvableContainerError) do
650       Container.resolve_container_image(cr.container_image)
651     end
652   end
653
654   test "incompatible docker image v2" do
655     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v2'=>{}})
656     # No migration link, don't return unsupported v1 image,
657
658     set_user_from_auth :active
659     cr = create_minimal_req!(command: ["true", "1"],
660                              container_image: collections(:docker_image).portable_data_hash)
661     assert_raises(ArvadosModel::UnresolvableContainerError) do
662       Container.resolve_container_image(cr.container_image)
663     end
664     cr = create_minimal_req!(command: ["true", "2"],
665                              container_image: links(:docker_image_collection_tag).name)
666     assert_raises(ArvadosModel::UnresolvableContainerError) do
667       Container.resolve_container_image(cr.container_image)
668     end
669   end
670
671   test "requestor can retrieve container owned by dispatch" do
672     assert_not_empty Container.readable_by(users(:admin)).where(uuid: containers(:running).uuid)
673     assert_not_empty Container.readable_by(users(:active)).where(uuid: containers(:running).uuid)
674     assert_empty Container.readable_by(users(:spectator)).where(uuid: containers(:running).uuid)
675   end
676
677   [
678     [{"var" => "value1"}, {"var" => "value1"}, nil],
679     [{"var" => "value1"}, {"var" => "value1"}, true],
680     [{"var" => "value1"}, {"var" => "value1"}, false],
681     [{"var" => "value1"}, {"var" => "value2"}, nil],
682   ].each do |env1, env2, use_existing|
683     test "Container request #{((env1 == env2) and (use_existing.nil? or use_existing == true)) ? 'does' : 'does not'} reuse container when committed#{use_existing.nil? ? '' : use_existing ? ' and use_existing == true' : ' and use_existing == false'}" do
684       common_attrs = {cwd: "test",
685                       priority: 1,
686                       command: ["echo", "hello"],
687                       output_path: "test",
688                       runtime_constraints: {"vcpus" => 4,
689                                             "ram" => 12000000000},
690                       mounts: {"test" => {"kind" => "json"}}}
691       set_user_from_auth :active
692       cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed,
693                                                     environment: env1}))
694       run_container(cr1)
695       cr1.reload
696       if use_existing.nil?
697         # Testing with use_existing default value
698         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
699                                                       environment: env2}))
700       else
701
702         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
703                                                       environment: env2,
704                                                       use_existing: use_existing}))
705       end
706       assert_not_nil cr1.container_uuid
707       assert_nil cr2.container_uuid
708
709       # Update cr2 to commited state and check for container equality on different cases:
710       # * When env1 and env2 are equal and use_existing is true, the same container
711       #   should be assigned.
712       # * When use_existing is false, a different container should be assigned.
713       # * When env1 and env2 are different, a different container should be assigned.
714       cr2.update_attributes!({state: ContainerRequest::Committed})
715       assert_equal (cr2.use_existing == true and (env1 == env2)),
716                    (cr1.container_uuid == cr2.container_uuid)
717     end
718   end
719
720   test "requesting_container_uuid at create is not allowed" do
721     set_user_from_auth :active
722     assert_raises(ActiveRecord::RecordInvalid) do
723       create_minimal_req!(state: "Uncommitted", priority: 1, requesting_container_uuid: 'youcantdothat')
724     end
725   end
726
727   test "Retry on container cancelled" do
728     set_user_from_auth :active
729     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2)
730     cr2 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "baz"])
731     prev_container_uuid = cr.container_uuid
732
733     c = act_as_system_user do
734       c = Container.find_by_uuid(cr.container_uuid)
735       c.update_attributes!(state: Container::Locked)
736       c.update_attributes!(state: Container::Running)
737       c
738     end
739
740     cr.reload
741     cr2.reload
742     assert_equal "Committed", cr.state
743     assert_equal prev_container_uuid, cr.container_uuid
744     assert_not_equal cr2.container_uuid, cr.container_uuid
745     prev_container_uuid = cr.container_uuid
746
747     act_as_system_user do
748       c.update_attributes!(state: Container::Cancelled)
749     end
750
751     cr.reload
752     cr2.reload
753     assert_equal "Committed", cr.state
754     assert_not_equal prev_container_uuid, cr.container_uuid
755     assert_not_equal cr2.container_uuid, cr.container_uuid
756     prev_container_uuid = cr.container_uuid
757
758     c = act_as_system_user do
759       c = Container.find_by_uuid(cr.container_uuid)
760       c.update_attributes!(state: Container::Cancelled)
761       c
762     end
763
764     cr.reload
765     cr2.reload
766     assert_equal "Final", cr.state
767     assert_equal prev_container_uuid, cr.container_uuid
768     assert_not_equal cr2.container_uuid, cr.container_uuid
769   end
770
771   test "Retry on container cancelled with runtime_token" do
772     set_user_from_auth :spectator
773     spec = api_client_authorizations(:active)
774     cr = create_minimal_req!(priority: 1, state: "Committed",
775                              runtime_token: spec.token,
776                              container_count_max: 2)
777     prev_container_uuid = cr.container_uuid
778
779     c = act_as_system_user do
780       c = Container.find_by_uuid(cr.container_uuid)
781       assert_equal spec.token, c.runtime_token
782       c.update_attributes!(state: Container::Locked)
783       c.update_attributes!(state: Container::Running)
784       c
785     end
786
787     cr.reload
788     assert_equal "Committed", cr.state
789     assert_equal prev_container_uuid, cr.container_uuid
790     prev_container_uuid = cr.container_uuid
791
792     act_as_system_user do
793       c.update_attributes!(state: Container::Cancelled)
794     end
795
796     cr.reload
797     assert_equal "Committed", cr.state
798     assert_not_equal prev_container_uuid, cr.container_uuid
799     prev_container_uuid = cr.container_uuid
800
801     c = act_as_system_user do
802       c = Container.find_by_uuid(cr.container_uuid)
803       assert_equal spec.token, c.runtime_token
804       c.update_attributes!(state: Container::Cancelled)
805       c
806     end
807
808     cr.reload
809     assert_equal "Final", cr.state
810     assert_equal prev_container_uuid, cr.container_uuid
811   end
812
813
814   test "Retry saves logs from previous attempts" do
815     set_user_from_auth :active
816     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 3)
817
818     c = act_as_system_user do
819       c = Container.find_by_uuid(cr.container_uuid)
820       c.update_attributes!(state: Container::Locked)
821       c.update_attributes!(state: Container::Running)
822       c
823     end
824
825     container_uuids = []
826
827     [0, 1, 2].each do
828       cr.reload
829       assert_equal "Committed", cr.state
830       container_uuids << cr.container_uuid
831
832       c = act_as_system_user do
833         logc = Collection.new(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
834         logc.save!
835         c = Container.find_by_uuid(cr.container_uuid)
836         c.update_attributes!(state: Container::Cancelled, log: logc.portable_data_hash)
837         c
838       end
839     end
840
841     container_uuids.sort!
842
843     cr.reload
844     assert_equal "Final", cr.state
845     assert_equal 3, cr.container_count
846     assert_equal ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
847 ./log\\040for\\040container\\040#{container_uuids[0]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
848 ./log\\040for\\040container\\040#{container_uuids[1]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
849 ./log\\040for\\040container\\040#{container_uuids[2]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
850 " , Collection.find_by_uuid(cr.log_uuid).manifest_text
851
852   end
853
854   test "Output collection name setting using output_name with name collision resolution" do
855     set_user_from_auth :active
856     output_name = 'unimaginative name'
857     Collection.create!(name: output_name)
858
859     cr = create_minimal_req!(priority: 1,
860                              state: ContainerRequest::Committed,
861                              output_name: output_name)
862     run_container(cr)
863     cr.reload
864     assert_equal ContainerRequest::Final, cr.state
865     output_coll = Collection.find_by_uuid(cr.output_uuid)
866     # Make sure the resulting output collection name include the original name
867     # plus the date
868     assert_not_equal output_name, output_coll.name,
869                      "more than one collection with the same owner and name"
870     assert output_coll.name.include?(output_name),
871            "New name should include original name"
872     assert_match /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z/, output_coll.name,
873                  "New name should include ISO8601 date"
874   end
875
876   [[0, :check_output_ttl_0],
877    [1, :check_output_ttl_1s],
878    [365*86400, :check_output_ttl_1y],
879   ].each do |ttl, checker|
880     test "output_ttl=#{ttl}" do
881       act_as_user users(:active) do
882         cr = create_minimal_req!(priority: 1,
883                                  state: ContainerRequest::Committed,
884                                  output_name: 'foo',
885                                  output_ttl: ttl)
886         run_container(cr)
887         cr.reload
888         output = Collection.find_by_uuid(cr.output_uuid)
889         send(checker, db_current_time, output.trash_at, output.delete_at)
890       end
891     end
892   end
893
894   def check_output_ttl_0(now, trash, delete)
895     assert_nil(trash)
896     assert_nil(delete)
897   end
898
899   def check_output_ttl_1s(now, trash, delete)
900     assert_not_nil(trash)
901     assert_not_nil(delete)
902     assert_in_delta(trash, now + 1.second, 10)
903     assert_in_delta(delete, now + Rails.configuration.Collections.BlobSigningTTL, 10)
904   end
905
906   def check_output_ttl_1y(now, trash, delete)
907     year = (86400*365).second
908     assert_not_nil(trash)
909     assert_not_nil(delete)
910     assert_in_delta(trash, now + year, 10)
911     assert_in_delta(delete, now + year, 10)
912   end
913
914   def run_container(cr)
915     act_as_system_user do
916       logc = Collection.new(owner_uuid: system_user_uuid,
917                             manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
918       logc.save!
919
920       c = Container.find_by_uuid(cr.container_uuid)
921       c.update_attributes!(state: Container::Locked)
922       c.update_attributes!(state: Container::Running)
923       c.update_attributes!(state: Container::Complete,
924                            exit_code: 0,
925                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
926                            log: logc.portable_data_hash)
927       logc.destroy
928       c
929     end
930   end
931
932   test "Finalize committed request when reusing a finished container" do
933     set_user_from_auth :active
934     cr = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
935     cr.reload
936     assert_equal ContainerRequest::Committed, cr.state
937     run_container(cr)
938     cr.reload
939     assert_equal ContainerRequest::Final, cr.state
940
941     cr2 = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
942     assert_equal cr.container_uuid, cr2.container_uuid
943     assert_equal ContainerRequest::Final, cr2.state
944
945     cr3 = create_minimal_req!(priority: 1, state: ContainerRequest::Uncommitted)
946     assert_equal ContainerRequest::Uncommitted, cr3.state
947     cr3.update_attributes!(state: ContainerRequest::Committed)
948     assert_equal cr.container_uuid, cr3.container_uuid
949     assert_equal ContainerRequest::Final, cr3.state
950   end
951
952   [
953     [false, ActiveRecord::RecordInvalid],
954     [true, nil],
955   ].each do |preemptible_conf, expected|
956     test "having Rails.configuration.Containers.UsePreemptibleInstances=#{preemptible_conf}, create preemptible container request and verify #{expected}" do
957       sp = {"preemptible" => true}
958       common_attrs = {cwd: "test",
959                       priority: 1,
960                       command: ["echo", "hello"],
961                       output_path: "test",
962                       scheduling_parameters: sp,
963                       mounts: {"test" => {"kind" => "json"}}}
964       Rails.configuration.Containers.UsePreemptibleInstances = preemptible_conf
965       set_user_from_auth :active
966
967       cr = create_minimal_req!(common_attrs)
968       cr.state = ContainerRequest::Committed
969
970       if !expected.nil?
971         assert_raises(expected) do
972           cr.save!
973         end
974       else
975         cr.save!
976         assert (sp.to_a - cr.scheduling_parameters.to_a).empty?
977       end
978     end
979   end
980
981   [
982     [true, 'zzzzz-dz642-runningcontainr', true],
983     [true, nil, false],
984     [false, 'zzzzz-dz642-runningcontainr', false],
985     [false, nil, false],
986   ].each do |preemptible_conf, requesting_c, schedule_preemptible|
987     test "having Rails.configuration.Containers.UsePreemptibleInstances=#{preemptible_conf}, #{requesting_c.nil? ? 'non-':''}child CR should #{schedule_preemptible ? '':'not'} ask for preemptible instance by default" do
988       common_attrs = {cwd: "test",
989                       priority: 1,
990                       command: ["echo", "hello"],
991                       output_path: "test",
992                       mounts: {"test" => {"kind" => "json"}}}
993
994       Rails.configuration.Containers.UsePreemptibleInstances = preemptible_conf
995       set_user_from_auth :active
996
997       if requesting_c
998         cr = with_container_auth(Container.find_by_uuid requesting_c) do
999           create_minimal_req!(common_attrs)
1000         end
1001         assert_not_nil cr.requesting_container_uuid
1002       else
1003         cr = create_minimal_req!(common_attrs)
1004       end
1005
1006       cr.state = ContainerRequest::Committed
1007       cr.save!
1008
1009       assert_equal schedule_preemptible, cr.scheduling_parameters['preemptible']
1010     end
1011   end
1012
1013   [
1014     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1015     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Uncommitted],
1016     [{"partitions" => "fastcpu"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1017     [{"partitions" => "fastcpu"}, ContainerRequest::Uncommitted],
1018     [{"partitions" => ["fastcpu","vfastcpu"]}, ContainerRequest::Committed],
1019     [{"max_run_time" => "one day"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1020     [{"max_run_time" => "one day"}, ContainerRequest::Uncommitted],
1021     [{"max_run_time" => -1}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1022     [{"max_run_time" => -1}, ContainerRequest::Uncommitted],
1023     [{"max_run_time" => 86400}, ContainerRequest::Committed],
1024   ].each do |sp, state, expected|
1025     test "create container request with scheduling_parameters #{sp} in state #{state} and verify #{expected}" do
1026       common_attrs = {cwd: "test",
1027                       priority: 1,
1028                       command: ["echo", "hello"],
1029                       output_path: "test",
1030                       scheduling_parameters: sp,
1031                       mounts: {"test" => {"kind" => "json"}}}
1032       set_user_from_auth :active
1033
1034       if expected == ActiveRecord::RecordInvalid
1035         assert_raises(ActiveRecord::RecordInvalid) do
1036           create_minimal_req!(common_attrs.merge({state: state}))
1037         end
1038       else
1039         cr = create_minimal_req!(common_attrs.merge({state: state}))
1040         assert (sp.to_a - cr.scheduling_parameters.to_a).empty?
1041
1042         if state == ContainerRequest::Committed
1043           c = Container.find_by_uuid(cr.container_uuid)
1044           assert (sp.to_a - c.scheduling_parameters.to_a).empty?
1045         end
1046       end
1047     end
1048   end
1049
1050   test "Having preemptible_instances=true create a committed child container request and verify the scheduling parameter of its container" do
1051     common_attrs = {cwd: "test",
1052                     priority: 1,
1053                     command: ["echo", "hello"],
1054                     output_path: "test",
1055                     state: ContainerRequest::Committed,
1056                     mounts: {"test" => {"kind" => "json"}}}
1057     set_user_from_auth :active
1058     Rails.configuration.Containers.UsePreemptibleInstances = true
1059
1060     cr = with_container_auth(Container.find_by_uuid 'zzzzz-dz642-runningcontainr') do
1061       create_minimal_req!(common_attrs)
1062     end
1063     assert_equal 'zzzzz-dz642-runningcontainr', cr.requesting_container_uuid
1064     assert_equal true, cr.scheduling_parameters["preemptible"]
1065
1066     c = Container.find_by_uuid(cr.container_uuid)
1067     assert_equal true, c.scheduling_parameters["preemptible"]
1068   end
1069
1070   [['Committed', true, {name: "foobar", priority: 123}],
1071    ['Committed', false, {container_count: 2}],
1072    ['Committed', false, {container_count: 0}],
1073    ['Committed', false, {container_count: nil}],
1074    ['Committed', true, {priority: 0, mounts: {"/out" => {"kind" => "tmp", "capacity" => 1000000}}}],
1075    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp"}}}],
1076    # addition of default values for mounts, as happens in a round-trip
1077    # through controller, should be ignored when mounts is not allowed
1078    # to change
1079    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "exclude_from_output": false}}}],
1080    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "repository_name": ""}}}],
1081    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "content": nil}}}],
1082    ['Committed', false, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "content": {}}}}],
1083    ['Committed', false, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "repository_name": "foo"}}}],
1084    ['Committed', false, {priority: 0, mounts: {"/out" => {"kind" => "tmp", "capacity" => 1234567}}}],
1085    ['Committed', false, {priority: 0, mounts: {}}],
1086    ['Final', false, {state: ContainerRequest::Committed, name: "foobar"}],
1087    ['Final', false, {name: "foobar", priority: 123}],
1088    ['Final', false, {name: "foobar", output_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1089    ['Final', false, {name: "foobar", log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1090    ['Final', false, {log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1091    ['Final', false, {priority: 123}],
1092    ['Final', false, {mounts: {}}],
1093    ['Final', false, {container_count: 2}],
1094    ['Final', true, {name: "foobar"}],
1095    ['Final', true, {name: "foobar", description: "baz"}],
1096   ].each do |state, permitted, updates|
1097     test "state=#{state} can#{'not' if !permitted} update #{updates.inspect}" do
1098       act_as_user users(:active) do
1099         cr = create_minimal_req!(priority: 1,
1100                                  state: "Committed",
1101                                  container_count_max: 1)
1102         case state
1103         when 'Committed'
1104           # already done
1105         when 'Final'
1106           act_as_system_user do
1107             Container.find_by_uuid(cr.container_uuid).
1108               update_attributes!(state: Container::Cancelled)
1109           end
1110           cr.reload
1111         else
1112           raise 'broken test case'
1113         end
1114         assert_equal state, cr.state
1115         if permitted
1116           assert cr.update_attributes!(updates)
1117         else
1118           assert_raises(ActiveRecord::RecordInvalid) do
1119             cr.update_attributes!(updates)
1120           end
1121         end
1122       end
1123     end
1124   end
1125
1126   test "delete container_request and check its container's priority" do
1127     act_as_user users(:active) do
1128       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
1129
1130       # initially the cr's container has priority > 0
1131       c = Container.find_by_uuid(cr.container_uuid)
1132       assert_equal 1, c.priority
1133
1134       cr.destroy
1135
1136       # the cr's container now has priority of 0
1137       c = Container.find_by_uuid(cr.container_uuid)
1138       assert_equal 0, c.priority
1139     end
1140   end
1141
1142   test "delete container_request in final state and expect no error due to before_destroy callback" do
1143     act_as_user users(:active) do
1144       cr = ContainerRequest.find_by_uuid container_requests(:completed).uuid
1145       assert_nothing_raised {cr.destroy}
1146     end
1147   end
1148
1149   test "Container request valid priority" do
1150     set_user_from_auth :active
1151     cr = create_minimal_req!
1152
1153     assert_raises(ActiveRecord::RecordInvalid) do
1154       cr.priority = -1
1155       cr.save!
1156     end
1157
1158     cr.priority = 0
1159     cr.save!
1160
1161     cr.priority = 1
1162     cr.save!
1163
1164     cr.priority = 500
1165     cr.save!
1166
1167     cr.priority = 999
1168     cr.save!
1169
1170     cr.priority = 1000
1171     cr.save!
1172
1173     assert_raises(ActiveRecord::RecordInvalid) do
1174       cr.priority = 1001
1175       cr.save!
1176     end
1177   end
1178
1179   # Note: some of these tests might look redundant because they test
1180   # that out-of-order spellings of hashes are still considered equal
1181   # regardless of whether the existing (container) or new (container
1182   # request) hash needs to be re-ordered.
1183   secrets = {"/foo" => {"kind" => "text", "content" => "xyzzy"}}
1184   same_secrets = {"/foo" => {"content" => "xyzzy", "kind" => "text"}}
1185   different_secrets = {"/foo" => {"kind" => "text", "content" => "something completely different"}}
1186   [
1187     [true, nil, nil],
1188     [true, nil, {}],
1189     [true, {}, nil],
1190     [true, {}, {}],
1191     [true, secrets, same_secrets],
1192     [true, same_secrets, secrets],
1193     [false, nil, secrets],
1194     [false, {}, secrets],
1195     [false, secrets, {}],
1196     [false, secrets, nil],
1197     [false, secrets, different_secrets],
1198   ].each do |expect_reuse, sm1, sm2|
1199     test "container reuse secret_mounts #{sm1.inspect}, #{sm2.inspect}" do
1200       set_user_from_auth :active
1201       cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm1)
1202       cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm2)
1203       assert_not_nil cr1.container_uuid
1204       assert_not_nil cr2.container_uuid
1205       if expect_reuse
1206         assert_equal cr1.container_uuid, cr2.container_uuid
1207       else
1208         assert_not_equal cr1.container_uuid, cr2.container_uuid
1209       end
1210     end
1211   end
1212
1213   test "scrub secret_mounts but reuse container for request with identical secret_mounts" do
1214     set_user_from_auth :active
1215     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1216     cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1217     run_container(cr1)
1218     cr1.reload
1219
1220     # secret_mounts scrubbed from db
1221     c = Container.where(uuid: cr1.container_uuid).first
1222     assert_equal({}, c.secret_mounts)
1223     assert_equal({}, cr1.secret_mounts)
1224
1225     # can reuse container if secret_mounts match
1226     cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1227     assert_equal cr1.container_uuid, cr2.container_uuid
1228
1229     # don't reuse container if secret_mounts don't match
1230     cr3 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: {})
1231     assert_not_equal cr1.container_uuid, cr3.container_uuid
1232
1233     assert_no_secrets_logged
1234   end
1235
1236   test "conflicting key in mounts and secret_mounts" do
1237     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1238     set_user_from_auth :active
1239     cr = create_minimal_req!
1240     assert_equal false, cr.update_attributes(state: "Committed",
1241                                              priority: 1,
1242                                              mounts: cr.mounts.merge(sm),
1243                                              secret_mounts: sm)
1244     assert_equal [:secret_mounts], cr.errors.messages.keys
1245   end
1246
1247   test "using runtime_token" do
1248     set_user_from_auth :spectator
1249     spec = api_client_authorizations(:active)
1250     cr = create_minimal_req!(state: "Committed", runtime_token: spec.token, priority: 1)
1251     cr.save!
1252     c = Container.find_by_uuid cr.container_uuid
1253     lock_and_run c
1254     assert_nil c.auth_uuid
1255     assert_equal c.runtime_token, spec.token
1256
1257     assert_not_nil ApiClientAuthorization.find_by_uuid(spec.uuid)
1258
1259     act_as_system_user do
1260       c.update_attributes!(state: Container::Complete,
1261                            exit_code: 0,
1262                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1263                            log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
1264     end
1265
1266     cr.reload
1267     c.reload
1268     assert_nil cr.runtime_token
1269     assert_nil c.runtime_token
1270   end
1271
1272   test "invalid runtime_token" do
1273     set_user_from_auth :active
1274     spec = api_client_authorizations(:spectator)
1275     assert_raises(ArgumentError) do
1276       cr = create_minimal_req!(state: "Committed", runtime_token: "#{spec.token}xx")
1277       cr.save!
1278     end
1279   end
1280 end