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