13822: Don't call list_sizes() in cloud client constructor.
[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
265     cr2 = create_minimal_req!
266     cr2.update_attributes!(priority: 10, state: "Committed", requesting_container_uuid: c.uuid, command: ["echo", "foo2"], container_count_max: 1)
267     cr2.reload
268     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
269
270     c2 = Container.find_by_uuid cr2.container_uuid
271     assert_operator 0, :<, c2.priority
272
273     act_as_system_user do
274       c.state = "Cancelled"
275       c.save!
276     end
277
278     cr.reload
279     assert_equal "Final", cr.state
280
281     cr2.reload
282     assert_equal 0, cr2.priority
283     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
284
285     c2.reload
286     assert_equal 0, c2.priority
287   end
288
289   test "child container priority follows same ordering as corresponding top-level ancestors" do
290     findctr = lambda { |cr| Container.find_by_uuid(cr.container_uuid) }
291
292     set_user_from_auth :active
293
294     toplevel_crs = [
295       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "0"}),
296       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "1"}),
297       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "2"}),
298     ]
299     parents = toplevel_crs.map(&findctr)
300
301     children = parents.map do |parent|
302       lock_and_run(parent)
303       with_container_auth(parent) do
304         create_minimal_req!(state: "Committed",
305                             priority: 1,
306                             environment: {"child" => parent.environment["workflow"]})
307       end
308     end.map(&findctr)
309
310     grandchildren = children.reverse.map do |child|
311       lock_and_run(child)
312       with_container_auth(child) do
313         create_minimal_req!(state: "Committed",
314                             priority: 1,
315                             environment: {"grandchild" => child.environment["child"]})
316       end
317     end.reverse.map(&findctr)
318
319     shared_grandchildren = children.map do |child|
320       with_container_auth(child) do
321         create_minimal_req!(state: "Committed",
322                             priority: 1,
323                             environment: {"grandchild" => "shared"})
324       end
325     end.map(&findctr)
326
327     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[1].uuid
328     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[2].uuid
329     shared_grandchild = shared_grandchildren[0]
330
331     set_user_from_auth :active
332
333     # parents should be prioritized by submit time.
334     assert_operator parents[0].priority, :>, parents[1].priority
335     assert_operator parents[1].priority, :>, parents[2].priority
336
337     # children should be prioritized in same order as their respective
338     # parents.
339     assert_operator children[0].priority, :>, children[1].priority
340     assert_operator children[1].priority, :>, children[2].priority
341
342     # grandchildren should also be prioritized in the same order,
343     # despite having been submitted in the opposite order.
344     assert_operator grandchildren[0].priority, :>, grandchildren[1].priority
345     assert_operator grandchildren[1].priority, :>, grandchildren[2].priority
346
347     # shared grandchild container should be prioritized above
348     # everything that isn't needed by parents[0], but not above
349     # earlier-submitted descendants of parents[0]
350     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
351     assert_operator shared_grandchild.priority, :>, children[1].priority
352     assert_operator shared_grandchild.priority, :>, parents[1].priority
353     assert_operator shared_grandchild.priority, :<=, grandchildren[0].priority
354     assert_operator shared_grandchild.priority, :<=, children[0].priority
355     assert_operator shared_grandchild.priority, :<=, parents[0].priority
356
357     # increasing priority of the most recent toplevel container should
358     # reprioritize all of its descendants (including the shared
359     # grandchild) above everything else.
360     toplevel_crs[2].update_attributes!(priority: 72)
361     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
362     assert_operator shared_grandchild.priority, :>, grandchildren[0].priority
363     assert_operator shared_grandchild.priority, :>, children[0].priority
364     assert_operator shared_grandchild.priority, :>, parents[0].priority
365     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
366     assert_operator shared_grandchild.priority, :>, children[1].priority
367     assert_operator shared_grandchild.priority, :>, parents[1].priority
368     # ...but the shared container should not have higher priority than
369     # the earlier-submitted descendants of the high-priority workflow.
370     assert_operator shared_grandchild.priority, :<=, grandchildren[2].priority
371     assert_operator shared_grandchild.priority, :<=, children[2].priority
372     assert_operator shared_grandchild.priority, :<=, parents[2].priority
373   end
374
375   [
376     ['running_container_auth', 'zzzzz-dz642-runningcontainr', 1],
377     ['active_no_prefs', nil, 0],
378   ].each do |token, expected, expected_priority|
379     test "create as #{token} and expect requesting_container_uuid to be #{expected}" do
380       set_user_from_auth token
381       cr = ContainerRequest.create(container_image: "img", output_path: "/tmp", command: ["echo", "foo"])
382       assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
383       assert_equal expected, cr.requesting_container_uuid
384       assert_equal expected_priority, cr.priority
385     end
386   end
387
388   [[{"vcpus" => [2, nil]},
389     lambda { |resolved| resolved["vcpus"] == 2 }],
390    [{"vcpus" => [3, 7]},
391     lambda { |resolved| resolved["vcpus"] == 3 }],
392    [{"vcpus" => 4},
393     lambda { |resolved| resolved["vcpus"] == 4 }],
394    [{"ram" => [1000000000, 2000000000]},
395     lambda { |resolved| resolved["ram"] == 1000000000 }],
396    [{"ram" => [1234234234]},
397     lambda { |resolved| resolved["ram"] == 1234234234 }],
398   ].each do |rc, okfunc|
399     test "resolve runtime constraint range #{rc} to values" do
400       resolved = Container.resolve_runtime_constraints(rc)
401       assert(okfunc.call(resolved),
402              "container runtime_constraints was #{resolved.inspect}")
403     end
404   end
405
406   [[{"/out" => {
407         "kind" => "collection",
408         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
409         "path" => "/foo"}},
410     lambda do |resolved|
411       resolved["/out"] == {
412         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
413         "kind" => "collection",
414         "path" => "/foo",
415       }
416     end],
417    [{"/out" => {
418         "kind" => "collection",
419         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
420         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
421         "path" => "/foo"}},
422     lambda do |resolved|
423       resolved["/out"] == {
424         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
425         "kind" => "collection",
426         "path" => "/foo",
427       }
428     end],
429   ].each do |mounts, okfunc|
430     test "resolve mounts #{mounts.inspect} to values" do
431       set_user_from_auth :active
432       resolved = Container.resolve_mounts(mounts)
433       assert(okfunc.call(resolved),
434              "Container.resolve_mounts returned #{resolved.inspect}")
435     end
436   end
437
438   test 'mount unreadable collection' do
439     set_user_from_auth :spectator
440     m = {
441       "/foo" => {
442         "kind" => "collection",
443         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
444         "path" => "/foo",
445       },
446     }
447     assert_raises(ArvadosModel::UnresolvableContainerError) do
448       Container.resolve_mounts(m)
449     end
450   end
451
452   test 'mount collection with mismatched UUID and PDH' do
453     set_user_from_auth :active
454     m = {
455       "/foo" => {
456         "kind" => "collection",
457         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
458         "portable_data_hash" => "fa7aeb5140e2848d39b416daeef4ffc5+45",
459         "path" => "/foo",
460       },
461     }
462     assert_raises(ArgumentError) do
463       Container.resolve_mounts(m)
464     end
465   end
466
467   ['arvados/apitestfixture:latest',
468    'arvados/apitestfixture',
469    'd8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678',
470   ].each do |tag|
471     test "Container.resolve_container_image(#{tag.inspect})" do
472       set_user_from_auth :active
473       resolved = Container.resolve_container_image(tag)
474       assert_equal resolved, collections(:docker_image).portable_data_hash
475     end
476   end
477
478   test "Container.resolve_container_image(pdh)" do
479     set_user_from_auth :active
480     [[:docker_image, 'v1'], [:docker_image_1_12, 'v2']].each do |coll, ver|
481       Rails.configuration.docker_image_formats = [ver]
482       pdh = collections(coll).portable_data_hash
483       resolved = Container.resolve_container_image(pdh)
484       assert_equal resolved, pdh
485     end
486   end
487
488   ['acbd18db4cc2f85cedef654fccc4a4d8+3',
489    'ENOEXIST',
490    'arvados/apitestfixture:ENOEXIST',
491   ].each do |img|
492     test "container_image_for_container(#{img.inspect}) => 422" do
493       set_user_from_auth :active
494       assert_raises(ArvadosModel::UnresolvableContainerError) do
495         Container.resolve_container_image(img)
496       end
497     end
498   end
499
500   test "migrated docker image" do
501     Rails.configuration.docker_image_formats = ['v2']
502     add_docker19_migration_link
503
504     # Test that it returns only v2 images even though request is for v1 image.
505
506     set_user_from_auth :active
507     cr = create_minimal_req!(command: ["true", "1"],
508                              container_image: collections(:docker_image).portable_data_hash)
509     assert_equal(Container.resolve_container_image(cr.container_image),
510                  collections(:docker_image_1_12).portable_data_hash)
511
512     cr = create_minimal_req!(command: ["true", "2"],
513                              container_image: links(:docker_image_collection_tag).name)
514     assert_equal(Container.resolve_container_image(cr.container_image),
515                  collections(:docker_image_1_12).portable_data_hash)
516   end
517
518   test "use unmigrated docker image" do
519     Rails.configuration.docker_image_formats = ['v1']
520     add_docker19_migration_link
521
522     # Test that it returns only supported v1 images even though there is a
523     # migration link.
524
525     set_user_from_auth :active
526     cr = create_minimal_req!(command: ["true", "1"],
527                              container_image: collections(:docker_image).portable_data_hash)
528     assert_equal(Container.resolve_container_image(cr.container_image),
529                  collections(:docker_image).portable_data_hash)
530
531     cr = create_minimal_req!(command: ["true", "2"],
532                              container_image: links(:docker_image_collection_tag).name)
533     assert_equal(Container.resolve_container_image(cr.container_image),
534                  collections(:docker_image).portable_data_hash)
535   end
536
537   test "incompatible docker image v1" do
538     Rails.configuration.docker_image_formats = ['v1']
539     add_docker19_migration_link
540
541     # Don't return unsupported v2 image even if we ask for it directly.
542     set_user_from_auth :active
543     cr = create_minimal_req!(command: ["true", "1"],
544                              container_image: collections(:docker_image_1_12).portable_data_hash)
545     assert_raises(ArvadosModel::UnresolvableContainerError) do
546       Container.resolve_container_image(cr.container_image)
547     end
548   end
549
550   test "incompatible docker image v2" do
551     Rails.configuration.docker_image_formats = ['v2']
552     # No migration link, don't return unsupported v1 image,
553
554     set_user_from_auth :active
555     cr = create_minimal_req!(command: ["true", "1"],
556                              container_image: collections(:docker_image).portable_data_hash)
557     assert_raises(ArvadosModel::UnresolvableContainerError) do
558       Container.resolve_container_image(cr.container_image)
559     end
560     cr = create_minimal_req!(command: ["true", "2"],
561                              container_image: links(:docker_image_collection_tag).name)
562     assert_raises(ArvadosModel::UnresolvableContainerError) do
563       Container.resolve_container_image(cr.container_image)
564     end
565   end
566
567   test "requestor can retrieve container owned by dispatch" do
568     assert_not_empty Container.readable_by(users(:admin)).where(uuid: containers(:running).uuid)
569     assert_not_empty Container.readable_by(users(:active)).where(uuid: containers(:running).uuid)
570     assert_empty Container.readable_by(users(:spectator)).where(uuid: containers(:running).uuid)
571   end
572
573   [
574     [{"var" => "value1"}, {"var" => "value1"}, nil],
575     [{"var" => "value1"}, {"var" => "value1"}, true],
576     [{"var" => "value1"}, {"var" => "value1"}, false],
577     [{"var" => "value1"}, {"var" => "value2"}, nil],
578   ].each do |env1, env2, use_existing|
579     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
580       common_attrs = {cwd: "test",
581                       priority: 1,
582                       command: ["echo", "hello"],
583                       output_path: "test",
584                       runtime_constraints: {"vcpus" => 4,
585                                             "ram" => 12000000000},
586                       mounts: {"test" => {"kind" => "json"}}}
587       set_user_from_auth :active
588       cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed,
589                                                     environment: env1}))
590       if use_existing.nil?
591         # Testing with use_existing default value
592         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
593                                                       environment: env2}))
594       else
595
596         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
597                                                       environment: env2,
598                                                       use_existing: use_existing}))
599       end
600       assert_not_nil cr1.container_uuid
601       assert_nil cr2.container_uuid
602
603       # Update cr2 to commited state and check for container equality on different cases:
604       # * When env1 and env2 are equal and use_existing is true, the same container
605       #   should be assigned.
606       # * When use_existing is false, a different container should be assigned.
607       # * When env1 and env2 are different, a different container should be assigned.
608       cr2.update_attributes!({state: ContainerRequest::Committed})
609       assert_equal (cr2.use_existing == true and (env1 == env2)),
610                    (cr1.container_uuid == cr2.container_uuid)
611     end
612   end
613
614   test "requesting_container_uuid at create is not allowed" do
615     set_user_from_auth :active
616     assert_raises(ActiveRecord::RecordNotSaved) do
617       create_minimal_req!(state: "Uncommitted", priority: 1, requesting_container_uuid: 'youcantdothat')
618     end
619   end
620
621   test "Retry on container cancelled" do
622     set_user_from_auth :active
623     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2)
624     cr2 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "baz"])
625     prev_container_uuid = cr.container_uuid
626
627     c = act_as_system_user do
628       c = Container.find_by_uuid(cr.container_uuid)
629       c.update_attributes!(state: Container::Locked)
630       c.update_attributes!(state: Container::Running)
631       c
632     end
633
634     cr.reload
635     cr2.reload
636     assert_equal "Committed", cr.state
637     assert_equal prev_container_uuid, cr.container_uuid
638     assert_not_equal cr2.container_uuid, cr.container_uuid
639     prev_container_uuid = cr.container_uuid
640
641     act_as_system_user do
642       c.update_attributes!(state: Container::Cancelled)
643     end
644
645     cr.reload
646     cr2.reload
647     assert_equal "Committed", cr.state
648     assert_not_equal prev_container_uuid, cr.container_uuid
649     assert_not_equal cr2.container_uuid, cr.container_uuid
650     prev_container_uuid = cr.container_uuid
651
652     c = act_as_system_user do
653       c = Container.find_by_uuid(cr.container_uuid)
654       c.update_attributes!(state: Container::Cancelled)
655       c
656     end
657
658     cr.reload
659     cr2.reload
660     assert_equal "Final", cr.state
661     assert_equal prev_container_uuid, cr.container_uuid
662     assert_not_equal cr2.container_uuid, cr.container_uuid
663   end
664
665   test "Output collection name setting using output_name with name collision resolution" do
666     set_user_from_auth :active
667     output_name = 'unimaginative name'
668     Collection.create!(name: output_name)
669
670     cr = create_minimal_req!(priority: 1,
671                              state: ContainerRequest::Committed,
672                              output_name: output_name)
673     run_container(cr)
674     cr.reload
675     assert_equal ContainerRequest::Final, cr.state
676     output_coll = Collection.find_by_uuid(cr.output_uuid)
677     # Make sure the resulting output collection name include the original name
678     # plus the date
679     assert_not_equal output_name, output_coll.name,
680                      "more than one collection with the same owner and name"
681     assert output_coll.name.include?(output_name),
682            "New name should include original name"
683     assert_match /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z/, output_coll.name,
684                  "New name should include ISO8601 date"
685   end
686
687   [[0, :check_output_ttl_0],
688    [1, :check_output_ttl_1s],
689    [365*86400, :check_output_ttl_1y],
690   ].each do |ttl, checker|
691     test "output_ttl=#{ttl}" do
692       act_as_user users(:active) do
693         cr = create_minimal_req!(priority: 1,
694                                  state: ContainerRequest::Committed,
695                                  output_name: 'foo',
696                                  output_ttl: ttl)
697         run_container(cr)
698         cr.reload
699         output = Collection.find_by_uuid(cr.output_uuid)
700         send(checker, db_current_time, output.trash_at, output.delete_at)
701       end
702     end
703   end
704
705   def check_output_ttl_0(now, trash, delete)
706     assert_nil(trash)
707     assert_nil(delete)
708   end
709
710   def check_output_ttl_1s(now, trash, delete)
711     assert_not_nil(trash)
712     assert_not_nil(delete)
713     assert_in_delta(trash, now + 1.second, 10)
714     assert_in_delta(delete, now + Rails.configuration.blob_signature_ttl.second, 10)
715   end
716
717   def check_output_ttl_1y(now, trash, delete)
718     year = (86400*365).second
719     assert_not_nil(trash)
720     assert_not_nil(delete)
721     assert_in_delta(trash, now + year, 10)
722     assert_in_delta(delete, now + year, 10)
723   end
724
725   def run_container(cr)
726     act_as_system_user do
727       c = Container.find_by_uuid(cr.container_uuid)
728       c.update_attributes!(state: Container::Locked)
729       c.update_attributes!(state: Container::Running)
730       c.update_attributes!(state: Container::Complete,
731                            exit_code: 0,
732                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
733                            log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
734       c
735     end
736   end
737
738   test "Finalize committed request when reusing a finished container" do
739     set_user_from_auth :active
740     cr = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
741     cr.reload
742     assert_equal ContainerRequest::Committed, cr.state
743     run_container(cr)
744     cr.reload
745     assert_equal ContainerRequest::Final, cr.state
746
747     cr2 = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
748     assert_equal cr.container_uuid, cr2.container_uuid
749     assert_equal ContainerRequest::Final, cr2.state
750
751     cr3 = create_minimal_req!(priority: 1, state: ContainerRequest::Uncommitted)
752     assert_equal ContainerRequest::Uncommitted, cr3.state
753     cr3.update_attributes!(state: ContainerRequest::Committed)
754     assert_equal cr.container_uuid, cr3.container_uuid
755     assert_equal ContainerRequest::Final, cr3.state
756   end
757
758   [
759     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
760     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Uncommitted],
761     [{"partitions" => "fastcpu"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
762     [{"partitions" => "fastcpu"}, ContainerRequest::Uncommitted],
763     [{"partitions" => ["fastcpu","vfastcpu"]}, ContainerRequest::Committed],
764   ].each do |sp, state, expected|
765     test "create container request with scheduling_parameters #{sp} in state #{state} and verify #{expected}" do
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       set_user_from_auth :active
773
774       if expected == ActiveRecord::RecordInvalid
775         assert_raises(ActiveRecord::RecordInvalid) do
776           create_minimal_req!(common_attrs.merge({state: state}))
777         end
778       else
779         cr = create_minimal_req!(common_attrs.merge({state: state}))
780         assert_equal sp, cr.scheduling_parameters
781
782         if state == ContainerRequest::Committed
783           c = Container.find_by_uuid(cr.container_uuid)
784           assert_equal sp, c.scheduling_parameters
785         end
786       end
787     end
788   end
789
790   [['Committed', true, {name: "foobar", priority: 123}],
791    ['Committed', false, {container_count: 2}],
792    ['Committed', false, {container_count: 0}],
793    ['Committed', false, {container_count: nil}],
794    ['Final', false, {state: ContainerRequest::Committed, name: "foobar"}],
795    ['Final', false, {name: "foobar", priority: 123}],
796    ['Final', false, {name: "foobar", output_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
797    ['Final', false, {name: "foobar", log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
798    ['Final', false, {log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
799    ['Final', false, {priority: 123}],
800    ['Final', false, {mounts: {}}],
801    ['Final', false, {container_count: 2}],
802    ['Final', true, {name: "foobar"}],
803    ['Final', true, {name: "foobar", description: "baz"}],
804   ].each do |state, permitted, updates|
805     test "state=#{state} can#{'not' if !permitted} update #{updates.inspect}" do
806       act_as_user users(:active) do
807         cr = create_minimal_req!(priority: 1,
808                                  state: "Committed",
809                                  container_count_max: 1)
810         case state
811         when 'Committed'
812           # already done
813         when 'Final'
814           act_as_system_user do
815             Container.find_by_uuid(cr.container_uuid).
816               update_attributes!(state: Container::Cancelled)
817           end
818           cr.reload
819         else
820           raise 'broken test case'
821         end
822         assert_equal state, cr.state
823         if permitted
824           assert cr.update_attributes!(updates)
825         else
826           assert_raises(ActiveRecord::RecordInvalid) do
827             cr.update_attributes!(updates)
828           end
829         end
830       end
831     end
832   end
833
834   test "delete container_request and check its container's priority" do
835     act_as_user users(:active) do
836       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
837
838       # initially the cr's container has priority > 0
839       c = Container.find_by_uuid(cr.container_uuid)
840       assert_equal 1, c.priority
841
842       cr.destroy
843
844       # the cr's container now has priority of 0
845       c = Container.find_by_uuid(cr.container_uuid)
846       assert_equal 0, c.priority
847     end
848   end
849
850   test "delete container_request in final state and expect no error due to before_destroy callback" do
851     act_as_user users(:active) do
852       cr = ContainerRequest.find_by_uuid container_requests(:completed).uuid
853       assert_nothing_raised {cr.destroy}
854     end
855   end
856
857   test "Container request valid priority" do
858     set_user_from_auth :active
859     cr = create_minimal_req!
860
861     assert_raises(ActiveRecord::RecordInvalid) do
862       cr.priority = -1
863       cr.save!
864     end
865
866     cr.priority = 0
867     cr.save!
868
869     cr.priority = 1
870     cr.save!
871
872     cr.priority = 500
873     cr.save!
874
875     cr.priority = 999
876     cr.save!
877
878     cr.priority = 1000
879     cr.save!
880
881     assert_raises(ActiveRecord::RecordInvalid) do
882       cr.priority = 1001
883       cr.save!
884     end
885   end
886
887   # Note: some of these tests might look redundant because they test
888   # that out-of-order spellings of hashes are still considered equal
889   # regardless of whether the existing (container) or new (container
890   # request) hash needs to be re-ordered.
891   secrets = {"/foo" => {"kind" => "text", "content" => "xyzzy"}}
892   same_secrets = {"/foo" => {"content" => "xyzzy", "kind" => "text"}}
893   different_secrets = {"/foo" => {"kind" => "text", "content" => "something completely different"}}
894   [
895     [true, nil, nil],
896     [true, nil, {}],
897     [true, {}, nil],
898     [true, {}, {}],
899     [true, secrets, same_secrets],
900     [true, same_secrets, secrets],
901     [false, nil, secrets],
902     [false, {}, secrets],
903     [false, secrets, {}],
904     [false, secrets, nil],
905     [false, secrets, different_secrets],
906   ].each do |expect_reuse, sm1, sm2|
907     test "container reuse secret_mounts #{sm1.inspect}, #{sm2.inspect}" do
908       set_user_from_auth :active
909       cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm1)
910       cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm2)
911       assert_not_nil cr1.container_uuid
912       assert_not_nil cr2.container_uuid
913       if expect_reuse
914         assert_equal cr1.container_uuid, cr2.container_uuid
915       else
916         assert_not_equal cr1.container_uuid, cr2.container_uuid
917       end
918     end
919   end
920
921   test "scrub secret_mounts but reuse container for request with identical secret_mounts" do
922     set_user_from_auth :active
923     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
924     cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
925     run_container(cr1)
926     cr1.reload
927
928     # secret_mounts scrubbed from db
929     c = Container.where(uuid: cr1.container_uuid).first
930     assert_equal({}, c.secret_mounts)
931     assert_equal({}, cr1.secret_mounts)
932
933     # can reuse container if secret_mounts match
934     cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
935     assert_equal cr1.container_uuid, cr2.container_uuid
936
937     # don't reuse container if secret_mounts don't match
938     cr3 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: {})
939     assert_not_equal cr1.container_uuid, cr3.container_uuid
940
941     assert_no_secrets_logged
942   end
943
944   test "conflicting key in mounts and secret_mounts" do
945     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
946     set_user_from_auth :active
947     cr = create_minimal_req!
948     assert_equal false, cr.update_attributes(state: "Committed",
949                                              priority: 1,
950                                              mounts: cr.mounts.merge(sm),
951                                              secret_mounts: sm)
952     assert_equal [:secret_mounts], cr.errors.messages.keys
953   end
954 end