21700: Install Bundler system-wide in Rails postinst
[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!(state: Container::Locked)
38         ctr.update!(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!({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!(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!(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!(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!(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!(state: Container::Locked)
256       c.update!(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!(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!(state: Container::Locked)
306       c.update!(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!(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!(state: Container::Locked)
337       c.update!(state: Container::Running)
338       c
339     end
340
341     cr.reload
342     assert_equal "Committed", cr.state
343
344     cr_uuid = cr.uuid
345     act_as_system_user do
346       Container.find_by_uuid(cr.container_uuid).destroy
347       cr.destroy
348     end
349     assert_nil ContainerRequest.find_by_uuid(cr_uuid)
350   end
351
352   test "Container makes container request, then is cancelled" do
353     set_user_from_auth :active
354     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 1)
355
356     c = Container.find_by_uuid cr.container_uuid
357     assert_operator 0, :<, c.priority
358     lock_and_run(c)
359
360     cr2 = with_container_auth(c) do
361       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
362     end
363     assert_equal c.uuid, cr2.requesting_container_uuid
364     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
365
366     c2 = Container.find_by_uuid cr2.container_uuid
367     assert_operator 0, :<, c2.priority
368
369     act_as_system_user do
370       c.state = "Cancelled"
371       c.save!
372     end
373
374     cr.reload
375     assert_equal "Final", cr.state
376
377     cr2.reload
378     assert_equal 0, cr2.priority
379     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
380
381     c2.reload
382     assert_equal 0, c2.priority
383   end
384
385   test "child container priority follows same ordering as corresponding top-level ancestors" do
386     findctr = lambda { |cr| Container.find_by_uuid(cr.container_uuid) }
387
388     set_user_from_auth :active
389
390     toplevel_crs = [
391       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "0"}),
392       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "1"}),
393       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "2"}),
394     ]
395     parents = toplevel_crs.map(&findctr)
396
397     children_crs = parents.map do |parent|
398       lock_and_run(parent)
399       with_container_auth(parent) do
400         create_minimal_req!(state: "Committed",
401                             priority: 1,
402                             environment: {"child" => parent.environment["workflow"]})
403       end
404     end
405     children = children_crs.map(&findctr)
406
407     grandchildren = children.reverse.map do |child|
408       lock_and_run(child)
409       with_container_auth(child) do
410         create_minimal_req!(state: "Committed",
411                             priority: 1,
412                             environment: {"grandchild" => child.environment["child"]})
413       end
414     end.reverse.map(&findctr)
415
416     shared_grandchildren = children.map do |child|
417       with_container_auth(child) do
418         create_minimal_req!(state: "Committed",
419                             priority: 1,
420                             environment: {"grandchild" => "shared"})
421       end
422     end.map(&findctr)
423
424     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[1].uuid
425     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[2].uuid
426     shared_grandchild = shared_grandchildren[0]
427
428     set_user_from_auth :active
429
430     # parents should be prioritized by submit time.
431     assert_operator parents[0].priority, :>, parents[1].priority
432     assert_operator parents[1].priority, :>, parents[2].priority
433
434     # children should be prioritized in same order as their respective
435     # parents.
436     assert_operator children[0].priority, :>, children[1].priority
437     assert_operator children[1].priority, :>, children[2].priority
438
439     # grandchildren should also be prioritized in the same order,
440     # despite having been submitted in the opposite order.
441     assert_operator grandchildren[0].priority, :>, grandchildren[1].priority
442     assert_operator grandchildren[1].priority, :>, grandchildren[2].priority
443
444     # shared grandchild container should be prioritized above
445     # everything that isn't needed by parents[0], but not above
446     # earlier-submitted descendants of parents[0]
447     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
448     assert_operator shared_grandchild.priority, :>, children[1].priority
449     assert_operator shared_grandchild.priority, :>, parents[1].priority
450     assert_operator shared_grandchild.priority, :<=, grandchildren[0].priority
451     assert_operator shared_grandchild.priority, :<=, children[0].priority
452     assert_operator shared_grandchild.priority, :<=, parents[0].priority
453
454     # increasing priority of the most recent toplevel container should
455     # reprioritize all of its descendants (including the shared
456     # grandchild) above everything else.
457     toplevel_crs[2].update!(priority: 72)
458     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
459     assert_operator shared_grandchild.priority, :>, grandchildren[0].priority
460     assert_operator shared_grandchild.priority, :>, children[0].priority
461     assert_operator shared_grandchild.priority, :>, parents[0].priority
462     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
463     assert_operator shared_grandchild.priority, :>, children[1].priority
464     assert_operator shared_grandchild.priority, :>, parents[1].priority
465     # ...but the shared container should not have higher priority than
466     # the earlier-submitted descendants of the high-priority workflow.
467     assert_operator shared_grandchild.priority, :<=, grandchildren[2].priority
468     assert_operator shared_grandchild.priority, :<=, children[2].priority
469     assert_operator shared_grandchild.priority, :<=, parents[2].priority
470
471     # cancelling the most recent toplevel container should
472     # reprioritize all of its descendants (except the shared
473     # grandchild) to zero
474     toplevel_crs[2].update!(priority: 0)
475     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
476     assert_operator 0, :==, parents[2].priority
477     assert_operator 0, :==, children[2].priority
478     assert_operator 0, :==, grandchildren[2].priority
479     assert_operator shared_grandchild.priority, :==, grandchildren[0].priority
480
481     # cancel a child request, the parent should be > 0 but
482     # the child and grandchild go to 0.
483     children_crs[1].update!(priority: 0)
484     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
485     assert_operator 0, :<, parents[1].priority
486     assert_operator parents[0].priority, :>, parents[1].priority
487     assert_operator 0, :==, children[1].priority
488     assert_operator 0, :==, grandchildren[1].priority
489     assert_operator shared_grandchild.priority, :==, grandchildren[0].priority
490
491     # update the parent, it should get a higher priority but the children and
492     # grandchildren should remain at 0
493     toplevel_crs[1].update!(priority: 6)
494     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
495     assert_operator 0, :<, parents[1].priority
496     assert_operator parents[0].priority, :<, parents[1].priority
497     assert_operator 0, :==, children[1].priority
498     assert_operator 0, :==, grandchildren[1].priority
499     assert_operator shared_grandchild.priority, :==, grandchildren[0].priority
500   end
501
502   [
503     ['running_container_auth', 'zzzzz-dz642-runningcontainr', 501],
504     ['active_no_prefs', nil, 0]
505   ].each do |token, expected, expected_priority|
506     test "create as #{token} and expect requesting_container_uuid to be #{expected}" do
507       set_user_from_auth token
508       cr = create_minimal_req!
509       assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
510       assert_equal expected, cr.requesting_container_uuid
511       assert_equal expected_priority, cr.priority
512     end
513   end
514
515   [
516     [:admin, 0, "output"],
517     [:admin, 19, "output"],
518     [:admin, nil, "output"],
519     [:running_container_auth, 0, "intermediate"],
520     [:running_container_auth, 29, "intermediate"],
521     [:running_container_auth, nil, "intermediate"],
522   ].each do |token, exit_code, expect_output_type|
523     test "container with exit_code #{exit_code} has collection types set with output type #{expect_output_type}" do
524       final_state = if exit_code.nil?
525                       Container::Cancelled
526                     else
527                       Container::Complete
528                     end
529       set_user_from_auth token
530       request = create_minimal_req!(
531         container_count_max: 1,
532         priority: 500,
533         state: ContainerRequest::Committed,
534       )
535       run_container(request, final_state: final_state, exit_code: exit_code)
536       request.reload
537       assert_equal(ContainerRequest::Final, request.state)
538
539       output = Collection.find_by_uuid(request.output_uuid)
540       assert_not_nil(output)
541       assert_equal(request.uuid, output.properties["container_request"])
542       assert_equal(expect_output_type, output.properties["type"])
543
544       log = Collection.find_by_uuid(request.log_uuid)
545       assert_not_nil(log)
546       assert_equal(request.uuid, log.properties["container_request"])
547       assert_equal("log", log.properties["type"])
548     end
549   end
550
551   test "create as container_runtime_token and expect requesting_container_uuid to be zzzzz-dz642-20isqbkl8xwnsao" do
552     set_user_from_auth :container_runtime_token
553     Thread.current[:token] = "#{Thread.current[:token]}/zzzzz-dz642-20isqbkl8xwnsao"
554     cr = ContainerRequest.create(container_image: "img", output_path: "/tmp", command: ["echo", "foo"])
555     assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
556     assert_equal 'zzzzz-dz642-20isqbkl8xwnsao', cr.requesting_container_uuid
557     assert_equal 1, cr.priority
558   end
559
560   [[{"vcpus" => [2, nil]},
561     lambda { |resolved| resolved["vcpus"] == 2 }],
562    [{"vcpus" => [3, 7]},
563     lambda { |resolved| resolved["vcpus"] == 3 }],
564    [{"vcpus" => 4},
565     lambda { |resolved| resolved["vcpus"] == 4 }],
566    [{"ram" => [1000000000, 2000000000]},
567     lambda { |resolved| resolved["ram"] == 1000000000 }],
568    [{"ram" => [1234234234]},
569     lambda { |resolved| resolved["ram"] == 1234234234 }],
570   ].each do |rc, okfunc|
571     test "resolve runtime constraint range #{rc} to values" do
572       resolved = Container.resolve_runtime_constraints(rc)
573       assert(okfunc.call(resolved),
574              "container runtime_constraints was #{resolved.inspect}")
575     end
576   end
577
578   [[{"/out" => {
579         "kind" => "collection",
580         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
581         "path" => "/foo"}},
582     lambda do |resolved|
583       resolved["/out"] == {
584         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
585         "kind" => "collection",
586         "path" => "/foo",
587       }
588     end],
589    [{"/out" => {
590         "kind" => "collection",
591         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
592         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
593         "path" => "/foo"}},
594     lambda do |resolved|
595       resolved["/out"] == {
596         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
597         "kind" => "collection",
598         "path" => "/foo",
599       }
600     end],
601    [{"/out" => {
602       "kind" => "collection",
603       "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
604       "path" => "/foo"}},
605     lambda do |resolved|
606       resolved["/out"] == {
607         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
608         "kind" => "collection",
609         "path" => "/foo",
610       }
611     end],
612     # Empty collection
613     [{"/out" => {
614       "kind" => "collection",
615       "path" => "/foo"}},
616     lambda do |resolved|
617       resolved["/out"] == {
618         "kind" => "collection",
619         "path" => "/foo",
620       }
621     end],
622   ].each do |mounts, okfunc|
623     test "resolve mounts #{mounts.inspect} to values" do
624       set_user_from_auth :active
625       resolved = Container.resolve_mounts(mounts)
626       assert(okfunc.call(resolved),
627              "Container.resolve_mounts returned #{resolved.inspect}")
628     end
629   end
630
631   test 'mount unreadable collection' do
632     set_user_from_auth :spectator
633     m = {
634       "/foo" => {
635         "kind" => "collection",
636         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
637         "path" => "/foo",
638       },
639     }
640     assert_raises(ArvadosModel::UnresolvableContainerError) do
641       Container.resolve_mounts(m)
642     end
643   end
644
645   test 'mount collection with mismatched UUID and PDH' do
646     set_user_from_auth :active
647     m = {
648       "/foo" => {
649         "kind" => "collection",
650         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
651         "portable_data_hash" => "fa7aeb5140e2848d39b416daeef4ffc5+45",
652         "path" => "/foo",
653       },
654     }
655     resolved_mounts = Container.resolve_mounts(m)
656     assert_equal m['portable_data_hash'], resolved_mounts['portable_data_hash']
657   end
658
659   ['arvados/apitestfixture:latest',
660    'arvados/apitestfixture',
661    'd8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678',
662   ].each do |tag|
663     test "Container.resolve_container_image(#{tag.inspect})" do
664       set_user_from_auth :active
665       resolved = Container.resolve_container_image(tag)
666       assert_equal resolved, collections(:docker_image).portable_data_hash
667     end
668   end
669
670   test "Container.resolve_container_image(pdh)" do
671     set_user_from_auth :active
672     [[:docker_image, 'v1'], [:docker_image_1_12, 'v2']].each do |coll, ver|
673       Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({ver=>{}})
674       pdh = collections(coll).portable_data_hash
675       resolved = Container.resolve_container_image(pdh)
676       assert_equal resolved, pdh
677     end
678   end
679
680   ['acbd18db4cc2f85cedef654fccc4a4d8+3',
681    'ENOEXIST',
682    'arvados/apitestfixture:ENOEXIST',
683   ].each do |img|
684     test "container_image_for_container(#{img.inspect}) => 422" do
685       set_user_from_auth :active
686       assert_raises(ArvadosModel::UnresolvableContainerError) do
687         Container.resolve_container_image(img)
688       end
689     end
690   end
691
692   test "allow unrecognized container when there are remote_hosts" do
693     set_user_from_auth :active
694     Rails.configuration.RemoteClusters = Rails.configuration.RemoteClusters.merge({foooo: ActiveSupport::InheritableOptions.new({Host: "bar.com"})})
695     Container.resolve_container_image('acbd18db4cc2f85cedef654fccc4a4d8+3')
696   end
697
698   test "migrated docker image" do
699     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v2'=>{}})
700     add_docker19_migration_link
701
702     # Test that it returns only v2 images even though request is for v1 image.
703
704     set_user_from_auth :active
705     cr = create_minimal_req!(command: ["true", "1"],
706                              container_image: collections(:docker_image).portable_data_hash)
707     assert_equal(Container.resolve_container_image(cr.container_image),
708                  collections(:docker_image_1_12).portable_data_hash)
709
710     cr = create_minimal_req!(command: ["true", "2"],
711                              container_image: links(:docker_image_collection_tag).name)
712     assert_equal(Container.resolve_container_image(cr.container_image),
713                  collections(:docker_image_1_12).portable_data_hash)
714   end
715
716   test "use unmigrated docker image" do
717     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v1'=>{}})
718     add_docker19_migration_link
719
720     # Test that it returns only supported v1 images even though there is a
721     # migration link.
722
723     set_user_from_auth :active
724     cr = create_minimal_req!(command: ["true", "1"],
725                              container_image: collections(:docker_image).portable_data_hash)
726     assert_equal(Container.resolve_container_image(cr.container_image),
727                  collections(:docker_image).portable_data_hash)
728
729     cr = create_minimal_req!(command: ["true", "2"],
730                              container_image: links(:docker_image_collection_tag).name)
731     assert_equal(Container.resolve_container_image(cr.container_image),
732                  collections(:docker_image).portable_data_hash)
733   end
734
735   test "incompatible docker image v1" do
736     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v1'=>{}})
737     add_docker19_migration_link
738
739     # Don't return unsupported v2 image even if we ask for it directly.
740     set_user_from_auth :active
741     cr = create_minimal_req!(command: ["true", "1"],
742                              container_image: collections(:docker_image_1_12).portable_data_hash)
743     assert_raises(ArvadosModel::UnresolvableContainerError) do
744       Container.resolve_container_image(cr.container_image)
745     end
746   end
747
748   test "incompatible docker image v2" do
749     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v2'=>{}})
750     # No migration link, don't return unsupported v1 image,
751
752     set_user_from_auth :active
753     cr = create_minimal_req!(command: ["true", "1"],
754                              container_image: collections(:docker_image).portable_data_hash)
755     assert_raises(ArvadosModel::UnresolvableContainerError) do
756       Container.resolve_container_image(cr.container_image)
757     end
758     cr = create_minimal_req!(command: ["true", "2"],
759                              container_image: links(:docker_image_collection_tag).name)
760     assert_raises(ArvadosModel::UnresolvableContainerError) do
761       Container.resolve_container_image(cr.container_image)
762     end
763   end
764
765   test "requestor can retrieve container owned by dispatch" do
766     assert_not_empty Container.readable_by(users(:admin)).where(uuid: containers(:running).uuid)
767     assert_not_empty Container.readable_by(users(:active)).where(uuid: containers(:running).uuid)
768     assert_empty Container.readable_by(users(:spectator)).where(uuid: containers(:running).uuid)
769   end
770
771   [
772     [{"var" => "value1"}, {"var" => "value1"}, nil],
773     [{"var" => "value1"}, {"var" => "value1"}, true],
774     [{"var" => "value1"}, {"var" => "value1"}, false],
775     [{"var" => "value1"}, {"var" => "value2"}, nil],
776   ].each do |env1, env2, use_existing|
777     test "Container request #{((env1 == env2) and (use_existing.nil? or use_existing == true)) ? 'does' : 'does not'} reuse container when committed#{use_existing.nil? ? '' : use_existing ? ' and use_existing == true' : ' and use_existing == false'}" do
778       common_attrs = {cwd: "test",
779                       priority: 1,
780                       command: ["echo", "hello"],
781                       output_path: "test",
782                       runtime_constraints: {"vcpus" => 4,
783                                             "ram" => 12000000000},
784                       mounts: {"test" => {"kind" => "json"}}}
785       set_user_from_auth :active
786       cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed,
787                                                     environment: env1}))
788       run_container(cr1)
789       cr1.reload
790       if use_existing.nil?
791         # Testing with use_existing default value
792         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
793                                                       environment: env2}))
794       else
795
796         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
797                                                       environment: env2,
798                                                       use_existing: use_existing}))
799       end
800       assert_not_nil cr1.container_uuid
801       assert_nil cr2.container_uuid
802
803       # Update cr2 to commited state and check for container equality on different cases:
804       # * When env1 and env2 are equal and use_existing is true, the same container
805       #   should be assigned.
806       # * When use_existing is false, a different container should be assigned.
807       # * When env1 and env2 are different, a different container should be assigned.
808       cr2.update!({state: ContainerRequest::Committed})
809       assert_equal (cr2.use_existing == true and (env1 == env2)),
810                    (cr1.container_uuid == cr2.container_uuid)
811     end
812   end
813
814   test "requesting_container_uuid at create is not allowed" do
815     set_user_from_auth :active
816     assert_raises(ActiveRecord::RecordInvalid) do
817       create_minimal_req!(state: "Uncommitted", priority: 1, requesting_container_uuid: 'youcantdothat')
818     end
819   end
820
821   test "Retry on container cancelled" do
822     set_user_from_auth :active
823     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2)
824     cr2 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "baz"])
825     prev_container_uuid = cr.container_uuid
826
827     c = act_as_system_user do
828       c = Container.find_by_uuid(cr.container_uuid)
829       c.update!(state: Container::Locked)
830       c.update!(state: Container::Running)
831       c
832     end
833
834     cr.reload
835     cr2.reload
836     assert_equal "Committed", cr.state
837     assert_equal prev_container_uuid, cr.container_uuid
838     assert_not_equal cr2.container_uuid, cr.container_uuid
839     prev_container_uuid = cr.container_uuid
840
841     act_as_system_user do
842       c.update!(cost: 0.5, subrequests_cost: 1.25)
843       c.update!(state: Container::Cancelled)
844     end
845
846     cr.reload
847     cr2.reload
848     assert_equal "Committed", cr.state
849     assert_not_equal prev_container_uuid, cr.container_uuid
850     assert_not_equal cr2.container_uuid, cr.container_uuid
851     prev_container_uuid = cr.container_uuid
852
853     c = act_as_system_user do
854       c = Container.find_by_uuid(cr.container_uuid)
855       c.update!(state: Container::Locked)
856       c.update!(state: Container::Running)
857       c.update!(cost: 0.125)
858       c.update!(state: Container::Cancelled)
859       c
860     end
861
862     cr.reload
863     cr2.reload
864     assert_equal "Final", cr.state
865     assert_equal prev_container_uuid, cr.container_uuid
866     assert_not_equal cr2.container_uuid, cr.container_uuid
867     assert_equal 1.875, cr.cumulative_cost
868   end
869
870   test "Retry on container cancelled with runtime_token" do
871     set_user_from_auth :spectator
872     spec = api_client_authorizations(:active)
873     cr = create_minimal_req!(priority: 1, state: "Committed",
874                              runtime_token: spec.token,
875                              container_count_max: 2)
876     prev_container_uuid = cr.container_uuid
877
878     c = act_as_system_user do
879       c = Container.find_by_uuid(cr.container_uuid)
880       assert_equal spec.token, c.runtime_token
881       c.update!(state: Container::Locked)
882       c.update!(state: Container::Running)
883       c
884     end
885
886     cr.reload
887     assert_equal "Committed", cr.state
888     assert_equal prev_container_uuid, cr.container_uuid
889     prev_container_uuid = cr.container_uuid
890
891     act_as_system_user do
892       c.update!(state: Container::Cancelled)
893     end
894
895     cr.reload
896     assert_equal "Committed", cr.state
897     assert_not_equal prev_container_uuid, cr.container_uuid
898     prev_container_uuid = cr.container_uuid
899
900     c = act_as_system_user do
901       c = Container.find_by_uuid(cr.container_uuid)
902       assert_equal spec.token, c.runtime_token
903       c.update!(state: Container::Cancelled)
904       c
905     end
906
907     cr.reload
908     assert_equal "Final", cr.state
909     assert_equal prev_container_uuid, cr.container_uuid
910   end
911
912
913   test "Retry saves logs from previous attempts" do
914     set_user_from_auth :active
915     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 3)
916
917     c = act_as_system_user do
918       c = Container.find_by_uuid(cr.container_uuid)
919       c.update!(state: Container::Locked)
920       c.update!(state: Container::Running)
921       c
922     end
923
924     container_uuids = []
925
926     [0, 1, 2].each do
927       cr.reload
928       assert_equal "Committed", cr.state
929       container_uuids << cr.container_uuid
930
931       c = act_as_system_user do
932         logc = Collection.new(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
933         logc.save!
934         c = Container.find_by_uuid(cr.container_uuid)
935         c.update!(state: Container::Cancelled, log: logc.portable_data_hash)
936         c
937       end
938     end
939
940     container_uuids.sort!
941
942     cr.reload
943     assert_equal "Final", cr.state
944     assert_equal 3, cr.container_count
945     assert_equal ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
946 ./log\\040for\\040container\\040#{container_uuids[0]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
947 ./log\\040for\\040container\\040#{container_uuids[1]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
948 ./log\\040for\\040container\\040#{container_uuids[2]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
949 " , Collection.find_by_uuid(cr.log_uuid).manifest_text
950
951   end
952
953   test "Retry sub-request on error" do
954     set_user_from_auth :active
955     cr1 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "foo1"])
956     c1 = Container.find_by_uuid(cr1.container_uuid)
957     act_as_system_user do
958       c1.update!(state: Container::Locked)
959       c1.update!(state: Container::Running)
960     end
961
962     cr2 = with_container_auth(c1) do
963       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo2"])
964     end
965     c2 = Container.find_by_uuid(cr2.container_uuid)
966     act_as_system_user do
967       c2.update!(state: Container::Locked)
968       c2.update!(state: Container::Running)
969     end
970
971     cr3 = with_container_auth(c2) do
972       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo3"])
973     end
974     c3 = Container.find_by_uuid(cr3.container_uuid)
975
976     act_as_system_user do
977       c3.update!(state: Container::Locked)
978       c3.update!(state: Container::Running)
979     end
980
981     # All the containers are in running state
982
983     c3.reload
984     cr3.reload
985
986     # c3 still running
987     assert_equal 'Running', c3.state
988     assert_equal 1, cr3.container_count
989     assert_equal 'Committed', cr3.state
990
991     # c3 goes to cancelled state
992     act_as_system_user do
993       c3.state = "Cancelled"
994       c3.save!
995     end
996
997     cr3.reload
998
999     # Because the parent request is still live, it should
1000     # be retried.
1001     assert_equal 2, cr3.container_count
1002     assert_equal 'Committed', cr3.state
1003   end
1004
1005   test "Do not retry sub-request when process tree is cancelled" do
1006     set_user_from_auth :active
1007     cr1 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "foo1"])
1008     c1 = Container.find_by_uuid(cr1.container_uuid)
1009     act_as_system_user do
1010       c1.update!(state: Container::Locked)
1011       c1.update!(state: Container::Running)
1012     end
1013
1014     cr2 = with_container_auth(c1) do
1015       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo2"])
1016     end
1017     c2 = Container.find_by_uuid(cr2.container_uuid)
1018     act_as_system_user do
1019       c2.update!(state: Container::Locked)
1020       c2.update!(state: Container::Running)
1021     end
1022
1023     cr3 = with_container_auth(c2) do
1024       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo3"])
1025     end
1026     c3 = Container.find_by_uuid(cr3.container_uuid)
1027
1028     act_as_system_user do
1029       c3.update!(state: Container::Locked)
1030       c3.update!(state: Container::Running)
1031     end
1032
1033     # All the containers are in running state
1034
1035     # Now cancel the toplevel container request
1036     act_as_system_user do
1037       cr1.priority = 0
1038       cr1.save!
1039     end
1040
1041     c3.reload
1042     cr3.reload
1043
1044     # c3 still running
1045     assert_equal 'Running', c3.state
1046     assert_equal 1, cr3.container_count
1047     assert_equal 'Committed', cr3.state
1048
1049     # c3 goes to cancelled state
1050     act_as_system_user do
1051       assert_equal 0, c3.priority
1052       c3.state = "Cancelled"
1053       c3.save!
1054     end
1055
1056     cr3.reload
1057
1058     # Because the parent process was cancelled, it _should not_ be
1059     # retried.
1060     assert_equal 1, cr3.container_count
1061     assert_equal 'Final', cr3.state
1062   end
1063
1064   test "Retry process tree on error" do
1065     set_user_from_auth :active
1066     cr1 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "foo1"])
1067     c1 = Container.find_by_uuid(cr1.container_uuid)
1068     act_as_system_user do
1069       c1.update!(state: Container::Locked)
1070       c1.update!(state: Container::Running)
1071     end
1072
1073     cr2 = with_container_auth(c1) do
1074       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo2"])
1075     end
1076     c2 = Container.find_by_uuid(cr2.container_uuid)
1077     act_as_system_user do
1078       c2.update!(state: Container::Locked)
1079       c2.update!(state: Container::Running)
1080     end
1081
1082     cr3 = with_container_auth(c2) do
1083       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo3"])
1084     end
1085     c3 = Container.find_by_uuid(cr3.container_uuid)
1086
1087     act_as_system_user do
1088       c3.update!(state: Container::Locked)
1089       c3.update!(state: Container::Running)
1090     end
1091
1092     # All the containers are in running state
1093
1094     c1.reload
1095
1096     # c1 goes to cancelled state
1097     act_as_system_user do
1098       c1.state = "Cancelled"
1099       c1.save!
1100     end
1101
1102     cr1.reload
1103     cr2.reload
1104     cr3.reload
1105
1106     # Because the root request is still live, it should be retried.
1107     # Assumes the root is something like arvados-cwl-runner where
1108     # container reuse enables it to more or less pick up where it left
1109     # off.
1110     assert_equal 2, cr1.container_count
1111     assert_equal 'Committed', cr1.state
1112
1113     # These keep running.
1114     assert_equal 1, cr2.container_count
1115     assert_equal 'Committed', cr2.state
1116
1117     assert_equal 1, cr3.container_count
1118     assert_equal 'Committed', cr3.state
1119   end
1120
1121   test "Output collection name setting using output_name with name collision resolution" do
1122     set_user_from_auth :active
1123     output_name = 'unimaginative name'
1124     Collection.create!(name: output_name)
1125
1126     cr = create_minimal_req!(priority: 1,
1127                              state: ContainerRequest::Committed,
1128                              output_name: output_name)
1129     run_container(cr)
1130     cr.reload
1131     assert_equal ContainerRequest::Final, cr.state
1132     output_coll = Collection.find_by_uuid(cr.output_uuid)
1133     # Make sure the resulting output collection name include the original name
1134     # plus the last 15 characters of uuid
1135     assert_not_equal output_name, output_coll.name,
1136                      "more than one collection with the same owner and name"
1137     assert output_coll.name.include?(output_name),
1138            "New name should include original name"
1139     assert_match /#{output_coll.uuid[-15..-1]}/, output_coll.name,
1140                  "New name should include last 15 characters of uuid"
1141   end
1142
1143   [[0, :check_output_ttl_0],
1144    [1, :check_output_ttl_1s],
1145    [365*86400, :check_output_ttl_1y],
1146   ].each do |ttl, checker|
1147     test "output_ttl=#{ttl}" do
1148       act_as_user users(:active) do
1149         cr = create_minimal_req!(priority: 1,
1150                                  state: ContainerRequest::Committed,
1151                                  output_name: 'foo',
1152                                  output_ttl: ttl)
1153         run_container(cr)
1154         cr.reload
1155         output = Collection.find_by_uuid(cr.output_uuid)
1156         send(checker, db_current_time, output.trash_at, output.delete_at)
1157       end
1158     end
1159   end
1160
1161   def check_output_ttl_0(now, trash, delete)
1162     assert_nil(trash)
1163     assert_nil(delete)
1164   end
1165
1166   def check_output_ttl_1s(now, trash, delete)
1167     assert_not_nil(trash)
1168     assert_not_nil(delete)
1169     assert_in_delta(trash, now + 1.second, 10)
1170     assert_in_delta(delete, now + Rails.configuration.Collections.BlobSigningTTL, 10)
1171   end
1172
1173   def check_output_ttl_1y(now, trash, delete)
1174     year = (86400*365).second
1175     assert_not_nil(trash)
1176     assert_not_nil(delete)
1177     assert_in_delta(trash, now + year, 10)
1178     assert_in_delta(delete, now + year, 10)
1179   end
1180
1181   def run_container(cr, final_state: Container::Complete, exit_code: 0)
1182     act_as_system_user do
1183       logc = Collection.new(owner_uuid: system_user_uuid,
1184                             manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
1185       logc.save!
1186
1187       c = Container.find_by_uuid(cr.container_uuid)
1188       c.update!(state: Container::Locked)
1189       c.update!(state: Container::Running)
1190       c.update!(state: final_state,
1191                            exit_code: exit_code,
1192                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1193                            log: logc.portable_data_hash)
1194       logc.destroy
1195       c
1196     end
1197   end
1198
1199   test "Finalize committed request when reusing a finished container" do
1200     set_user_from_auth :active
1201     cr = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
1202     cr.reload
1203     assert_equal ContainerRequest::Committed, cr.state
1204     run_container(cr)
1205     cr.reload
1206     assert_equal ContainerRequest::Final, cr.state
1207
1208     cr2 = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
1209     assert_equal cr.container_uuid, cr2.container_uuid
1210     assert_equal ContainerRequest::Final, cr2.state
1211
1212     cr3 = create_minimal_req!(priority: 1, state: ContainerRequest::Uncommitted)
1213     assert_equal ContainerRequest::Uncommitted, cr3.state
1214     cr3.update!(state: ContainerRequest::Committed)
1215     assert_equal cr.container_uuid, cr3.container_uuid
1216     assert_equal ContainerRequest::Final, cr3.state
1217   end
1218
1219   [
1220     # client requests preemptible, but types are not configured
1221     [false, false, false, true, ActiveRecord::RecordInvalid],
1222     [true, false, false, true, ActiveRecord::RecordInvalid],
1223     # client requests preemptible, types are configured
1224     [false, true, false, true, true],
1225     [true, true, false, true, true],
1226     # client requests non-preemptible for top-level container
1227     [false, false, false, false, false],
1228     [true, false, false, false, false],
1229     [false, true, false, false, false],
1230     [true, true, false, false, false],
1231     # client requests non-preemptible for child container, preemptible
1232     # is enabled anyway if AlwaysUsePreemptibleInstances and instance types
1233     # are configured.
1234     [false, false, true, false, false],
1235     [true, false, true, false, false],
1236     [false, true, true, false, false],
1237     [true, true, true, false, true],
1238   ].each do |use_preemptible, have_preemptible, is_child, ask, expect|
1239     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
1240       Rails.configuration.Containers.AlwaysUsePreemptibleInstances = use_preemptible
1241       if have_preemptible
1242         configure_preemptible_instance_type
1243       end
1244       common_attrs = {
1245         cwd: "test",
1246         priority: 1,
1247         command: ["echo", "hello"],
1248         output_path: "test",
1249         scheduling_parameters: {"preemptible" => ask},
1250         mounts: {"test" => {"kind" => "json"}},
1251       }
1252       set_user_from_auth :active
1253
1254       if is_child
1255         cr = with_container_auth(containers(:running)) do
1256           create_minimal_req!(common_attrs)
1257         end
1258       else
1259         cr = create_minimal_req!(common_attrs)
1260       end
1261
1262       cr.reload
1263       cr.state = ContainerRequest::Committed
1264
1265       if expect == true || expect == false
1266         cr.save!
1267         assert_equal expect, cr.scheduling_parameters["preemptible"]
1268       else
1269         assert_raises(expect) do
1270           cr.save!
1271         end
1272       end
1273     end
1274   end
1275
1276   test "config update does not flip preemptible flag on already-committed container requests" do
1277     parent = containers(:running_container_with_logs)
1278     attrs_p = {
1279       scheduling_parameters: {"preemptible" => true},
1280       "state" => "Committed",
1281       "priority" => 1,
1282     }
1283     attrs_nonp = {
1284       scheduling_parameters: {"preemptible" => false},
1285       "state" => "Committed",
1286       "priority" => 1,
1287     }
1288     expect = {false => [], true => []}
1289
1290     with_container_auth(parent) do
1291       configure_preemptible_instance_type
1292       Rails.configuration.Containers.AlwaysUsePreemptibleInstances = false
1293
1294       expect[true].push create_minimal_req!(attrs_p)
1295       expect[false].push create_minimal_req!(attrs_nonp)
1296
1297       Rails.configuration.Containers.AlwaysUsePreemptibleInstances = true
1298
1299       expect[true].push create_minimal_req!(attrs_p)
1300       expect[true].push create_minimal_req!(attrs_nonp)
1301       commit_later = create_minimal_req!()
1302
1303       Rails.configuration.InstanceTypes = ConfigLoader.to_OrderedOptions({})
1304
1305       expect[false].push create_minimal_req!(attrs_nonp)
1306
1307       # Even though preemptible is not allowed, we should be able to
1308       # commit a CR that was created earlier when preemptible was the
1309       # default.
1310       commit_later.update!(priority: 1, state: "Committed")
1311       expect[false].push commit_later
1312     end
1313
1314     set_user_from_auth :active
1315     [false, true].each do |pflag|
1316       expect[pflag].each do |cr|
1317         cr.reload
1318         assert_equal pflag, cr.scheduling_parameters['preemptible']
1319       end
1320     end
1321
1322     act_as_system_user do
1323       # Cancelling the parent used to fail while updating the child
1324       # containers' priority, because the child containers' unchanged
1325       # preemptible fields caused validation to fail.
1326       parent.update!(state: 'Cancelled')
1327
1328       [false, true].each do |pflag|
1329         expect[pflag].each do |cr|
1330           cr.reload
1331           assert_equal 0, cr.priority, "unexpected non-zero priority #{cr.priority} for #{cr.uuid}"
1332         end
1333       end
1334     end
1335   end
1336
1337   [
1338     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1339     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Uncommitted],
1340     [{"partitions" => "fastcpu"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1341     [{"partitions" => "fastcpu"}, ContainerRequest::Uncommitted],
1342     [{"partitions" => ["fastcpu","vfastcpu"]}, ContainerRequest::Committed],
1343     [{"max_run_time" => "one day"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1344     [{"max_run_time" => "one day"}, ContainerRequest::Uncommitted],
1345     [{"max_run_time" => -1}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1346     [{"max_run_time" => -1}, ContainerRequest::Uncommitted],
1347     [{"max_run_time" => 86400}, ContainerRequest::Committed],
1348   ].each do |sp, state, expected|
1349     test "create container request with scheduling_parameters #{sp} in state #{state} and verify #{expected}" do
1350       common_attrs = {cwd: "test",
1351                       priority: 1,
1352                       command: ["echo", "hello"],
1353                       output_path: "test",
1354                       scheduling_parameters: sp,
1355                       mounts: {"test" => {"kind" => "json"}}}
1356       set_user_from_auth :active
1357
1358       if expected == ActiveRecord::RecordInvalid
1359         assert_raises(ActiveRecord::RecordInvalid) do
1360           create_minimal_req!(common_attrs.merge({state: state}))
1361         end
1362       else
1363         cr = create_minimal_req!(common_attrs.merge({state: state}))
1364         assert (sp.to_a - cr.scheduling_parameters.to_a).empty?
1365
1366         if state == ContainerRequest::Committed
1367           c = Container.find_by_uuid(cr.container_uuid)
1368           assert (sp.to_a - c.scheduling_parameters.to_a).empty?
1369         end
1370       end
1371     end
1372   end
1373
1374   test "AlwaysUsePreemptibleInstances makes child containers preemptible" do
1375     Rails.configuration.Containers.AlwaysUsePreemptibleInstances = true
1376     common_attrs = {cwd: "test",
1377                     priority: 1,
1378                     command: ["echo", "hello"],
1379                     output_path: "test",
1380                     state: ContainerRequest::Committed,
1381                     mounts: {"test" => {"kind" => "json"}}}
1382     set_user_from_auth :active
1383     configure_preemptible_instance_type
1384
1385     cr = with_container_auth(Container.find_by_uuid 'zzzzz-dz642-runningcontainr') do
1386       create_minimal_req!(common_attrs)
1387     end
1388     assert_equal 'zzzzz-dz642-runningcontainr', cr.requesting_container_uuid
1389     assert_equal true, cr.scheduling_parameters["preemptible"]
1390
1391     c = Container.find_by_uuid(cr.container_uuid)
1392     assert_equal true, c.scheduling_parameters["preemptible"]
1393   end
1394
1395   [['Committed', true, {name: "foobar", priority: 123}],
1396    ['Committed', false, {container_count: 2}],
1397    ['Committed', false, {container_count: 0}],
1398    ['Committed', false, {container_count: nil}],
1399    ['Committed', true, {priority: 0, mounts: {"/out" => {"kind" => "tmp", "capacity" => 1000000}}}],
1400    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp"}}}],
1401    # Addition of default values for mounts / runtime_constraints /
1402    # scheduling_parameters, as happens in a round-trip through
1403    # controller, does not have any real effect and should be
1404    # accepted/ignored rather than causing an error when the CR state
1405    # dictates those attributes are not allowed to change.
1406    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 0, "kind" => "tmp"}}}, {mounts: {"/out" => {"kind" => "tmp"}}}],
1407    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "exclude_from_output": false}}}],
1408    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "repository_name": ""}}}],
1409    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "content": nil}}}],
1410    ['Committed', false, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "content": {}}}}],
1411    ['Committed', false, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "repository_name": "foo"}}}],
1412    ['Committed', false, {priority: 0, mounts: {"/out" => {"kind" => "tmp", "capacity" => 1234567}}}],
1413    ['Committed', false, {priority: 0, mounts: {}}],
1414    ['Committed', true, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2}}],
1415    ['Committed', true, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "keep_cache_ram" => 0}}],
1416    ['Committed', true, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "API" => false}}],
1417    ['Committed', false, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "keep_cache_ram" => 1}}],
1418    ['Committed', false, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "API" => true}}],
1419    ['Committed', true, {priority: 0, scheduling_parameters: {"preemptible" => false}}],
1420    ['Committed', true, {priority: 0, scheduling_parameters: {"partitions" => []}}],
1421    ['Committed', true, {priority: 0, scheduling_parameters: {"max_run_time" => 0}}],
1422    ['Committed', false, {priority: 0, scheduling_parameters: {"preemptible" => true}}],
1423    ['Committed', false, {priority: 0, scheduling_parameters: {"partitions" => ["foo"]}}],
1424    ['Committed', false, {priority: 0, scheduling_parameters: {"max_run_time" => 1}}],
1425    ['Final', false, {state: ContainerRequest::Committed, name: "foobar"}],
1426    ['Final', false, {name: "foobar", priority: 123}],
1427    ['Final', false, {name: "foobar", output_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1428    ['Final', false, {name: "foobar", log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1429    ['Final', false, {log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1430    ['Final', false, {priority: 123}],
1431    ['Final', false, {mounts: {}}],
1432    ['Final', false, {container_count: 2}],
1433    ['Final', true, {name: "foobar"}],
1434    ['Final', true, {name: "foobar", description: "baz"}],
1435   ].each do |state, permitted, updates, create_attrs|
1436     test "state=#{state} can#{'not' if !permitted} update #{updates.inspect}" do
1437       act_as_user users(:active) do
1438         attrs = {
1439           priority: 1,
1440           state: "Committed",
1441           container_count_max: 1
1442         }
1443         if !create_attrs.nil?
1444           attrs.merge!(create_attrs)
1445         end
1446         cr = create_minimal_req!(attrs)
1447         case state
1448         when 'Committed'
1449           # already done
1450         when 'Final'
1451           act_as_system_user do
1452             Container.find_by_uuid(cr.container_uuid).
1453               update!(state: Container::Cancelled)
1454           end
1455           cr.reload
1456         else
1457           raise 'broken test case'
1458         end
1459         assert_equal state, cr.state
1460         if permitted
1461           assert cr.update!(updates)
1462         else
1463           assert_raises(ActiveRecord::RecordInvalid) do
1464             cr.update!(updates)
1465           end
1466         end
1467       end
1468     end
1469   end
1470
1471   test "delete container_request and check its container's priority" do
1472     act_as_user users(:active) do
1473       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
1474
1475       # initially the cr's container has priority > 0
1476       c = Container.find_by_uuid(cr.container_uuid)
1477       assert_equal 1, c.priority
1478
1479       cr.destroy
1480
1481       # the cr's container now has priority of 0
1482       c.reload
1483       assert_equal 0, c.priority
1484     end
1485   end
1486
1487   test "trash the project containing a container_request and check its container's priority" do
1488     act_as_user users(:active) do
1489       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
1490
1491       # initially the cr's container has priority > 0
1492       c = Container.find_by_uuid(cr.container_uuid)
1493       assert_equal 1, c.priority
1494
1495       prj = Group.find_by_uuid cr.owner_uuid
1496       prj.update!(trash_at: db_current_time)
1497
1498       # the cr's container now has priority of 0
1499       c.reload
1500       assert_equal 0, c.priority
1501
1502       assert_equal c.state, 'Running'
1503       assert_equal cr.state, 'Committed'
1504
1505       # mark the container as cancelled, this should cause the
1506       # container request to go to final state and run the finalize
1507       # function
1508       act_as_system_user do
1509         c.update!(state: 'Cancelled', log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
1510       end
1511       c.reload
1512       cr.reload
1513
1514       assert_equal c.state, 'Cancelled'
1515       assert_equal cr.state, 'Final'
1516       assert_equal nil, cr.log_uuid
1517     end
1518   end
1519
1520   test "delete container_request in final state and expect no error due to before_destroy callback" do
1521     act_as_user users(:active) do
1522       cr = ContainerRequest.find_by_uuid container_requests(:completed).uuid
1523       assert_nothing_raised {cr.destroy}
1524     end
1525   end
1526
1527   test "Container request valid priority" do
1528     set_user_from_auth :active
1529     cr = create_minimal_req!
1530
1531     assert_raises(ActiveRecord::RecordInvalid) do
1532       cr.priority = -1
1533       cr.save!
1534     end
1535
1536     cr.priority = 0
1537     cr.save!
1538
1539     cr.priority = 1
1540     cr.save!
1541
1542     cr.priority = 500
1543     cr.save!
1544
1545     cr.priority = 999
1546     cr.save!
1547
1548     cr.priority = 1000
1549     cr.save!
1550
1551     assert_raises(ActiveRecord::RecordInvalid) do
1552       cr.priority = 1001
1553       cr.save!
1554     end
1555   end
1556
1557   # Note: some of these tests might look redundant because they test
1558   # that out-of-order spellings of hashes are still considered equal
1559   # regardless of whether the existing (container) or new (container
1560   # request) hash needs to be re-ordered.
1561   secrets = {"/foo" => {"kind" => "text", "content" => "xyzzy"}}
1562   same_secrets = {"/foo" => {"content" => "xyzzy", "kind" => "text"}}
1563   different_secrets = {"/foo" => {"kind" => "text", "content" => "something completely different"}}
1564   [
1565     [true, nil, nil],
1566     [true, nil, {}],
1567     [true, {}, nil],
1568     [true, {}, {}],
1569     [true, secrets, same_secrets],
1570     [true, same_secrets, secrets],
1571     [false, nil, secrets],
1572     [false, {}, secrets],
1573     [false, secrets, {}],
1574     [false, secrets, nil],
1575     [false, secrets, different_secrets],
1576   ].each do |expect_reuse, sm1, sm2|
1577     test "container reuse secret_mounts #{sm1.inspect}, #{sm2.inspect}" do
1578       set_user_from_auth :active
1579       cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm1)
1580       cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm2)
1581       assert_not_nil cr1.container_uuid
1582       assert_not_nil cr2.container_uuid
1583       if expect_reuse
1584         assert_equal cr1.container_uuid, cr2.container_uuid
1585       else
1586         assert_not_equal cr1.container_uuid, cr2.container_uuid
1587       end
1588     end
1589   end
1590
1591   test "scrub secret_mounts but reuse container for request with identical secret_mounts" do
1592     set_user_from_auth :active
1593     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1594     cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1595     run_container(cr1)
1596     cr1.reload
1597
1598     # secret_mounts scrubbed from db
1599     c = Container.where(uuid: cr1.container_uuid).first
1600     assert_equal({}, c.secret_mounts)
1601     assert_equal({}, cr1.secret_mounts)
1602
1603     # can reuse container if secret_mounts match
1604     cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1605     assert_equal cr1.container_uuid, cr2.container_uuid
1606
1607     # don't reuse container if secret_mounts don't match
1608     cr3 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: {})
1609     assert_not_equal cr1.container_uuid, cr3.container_uuid
1610
1611     assert_no_secrets_logged
1612   end
1613
1614   test "conflicting key in mounts and secret_mounts" do
1615     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1616     set_user_from_auth :active
1617     cr = create_minimal_req!
1618     assert_equal false, cr.update(state: "Committed",
1619                                              priority: 1,
1620                                              mounts: cr.mounts.merge(sm),
1621                                              secret_mounts: sm)
1622     assert_equal [:secret_mounts], cr.errors.messages.keys
1623   end
1624
1625   test "using runtime_token" do
1626     set_user_from_auth :spectator
1627     spec = api_client_authorizations(:active)
1628     cr = create_minimal_req!(state: "Committed", runtime_token: spec.token, priority: 1)
1629     cr.save!
1630     c = Container.find_by_uuid cr.container_uuid
1631     lock_and_run c
1632     assert_nil c.auth_uuid
1633     assert_equal c.runtime_token, spec.token
1634
1635     assert_not_nil ApiClientAuthorization.find_by_uuid(spec.uuid)
1636
1637     act_as_system_user do
1638       c.update!(state: Container::Complete,
1639                            exit_code: 0,
1640                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1641                            log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
1642     end
1643
1644     cr.reload
1645     c.reload
1646     assert_nil cr.runtime_token
1647     assert_nil c.runtime_token
1648   end
1649
1650   test "invalid runtime_token" do
1651     set_user_from_auth :active
1652     spec = api_client_authorizations(:spectator)
1653     assert_raises(ArgumentError) do
1654       cr = create_minimal_req!(state: "Committed", runtime_token: "#{spec.token}xx")
1655       cr.save!
1656     end
1657   end
1658
1659   test "default output_storage_classes" do
1660     saved = Rails.configuration.DefaultStorageClasses
1661     Rails.configuration.DefaultStorageClasses = ["foo"]
1662     begin
1663       act_as_user users(:active) do
1664         cr = create_minimal_req!(priority: 1,
1665                                  state: ContainerRequest::Committed,
1666                                  output_name: 'foo')
1667         run_container(cr)
1668         cr.reload
1669         output = Collection.find_by_uuid(cr.output_uuid)
1670         assert_equal ["foo"], output.storage_classes_desired
1671       end
1672     ensure
1673       Rails.configuration.DefaultStorageClasses = saved
1674     end
1675   end
1676
1677   test "setting output_storage_classes" do
1678     act_as_user users(:active) do
1679       cr = create_minimal_req!(priority: 1,
1680                                state: ContainerRequest::Committed,
1681                                output_name: 'foo',
1682                                output_storage_classes: ["foo_storage_class", "bar_storage_class"])
1683       run_container(cr)
1684       cr.reload
1685       output = Collection.find_by_uuid(cr.output_uuid)
1686       assert_equal ["foo_storage_class", "bar_storage_class"], output.storage_classes_desired
1687       log = Collection.find_by_uuid(cr.log_uuid)
1688       assert_equal ["foo_storage_class", "bar_storage_class"], log.storage_classes_desired
1689     end
1690   end
1691
1692   test "reusing container with different container_request.output_storage_classes" do
1693     common_attrs = {cwd: "test",
1694                     priority: 1,
1695                     command: ["echo", "hello"],
1696                     output_path: "test",
1697                     runtime_constraints: {"vcpus" => 4,
1698                                           "ram" => 12000000000},
1699                     mounts: {"test" => {"kind" => "json"}},
1700                     environment: {"var" => "value1"},
1701                     output_storage_classes: ["foo_storage_class"]}
1702     set_user_from_auth :active
1703     cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed}))
1704     cont1 = run_container(cr1)
1705     cr1.reload
1706
1707     output1 = Collection.find_by_uuid(cr1.output_uuid)
1708
1709     # Testing with use_existing default value
1710     cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
1711                                                   output_storage_classes: ["bar_storage_class"]}))
1712
1713     assert_not_nil cr1.container_uuid
1714     assert_nil cr2.container_uuid
1715
1716     # Update cr2 to commited state, check for reuse, then run it
1717     cr2.update!({state: ContainerRequest::Committed})
1718     assert_equal cr1.container_uuid, cr2.container_uuid
1719
1720     cr2.reload
1721     output2 = Collection.find_by_uuid(cr2.output_uuid)
1722
1723     # the original CR output has the original storage class,
1724     # but the second CR output has the new storage class.
1725     assert_equal ["foo_storage_class"], cont1.output_storage_classes
1726     assert_equal ["foo_storage_class"], output1.storage_classes_desired
1727     assert_equal ["bar_storage_class"], output2.storage_classes_desired
1728   end
1729
1730   [
1731     [{},               {},           {"type": "output"}],
1732     [{"a1": "b1"},     {},           {"type": "output", "a1": "b1"}],
1733     [{},               {"a1": "b1"}, {"type": "output", "a1": "b1"}],
1734     [{"a1": "b1"},     {"a1": "c1"}, {"type": "output", "a1": "b1"}],
1735     [{"a1": "b1"},     {"a2": "c2"}, {"type": "output", "a1": "b1", "a2": "c2"}],
1736     [{"type": "blah"}, {},           {"type": "blah"}],
1737   ].each do |cr_prop, container_prop, expect_prop|
1738     test "setting output_properties #{cr_prop} #{container_prop} on current container" do
1739       act_as_user users(:active) do
1740         cr = create_minimal_req!(priority: 1,
1741                                  state: ContainerRequest::Committed,
1742                                  output_name: 'foo',
1743                                  output_properties: cr_prop)
1744
1745         act_as_system_user do
1746           logc = Collection.new(owner_uuid: system_user_uuid,
1747                                 manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
1748           logc.save!
1749
1750           c = Container.find_by_uuid(cr.container_uuid)
1751           c.update!(state: Container::Locked)
1752           c.update!(state: Container::Running)
1753
1754           c.update!(output_properties: container_prop)
1755
1756           c.update!(state: Container::Complete,
1757                                exit_code: 0,
1758                                output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1759                                log: logc.portable_data_hash)
1760           logc.destroy
1761         end
1762
1763         cr.reload
1764         expect_prop["container_request"] = cr.uuid
1765         output = Collection.find_by_uuid(cr.output_uuid)
1766         assert_equal expect_prop.symbolize_keys, output.properties.symbolize_keys
1767       end
1768     end
1769   end
1770
1771   test "Cumulative cost includes retried attempts but not reused containers" do
1772     set_user_from_auth :active
1773     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 3)
1774     c = Container.find_by_uuid cr.container_uuid
1775     act_as_system_user do
1776       c.update!(state: Container::Locked)
1777       c.update!(state: Container::Running)
1778       c.update!(state: Container::Cancelled, cost: 3)
1779     end
1780     cr.reload
1781     assert_equal 3, cr.cumulative_cost
1782
1783     c = Container.find_by_uuid cr.container_uuid
1784     lock_and_run c
1785     c.reload
1786     assert_equal 0, c.subrequests_cost
1787
1788     # cr2 is a child/subrequest
1789     cr2 = with_container_auth(c) do
1790       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
1791     end
1792     assert_equal c.uuid, cr2.requesting_container_uuid
1793     c2 = Container.find_by_uuid cr2.container_uuid
1794     act_as_system_user do
1795       c2.update!(state: Container::Locked)
1796       c2.update!(state: Container::Running)
1797       logc = Collection.new(owner_uuid: system_user_uuid,
1798                             manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
1799       logc.save!
1800       c2.update!(state: Container::Complete,
1801                             exit_code: 0,
1802                             output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1803                             log: logc.portable_data_hash,
1804                             cost: 7)
1805     end
1806     c.reload
1807     assert_equal 7, c.subrequests_cost
1808
1809     # cr3 is an identical child/subrequest, will reuse c2
1810     cr3 = with_container_auth(c) do
1811       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
1812     end
1813     assert_equal c.uuid, cr3.requesting_container_uuid
1814     c3 = Container.find_by_uuid cr3.container_uuid
1815     assert_equal c2.uuid, c3.uuid
1816     assert_equal Container::Complete, c3.state
1817     c.reload
1818     assert_equal 7, c.subrequests_cost
1819
1820     act_as_system_user do
1821       c.update!(state: Container::Complete, exit_code: 0, cost: 9)
1822     end
1823
1824     c.reload
1825     assert_equal 7, c.subrequests_cost
1826     cr.reload
1827     assert_equal 3+7+9, cr.cumulative_cost
1828   end
1829
1830 end