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