Merge branch '13973-child-priority' refs #13973
[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
9 class ContainerRequestTest < ActiveSupport::TestCase
10   include DockerMigrationHelper
11   include DbCurrentTime
12   include ContainerTestHelper
13
14   def with_container_auth(ctr)
15     auth_was = Thread.current[:api_client_authorization]
16     Thread.current[:api_client_authorization] = ApiClientAuthorization.find_by_uuid(ctr.auth_uuid)
17     begin
18       yield
19     ensure
20       Thread.current[:api_client_authorization] = auth_was
21     end
22   end
23
24   def lock_and_run(ctr)
25       act_as_system_user do
26         ctr.update_attributes!(state: Container::Locked)
27         ctr.update_attributes!(state: Container::Running)
28       end
29   end
30
31   def create_minimal_req! attrs={}
32     defaults = {
33       command: ["echo", "foo"],
34       container_image: links(:docker_image_collection_tag).name,
35       cwd: "/tmp",
36       environment: {},
37       mounts: {"/out" => {"kind" => "tmp", "capacity" => 1000000}},
38       output_path: "/out",
39       runtime_constraints: {"vcpus" => 1, "ram" => 2},
40       name: "foo",
41       description: "bar",
42     }
43     cr = ContainerRequest.create!(defaults.merge(attrs))
44     cr.reload
45     return cr
46   end
47
48   def check_bogus_states cr
49     [nil, "Flubber"].each do |state|
50       assert_raises(ActiveRecord::RecordInvalid) do
51         cr.state = state
52         cr.save!
53       end
54       cr.reload
55     end
56   end
57
58   test "Container request create" do
59     set_user_from_auth :active
60     cr = create_minimal_req!
61
62     assert_nil cr.container_uuid
63     assert_equal 0, cr.priority
64
65     check_bogus_states cr
66
67     # Ensure we can modify all attributes
68     cr.command = ["echo", "foo3"]
69     cr.container_image = "img3"
70     cr.cwd = "/tmp3"
71     cr.environment = {"BUP" => "BOP"}
72     cr.mounts = {"BAR" => {"kind" => "BAZ"}}
73     cr.output_path = "/tmp4"
74     cr.priority = 2
75     cr.runtime_constraints = {"vcpus" => 4}
76     cr.name = "foo3"
77     cr.description = "bar3"
78     cr.save!
79
80     assert_nil cr.container_uuid
81   end
82
83   [
84     {"runtime_constraints" => {"vcpus" => 1}},
85     {"runtime_constraints" => {"vcpus" => 1, "ram" => nil}},
86     {"runtime_constraints" => {"vcpus" => 0, "ram" => 123}},
87     {"runtime_constraints" => {"vcpus" => "1", "ram" => "123"}},
88     {"mounts" => {"FOO" => "BAR"}},
89     {"mounts" => {"FOO" => {}}},
90     {"mounts" => {"FOO" => {"kind" => "tmp", "capacity" => 42.222}}},
91     {"command" => ["echo", 55]},
92     {"environment" => {"FOO" => 55}}
93   ].each do |value|
94     test "Create with invalid #{value}" do
95       set_user_from_auth :active
96       assert_raises(ActiveRecord::RecordInvalid) do
97         cr = create_minimal_req!({state: "Committed",
98                priority: 1}.merge(value))
99         cr.save!
100       end
101     end
102
103     test "Update with invalid #{value}" do
104       set_user_from_auth :active
105       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
106       cr.save!
107       assert_raises(ActiveRecord::RecordInvalid) do
108         cr = ContainerRequest.find_by_uuid cr.uuid
109         cr.update_attributes!({state: "Committed",
110                                priority: 1}.merge(value))
111       end
112     end
113   end
114
115   test "Update from fixture" do
116     set_user_from_auth :active
117     cr = ContainerRequest.find_by_uuid(container_requests(:running).uuid)
118     cr.update_attributes!(description: "New description")
119     assert_equal "New description", cr.description
120   end
121
122   test "Update with valid runtime constraints" do
123       set_user_from_auth :active
124       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
125       cr.save!
126       cr = ContainerRequest.find_by_uuid cr.uuid
127       cr.update_attributes!(state: "Committed",
128                             runtime_constraints: {"vcpus" => 1, "ram" => 23})
129       assert_not_nil cr.container_uuid
130   end
131
132   test "Container request priority must be non-nil" do
133     set_user_from_auth :active
134     cr = create_minimal_req!
135     cr.priority = nil
136     cr.state = "Committed"
137     assert_raises(ActiveRecord::RecordInvalid) do
138       cr.save!
139     end
140   end
141
142   test "Container request commit" do
143     set_user_from_auth :active
144     cr = create_minimal_req!(runtime_constraints: {"vcpus" => 2, "ram" => 30})
145
146     assert_nil cr.container_uuid
147
148     cr.reload
149     cr.state = "Committed"
150     cr.priority = 1
151     cr.save!
152
153     cr.reload
154
155     assert_equal({"vcpus" => 2, "ram" => 30}, cr.runtime_constraints)
156
157     assert_not_nil cr.container_uuid
158     c = Container.find_by_uuid cr.container_uuid
159     assert_not_nil c
160     assert_equal ["echo", "foo"], c.command
161     assert_equal collections(:docker_image).portable_data_hash, c.container_image
162     assert_equal "/tmp", c.cwd
163     assert_equal({}, c.environment)
164     assert_equal({"/out" => {"kind"=>"tmp", "capacity"=>1000000}}, c.mounts)
165     assert_equal "/out", c.output_path
166     assert_equal({"keep_cache_ram"=>268435456, "vcpus" => 2, "ram" => 30}, c.runtime_constraints)
167     assert_operator 0, :<, c.priority
168
169     assert_raises(ActiveRecord::RecordInvalid) do
170       cr.priority = nil
171       cr.save!
172     end
173
174     cr.priority = 0
175     cr.save!
176
177     cr.reload
178     c.reload
179     assert_equal 0, cr.priority
180     assert_equal 0, c.priority
181   end
182
183   test "Independent container requests" do
184     set_user_from_auth :active
185     cr1 = create_minimal_req!(command: ["foo", "1"], priority: 5, state: "Committed")
186     cr2 = create_minimal_req!(command: ["foo", "2"], priority: 10, state: "Committed")
187
188     c1 = Container.find_by_uuid cr1.container_uuid
189     assert_operator 0, :<, c1.priority
190
191     c2 = Container.find_by_uuid cr2.container_uuid
192     assert_operator c1.priority, :<, c2.priority
193     c2priority_was = c2.priority
194
195     cr1.update_attributes!(priority: 0)
196
197     c1.reload
198     assert_equal 0, c1.priority
199
200     c2.reload
201     assert_equal c2priority_was, c2.priority
202   end
203
204   test "Request is finalized when its container is cancelled" do
205     set_user_from_auth :active
206     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 1)
207     assert_equal users(:active).uuid, cr.modified_by_user_uuid
208
209     act_as_system_user do
210       Container.find_by_uuid(cr.container_uuid).
211         update_attributes!(state: Container::Cancelled)
212     end
213
214     cr.reload
215     assert_equal "Final", cr.state
216     assert_equal users(:active).uuid, cr.modified_by_user_uuid
217   end
218
219   test "Request is finalized when its container is completed" do
220     set_user_from_auth :active
221     project = groups(:private)
222     cr = create_minimal_req!(owner_uuid: project.uuid,
223                              priority: 1,
224                              state: "Committed")
225     assert_equal users(:active).uuid, cr.modified_by_user_uuid
226
227     c = act_as_system_user do
228       c = Container.find_by_uuid(cr.container_uuid)
229       c.update_attributes!(state: Container::Locked)
230       c.update_attributes!(state: Container::Running)
231       c
232     end
233
234     cr.reload
235     assert_equal "Committed", cr.state
236
237     output_pdh = '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
238     log_pdh = 'fa7aeb5140e2848d39b416daeef4ffc5+45'
239     act_as_system_user do
240       c.update_attributes!(state: Container::Complete,
241                            output: output_pdh,
242                            log: log_pdh)
243     end
244
245     cr.reload
246     assert_equal "Final", cr.state
247     assert_equal users(:active).uuid, cr.modified_by_user_uuid
248     ['output', 'log'].each do |out_type|
249       pdh = Container.find_by_uuid(cr.container_uuid).send(out_type)
250       assert_equal(1, Collection.where(portable_data_hash: pdh,
251                                        owner_uuid: project.uuid).count,
252                    "Container #{out_type} should be copied to #{project.uuid}")
253     end
254     assert_not_nil cr.output_uuid
255     assert_not_nil cr.log_uuid
256     output = Collection.find_by_uuid cr.output_uuid
257     assert_equal output_pdh, output.portable_data_hash
258     log = Collection.find_by_uuid cr.log_uuid
259     assert_equal log_pdh, log.portable_data_hash
260   end
261
262   test "Container makes container request, then is cancelled" do
263     set_user_from_auth :active
264     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 1)
265
266     c = Container.find_by_uuid cr.container_uuid
267     assert_operator 0, :<, c.priority
268     lock_and_run(c)
269
270     cr2 = with_container_auth(c) do
271       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
272     end
273     assert_not_nil cr2.requesting_container_uuid
274     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
275
276     c2 = Container.find_by_uuid cr2.container_uuid
277     assert_operator 0, :<, c2.priority
278
279     act_as_system_user do
280       c.state = "Cancelled"
281       c.save!
282     end
283
284     cr.reload
285     assert_equal "Final", cr.state
286
287     cr2.reload
288     assert_equal 0, cr2.priority
289     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
290
291     c2.reload
292     assert_equal 0, c2.priority
293   end
294
295   test "child container priority follows same ordering as corresponding top-level ancestors" do
296     findctr = lambda { |cr| Container.find_by_uuid(cr.container_uuid) }
297
298     set_user_from_auth :active
299
300     toplevel_crs = [
301       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "0"}),
302       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "1"}),
303       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "2"}),
304     ]
305     parents = toplevel_crs.map(&findctr)
306
307     children = parents.map do |parent|
308       lock_and_run(parent)
309       with_container_auth(parent) do
310         create_minimal_req!(state: "Committed",
311                             priority: 1,
312                             environment: {"child" => parent.environment["workflow"]})
313       end
314     end.map(&findctr)
315
316     grandchildren = children.reverse.map do |child|
317       lock_and_run(child)
318       with_container_auth(child) do
319         create_minimal_req!(state: "Committed",
320                             priority: 1,
321                             environment: {"grandchild" => child.environment["child"]})
322       end
323     end.reverse.map(&findctr)
324
325     shared_grandchildren = children.map do |child|
326       with_container_auth(child) do
327         create_minimal_req!(state: "Committed",
328                             priority: 1,
329                             environment: {"grandchild" => "shared"})
330       end
331     end.map(&findctr)
332
333     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[1].uuid
334     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[2].uuid
335     shared_grandchild = shared_grandchildren[0]
336
337     set_user_from_auth :active
338
339     # parents should be prioritized by submit time.
340     assert_operator parents[0].priority, :>, parents[1].priority
341     assert_operator parents[1].priority, :>, parents[2].priority
342
343     # children should be prioritized in same order as their respective
344     # parents.
345     assert_operator children[0].priority, :>, children[1].priority
346     assert_operator children[1].priority, :>, children[2].priority
347
348     # grandchildren should also be prioritized in the same order,
349     # despite having been submitted in the opposite order.
350     assert_operator grandchildren[0].priority, :>, grandchildren[1].priority
351     assert_operator grandchildren[1].priority, :>, grandchildren[2].priority
352
353     # shared grandchild container should be prioritized above
354     # everything that isn't needed by parents[0], but not above
355     # earlier-submitted descendants of parents[0]
356     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
357     assert_operator shared_grandchild.priority, :>, children[1].priority
358     assert_operator shared_grandchild.priority, :>, parents[1].priority
359     assert_operator shared_grandchild.priority, :<=, grandchildren[0].priority
360     assert_operator shared_grandchild.priority, :<=, children[0].priority
361     assert_operator shared_grandchild.priority, :<=, parents[0].priority
362
363     # increasing priority of the most recent toplevel container should
364     # reprioritize all of its descendants (including the shared
365     # grandchild) above everything else.
366     toplevel_crs[2].update_attributes!(priority: 72)
367     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
368     assert_operator shared_grandchild.priority, :>, grandchildren[0].priority
369     assert_operator shared_grandchild.priority, :>, children[0].priority
370     assert_operator shared_grandchild.priority, :>, parents[0].priority
371     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
372     assert_operator shared_grandchild.priority, :>, children[1].priority
373     assert_operator shared_grandchild.priority, :>, parents[1].priority
374     # ...but the shared container should not have higher priority than
375     # the earlier-submitted descendants of the high-priority workflow.
376     assert_operator shared_grandchild.priority, :<=, grandchildren[2].priority
377     assert_operator shared_grandchild.priority, :<=, children[2].priority
378     assert_operator shared_grandchild.priority, :<=, parents[2].priority
379   end
380
381   [
382     ['running_container_auth', 'zzzzz-dz642-runningcontainr', 501],
383     ['active_no_prefs', nil, 0],
384   ].each do |token, expected, expected_priority|
385     test "create as #{token} and expect requesting_container_uuid to be #{expected}" do
386       set_user_from_auth token
387       cr = ContainerRequest.create(container_image: "img", output_path: "/tmp", command: ["echo", "foo"])
388       assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
389       assert_equal expected, cr.requesting_container_uuid
390       assert_equal expected_priority, cr.priority
391     end
392   end
393
394   [[{"vcpus" => [2, nil]},
395     lambda { |resolved| resolved["vcpus"] == 2 }],
396    [{"vcpus" => [3, 7]},
397     lambda { |resolved| resolved["vcpus"] == 3 }],
398    [{"vcpus" => 4},
399     lambda { |resolved| resolved["vcpus"] == 4 }],
400    [{"ram" => [1000000000, 2000000000]},
401     lambda { |resolved| resolved["ram"] == 1000000000 }],
402    [{"ram" => [1234234234]},
403     lambda { |resolved| resolved["ram"] == 1234234234 }],
404   ].each do |rc, okfunc|
405     test "resolve runtime constraint range #{rc} to values" do
406       resolved = Container.resolve_runtime_constraints(rc)
407       assert(okfunc.call(resolved),
408              "container runtime_constraints was #{resolved.inspect}")
409     end
410   end
411
412   [[{"/out" => {
413         "kind" => "collection",
414         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
415         "path" => "/foo"}},
416     lambda do |resolved|
417       resolved["/out"] == {
418         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
419         "kind" => "collection",
420         "path" => "/foo",
421       }
422     end],
423    [{"/out" => {
424         "kind" => "collection",
425         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
426         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
427         "path" => "/foo"}},
428     lambda do |resolved|
429       resolved["/out"] == {
430         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
431         "kind" => "collection",
432         "path" => "/foo",
433       }
434     end],
435   ].each do |mounts, okfunc|
436     test "resolve mounts #{mounts.inspect} to values" do
437       set_user_from_auth :active
438       resolved = Container.resolve_mounts(mounts)
439       assert(okfunc.call(resolved),
440              "Container.resolve_mounts returned #{resolved.inspect}")
441     end
442   end
443
444   test 'mount unreadable collection' do
445     set_user_from_auth :spectator
446     m = {
447       "/foo" => {
448         "kind" => "collection",
449         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
450         "path" => "/foo",
451       },
452     }
453     assert_raises(ArvadosModel::UnresolvableContainerError) do
454       Container.resolve_mounts(m)
455     end
456   end
457
458   test 'mount collection with mismatched UUID and PDH' do
459     set_user_from_auth :active
460     m = {
461       "/foo" => {
462         "kind" => "collection",
463         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
464         "portable_data_hash" => "fa7aeb5140e2848d39b416daeef4ffc5+45",
465         "path" => "/foo",
466       },
467     }
468     assert_raises(ArgumentError) do
469       Container.resolve_mounts(m)
470     end
471   end
472
473   ['arvados/apitestfixture:latest',
474    'arvados/apitestfixture',
475    'd8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678',
476   ].each do |tag|
477     test "Container.resolve_container_image(#{tag.inspect})" do
478       set_user_from_auth :active
479       resolved = Container.resolve_container_image(tag)
480       assert_equal resolved, collections(:docker_image).portable_data_hash
481     end
482   end
483
484   test "Container.resolve_container_image(pdh)" do
485     set_user_from_auth :active
486     [[:docker_image, 'v1'], [:docker_image_1_12, 'v2']].each do |coll, ver|
487       Rails.configuration.docker_image_formats = [ver]
488       pdh = collections(coll).portable_data_hash
489       resolved = Container.resolve_container_image(pdh)
490       assert_equal resolved, pdh
491     end
492   end
493
494   ['acbd18db4cc2f85cedef654fccc4a4d8+3',
495    'ENOEXIST',
496    'arvados/apitestfixture:ENOEXIST',
497   ].each do |img|
498     test "container_image_for_container(#{img.inspect}) => 422" do
499       set_user_from_auth :active
500       assert_raises(ArvadosModel::UnresolvableContainerError) do
501         Container.resolve_container_image(img)
502       end
503     end
504   end
505
506   test "migrated docker image" do
507     Rails.configuration.docker_image_formats = ['v2']
508     add_docker19_migration_link
509
510     # Test that it returns only v2 images even though request is for v1 image.
511
512     set_user_from_auth :active
513     cr = create_minimal_req!(command: ["true", "1"],
514                              container_image: collections(:docker_image).portable_data_hash)
515     assert_equal(Container.resolve_container_image(cr.container_image),
516                  collections(:docker_image_1_12).portable_data_hash)
517
518     cr = create_minimal_req!(command: ["true", "2"],
519                              container_image: links(:docker_image_collection_tag).name)
520     assert_equal(Container.resolve_container_image(cr.container_image),
521                  collections(:docker_image_1_12).portable_data_hash)
522   end
523
524   test "use unmigrated docker image" do
525     Rails.configuration.docker_image_formats = ['v1']
526     add_docker19_migration_link
527
528     # Test that it returns only supported v1 images even though there is a
529     # migration link.
530
531     set_user_from_auth :active
532     cr = create_minimal_req!(command: ["true", "1"],
533                              container_image: collections(:docker_image).portable_data_hash)
534     assert_equal(Container.resolve_container_image(cr.container_image),
535                  collections(:docker_image).portable_data_hash)
536
537     cr = create_minimal_req!(command: ["true", "2"],
538                              container_image: links(:docker_image_collection_tag).name)
539     assert_equal(Container.resolve_container_image(cr.container_image),
540                  collections(:docker_image).portable_data_hash)
541   end
542
543   test "incompatible docker image v1" do
544     Rails.configuration.docker_image_formats = ['v1']
545     add_docker19_migration_link
546
547     # Don't return unsupported v2 image even if we ask for it directly.
548     set_user_from_auth :active
549     cr = create_minimal_req!(command: ["true", "1"],
550                              container_image: collections(:docker_image_1_12).portable_data_hash)
551     assert_raises(ArvadosModel::UnresolvableContainerError) do
552       Container.resolve_container_image(cr.container_image)
553     end
554   end
555
556   test "incompatible docker image v2" do
557     Rails.configuration.docker_image_formats = ['v2']
558     # No migration link, don't return unsupported v1 image,
559
560     set_user_from_auth :active
561     cr = create_minimal_req!(command: ["true", "1"],
562                              container_image: collections(:docker_image).portable_data_hash)
563     assert_raises(ArvadosModel::UnresolvableContainerError) do
564       Container.resolve_container_image(cr.container_image)
565     end
566     cr = create_minimal_req!(command: ["true", "2"],
567                              container_image: links(:docker_image_collection_tag).name)
568     assert_raises(ArvadosModel::UnresolvableContainerError) do
569       Container.resolve_container_image(cr.container_image)
570     end
571   end
572
573   test "requestor can retrieve container owned by dispatch" do
574     assert_not_empty Container.readable_by(users(:admin)).where(uuid: containers(:running).uuid)
575     assert_not_empty Container.readable_by(users(:active)).where(uuid: containers(:running).uuid)
576     assert_empty Container.readable_by(users(:spectator)).where(uuid: containers(:running).uuid)
577   end
578
579   [
580     [{"var" => "value1"}, {"var" => "value1"}, nil],
581     [{"var" => "value1"}, {"var" => "value1"}, true],
582     [{"var" => "value1"}, {"var" => "value1"}, false],
583     [{"var" => "value1"}, {"var" => "value2"}, nil],
584   ].each do |env1, env2, use_existing|
585     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
586       common_attrs = {cwd: "test",
587                       priority: 1,
588                       command: ["echo", "hello"],
589                       output_path: "test",
590                       runtime_constraints: {"vcpus" => 4,
591                                             "ram" => 12000000000},
592                       mounts: {"test" => {"kind" => "json"}}}
593       set_user_from_auth :active
594       cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed,
595                                                     environment: env1}))
596       if use_existing.nil?
597         # Testing with use_existing default value
598         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
599                                                       environment: env2}))
600       else
601
602         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
603                                                       environment: env2,
604                                                       use_existing: use_existing}))
605       end
606       assert_not_nil cr1.container_uuid
607       assert_nil cr2.container_uuid
608
609       # Update cr2 to commited state and check for container equality on different cases:
610       # * When env1 and env2 are equal and use_existing is true, the same container
611       #   should be assigned.
612       # * When use_existing is false, a different container should be assigned.
613       # * When env1 and env2 are different, a different container should be assigned.
614       cr2.update_attributes!({state: ContainerRequest::Committed})
615       assert_equal (cr2.use_existing == true and (env1 == env2)),
616                    (cr1.container_uuid == cr2.container_uuid)
617     end
618   end
619
620   test "requesting_container_uuid at create is not allowed" do
621     set_user_from_auth :active
622     assert_raises(ActiveRecord::RecordInvalid) do
623       create_minimal_req!(state: "Uncommitted", priority: 1, requesting_container_uuid: 'youcantdothat')
624     end
625   end
626
627   test "Retry on container cancelled" do
628     set_user_from_auth :active
629     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2)
630     cr2 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "baz"])
631     prev_container_uuid = cr.container_uuid
632
633     c = act_as_system_user do
634       c = Container.find_by_uuid(cr.container_uuid)
635       c.update_attributes!(state: Container::Locked)
636       c.update_attributes!(state: Container::Running)
637       c
638     end
639
640     cr.reload
641     cr2.reload
642     assert_equal "Committed", cr.state
643     assert_equal prev_container_uuid, cr.container_uuid
644     assert_not_equal cr2.container_uuid, cr.container_uuid
645     prev_container_uuid = cr.container_uuid
646
647     act_as_system_user do
648       c.update_attributes!(state: Container::Cancelled)
649     end
650
651     cr.reload
652     cr2.reload
653     assert_equal "Committed", cr.state
654     assert_not_equal prev_container_uuid, cr.container_uuid
655     assert_not_equal cr2.container_uuid, cr.container_uuid
656     prev_container_uuid = cr.container_uuid
657
658     c = act_as_system_user do
659       c = Container.find_by_uuid(cr.container_uuid)
660       c.update_attributes!(state: Container::Cancelled)
661       c
662     end
663
664     cr.reload
665     cr2.reload
666     assert_equal "Final", cr.state
667     assert_equal prev_container_uuid, cr.container_uuid
668     assert_not_equal cr2.container_uuid, cr.container_uuid
669   end
670
671   test "Output collection name setting using output_name with name collision resolution" do
672     set_user_from_auth :active
673     output_name = 'unimaginative name'
674     Collection.create!(name: output_name)
675
676     cr = create_minimal_req!(priority: 1,
677                              state: ContainerRequest::Committed,
678                              output_name: output_name)
679     run_container(cr)
680     cr.reload
681     assert_equal ContainerRequest::Final, cr.state
682     output_coll = Collection.find_by_uuid(cr.output_uuid)
683     # Make sure the resulting output collection name include the original name
684     # plus the date
685     assert_not_equal output_name, output_coll.name,
686                      "more than one collection with the same owner and name"
687     assert output_coll.name.include?(output_name),
688            "New name should include original name"
689     assert_match /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z/, output_coll.name,
690                  "New name should include ISO8601 date"
691   end
692
693   [[0, :check_output_ttl_0],
694    [1, :check_output_ttl_1s],
695    [365*86400, :check_output_ttl_1y],
696   ].each do |ttl, checker|
697     test "output_ttl=#{ttl}" do
698       act_as_user users(:active) do
699         cr = create_minimal_req!(priority: 1,
700                                  state: ContainerRequest::Committed,
701                                  output_name: 'foo',
702                                  output_ttl: ttl)
703         run_container(cr)
704         cr.reload
705         output = Collection.find_by_uuid(cr.output_uuid)
706         send(checker, db_current_time, output.trash_at, output.delete_at)
707       end
708     end
709   end
710
711   def check_output_ttl_0(now, trash, delete)
712     assert_nil(trash)
713     assert_nil(delete)
714   end
715
716   def check_output_ttl_1s(now, trash, delete)
717     assert_not_nil(trash)
718     assert_not_nil(delete)
719     assert_in_delta(trash, now + 1.second, 10)
720     assert_in_delta(delete, now + Rails.configuration.blob_signature_ttl.second, 10)
721   end
722
723   def check_output_ttl_1y(now, trash, delete)
724     year = (86400*365).second
725     assert_not_nil(trash)
726     assert_not_nil(delete)
727     assert_in_delta(trash, now + year, 10)
728     assert_in_delta(delete, now + year, 10)
729   end
730
731   def run_container(cr)
732     act_as_system_user do
733       c = Container.find_by_uuid(cr.container_uuid)
734       c.update_attributes!(state: Container::Locked)
735       c.update_attributes!(state: Container::Running)
736       c.update_attributes!(state: Container::Complete,
737                            exit_code: 0,
738                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
739                            log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
740       c
741     end
742   end
743
744   test "Finalize committed request when reusing a finished container" do
745     set_user_from_auth :active
746     cr = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
747     cr.reload
748     assert_equal ContainerRequest::Committed, cr.state
749     run_container(cr)
750     cr.reload
751     assert_equal ContainerRequest::Final, cr.state
752
753     cr2 = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
754     assert_equal cr.container_uuid, cr2.container_uuid
755     assert_equal ContainerRequest::Final, cr2.state
756
757     cr3 = create_minimal_req!(priority: 1, state: ContainerRequest::Uncommitted)
758     assert_equal ContainerRequest::Uncommitted, cr3.state
759     cr3.update_attributes!(state: ContainerRequest::Committed)
760     assert_equal cr.container_uuid, cr3.container_uuid
761     assert_equal ContainerRequest::Final, cr3.state
762   end
763
764   [
765     [false, ActiveRecord::RecordInvalid],
766     [true, nil],
767   ].each do |preemptible_conf, expected|
768     test "having Rails.configuration.preemptible_instances=#{preemptible_conf}, create preemptible container request and verify #{expected}" do
769       sp = {"preemptible" => true}
770       common_attrs = {cwd: "test",
771                       priority: 1,
772                       command: ["echo", "hello"],
773                       output_path: "test",
774                       scheduling_parameters: sp,
775                       mounts: {"test" => {"kind" => "json"}}}
776       Rails.configuration.preemptible_instances = preemptible_conf
777       set_user_from_auth :active
778
779       cr = create_minimal_req!(common_attrs)
780       cr.state = ContainerRequest::Committed
781
782       if !expected.nil?
783         assert_raises(expected) do
784           cr.save!
785         end
786       else
787         cr.save!
788         assert_equal sp, cr.scheduling_parameters
789       end
790     end
791   end
792
793   [
794     'zzzzz-dz642-runningcontainr',
795     nil,
796   ].each do |requesting_c|
797     test "having preemptible instances active on the API server, a committed #{requesting_c.nil? ? 'non-':''}child CR should not ask for preemptible instance if parameter already set to false" do
798       common_attrs = {cwd: "test",
799                       priority: 1,
800                       command: ["echo", "hello"],
801                       output_path: "test",
802                       scheduling_parameters: {"preemptible" => false},
803                       mounts: {"test" => {"kind" => "json"}}}
804
805       Rails.configuration.preemptible_instances = true
806       set_user_from_auth :active
807
808       if requesting_c
809         cr = with_container_auth(Container.find_by_uuid requesting_c) do
810           create_minimal_req!(common_attrs)
811         end
812         assert_not_nil cr.requesting_container_uuid
813       else
814         cr = create_minimal_req!(common_attrs)
815       end
816
817       cr.state = ContainerRequest::Committed
818       cr.save!
819
820       assert_equal false, cr.scheduling_parameters['preemptible']
821     end
822   end
823
824   [
825     [true, 'zzzzz-dz642-runningcontainr', true],
826     [true, nil, nil],
827     [false, 'zzzzz-dz642-runningcontainr', nil],
828     [false, nil, nil],
829   ].each do |preemptible_conf, requesting_c, schedule_preemptible|
830     test "having Rails.configuration.preemptible_instances=#{preemptible_conf}, #{requesting_c.nil? ? 'non-':''}child CR should #{schedule_preemptible ? '':'not'} ask for preemptible instance by default" do
831       common_attrs = {cwd: "test",
832                       priority: 1,
833                       command: ["echo", "hello"],
834                       output_path: "test",
835                       mounts: {"test" => {"kind" => "json"}}}
836
837       Rails.configuration.preemptible_instances = preemptible_conf
838       set_user_from_auth :active
839
840       if requesting_c
841         cr = with_container_auth(Container.find_by_uuid requesting_c) do
842           create_minimal_req!(common_attrs)
843         end
844         assert_not_nil cr.requesting_container_uuid
845       else
846         cr = create_minimal_req!(common_attrs)
847       end
848
849       cr.state = ContainerRequest::Committed
850       cr.save!
851
852       assert_equal schedule_preemptible, cr.scheduling_parameters['preemptible']
853     end
854   end
855
856   [
857     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
858     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Uncommitted],
859     [{"partitions" => "fastcpu"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
860     [{"partitions" => "fastcpu"}, ContainerRequest::Uncommitted],
861     [{"partitions" => ["fastcpu","vfastcpu"]}, ContainerRequest::Committed],
862     [{"max_run_time" => "one day"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
863     [{"max_run_time" => "one day"}, ContainerRequest::Uncommitted],
864     [{"max_run_time" => -1}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
865     [{"max_run_time" => -1}, ContainerRequest::Uncommitted],
866     [{"max_run_time" => 86400}, ContainerRequest::Committed],
867   ].each do |sp, state, expected|
868     test "create container request with scheduling_parameters #{sp} in state #{state} and verify #{expected}" do
869       common_attrs = {cwd: "test",
870                       priority: 1,
871                       command: ["echo", "hello"],
872                       output_path: "test",
873                       scheduling_parameters: sp,
874                       mounts: {"test" => {"kind" => "json"}}}
875       set_user_from_auth :active
876
877       if expected == ActiveRecord::RecordInvalid
878         assert_raises(ActiveRecord::RecordInvalid) do
879           create_minimal_req!(common_attrs.merge({state: state}))
880         end
881       else
882         cr = create_minimal_req!(common_attrs.merge({state: state}))
883         assert_equal sp, cr.scheduling_parameters
884
885         if state == ContainerRequest::Committed
886           c = Container.find_by_uuid(cr.container_uuid)
887           assert_equal sp, c.scheduling_parameters
888         end
889       end
890     end
891   end
892
893   test "Having preemptible_instances=true create a committed child container request and verify the scheduling parameter of its container" do
894     common_attrs = {cwd: "test",
895                     priority: 1,
896                     command: ["echo", "hello"],
897                     output_path: "test",
898                     state: ContainerRequest::Committed,
899                     mounts: {"test" => {"kind" => "json"}}}
900     set_user_from_auth :active
901     Rails.configuration.preemptible_instances = true
902
903     cr = with_container_auth(Container.find_by_uuid 'zzzzz-dz642-runningcontainr') do
904       create_minimal_req!(common_attrs)
905     end
906     assert_equal 'zzzzz-dz642-runningcontainr', cr.requesting_container_uuid
907     assert_equal true, cr.scheduling_parameters["preemptible"]
908
909     c = Container.find_by_uuid(cr.container_uuid)
910     assert_equal true, c.scheduling_parameters["preemptible"]
911   end
912
913   [['Committed', true, {name: "foobar", priority: 123}],
914    ['Committed', false, {container_count: 2}],
915    ['Committed', false, {container_count: 0}],
916    ['Committed', false, {container_count: nil}],
917    ['Final', false, {state: ContainerRequest::Committed, name: "foobar"}],
918    ['Final', false, {name: "foobar", priority: 123}],
919    ['Final', false, {name: "foobar", output_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
920    ['Final', false, {name: "foobar", log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
921    ['Final', false, {log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
922    ['Final', false, {priority: 123}],
923    ['Final', false, {mounts: {}}],
924    ['Final', false, {container_count: 2}],
925    ['Final', true, {name: "foobar"}],
926    ['Final', true, {name: "foobar", description: "baz"}],
927   ].each do |state, permitted, updates|
928     test "state=#{state} can#{'not' if !permitted} update #{updates.inspect}" do
929       act_as_user users(:active) do
930         cr = create_minimal_req!(priority: 1,
931                                  state: "Committed",
932                                  container_count_max: 1)
933         case state
934         when 'Committed'
935           # already done
936         when 'Final'
937           act_as_system_user do
938             Container.find_by_uuid(cr.container_uuid).
939               update_attributes!(state: Container::Cancelled)
940           end
941           cr.reload
942         else
943           raise 'broken test case'
944         end
945         assert_equal state, cr.state
946         if permitted
947           assert cr.update_attributes!(updates)
948         else
949           assert_raises(ActiveRecord::RecordInvalid) do
950             cr.update_attributes!(updates)
951           end
952         end
953       end
954     end
955   end
956
957   test "delete container_request and check its container's priority" do
958     act_as_user users(:active) do
959       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
960
961       # initially the cr's container has priority > 0
962       c = Container.find_by_uuid(cr.container_uuid)
963       assert_equal 1, c.priority
964
965       cr.destroy
966
967       # the cr's container now has priority of 0
968       c = Container.find_by_uuid(cr.container_uuid)
969       assert_equal 0, c.priority
970     end
971   end
972
973   test "delete container_request in final state and expect no error due to before_destroy callback" do
974     act_as_user users(:active) do
975       cr = ContainerRequest.find_by_uuid container_requests(:completed).uuid
976       assert_nothing_raised {cr.destroy}
977     end
978   end
979
980   test "Container request valid priority" do
981     set_user_from_auth :active
982     cr = create_minimal_req!
983
984     assert_raises(ActiveRecord::RecordInvalid) do
985       cr.priority = -1
986       cr.save!
987     end
988
989     cr.priority = 0
990     cr.save!
991
992     cr.priority = 1
993     cr.save!
994
995     cr.priority = 500
996     cr.save!
997
998     cr.priority = 999
999     cr.save!
1000
1001     cr.priority = 1000
1002     cr.save!
1003
1004     assert_raises(ActiveRecord::RecordInvalid) do
1005       cr.priority = 1001
1006       cr.save!
1007     end
1008   end
1009
1010   # Note: some of these tests might look redundant because they test
1011   # that out-of-order spellings of hashes are still considered equal
1012   # regardless of whether the existing (container) or new (container
1013   # request) hash needs to be re-ordered.
1014   secrets = {"/foo" => {"kind" => "text", "content" => "xyzzy"}}
1015   same_secrets = {"/foo" => {"content" => "xyzzy", "kind" => "text"}}
1016   different_secrets = {"/foo" => {"kind" => "text", "content" => "something completely different"}}
1017   [
1018     [true, nil, nil],
1019     [true, nil, {}],
1020     [true, {}, nil],
1021     [true, {}, {}],
1022     [true, secrets, same_secrets],
1023     [true, same_secrets, secrets],
1024     [false, nil, secrets],
1025     [false, {}, secrets],
1026     [false, secrets, {}],
1027     [false, secrets, nil],
1028     [false, secrets, different_secrets],
1029   ].each do |expect_reuse, sm1, sm2|
1030     test "container reuse secret_mounts #{sm1.inspect}, #{sm2.inspect}" do
1031       set_user_from_auth :active
1032       cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm1)
1033       cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm2)
1034       assert_not_nil cr1.container_uuid
1035       assert_not_nil cr2.container_uuid
1036       if expect_reuse
1037         assert_equal cr1.container_uuid, cr2.container_uuid
1038       else
1039         assert_not_equal cr1.container_uuid, cr2.container_uuid
1040       end
1041     end
1042   end
1043
1044   test "scrub secret_mounts but reuse container for request with identical secret_mounts" do
1045     set_user_from_auth :active
1046     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1047     cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1048     run_container(cr1)
1049     cr1.reload
1050
1051     # secret_mounts scrubbed from db
1052     c = Container.where(uuid: cr1.container_uuid).first
1053     assert_equal({}, c.secret_mounts)
1054     assert_equal({}, cr1.secret_mounts)
1055
1056     # can reuse container if secret_mounts match
1057     cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1058     assert_equal cr1.container_uuid, cr2.container_uuid
1059
1060     # don't reuse container if secret_mounts don't match
1061     cr3 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: {})
1062     assert_not_equal cr1.container_uuid, cr3.container_uuid
1063
1064     assert_no_secrets_logged
1065   end
1066
1067   test "conflicting key in mounts and secret_mounts" do
1068     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1069     set_user_from_auth :active
1070     cr = create_minimal_req!
1071     assert_equal false, cr.update_attributes(state: "Committed",
1072                                              priority: 1,
1073                                              mounts: cr.mounts.merge(sm),
1074                                              secret_mounts: sm)
1075     assert_equal [:secret_mounts], cr.errors.messages.keys
1076   end
1077 end