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