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