Merge branch '20468-installer-perf-knobs'. Closes #20468
[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     client_was = Thread.current[:api_client]
18     token_was = Thread.current[:token]
19     user_was = Thread.current[:user]
20     auth = ApiClientAuthorization.find_by_uuid(ctr.auth_uuid)
21     Thread.current[:api_client_authorization] = auth
22     Thread.current[:api_client] = auth.api_client
23     Thread.current[:token] = auth.token
24     Thread.current[:user] = auth.user
25     begin
26       yield
27     ensure
28       Thread.current[:api_client_authorization] = auth_was
29       Thread.current[:api_client] = client_was
30       Thread.current[:token] = token_was
31       Thread.current[:user] = user_was
32     end
33   end
34
35   def lock_and_run(ctr)
36       act_as_system_user do
37         ctr.update_attributes!(state: Container::Locked)
38         ctr.update_attributes!(state: Container::Running)
39       end
40   end
41
42   def create_minimal_req! attrs={}
43     defaults = {
44       command: ["echo", "foo"],
45       container_image: links(:docker_image_collection_tag).name,
46       cwd: "/tmp",
47       environment: {},
48       mounts: {"/out" => {"kind" => "tmp", "capacity" => 1000000}},
49       output_path: "/out",
50       runtime_constraints: {"vcpus" => 1, "ram" => 2},
51       name: "foo",
52       description: "bar",
53     }
54     cr = ContainerRequest.create!(defaults.merge(attrs))
55     cr.reload
56     return cr
57   end
58
59   def check_bogus_states cr
60     [nil, "Flubber"].each do |state|
61       assert_raises(ActiveRecord::RecordInvalid) do
62         cr.state = state
63         cr.save!
64       end
65       cr.reload
66     end
67   end
68
69   def configure_preemptible_instance_type
70     Rails.configuration.InstanceTypes = ConfigLoader.to_OrderedOptions({
71       "a1.small.pre" => {
72         "Preemptible" => true,
73         "Price" => 0.1,
74         "ProviderType" => "a1.small",
75         "VCPUs" => 1,
76         "RAM" => 1000000000,
77       },
78     })
79   end
80
81   test "Container request create" do
82     set_user_from_auth :active
83     cr = create_minimal_req!
84
85     assert_nil cr.container_uuid
86     assert_equal 0, cr.priority
87
88     check_bogus_states cr
89
90     # Ensure we can modify all attributes
91     cr.command = ["echo", "foo3"]
92     cr.container_image = "img3"
93     cr.cwd = "/tmp3"
94     cr.environment = {"BUP" => "BOP"}
95     cr.mounts = {"BAR" => {"kind" => "BAZ"}}
96     cr.output_path = "/tmp4"
97     cr.priority = 2
98     cr.runtime_constraints = {"vcpus" => 4}
99     cr.name = "foo3"
100     cr.description = "bar3"
101     cr.save!
102
103     assert_nil cr.container_uuid
104   end
105
106   [
107     {"runtime_constraints" => {"vcpus" => 1}},
108     {"runtime_constraints" => {"vcpus" => 1, "ram" => nil}},
109     {"runtime_constraints" => {"vcpus" => 0, "ram" => 123}},
110     {"runtime_constraints" => {"vcpus" => "1", "ram" => -1}},
111     {"mounts" => {"FOO" => "BAR"}},
112     {"mounts" => {"FOO" => {}}},
113     {"mounts" => {"FOO" => {"kind" => "tmp", "capacity" => 42.222}}},
114     {"command" => ["echo", 55]},
115     {"environment" => {"FOO" => 55}}
116   ].each do |value|
117     test "Create with invalid #{value}" do
118       set_user_from_auth :active
119       assert_raises(ActiveRecord::RecordInvalid) do
120         cr = create_minimal_req!({state: "Committed",
121                priority: 1}.merge(value))
122         cr.save!
123       end
124     end
125
126     test "Update with invalid #{value}" do
127       set_user_from_auth :active
128       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
129       cr.save!
130       assert_raises(ActiveRecord::RecordInvalid) do
131         cr = ContainerRequest.find_by_uuid cr.uuid
132         cr.update_attributes!({state: "Committed",
133                                priority: 1}.merge(value))
134       end
135     end
136   end
137
138   test "Update from fixture" do
139     set_user_from_auth :active
140     cr = ContainerRequest.find_by_uuid(container_requests(:running).uuid)
141     cr.update_attributes!(description: "New description")
142     assert_equal "New description", cr.description
143   end
144
145   test "Update with valid runtime constraints" do
146       set_user_from_auth :active
147       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
148       cr.save!
149       cr = ContainerRequest.find_by_uuid cr.uuid
150       cr.update_attributes!(state: "Committed",
151                             runtime_constraints: {"vcpus" => 1, "ram" => 23})
152       assert_not_nil cr.container_uuid
153   end
154
155   test "Container request priority must be non-nil" do
156     set_user_from_auth :active
157     cr = create_minimal_req!
158     cr.priority = nil
159     cr.state = "Committed"
160     assert_raises(ActiveRecord::RecordInvalid) do
161       cr.save!
162     end
163   end
164
165   test "Container request commit" do
166     set_user_from_auth :active
167     cr = create_minimal_req!(runtime_constraints: {"vcpus" => 2, "ram" => 300000000})
168
169     assert_nil cr.container_uuid
170
171     cr.reload
172     cr.state = "Committed"
173     cr.priority = 1
174     cr.save!
175
176     cr.reload
177
178     assert_empty({"vcpus" => 2, "ram" => 300000000}.to_a - cr.runtime_constraints.to_a)
179
180     assert_equal 0, Rails.configuration.Containers.DefaultKeepCacheRAM
181
182     assert_not_nil cr.container_uuid
183     c = Container.find_by_uuid cr.container_uuid
184     assert_not_nil c
185     assert_equal ["echo", "foo"], c.command
186     assert_equal collections(:docker_image).portable_data_hash, c.container_image
187     assert_equal "/tmp", c.cwd
188     assert_equal({}, c.environment)
189     assert_equal({"/out" => {"kind"=>"tmp", "capacity"=>1000000}}, c.mounts)
190     assert_equal "/out", c.output_path
191     assert ({"keep_cache_disk" => 2<<30, "keep_cache_ram" => 0, "vcpus" => 2, "ram" => 300000000}.to_a - c.runtime_constraints.to_a).empty?
192     assert_operator 0, :<, c.priority
193
194     assert_raises(ActiveRecord::RecordInvalid) do
195       cr.priority = nil
196       cr.save!
197     end
198
199     cr.priority = 0
200     cr.save!
201
202     cr.reload
203     c.reload
204     assert_equal 0, cr.priority
205     assert_equal 0, c.priority
206   end
207
208   test "Independent container requests" do
209     set_user_from_auth :active
210     cr1 = create_minimal_req!(command: ["foo", "1"], priority: 5, state: "Committed")
211     cr2 = create_minimal_req!(command: ["foo", "2"], priority: 10, state: "Committed")
212
213     c1 = Container.find_by_uuid cr1.container_uuid
214     assert_operator 0, :<, c1.priority
215
216     c2 = Container.find_by_uuid cr2.container_uuid
217     assert_operator c1.priority, :<, c2.priority
218     c2priority_was = c2.priority
219
220     cr1.update_attributes!(priority: 0)
221
222     c1.reload
223     assert_equal 0, c1.priority
224
225     c2.reload
226     assert_equal c2priority_was, c2.priority
227   end
228
229   test "Request is finalized when its container is cancelled" do
230     set_user_from_auth :active
231     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 1)
232     assert_equal users(:active).uuid, cr.modified_by_user_uuid
233
234     act_as_system_user do
235       Container.find_by_uuid(cr.container_uuid).
236         update_attributes!(state: Container::Cancelled, cost: 1.25)
237     end
238
239     cr.reload
240     assert_equal "Final", cr.state
241     assert_equal 1.25, cr.cumulative_cost
242     assert_equal users(:active).uuid, cr.modified_by_user_uuid
243   end
244
245   test "Request is finalized when its container is completed" do
246     set_user_from_auth :active
247     project = groups(:private)
248     cr = create_minimal_req!(owner_uuid: project.uuid,
249                              priority: 1,
250                              state: "Committed")
251     assert_equal users(:active).uuid, cr.modified_by_user_uuid
252
253     c = act_as_system_user do
254       c = Container.find_by_uuid(cr.container_uuid)
255       c.update_attributes!(state: Container::Locked)
256       c.update_attributes!(state: Container::Running)
257       c
258     end
259
260     cr.reload
261     assert_equal "Committed", cr.state
262
263     output_pdh = '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
264     log_pdh = 'fa7aeb5140e2848d39b416daeef4ffc5+45'
265     act_as_system_user do
266       c.update_attributes!(state: Container::Complete,
267                            cost: 1.25,
268                            output: output_pdh,
269                            log: log_pdh)
270     end
271
272     cr.reload
273     assert_equal "Final", cr.state
274     assert_equal 1.25, cr.cumulative_cost
275     assert_equal users(:active).uuid, cr.modified_by_user_uuid
276
277     assert_not_nil cr.output_uuid
278     assert_not_nil cr.log_uuid
279     output = Collection.find_by_uuid cr.output_uuid
280     assert_equal output_pdh, output.portable_data_hash
281     assert_equal output.owner_uuid, project.uuid, "Container output should be copied to #{project.uuid}"
282     assert_not_nil output.modified_at
283
284     log = Collection.find_by_uuid cr.log_uuid
285     assert_equal log.manifest_text, ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
286 ./log\\040for\\040container\\040#{cr.container_uuid} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n"
287
288     assert_equal log.owner_uuid, project.uuid, "Container log should be copied to #{project.uuid}"
289   end
290
291   # This tests bug report #16144
292   test "Request is finalized when its container is completed even when log & output don't exist" do
293     set_user_from_auth :active
294     project = groups(:private)
295     cr = create_minimal_req!(owner_uuid: project.uuid,
296                              priority: 1,
297                              state: "Committed")
298     assert_equal users(:active).uuid, cr.modified_by_user_uuid
299
300     output_pdh = '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
301     log_pdh = 'fa7aeb5140e2848d39b416daeef4ffc5+45'
302
303     c = act_as_system_user do
304       c = Container.find_by_uuid(cr.container_uuid)
305       c.update_attributes!(state: Container::Locked)
306       c.update_attributes!(state: Container::Running,
307                            output: output_pdh,
308                            log: log_pdh)
309       c
310     end
311
312     cr.reload
313     assert_equal "Committed", cr.state
314
315     act_as_system_user do
316       Collection.where(portable_data_hash: output_pdh).delete_all
317       Collection.where(portable_data_hash: log_pdh).delete_all
318       c.update_attributes!(state: Container::Complete)
319     end
320
321     cr.reload
322     assert_equal "Final", cr.state
323   end
324
325   # This tests bug report #16144
326   test "Can destroy CR even if its container doesn't exist" do
327     set_user_from_auth :active
328     project = groups(:private)
329     cr = create_minimal_req!(owner_uuid: project.uuid,
330                              priority: 1,
331                              state: "Committed")
332     assert_equal users(:active).uuid, cr.modified_by_user_uuid
333
334     c = act_as_system_user do
335       c = Container.find_by_uuid(cr.container_uuid)
336       c.update_attributes!(state: Container::Locked)
337       c.update_attributes!(state: Container::Running)
338       c
339     end
340
341     cr.reload
342     assert_equal "Committed", cr.state
343
344     cr_uuid = cr.uuid
345     act_as_system_user do
346       Container.find_by_uuid(cr.container_uuid).destroy
347       cr.destroy
348     end
349     assert_nil ContainerRequest.find_by_uuid(cr_uuid)
350   end
351
352   test "Container makes container request, then is cancelled" do
353     set_user_from_auth :active
354     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 1)
355
356     c = Container.find_by_uuid cr.container_uuid
357     assert_operator 0, :<, c.priority
358     lock_and_run(c)
359
360     cr2 = with_container_auth(c) do
361       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
362     end
363     assert_equal c.uuid, cr2.requesting_container_uuid
364     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
365
366     c2 = Container.find_by_uuid cr2.container_uuid
367     assert_operator 0, :<, c2.priority
368
369     act_as_system_user do
370       c.state = "Cancelled"
371       c.save!
372     end
373
374     cr.reload
375     assert_equal "Final", cr.state
376
377     cr2.reload
378     assert_equal 0, cr2.priority
379     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
380
381     c2.reload
382     assert_equal 0, c2.priority
383   end
384
385   test "child container priority follows same ordering as corresponding top-level ancestors" do
386     findctr = lambda { |cr| Container.find_by_uuid(cr.container_uuid) }
387
388     set_user_from_auth :active
389
390     toplevel_crs = [
391       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "0"}),
392       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "1"}),
393       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "2"}),
394     ]
395     parents = toplevel_crs.map(&findctr)
396
397     children_crs = parents.map do |parent|
398       lock_and_run(parent)
399       with_container_auth(parent) do
400         create_minimal_req!(state: "Committed",
401                             priority: 1,
402                             environment: {"child" => parent.environment["workflow"]})
403       end
404     end
405     children = children_crs.map(&findctr)
406
407     grandchildren = children.reverse.map do |child|
408       lock_and_run(child)
409       with_container_auth(child) do
410         create_minimal_req!(state: "Committed",
411                             priority: 1,
412                             environment: {"grandchild" => child.environment["child"]})
413       end
414     end.reverse.map(&findctr)
415
416     shared_grandchildren = children.map do |child|
417       with_container_auth(child) do
418         create_minimal_req!(state: "Committed",
419                             priority: 1,
420                             environment: {"grandchild" => "shared"})
421       end
422     end.map(&findctr)
423
424     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[1].uuid
425     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[2].uuid
426     shared_grandchild = shared_grandchildren[0]
427
428     set_user_from_auth :active
429
430     # parents should be prioritized by submit time.
431     assert_operator parents[0].priority, :>, parents[1].priority
432     assert_operator parents[1].priority, :>, parents[2].priority
433
434     # children should be prioritized in same order as their respective
435     # parents.
436     assert_operator children[0].priority, :>, children[1].priority
437     assert_operator children[1].priority, :>, children[2].priority
438
439     # grandchildren should also be prioritized in the same order,
440     # despite having been submitted in the opposite order.
441     assert_operator grandchildren[0].priority, :>, grandchildren[1].priority
442     assert_operator grandchildren[1].priority, :>, grandchildren[2].priority
443
444     # shared grandchild container should be prioritized above
445     # everything that isn't needed by parents[0], but not above
446     # earlier-submitted descendants of parents[0]
447     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
448     assert_operator shared_grandchild.priority, :>, children[1].priority
449     assert_operator shared_grandchild.priority, :>, parents[1].priority
450     assert_operator shared_grandchild.priority, :<=, grandchildren[0].priority
451     assert_operator shared_grandchild.priority, :<=, children[0].priority
452     assert_operator shared_grandchild.priority, :<=, parents[0].priority
453
454     # increasing priority of the most recent toplevel container should
455     # reprioritize all of its descendants (including the shared
456     # grandchild) above everything else.
457     toplevel_crs[2].update_attributes!(priority: 72)
458     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
459     assert_operator shared_grandchild.priority, :>, grandchildren[0].priority
460     assert_operator shared_grandchild.priority, :>, children[0].priority
461     assert_operator shared_grandchild.priority, :>, parents[0].priority
462     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
463     assert_operator shared_grandchild.priority, :>, children[1].priority
464     assert_operator shared_grandchild.priority, :>, parents[1].priority
465     # ...but the shared container should not have higher priority than
466     # the earlier-submitted descendants of the high-priority workflow.
467     assert_operator shared_grandchild.priority, :<=, grandchildren[2].priority
468     assert_operator shared_grandchild.priority, :<=, children[2].priority
469     assert_operator shared_grandchild.priority, :<=, parents[2].priority
470
471     # cancelling the most recent toplevel container should
472     # reprioritize all of its descendants (except the shared
473     # grandchild) to zero
474     toplevel_crs[2].update_attributes!(priority: 0)
475     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
476     assert_operator 0, :==, parents[2].priority
477     assert_operator 0, :==, children[2].priority
478     assert_operator 0, :==, grandchildren[2].priority
479     assert_operator shared_grandchild.priority, :==, grandchildren[0].priority
480
481     # cancel a child request, the parent should be > 0 but
482     # the child and grandchild go to 0.
483     children_crs[1].update_attributes!(priority: 0)
484     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
485     assert_operator 0, :<, parents[1].priority
486     assert_operator parents[0].priority, :>, parents[1].priority
487     assert_operator 0, :==, children[1].priority
488     assert_operator 0, :==, grandchildren[1].priority
489     assert_operator shared_grandchild.priority, :==, grandchildren[0].priority
490
491     # update the parent, it should get a higher priority but the children and
492     # grandchildren should remain at 0
493     toplevel_crs[1].update_attributes!(priority: 6)
494     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
495     assert_operator 0, :<, parents[1].priority
496     assert_operator parents[0].priority, :<, parents[1].priority
497     assert_operator 0, :==, children[1].priority
498     assert_operator 0, :==, grandchildren[1].priority
499     assert_operator shared_grandchild.priority, :==, grandchildren[0].priority
500   end
501
502   [
503     ['running_container_auth', 'zzzzz-dz642-runningcontainr', 501],
504     ['active_no_prefs', nil, 0]
505   ].each do |token, expected, expected_priority|
506     test "create as #{token} and expect requesting_container_uuid to be #{expected}" do
507       set_user_from_auth token
508       cr = create_minimal_req!
509       assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
510       assert_equal expected, cr.requesting_container_uuid
511       assert_equal expected_priority, cr.priority
512     end
513   end
514
515   [
516     [:admin, 0, "output"],
517     [:admin, 19, "output"],
518     [:admin, nil, "output"],
519     [:running_container_auth, 0, "intermediate"],
520     [:running_container_auth, 29, "intermediate"],
521     [:running_container_auth, nil, "intermediate"],
522   ].each do |token, exit_code, expect_output_type|
523     test "container with exit_code #{exit_code} has collection types set with output type #{expect_output_type}" do
524       final_state = if exit_code.nil?
525                       Container::Cancelled
526                     else
527                       Container::Complete
528                     end
529       set_user_from_auth token
530       request = create_minimal_req!(
531         container_count_max: 1,
532         priority: 500,
533         state: ContainerRequest::Committed,
534       )
535       run_container(request, final_state: final_state, exit_code: exit_code)
536       request.reload
537       assert_equal(ContainerRequest::Final, request.state)
538
539       output = Collection.find_by_uuid(request.output_uuid)
540       assert_not_nil(output)
541       assert_equal(request.uuid, output.properties["container_request"])
542       assert_equal(expect_output_type, output.properties["type"])
543
544       log = Collection.find_by_uuid(request.log_uuid)
545       assert_not_nil(log)
546       assert_equal(request.uuid, log.properties["container_request"])
547       assert_equal("log", log.properties["type"])
548     end
549   end
550
551   test "create as container_runtime_token and expect requesting_container_uuid to be zzzzz-dz642-20isqbkl8xwnsao" do
552     set_user_from_auth :container_runtime_token
553     Thread.current[:token] = "#{Thread.current[:token]}/zzzzz-dz642-20isqbkl8xwnsao"
554     cr = ContainerRequest.create(container_image: "img", output_path: "/tmp", command: ["echo", "foo"])
555     assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
556     assert_equal 'zzzzz-dz642-20isqbkl8xwnsao', cr.requesting_container_uuid
557     assert_equal 1, cr.priority
558   end
559
560   [[{"vcpus" => [2, nil]},
561     lambda { |resolved| resolved["vcpus"] == 2 }],
562    [{"vcpus" => [3, 7]},
563     lambda { |resolved| resolved["vcpus"] == 3 }],
564    [{"vcpus" => 4},
565     lambda { |resolved| resolved["vcpus"] == 4 }],
566    [{"ram" => [1000000000, 2000000000]},
567     lambda { |resolved| resolved["ram"] == 1000000000 }],
568    [{"ram" => [1234234234]},
569     lambda { |resolved| resolved["ram"] == 1234234234 }],
570   ].each do |rc, okfunc|
571     test "resolve runtime constraint range #{rc} to values" do
572       resolved = Container.resolve_runtime_constraints(rc)
573       assert(okfunc.call(resolved),
574              "container runtime_constraints was #{resolved.inspect}")
575     end
576   end
577
578   [[{"/out" => {
579         "kind" => "collection",
580         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
581         "path" => "/foo"}},
582     lambda do |resolved|
583       resolved["/out"] == {
584         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
585         "kind" => "collection",
586         "path" => "/foo",
587       }
588     end],
589    [{"/out" => {
590         "kind" => "collection",
591         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
592         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
593         "path" => "/foo"}},
594     lambda do |resolved|
595       resolved["/out"] == {
596         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
597         "kind" => "collection",
598         "path" => "/foo",
599       }
600     end],
601    [{"/out" => {
602       "kind" => "collection",
603       "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
604       "path" => "/foo"}},
605     lambda do |resolved|
606       resolved["/out"] == {
607         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
608         "kind" => "collection",
609         "path" => "/foo",
610       }
611     end],
612     # Empty collection
613     [{"/out" => {
614       "kind" => "collection",
615       "path" => "/foo"}},
616     lambda do |resolved|
617       resolved["/out"] == {
618         "kind" => "collection",
619         "path" => "/foo",
620       }
621     end],
622   ].each do |mounts, okfunc|
623     test "resolve mounts #{mounts.inspect} to values" do
624       set_user_from_auth :active
625       resolved = Container.resolve_mounts(mounts)
626       assert(okfunc.call(resolved),
627              "Container.resolve_mounts returned #{resolved.inspect}")
628     end
629   end
630
631   test 'mount unreadable collection' do
632     set_user_from_auth :spectator
633     m = {
634       "/foo" => {
635         "kind" => "collection",
636         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
637         "path" => "/foo",
638       },
639     }
640     assert_raises(ArvadosModel::UnresolvableContainerError) do
641       Container.resolve_mounts(m)
642     end
643   end
644
645   test 'mount collection with mismatched UUID and PDH' do
646     set_user_from_auth :active
647     m = {
648       "/foo" => {
649         "kind" => "collection",
650         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
651         "portable_data_hash" => "fa7aeb5140e2848d39b416daeef4ffc5+45",
652         "path" => "/foo",
653       },
654     }
655     resolved_mounts = Container.resolve_mounts(m)
656     assert_equal m['portable_data_hash'], resolved_mounts['portable_data_hash']
657   end
658
659   ['arvados/apitestfixture:latest',
660    'arvados/apitestfixture',
661    'd8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678',
662   ].each do |tag|
663     test "Container.resolve_container_image(#{tag.inspect})" do
664       set_user_from_auth :active
665       resolved = Container.resolve_container_image(tag)
666       assert_equal resolved, collections(:docker_image).portable_data_hash
667     end
668   end
669
670   test "Container.resolve_container_image(pdh)" do
671     set_user_from_auth :active
672     [[:docker_image, 'v1'], [:docker_image_1_12, 'v2']].each do |coll, ver|
673       Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({ver=>{}})
674       pdh = collections(coll).portable_data_hash
675       resolved = Container.resolve_container_image(pdh)
676       assert_equal resolved, pdh
677     end
678   end
679
680   ['acbd18db4cc2f85cedef654fccc4a4d8+3',
681    'ENOEXIST',
682    'arvados/apitestfixture:ENOEXIST',
683   ].each do |img|
684     test "container_image_for_container(#{img.inspect}) => 422" do
685       set_user_from_auth :active
686       assert_raises(ArvadosModel::UnresolvableContainerError) do
687         Container.resolve_container_image(img)
688       end
689     end
690   end
691
692   test "allow unrecognized container when there are remote_hosts" do
693     set_user_from_auth :active
694     Rails.configuration.RemoteClusters = Rails.configuration.RemoteClusters.merge({foooo: ActiveSupport::InheritableOptions.new({Host: "bar.com"})})
695     Container.resolve_container_image('acbd18db4cc2f85cedef654fccc4a4d8+3')
696   end
697
698   test "migrated docker image" do
699     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v2'=>{}})
700     add_docker19_migration_link
701
702     # Test that it returns only v2 images even though request is for v1 image.
703
704     set_user_from_auth :active
705     cr = create_minimal_req!(command: ["true", "1"],
706                              container_image: collections(:docker_image).portable_data_hash)
707     assert_equal(Container.resolve_container_image(cr.container_image),
708                  collections(:docker_image_1_12).portable_data_hash)
709
710     cr = create_minimal_req!(command: ["true", "2"],
711                              container_image: links(:docker_image_collection_tag).name)
712     assert_equal(Container.resolve_container_image(cr.container_image),
713                  collections(:docker_image_1_12).portable_data_hash)
714   end
715
716   test "use unmigrated docker image" do
717     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v1'=>{}})
718     add_docker19_migration_link
719
720     # Test that it returns only supported v1 images even though there is a
721     # migration link.
722
723     set_user_from_auth :active
724     cr = create_minimal_req!(command: ["true", "1"],
725                              container_image: collections(:docker_image).portable_data_hash)
726     assert_equal(Container.resolve_container_image(cr.container_image),
727                  collections(:docker_image).portable_data_hash)
728
729     cr = create_minimal_req!(command: ["true", "2"],
730                              container_image: links(:docker_image_collection_tag).name)
731     assert_equal(Container.resolve_container_image(cr.container_image),
732                  collections(:docker_image).portable_data_hash)
733   end
734
735   test "incompatible docker image v1" do
736     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v1'=>{}})
737     add_docker19_migration_link
738
739     # Don't return unsupported v2 image even if we ask for it directly.
740     set_user_from_auth :active
741     cr = create_minimal_req!(command: ["true", "1"],
742                              container_image: collections(:docker_image_1_12).portable_data_hash)
743     assert_raises(ArvadosModel::UnresolvableContainerError) do
744       Container.resolve_container_image(cr.container_image)
745     end
746   end
747
748   test "incompatible docker image v2" do
749     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v2'=>{}})
750     # No migration link, don't return unsupported v1 image,
751
752     set_user_from_auth :active
753     cr = create_minimal_req!(command: ["true", "1"],
754                              container_image: collections(:docker_image).portable_data_hash)
755     assert_raises(ArvadosModel::UnresolvableContainerError) do
756       Container.resolve_container_image(cr.container_image)
757     end
758     cr = create_minimal_req!(command: ["true", "2"],
759                              container_image: links(:docker_image_collection_tag).name)
760     assert_raises(ArvadosModel::UnresolvableContainerError) do
761       Container.resolve_container_image(cr.container_image)
762     end
763   end
764
765   test "requestor can retrieve container owned by dispatch" do
766     assert_not_empty Container.readable_by(users(:admin)).where(uuid: containers(:running).uuid)
767     assert_not_empty Container.readable_by(users(:active)).where(uuid: containers(:running).uuid)
768     assert_empty Container.readable_by(users(:spectator)).where(uuid: containers(:running).uuid)
769   end
770
771   [
772     [{"var" => "value1"}, {"var" => "value1"}, nil],
773     [{"var" => "value1"}, {"var" => "value1"}, true],
774     [{"var" => "value1"}, {"var" => "value1"}, false],
775     [{"var" => "value1"}, {"var" => "value2"}, nil],
776   ].each do |env1, env2, use_existing|
777     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
778       common_attrs = {cwd: "test",
779                       priority: 1,
780                       command: ["echo", "hello"],
781                       output_path: "test",
782                       runtime_constraints: {"vcpus" => 4,
783                                             "ram" => 12000000000},
784                       mounts: {"test" => {"kind" => "json"}}}
785       set_user_from_auth :active
786       cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed,
787                                                     environment: env1}))
788       run_container(cr1)
789       cr1.reload
790       if use_existing.nil?
791         # Testing with use_existing default value
792         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
793                                                       environment: env2}))
794       else
795
796         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
797                                                       environment: env2,
798                                                       use_existing: use_existing}))
799       end
800       assert_not_nil cr1.container_uuid
801       assert_nil cr2.container_uuid
802
803       # Update cr2 to commited state and check for container equality on different cases:
804       # * When env1 and env2 are equal and use_existing is true, the same container
805       #   should be assigned.
806       # * When use_existing is false, a different container should be assigned.
807       # * When env1 and env2 are different, a different container should be assigned.
808       cr2.update_attributes!({state: ContainerRequest::Committed})
809       assert_equal (cr2.use_existing == true and (env1 == env2)),
810                    (cr1.container_uuid == cr2.container_uuid)
811     end
812   end
813
814   test "requesting_container_uuid at create is not allowed" do
815     set_user_from_auth :active
816     assert_raises(ActiveRecord::RecordInvalid) do
817       create_minimal_req!(state: "Uncommitted", priority: 1, requesting_container_uuid: 'youcantdothat')
818     end
819   end
820
821   test "Retry on container cancelled" do
822     set_user_from_auth :active
823     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2)
824     cr2 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "baz"])
825     prev_container_uuid = cr.container_uuid
826
827     c = act_as_system_user do
828       c = Container.find_by_uuid(cr.container_uuid)
829       c.update_attributes!(state: Container::Locked)
830       c.update_attributes!(state: Container::Running)
831       c
832     end
833
834     cr.reload
835     cr2.reload
836     assert_equal "Committed", cr.state
837     assert_equal prev_container_uuid, cr.container_uuid
838     assert_not_equal cr2.container_uuid, cr.container_uuid
839     prev_container_uuid = cr.container_uuid
840
841     act_as_system_user do
842       c.update_attributes!(cost: 0.5, subrequests_cost: 1.25)
843       c.update_attributes!(state: Container::Cancelled)
844     end
845
846     cr.reload
847     cr2.reload
848     assert_equal "Committed", cr.state
849     assert_not_equal prev_container_uuid, cr.container_uuid
850     assert_not_equal cr2.container_uuid, cr.container_uuid
851     prev_container_uuid = cr.container_uuid
852
853     c = act_as_system_user do
854       c = Container.find_by_uuid(cr.container_uuid)
855       c.update_attributes!(state: Container::Locked)
856       c.update_attributes!(state: Container::Running)
857       c.update_attributes!(cost: 0.125)
858       c.update_attributes!(state: Container::Cancelled)
859       c
860     end
861
862     cr.reload
863     cr2.reload
864     assert_equal "Final", cr.state
865     assert_equal prev_container_uuid, cr.container_uuid
866     assert_not_equal cr2.container_uuid, cr.container_uuid
867     assert_equal 1.875, cr.cumulative_cost
868   end
869
870   test "Retry on container cancelled with runtime_token" do
871     set_user_from_auth :spectator
872     spec = api_client_authorizations(:active)
873     cr = create_minimal_req!(priority: 1, state: "Committed",
874                              runtime_token: spec.token,
875                              container_count_max: 2)
876     prev_container_uuid = cr.container_uuid
877
878     c = act_as_system_user do
879       c = Container.find_by_uuid(cr.container_uuid)
880       assert_equal spec.token, c.runtime_token
881       c.update_attributes!(state: Container::Locked)
882       c.update_attributes!(state: Container::Running)
883       c
884     end
885
886     cr.reload
887     assert_equal "Committed", cr.state
888     assert_equal prev_container_uuid, cr.container_uuid
889     prev_container_uuid = cr.container_uuid
890
891     act_as_system_user do
892       c.update_attributes!(state: Container::Cancelled)
893     end
894
895     cr.reload
896     assert_equal "Committed", cr.state
897     assert_not_equal prev_container_uuid, cr.container_uuid
898     prev_container_uuid = cr.container_uuid
899
900     c = act_as_system_user do
901       c = Container.find_by_uuid(cr.container_uuid)
902       assert_equal spec.token, c.runtime_token
903       c.update_attributes!(state: Container::Cancelled)
904       c
905     end
906
907     cr.reload
908     assert_equal "Final", cr.state
909     assert_equal prev_container_uuid, cr.container_uuid
910   end
911
912
913   test "Retry saves logs from previous attempts" do
914     set_user_from_auth :active
915     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 3)
916
917     c = act_as_system_user do
918       c = Container.find_by_uuid(cr.container_uuid)
919       c.update_attributes!(state: Container::Locked)
920       c.update_attributes!(state: Container::Running)
921       c
922     end
923
924     container_uuids = []
925
926     [0, 1, 2].each do
927       cr.reload
928       assert_equal "Committed", cr.state
929       container_uuids << cr.container_uuid
930
931       c = act_as_system_user do
932         logc = Collection.new(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
933         logc.save!
934         c = Container.find_by_uuid(cr.container_uuid)
935         c.update_attributes!(state: Container::Cancelled, log: logc.portable_data_hash)
936         c
937       end
938     end
939
940     container_uuids.sort!
941
942     cr.reload
943     assert_equal "Final", cr.state
944     assert_equal 3, cr.container_count
945     assert_equal ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
946 ./log\\040for\\040container\\040#{container_uuids[0]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
947 ./log\\040for\\040container\\040#{container_uuids[1]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
948 ./log\\040for\\040container\\040#{container_uuids[2]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
949 " , Collection.find_by_uuid(cr.log_uuid).manifest_text
950
951   end
952
953   test "Output collection name setting using output_name with name collision resolution" do
954     set_user_from_auth :active
955     output_name = 'unimaginative name'
956     Collection.create!(name: output_name)
957
958     cr = create_minimal_req!(priority: 1,
959                              state: ContainerRequest::Committed,
960                              output_name: output_name)
961     run_container(cr)
962     cr.reload
963     assert_equal ContainerRequest::Final, cr.state
964     output_coll = Collection.find_by_uuid(cr.output_uuid)
965     # Make sure the resulting output collection name include the original name
966     # plus the date
967     assert_not_equal output_name, output_coll.name,
968                      "more than one collection with the same owner and name"
969     assert output_coll.name.include?(output_name),
970            "New name should include original name"
971     assert_match /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z/, output_coll.name,
972                  "New name should include ISO8601 date"
973   end
974
975   [[0, :check_output_ttl_0],
976    [1, :check_output_ttl_1s],
977    [365*86400, :check_output_ttl_1y],
978   ].each do |ttl, checker|
979     test "output_ttl=#{ttl}" do
980       act_as_user users(:active) do
981         cr = create_minimal_req!(priority: 1,
982                                  state: ContainerRequest::Committed,
983                                  output_name: 'foo',
984                                  output_ttl: ttl)
985         run_container(cr)
986         cr.reload
987         output = Collection.find_by_uuid(cr.output_uuid)
988         send(checker, db_current_time, output.trash_at, output.delete_at)
989       end
990     end
991   end
992
993   def check_output_ttl_0(now, trash, delete)
994     assert_nil(trash)
995     assert_nil(delete)
996   end
997
998   def check_output_ttl_1s(now, trash, delete)
999     assert_not_nil(trash)
1000     assert_not_nil(delete)
1001     assert_in_delta(trash, now + 1.second, 10)
1002     assert_in_delta(delete, now + Rails.configuration.Collections.BlobSigningTTL, 10)
1003   end
1004
1005   def check_output_ttl_1y(now, trash, delete)
1006     year = (86400*365).second
1007     assert_not_nil(trash)
1008     assert_not_nil(delete)
1009     assert_in_delta(trash, now + year, 10)
1010     assert_in_delta(delete, now + year, 10)
1011   end
1012
1013   def run_container(cr, final_state: Container::Complete, exit_code: 0)
1014     act_as_system_user do
1015       logc = Collection.new(owner_uuid: system_user_uuid,
1016                             manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
1017       logc.save!
1018
1019       c = Container.find_by_uuid(cr.container_uuid)
1020       c.update_attributes!(state: Container::Locked)
1021       c.update_attributes!(state: Container::Running)
1022       c.update_attributes!(state: final_state,
1023                            exit_code: exit_code,
1024                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1025                            log: logc.portable_data_hash)
1026       logc.destroy
1027       c
1028     end
1029   end
1030
1031   test "Finalize committed request when reusing a finished container" do
1032     set_user_from_auth :active
1033     cr = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
1034     cr.reload
1035     assert_equal ContainerRequest::Committed, cr.state
1036     run_container(cr)
1037     cr.reload
1038     assert_equal ContainerRequest::Final, cr.state
1039
1040     cr2 = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
1041     assert_equal cr.container_uuid, cr2.container_uuid
1042     assert_equal ContainerRequest::Final, cr2.state
1043
1044     cr3 = create_minimal_req!(priority: 1, state: ContainerRequest::Uncommitted)
1045     assert_equal ContainerRequest::Uncommitted, cr3.state
1046     cr3.update_attributes!(state: ContainerRequest::Committed)
1047     assert_equal cr.container_uuid, cr3.container_uuid
1048     assert_equal ContainerRequest::Final, cr3.state
1049   end
1050
1051   [
1052     # client requests preemptible, but types are not configured
1053     [false, false, false, true, ActiveRecord::RecordInvalid],
1054     [true, false, false, true, ActiveRecord::RecordInvalid],
1055     # client requests preemptible, types are configured
1056     [false, true, false, true, true],
1057     [true, true, false, true, true],
1058     # client requests non-preemptible for top-level container
1059     [false, false, false, false, false],
1060     [true, false, false, false, false],
1061     [false, true, false, false, false],
1062     [true, true, false, false, false],
1063     # client requests non-preemptible for child container, preemptible
1064     # is enabled anyway if AlwaysUsePreemptibleInstances and instance types
1065     # are configured.
1066     [false, false, true, false, false],
1067     [true, false, true, false, false],
1068     [false, true, true, false, false],
1069     [true, true, true, false, true],
1070   ].each do |use_preemptible, have_preemptible, is_child, ask, expect|
1071     test "with AlwaysUsePreemptibleInstances=#{use_preemptible} and preemptible types #{have_preemptible ? '' : 'not '}configured, create #{is_child ? 'child' : 'top-level'} container request with preemptible=#{ask} and expect #{expect}" do
1072       Rails.configuration.Containers.AlwaysUsePreemptibleInstances = use_preemptible
1073       if have_preemptible
1074         configure_preemptible_instance_type
1075       end
1076       common_attrs = {
1077         cwd: "test",
1078         priority: 1,
1079         command: ["echo", "hello"],
1080         output_path: "test",
1081         scheduling_parameters: {"preemptible" => ask},
1082         mounts: {"test" => {"kind" => "json"}},
1083       }
1084       set_user_from_auth :active
1085
1086       if is_child
1087         cr = with_container_auth(containers(:running)) do
1088           create_minimal_req!(common_attrs)
1089         end
1090       else
1091         cr = create_minimal_req!(common_attrs)
1092       end
1093
1094       cr.reload
1095       cr.state = ContainerRequest::Committed
1096
1097       if expect == true || expect == false
1098         cr.save!
1099         assert_equal expect, cr.scheduling_parameters["preemptible"]
1100       else
1101         assert_raises(expect) do
1102           cr.save!
1103         end
1104       end
1105     end
1106   end
1107
1108   test "config update does not flip preemptible flag on already-committed container requests" do
1109     parent = containers(:running_container_with_logs)
1110     attrs_p = {
1111       scheduling_parameters: {"preemptible" => true},
1112       "state" => "Committed",
1113       "priority" => 1,
1114     }
1115     attrs_nonp = {
1116       scheduling_parameters: {"preemptible" => false},
1117       "state" => "Committed",
1118       "priority" => 1,
1119     }
1120     expect = {false => [], true => []}
1121
1122     with_container_auth(parent) do
1123       configure_preemptible_instance_type
1124       Rails.configuration.Containers.AlwaysUsePreemptibleInstances = false
1125
1126       expect[true].push create_minimal_req!(attrs_p)
1127       expect[false].push create_minimal_req!(attrs_nonp)
1128
1129       Rails.configuration.Containers.AlwaysUsePreemptibleInstances = true
1130
1131       expect[true].push create_minimal_req!(attrs_p)
1132       expect[true].push create_minimal_req!(attrs_nonp)
1133       commit_later = create_minimal_req!()
1134
1135       Rails.configuration.InstanceTypes = ConfigLoader.to_OrderedOptions({})
1136
1137       expect[false].push create_minimal_req!(attrs_nonp)
1138
1139       # Even though preemptible is not allowed, we should be able to
1140       # commit a CR that was created earlier when preemptible was the
1141       # default.
1142       commit_later.update_attributes!(priority: 1, state: "Committed")
1143       expect[false].push commit_later
1144     end
1145
1146     set_user_from_auth :active
1147     [false, true].each do |pflag|
1148       expect[pflag].each do |cr|
1149         cr.reload
1150         assert_equal pflag, cr.scheduling_parameters['preemptible']
1151       end
1152     end
1153
1154     act_as_system_user do
1155       # Cancelling the parent used to fail while updating the child
1156       # containers' priority, because the child containers' unchanged
1157       # preemptible fields caused validation to fail.
1158       parent.update_attributes!(state: 'Cancelled')
1159
1160       [false, true].each do |pflag|
1161         expect[pflag].each do |cr|
1162           cr.reload
1163           assert_equal 0, cr.priority, "unexpected non-zero priority #{cr.priority} for #{cr.uuid}"
1164         end
1165       end
1166     end
1167   end
1168
1169   [
1170     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1171     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Uncommitted],
1172     [{"partitions" => "fastcpu"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1173     [{"partitions" => "fastcpu"}, ContainerRequest::Uncommitted],
1174     [{"partitions" => ["fastcpu","vfastcpu"]}, ContainerRequest::Committed],
1175     [{"max_run_time" => "one day"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1176     [{"max_run_time" => "one day"}, ContainerRequest::Uncommitted],
1177     [{"max_run_time" => -1}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1178     [{"max_run_time" => -1}, ContainerRequest::Uncommitted],
1179     [{"max_run_time" => 86400}, ContainerRequest::Committed],
1180   ].each do |sp, state, expected|
1181     test "create container request with scheduling_parameters #{sp} in state #{state} and verify #{expected}" do
1182       common_attrs = {cwd: "test",
1183                       priority: 1,
1184                       command: ["echo", "hello"],
1185                       output_path: "test",
1186                       scheduling_parameters: sp,
1187                       mounts: {"test" => {"kind" => "json"}}}
1188       set_user_from_auth :active
1189
1190       if expected == ActiveRecord::RecordInvalid
1191         assert_raises(ActiveRecord::RecordInvalid) do
1192           create_minimal_req!(common_attrs.merge({state: state}))
1193         end
1194       else
1195         cr = create_minimal_req!(common_attrs.merge({state: state}))
1196         assert (sp.to_a - cr.scheduling_parameters.to_a).empty?
1197
1198         if state == ContainerRequest::Committed
1199           c = Container.find_by_uuid(cr.container_uuid)
1200           assert (sp.to_a - c.scheduling_parameters.to_a).empty?
1201         end
1202       end
1203     end
1204   end
1205
1206   test "AlwaysUsePreemptibleInstances makes child containers preemptible" do
1207     Rails.configuration.Containers.AlwaysUsePreemptibleInstances = true
1208     common_attrs = {cwd: "test",
1209                     priority: 1,
1210                     command: ["echo", "hello"],
1211                     output_path: "test",
1212                     state: ContainerRequest::Committed,
1213                     mounts: {"test" => {"kind" => "json"}}}
1214     set_user_from_auth :active
1215     configure_preemptible_instance_type
1216
1217     cr = with_container_auth(Container.find_by_uuid 'zzzzz-dz642-runningcontainr') do
1218       create_minimal_req!(common_attrs)
1219     end
1220     assert_equal 'zzzzz-dz642-runningcontainr', cr.requesting_container_uuid
1221     assert_equal true, cr.scheduling_parameters["preemptible"]
1222
1223     c = Container.find_by_uuid(cr.container_uuid)
1224     assert_equal true, c.scheduling_parameters["preemptible"]
1225   end
1226
1227   [['Committed', true, {name: "foobar", priority: 123}],
1228    ['Committed', false, {container_count: 2}],
1229    ['Committed', false, {container_count: 0}],
1230    ['Committed', false, {container_count: nil}],
1231    ['Committed', true, {priority: 0, mounts: {"/out" => {"kind" => "tmp", "capacity" => 1000000}}}],
1232    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp"}}}],
1233    # Addition of default values for mounts / runtime_constraints /
1234    # scheduling_parameters, as happens in a round-trip through
1235    # controller, does not have any real effect and should be
1236    # accepted/ignored rather than causing an error when the CR state
1237    # dictates those attributes are not allowed to change.
1238    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 0, "kind" => "tmp"}}}, {mounts: {"/out" => {"kind" => "tmp"}}}],
1239    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "exclude_from_output": false}}}],
1240    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "repository_name": ""}}}],
1241    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "content": nil}}}],
1242    ['Committed', false, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "content": {}}}}],
1243    ['Committed', false, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "repository_name": "foo"}}}],
1244    ['Committed', false, {priority: 0, mounts: {"/out" => {"kind" => "tmp", "capacity" => 1234567}}}],
1245    ['Committed', false, {priority: 0, mounts: {}}],
1246    ['Committed', true, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2}}],
1247    ['Committed', true, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "keep_cache_ram" => 0}}],
1248    ['Committed', true, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "API" => false}}],
1249    ['Committed', false, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "keep_cache_ram" => 1}}],
1250    ['Committed', false, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "API" => true}}],
1251    ['Committed', true, {priority: 0, scheduling_parameters: {"preemptible" => false}}],
1252    ['Committed', true, {priority: 0, scheduling_parameters: {"partitions" => []}}],
1253    ['Committed', true, {priority: 0, scheduling_parameters: {"max_run_time" => 0}}],
1254    ['Committed', false, {priority: 0, scheduling_parameters: {"preemptible" => true}}],
1255    ['Committed', false, {priority: 0, scheduling_parameters: {"partitions" => ["foo"]}}],
1256    ['Committed', false, {priority: 0, scheduling_parameters: {"max_run_time" => 1}}],
1257    ['Final', false, {state: ContainerRequest::Committed, name: "foobar"}],
1258    ['Final', false, {name: "foobar", priority: 123}],
1259    ['Final', false, {name: "foobar", output_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1260    ['Final', false, {name: "foobar", log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1261    ['Final', false, {log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1262    ['Final', false, {priority: 123}],
1263    ['Final', false, {mounts: {}}],
1264    ['Final', false, {container_count: 2}],
1265    ['Final', true, {name: "foobar"}],
1266    ['Final', true, {name: "foobar", description: "baz"}],
1267   ].each do |state, permitted, updates, create_attrs|
1268     test "state=#{state} can#{'not' if !permitted} update #{updates.inspect}" do
1269       act_as_user users(:active) do
1270         attrs = {
1271           priority: 1,
1272           state: "Committed",
1273           container_count_max: 1
1274         }
1275         if !create_attrs.nil?
1276           attrs.merge!(create_attrs)
1277         end
1278         cr = create_minimal_req!(attrs)
1279         case state
1280         when 'Committed'
1281           # already done
1282         when 'Final'
1283           act_as_system_user do
1284             Container.find_by_uuid(cr.container_uuid).
1285               update_attributes!(state: Container::Cancelled)
1286           end
1287           cr.reload
1288         else
1289           raise 'broken test case'
1290         end
1291         assert_equal state, cr.state
1292         if permitted
1293           assert cr.update_attributes!(updates)
1294         else
1295           assert_raises(ActiveRecord::RecordInvalid) do
1296             cr.update_attributes!(updates)
1297           end
1298         end
1299       end
1300     end
1301   end
1302
1303   test "delete container_request and check its container's priority" do
1304     act_as_user users(:active) do
1305       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
1306
1307       # initially the cr's container has priority > 0
1308       c = Container.find_by_uuid(cr.container_uuid)
1309       assert_equal 1, c.priority
1310
1311       cr.destroy
1312
1313       # the cr's container now has priority of 0
1314       c = Container.find_by_uuid(cr.container_uuid)
1315       assert_equal 0, c.priority
1316     end
1317   end
1318
1319   test "delete container_request in final state and expect no error due to before_destroy callback" do
1320     act_as_user users(:active) do
1321       cr = ContainerRequest.find_by_uuid container_requests(:completed).uuid
1322       assert_nothing_raised {cr.destroy}
1323     end
1324   end
1325
1326   test "Container request valid priority" do
1327     set_user_from_auth :active
1328     cr = create_minimal_req!
1329
1330     assert_raises(ActiveRecord::RecordInvalid) do
1331       cr.priority = -1
1332       cr.save!
1333     end
1334
1335     cr.priority = 0
1336     cr.save!
1337
1338     cr.priority = 1
1339     cr.save!
1340
1341     cr.priority = 500
1342     cr.save!
1343
1344     cr.priority = 999
1345     cr.save!
1346
1347     cr.priority = 1000
1348     cr.save!
1349
1350     assert_raises(ActiveRecord::RecordInvalid) do
1351       cr.priority = 1001
1352       cr.save!
1353     end
1354   end
1355
1356   # Note: some of these tests might look redundant because they test
1357   # that out-of-order spellings of hashes are still considered equal
1358   # regardless of whether the existing (container) or new (container
1359   # request) hash needs to be re-ordered.
1360   secrets = {"/foo" => {"kind" => "text", "content" => "xyzzy"}}
1361   same_secrets = {"/foo" => {"content" => "xyzzy", "kind" => "text"}}
1362   different_secrets = {"/foo" => {"kind" => "text", "content" => "something completely different"}}
1363   [
1364     [true, nil, nil],
1365     [true, nil, {}],
1366     [true, {}, nil],
1367     [true, {}, {}],
1368     [true, secrets, same_secrets],
1369     [true, same_secrets, secrets],
1370     [false, nil, secrets],
1371     [false, {}, secrets],
1372     [false, secrets, {}],
1373     [false, secrets, nil],
1374     [false, secrets, different_secrets],
1375   ].each do |expect_reuse, sm1, sm2|
1376     test "container reuse secret_mounts #{sm1.inspect}, #{sm2.inspect}" do
1377       set_user_from_auth :active
1378       cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm1)
1379       cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm2)
1380       assert_not_nil cr1.container_uuid
1381       assert_not_nil cr2.container_uuid
1382       if expect_reuse
1383         assert_equal cr1.container_uuid, cr2.container_uuid
1384       else
1385         assert_not_equal cr1.container_uuid, cr2.container_uuid
1386       end
1387     end
1388   end
1389
1390   test "scrub secret_mounts but reuse container for request with identical secret_mounts" do
1391     set_user_from_auth :active
1392     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1393     cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1394     run_container(cr1)
1395     cr1.reload
1396
1397     # secret_mounts scrubbed from db
1398     c = Container.where(uuid: cr1.container_uuid).first
1399     assert_equal({}, c.secret_mounts)
1400     assert_equal({}, cr1.secret_mounts)
1401
1402     # can reuse container if secret_mounts match
1403     cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1404     assert_equal cr1.container_uuid, cr2.container_uuid
1405
1406     # don't reuse container if secret_mounts don't match
1407     cr3 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: {})
1408     assert_not_equal cr1.container_uuid, cr3.container_uuid
1409
1410     assert_no_secrets_logged
1411   end
1412
1413   test "conflicting key in mounts and secret_mounts" do
1414     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1415     set_user_from_auth :active
1416     cr = create_minimal_req!
1417     assert_equal false, cr.update_attributes(state: "Committed",
1418                                              priority: 1,
1419                                              mounts: cr.mounts.merge(sm),
1420                                              secret_mounts: sm)
1421     assert_equal [:secret_mounts], cr.errors.messages.keys
1422   end
1423
1424   test "using runtime_token" do
1425     set_user_from_auth :spectator
1426     spec = api_client_authorizations(:active)
1427     cr = create_minimal_req!(state: "Committed", runtime_token: spec.token, priority: 1)
1428     cr.save!
1429     c = Container.find_by_uuid cr.container_uuid
1430     lock_and_run c
1431     assert_nil c.auth_uuid
1432     assert_equal c.runtime_token, spec.token
1433
1434     assert_not_nil ApiClientAuthorization.find_by_uuid(spec.uuid)
1435
1436     act_as_system_user do
1437       c.update_attributes!(state: Container::Complete,
1438                            exit_code: 0,
1439                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1440                            log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
1441     end
1442
1443     cr.reload
1444     c.reload
1445     assert_nil cr.runtime_token
1446     assert_nil c.runtime_token
1447   end
1448
1449   test "invalid runtime_token" do
1450     set_user_from_auth :active
1451     spec = api_client_authorizations(:spectator)
1452     assert_raises(ArgumentError) do
1453       cr = create_minimal_req!(state: "Committed", runtime_token: "#{spec.token}xx")
1454       cr.save!
1455     end
1456   end
1457
1458   test "default output_storage_classes" do
1459     saved = Rails.configuration.DefaultStorageClasses
1460     Rails.configuration.DefaultStorageClasses = ["foo"]
1461     begin
1462       act_as_user users(:active) do
1463         cr = create_minimal_req!(priority: 1,
1464                                  state: ContainerRequest::Committed,
1465                                  output_name: 'foo')
1466         run_container(cr)
1467         cr.reload
1468         output = Collection.find_by_uuid(cr.output_uuid)
1469         assert_equal ["foo"], output.storage_classes_desired
1470       end
1471     ensure
1472       Rails.configuration.DefaultStorageClasses = saved
1473     end
1474   end
1475
1476   test "setting output_storage_classes" do
1477     act_as_user users(:active) do
1478       cr = create_minimal_req!(priority: 1,
1479                                state: ContainerRequest::Committed,
1480                                output_name: 'foo',
1481                                output_storage_classes: ["foo_storage_class", "bar_storage_class"])
1482       run_container(cr)
1483       cr.reload
1484       output = Collection.find_by_uuid(cr.output_uuid)
1485       assert_equal ["foo_storage_class", "bar_storage_class"], output.storage_classes_desired
1486       log = Collection.find_by_uuid(cr.log_uuid)
1487       assert_equal ["foo_storage_class", "bar_storage_class"], log.storage_classes_desired
1488     end
1489   end
1490
1491   test "reusing container with different container_request.output_storage_classes" do
1492     common_attrs = {cwd: "test",
1493                     priority: 1,
1494                     command: ["echo", "hello"],
1495                     output_path: "test",
1496                     runtime_constraints: {"vcpus" => 4,
1497                                           "ram" => 12000000000},
1498                     mounts: {"test" => {"kind" => "json"}},
1499                     environment: {"var" => "value1"},
1500                     output_storage_classes: ["foo_storage_class"]}
1501     set_user_from_auth :active
1502     cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed}))
1503     cont1 = run_container(cr1)
1504     cr1.reload
1505
1506     output1 = Collection.find_by_uuid(cr1.output_uuid)
1507
1508     # Testing with use_existing default value
1509     cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
1510                                                   output_storage_classes: ["bar_storage_class"]}))
1511
1512     assert_not_nil cr1.container_uuid
1513     assert_nil cr2.container_uuid
1514
1515     # Update cr2 to commited state, check for reuse, then run it
1516     cr2.update_attributes!({state: ContainerRequest::Committed})
1517     assert_equal cr1.container_uuid, cr2.container_uuid
1518
1519     cr2.reload
1520     output2 = Collection.find_by_uuid(cr2.output_uuid)
1521
1522     # the original CR output has the original storage class,
1523     # but the second CR output has the new storage class.
1524     assert_equal ["foo_storage_class"], cont1.output_storage_classes
1525     assert_equal ["foo_storage_class"], output1.storage_classes_desired
1526     assert_equal ["bar_storage_class"], output2.storage_classes_desired
1527   end
1528
1529   [
1530     [{},               {},           {"type": "output"}],
1531     [{"a1": "b1"},     {},           {"type": "output", "a1": "b1"}],
1532     [{},               {"a1": "b1"}, {"type": "output", "a1": "b1"}],
1533     [{"a1": "b1"},     {"a1": "c1"}, {"type": "output", "a1": "b1"}],
1534     [{"a1": "b1"},     {"a2": "c2"}, {"type": "output", "a1": "b1", "a2": "c2"}],
1535     [{"type": "blah"}, {},           {"type": "blah"}],
1536   ].each do |cr_prop, container_prop, expect_prop|
1537     test "setting output_properties #{cr_prop} #{container_prop} on current container" do
1538       act_as_user users(:active) do
1539         cr = create_minimal_req!(priority: 1,
1540                                  state: ContainerRequest::Committed,
1541                                  output_name: 'foo',
1542                                  output_properties: cr_prop)
1543
1544         act_as_system_user do
1545           logc = Collection.new(owner_uuid: system_user_uuid,
1546                                 manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
1547           logc.save!
1548
1549           c = Container.find_by_uuid(cr.container_uuid)
1550           c.update_attributes!(state: Container::Locked)
1551           c.update_attributes!(state: Container::Running)
1552
1553           c.update_attributes!(output_properties: container_prop)
1554
1555           c.update_attributes!(state: Container::Complete,
1556                                exit_code: 0,
1557                                output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1558                                log: logc.portable_data_hash)
1559           logc.destroy
1560         end
1561
1562         cr.reload
1563         expect_prop["container_request"] = cr.uuid
1564         output = Collection.find_by_uuid(cr.output_uuid)
1565         assert_equal expect_prop.symbolize_keys, output.properties.symbolize_keys
1566       end
1567     end
1568   end
1569
1570   test "Cumulative cost includes retried attempts but not reused containers" do
1571     set_user_from_auth :active
1572     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 3)
1573     c = Container.find_by_uuid cr.container_uuid
1574     act_as_system_user do
1575       c.update_attributes!(state: Container::Locked)
1576       c.update_attributes!(state: Container::Running)
1577       c.update_attributes!(state: Container::Cancelled, cost: 3)
1578     end
1579     cr.reload
1580     assert_equal 3, cr.cumulative_cost
1581
1582     c = Container.find_by_uuid cr.container_uuid
1583     lock_and_run c
1584     c.reload
1585     assert_equal 0, c.subrequests_cost
1586
1587     # cr2 is a child/subrequest
1588     cr2 = with_container_auth(c) do
1589       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
1590     end
1591     assert_equal c.uuid, cr2.requesting_container_uuid
1592     c2 = Container.find_by_uuid cr2.container_uuid
1593     act_as_system_user do
1594       c2.update_attributes!(state: Container::Locked)
1595       c2.update_attributes!(state: Container::Running)
1596       logc = Collection.new(owner_uuid: system_user_uuid,
1597                             manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
1598       logc.save!
1599       c2.update_attributes!(state: Container::Complete,
1600                             exit_code: 0,
1601                             output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1602                             log: logc.portable_data_hash,
1603                             cost: 7)
1604     end
1605     c.reload
1606     assert_equal 7, c.subrequests_cost
1607
1608     # cr3 is an identical child/subrequest, will reuse c2
1609     cr3 = with_container_auth(c) do
1610       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
1611     end
1612     assert_equal c.uuid, cr3.requesting_container_uuid
1613     c3 = Container.find_by_uuid cr3.container_uuid
1614     assert_equal c2.uuid, c3.uuid
1615     assert_equal Container::Complete, c3.state
1616     c.reload
1617     assert_equal 7, c.subrequests_cost
1618
1619     act_as_system_user do
1620       c.update_attributes!(state: Container::Complete, exit_code: 0, cost: 9)
1621     end
1622
1623     c.reload
1624     assert_equal 7, c.subrequests_cost
1625     cr.reload
1626     assert_equal 3+7+9, cr.cumulative_cost
1627   end
1628
1629 end