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