14328: Merge branch 'master'
[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   test "create as container_runtime_token and expect requesting_container_uuid to be zzzzz-dz642-20isqbkl8xwnsao" do
395     set_user_from_auth :container_runtime_token
396     Thread.current[:token] = "#{Thread.current[:token]}/zzzzz-dz642-20isqbkl8xwnsao"
397     cr = ContainerRequest.create(container_image: "img", output_path: "/tmp", command: ["echo", "foo"])
398     assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
399     assert_equal 'zzzzz-dz642-20isqbkl8xwnsao', cr.requesting_container_uuid
400     assert_equal 1, cr.priority
401   end
402
403   [[{"vcpus" => [2, nil]},
404     lambda { |resolved| resolved["vcpus"] == 2 }],
405    [{"vcpus" => [3, 7]},
406     lambda { |resolved| resolved["vcpus"] == 3 }],
407    [{"vcpus" => 4},
408     lambda { |resolved| resolved["vcpus"] == 4 }],
409    [{"ram" => [1000000000, 2000000000]},
410     lambda { |resolved| resolved["ram"] == 1000000000 }],
411    [{"ram" => [1234234234]},
412     lambda { |resolved| resolved["ram"] == 1234234234 }],
413   ].each do |rc, okfunc|
414     test "resolve runtime constraint range #{rc} to values" do
415       resolved = Container.resolve_runtime_constraints(rc)
416       assert(okfunc.call(resolved),
417              "container runtime_constraints was #{resolved.inspect}")
418     end
419   end
420
421   [[{"/out" => {
422         "kind" => "collection",
423         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
424         "path" => "/foo"}},
425     lambda do |resolved|
426       resolved["/out"] == {
427         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
428         "kind" => "collection",
429         "path" => "/foo",
430       }
431     end],
432    [{"/out" => {
433         "kind" => "collection",
434         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
435         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
436         "path" => "/foo"}},
437     lambda do |resolved|
438       resolved["/out"] == {
439         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
440         "kind" => "collection",
441         "path" => "/foo",
442       }
443     end],
444    [{"/out" => {
445       "kind" => "collection",
446       "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
447       "path" => "/foo"}},
448     lambda do |resolved|
449       resolved["/out"] == {
450         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
451         "kind" => "collection",
452         "path" => "/foo",
453       }
454     end],
455     # Empty collection
456     [{"/out" => {
457       "kind" => "collection",
458       "path" => "/foo"}},
459     lambda do |resolved|
460       resolved["/out"] == {
461         "kind" => "collection",
462         "path" => "/foo",
463       }
464     end],
465   ].each do |mounts, okfunc|
466     test "resolve mounts #{mounts.inspect} to values" do
467       set_user_from_auth :active
468       resolved = Container.resolve_mounts(mounts)
469       assert(okfunc.call(resolved),
470              "Container.resolve_mounts returned #{resolved.inspect}")
471     end
472   end
473
474   test 'mount unreadable collection' do
475     set_user_from_auth :spectator
476     m = {
477       "/foo" => {
478         "kind" => "collection",
479         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
480         "path" => "/foo",
481       },
482     }
483     assert_raises(ArvadosModel::UnresolvableContainerError) do
484       Container.resolve_mounts(m)
485     end
486   end
487
488   test 'mount collection with mismatched UUID and PDH' do
489     set_user_from_auth :active
490     m = {
491       "/foo" => {
492         "kind" => "collection",
493         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
494         "portable_data_hash" => "fa7aeb5140e2848d39b416daeef4ffc5+45",
495         "path" => "/foo",
496       },
497     }
498     resolved_mounts = Container.resolve_mounts(m)
499     assert_equal m['portable_data_hash'], resolved_mounts['portable_data_hash']
500   end
501
502   ['arvados/apitestfixture:latest',
503    'arvados/apitestfixture',
504    'd8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678',
505   ].each do |tag|
506     test "Container.resolve_container_image(#{tag.inspect})" do
507       set_user_from_auth :active
508       resolved = Container.resolve_container_image(tag)
509       assert_equal resolved, collections(:docker_image).portable_data_hash
510     end
511   end
512
513   test "Container.resolve_container_image(pdh)" do
514     set_user_from_auth :active
515     [[:docker_image, 'v1'], [:docker_image_1_12, 'v2']].each do |coll, ver|
516       Rails.configuration.docker_image_formats = [ver]
517       pdh = collections(coll).portable_data_hash
518       resolved = Container.resolve_container_image(pdh)
519       assert_equal resolved, pdh
520     end
521   end
522
523   ['acbd18db4cc2f85cedef654fccc4a4d8+3',
524    'ENOEXIST',
525    'arvados/apitestfixture:ENOEXIST',
526   ].each do |img|
527     test "container_image_for_container(#{img.inspect}) => 422" do
528       set_user_from_auth :active
529       assert_raises(ArvadosModel::UnresolvableContainerError) do
530         Container.resolve_container_image(img)
531       end
532     end
533   end
534
535   test "allow unrecognized container when there are remote_hosts" do
536     set_user_from_auth :active
537     Rails.configuration.remote_hosts = {"foooo" => "bar.com"}
538     Container.resolve_container_image('acbd18db4cc2f85cedef654fccc4a4d8+3')
539   end
540
541   test "migrated docker image" do
542     Rails.configuration.docker_image_formats = ['v2']
543     add_docker19_migration_link
544
545     # Test that it returns only v2 images even though request is for v1 image.
546
547     set_user_from_auth :active
548     cr = create_minimal_req!(command: ["true", "1"],
549                              container_image: collections(:docker_image).portable_data_hash)
550     assert_equal(Container.resolve_container_image(cr.container_image),
551                  collections(:docker_image_1_12).portable_data_hash)
552
553     cr = create_minimal_req!(command: ["true", "2"],
554                              container_image: links(:docker_image_collection_tag).name)
555     assert_equal(Container.resolve_container_image(cr.container_image),
556                  collections(:docker_image_1_12).portable_data_hash)
557   end
558
559   test "use unmigrated docker image" do
560     Rails.configuration.docker_image_formats = ['v1']
561     add_docker19_migration_link
562
563     # Test that it returns only supported v1 images even though there is a
564     # migration link.
565
566     set_user_from_auth :active
567     cr = create_minimal_req!(command: ["true", "1"],
568                              container_image: collections(:docker_image).portable_data_hash)
569     assert_equal(Container.resolve_container_image(cr.container_image),
570                  collections(:docker_image).portable_data_hash)
571
572     cr = create_minimal_req!(command: ["true", "2"],
573                              container_image: links(:docker_image_collection_tag).name)
574     assert_equal(Container.resolve_container_image(cr.container_image),
575                  collections(:docker_image).portable_data_hash)
576   end
577
578   test "incompatible docker image v1" do
579     Rails.configuration.docker_image_formats = ['v1']
580     add_docker19_migration_link
581
582     # Don't return unsupported v2 image even if we ask for it directly.
583     set_user_from_auth :active
584     cr = create_minimal_req!(command: ["true", "1"],
585                              container_image: collections(:docker_image_1_12).portable_data_hash)
586     assert_raises(ArvadosModel::UnresolvableContainerError) do
587       Container.resolve_container_image(cr.container_image)
588     end
589   end
590
591   test "incompatible docker image v2" do
592     Rails.configuration.docker_image_formats = ['v2']
593     # No migration link, don't return unsupported v1 image,
594
595     set_user_from_auth :active
596     cr = create_minimal_req!(command: ["true", "1"],
597                              container_image: collections(:docker_image).portable_data_hash)
598     assert_raises(ArvadosModel::UnresolvableContainerError) do
599       Container.resolve_container_image(cr.container_image)
600     end
601     cr = create_minimal_req!(command: ["true", "2"],
602                              container_image: links(:docker_image_collection_tag).name)
603     assert_raises(ArvadosModel::UnresolvableContainerError) do
604       Container.resolve_container_image(cr.container_image)
605     end
606   end
607
608   test "requestor can retrieve container owned by dispatch" do
609     assert_not_empty Container.readable_by(users(:admin)).where(uuid: containers(:running).uuid)
610     assert_not_empty Container.readable_by(users(:active)).where(uuid: containers(:running).uuid)
611     assert_empty Container.readable_by(users(:spectator)).where(uuid: containers(:running).uuid)
612   end
613
614   [
615     [{"var" => "value1"}, {"var" => "value1"}, nil],
616     [{"var" => "value1"}, {"var" => "value1"}, true],
617     [{"var" => "value1"}, {"var" => "value1"}, false],
618     [{"var" => "value1"}, {"var" => "value2"}, nil],
619   ].each do |env1, env2, use_existing|
620     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
621       common_attrs = {cwd: "test",
622                       priority: 1,
623                       command: ["echo", "hello"],
624                       output_path: "test",
625                       runtime_constraints: {"vcpus" => 4,
626                                             "ram" => 12000000000},
627                       mounts: {"test" => {"kind" => "json"}}}
628       set_user_from_auth :active
629       cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed,
630                                                     environment: env1}))
631       if use_existing.nil?
632         # Testing with use_existing default value
633         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
634                                                       environment: env2}))
635       else
636
637         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
638                                                       environment: env2,
639                                                       use_existing: use_existing}))
640       end
641       assert_not_nil cr1.container_uuid
642       assert_nil cr2.container_uuid
643
644       # Update cr2 to commited state and check for container equality on different cases:
645       # * When env1 and env2 are equal and use_existing is true, the same container
646       #   should be assigned.
647       # * When use_existing is false, a different container should be assigned.
648       # * When env1 and env2 are different, a different container should be assigned.
649       cr2.update_attributes!({state: ContainerRequest::Committed})
650       assert_equal (cr2.use_existing == true and (env1 == env2)),
651                    (cr1.container_uuid == cr2.container_uuid)
652     end
653   end
654
655   test "requesting_container_uuid at create is not allowed" do
656     set_user_from_auth :active
657     assert_raises(ActiveRecord::RecordInvalid) do
658       create_minimal_req!(state: "Uncommitted", priority: 1, requesting_container_uuid: 'youcantdothat')
659     end
660   end
661
662   test "Retry on container cancelled" do
663     set_user_from_auth :active
664     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2)
665     cr2 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "baz"])
666     prev_container_uuid = cr.container_uuid
667
668     c = act_as_system_user do
669       c = Container.find_by_uuid(cr.container_uuid)
670       c.update_attributes!(state: Container::Locked)
671       c.update_attributes!(state: Container::Running)
672       c
673     end
674
675     cr.reload
676     cr2.reload
677     assert_equal "Committed", cr.state
678     assert_equal prev_container_uuid, cr.container_uuid
679     assert_not_equal cr2.container_uuid, cr.container_uuid
680     prev_container_uuid = cr.container_uuid
681
682     act_as_system_user do
683       c.update_attributes!(state: Container::Cancelled)
684     end
685
686     cr.reload
687     cr2.reload
688     assert_equal "Committed", cr.state
689     assert_not_equal prev_container_uuid, cr.container_uuid
690     assert_not_equal cr2.container_uuid, cr.container_uuid
691     prev_container_uuid = cr.container_uuid
692
693     c = act_as_system_user do
694       c = Container.find_by_uuid(cr.container_uuid)
695       c.update_attributes!(state: Container::Cancelled)
696       c
697     end
698
699     cr.reload
700     cr2.reload
701     assert_equal "Final", cr.state
702     assert_equal prev_container_uuid, cr.container_uuid
703     assert_not_equal cr2.container_uuid, cr.container_uuid
704   end
705
706   test "Retry on container cancelled with runtime_token" do
707     set_user_from_auth :spectator
708     spec = api_client_authorizations(:active)
709     cr = create_minimal_req!(priority: 1, state: "Committed",
710                              runtime_token: spec.token,
711                              container_count_max: 2)
712     prev_container_uuid = cr.container_uuid
713
714     c = act_as_system_user do
715       c = Container.find_by_uuid(cr.container_uuid)
716       assert_equal spec.token, c.runtime_token
717       c.update_attributes!(state: Container::Locked)
718       c.update_attributes!(state: Container::Running)
719       c
720     end
721
722     cr.reload
723     assert_equal "Committed", cr.state
724     assert_equal prev_container_uuid, cr.container_uuid
725     prev_container_uuid = cr.container_uuid
726
727     act_as_system_user do
728       c.update_attributes!(state: Container::Cancelled)
729     end
730
731     cr.reload
732     assert_equal "Committed", cr.state
733     assert_not_equal prev_container_uuid, cr.container_uuid
734     prev_container_uuid = cr.container_uuid
735
736     c = act_as_system_user do
737       c = Container.find_by_uuid(cr.container_uuid)
738       assert_equal spec.token, c.runtime_token
739       c.update_attributes!(state: Container::Cancelled)
740       c
741     end
742
743     cr.reload
744     assert_equal "Final", cr.state
745     assert_equal prev_container_uuid, cr.container_uuid
746
747   end
748
749   test "Output collection name setting using output_name with name collision resolution" do
750     set_user_from_auth :active
751     output_name = 'unimaginative name'
752     Collection.create!(name: output_name)
753
754     cr = create_minimal_req!(priority: 1,
755                              state: ContainerRequest::Committed,
756                              output_name: output_name)
757     run_container(cr)
758     cr.reload
759     assert_equal ContainerRequest::Final, cr.state
760     output_coll = Collection.find_by_uuid(cr.output_uuid)
761     # Make sure the resulting output collection name include the original name
762     # plus the date
763     assert_not_equal output_name, output_coll.name,
764                      "more than one collection with the same owner and name"
765     assert output_coll.name.include?(output_name),
766            "New name should include original name"
767     assert_match /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z/, output_coll.name,
768                  "New name should include ISO8601 date"
769   end
770
771   [[0, :check_output_ttl_0],
772    [1, :check_output_ttl_1s],
773    [365*86400, :check_output_ttl_1y],
774   ].each do |ttl, checker|
775     test "output_ttl=#{ttl}" do
776       act_as_user users(:active) do
777         cr = create_minimal_req!(priority: 1,
778                                  state: ContainerRequest::Committed,
779                                  output_name: 'foo',
780                                  output_ttl: ttl)
781         run_container(cr)
782         cr.reload
783         output = Collection.find_by_uuid(cr.output_uuid)
784         send(checker, db_current_time, output.trash_at, output.delete_at)
785       end
786     end
787   end
788
789   def check_output_ttl_0(now, trash, delete)
790     assert_nil(trash)
791     assert_nil(delete)
792   end
793
794   def check_output_ttl_1s(now, trash, delete)
795     assert_not_nil(trash)
796     assert_not_nil(delete)
797     assert_in_delta(trash, now + 1.second, 10)
798     assert_in_delta(delete, now + Rails.configuration.blob_signature_ttl.second, 10)
799   end
800
801   def check_output_ttl_1y(now, trash, delete)
802     year = (86400*365).second
803     assert_not_nil(trash)
804     assert_not_nil(delete)
805     assert_in_delta(trash, now + year, 10)
806     assert_in_delta(delete, now + year, 10)
807   end
808
809   def run_container(cr)
810     act_as_system_user do
811       c = Container.find_by_uuid(cr.container_uuid)
812       c.update_attributes!(state: Container::Locked)
813       c.update_attributes!(state: Container::Running)
814       c.update_attributes!(state: Container::Complete,
815                            exit_code: 0,
816                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
817                            log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
818       c
819     end
820   end
821
822   test "Finalize committed request when reusing a finished container" do
823     set_user_from_auth :active
824     cr = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
825     cr.reload
826     assert_equal ContainerRequest::Committed, cr.state
827     run_container(cr)
828     cr.reload
829     assert_equal ContainerRequest::Final, cr.state
830
831     cr2 = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
832     assert_equal cr.container_uuid, cr2.container_uuid
833     assert_equal ContainerRequest::Final, cr2.state
834
835     cr3 = create_minimal_req!(priority: 1, state: ContainerRequest::Uncommitted)
836     assert_equal ContainerRequest::Uncommitted, cr3.state
837     cr3.update_attributes!(state: ContainerRequest::Committed)
838     assert_equal cr.container_uuid, cr3.container_uuid
839     assert_equal ContainerRequest::Final, cr3.state
840   end
841
842   [
843     [false, ActiveRecord::RecordInvalid],
844     [true, nil],
845   ].each do |preemptible_conf, expected|
846     test "having Rails.configuration.preemptible_instances=#{preemptible_conf}, create preemptible container request and verify #{expected}" do
847       sp = {"preemptible" => true}
848       common_attrs = {cwd: "test",
849                       priority: 1,
850                       command: ["echo", "hello"],
851                       output_path: "test",
852                       scheduling_parameters: sp,
853                       mounts: {"test" => {"kind" => "json"}}}
854       Rails.configuration.preemptible_instances = preemptible_conf
855       set_user_from_auth :active
856
857       cr = create_minimal_req!(common_attrs)
858       cr.state = ContainerRequest::Committed
859
860       if !expected.nil?
861         assert_raises(expected) do
862           cr.save!
863         end
864       else
865         cr.save!
866         assert_equal sp, cr.scheduling_parameters
867       end
868     end
869   end
870
871   [
872     'zzzzz-dz642-runningcontainr',
873     nil,
874   ].each do |requesting_c|
875     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
876       common_attrs = {cwd: "test",
877                       priority: 1,
878                       command: ["echo", "hello"],
879                       output_path: "test",
880                       scheduling_parameters: {"preemptible" => false},
881                       mounts: {"test" => {"kind" => "json"}}}
882
883       Rails.configuration.preemptible_instances = true
884       set_user_from_auth :active
885
886       if requesting_c
887         cr = with_container_auth(Container.find_by_uuid requesting_c) do
888           create_minimal_req!(common_attrs)
889         end
890         assert_not_nil cr.requesting_container_uuid
891       else
892         cr = create_minimal_req!(common_attrs)
893       end
894
895       cr.state = ContainerRequest::Committed
896       cr.save!
897
898       assert_equal false, cr.scheduling_parameters['preemptible']
899     end
900   end
901
902   [
903     [true, 'zzzzz-dz642-runningcontainr', true],
904     [true, nil, nil],
905     [false, 'zzzzz-dz642-runningcontainr', nil],
906     [false, nil, nil],
907   ].each do |preemptible_conf, requesting_c, schedule_preemptible|
908     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
909       common_attrs = {cwd: "test",
910                       priority: 1,
911                       command: ["echo", "hello"],
912                       output_path: "test",
913                       mounts: {"test" => {"kind" => "json"}}}
914
915       Rails.configuration.preemptible_instances = preemptible_conf
916       set_user_from_auth :active
917
918       if requesting_c
919         cr = with_container_auth(Container.find_by_uuid requesting_c) do
920           create_minimal_req!(common_attrs)
921         end
922         assert_not_nil cr.requesting_container_uuid
923       else
924         cr = create_minimal_req!(common_attrs)
925       end
926
927       cr.state = ContainerRequest::Committed
928       cr.save!
929
930       assert_equal schedule_preemptible, cr.scheduling_parameters['preemptible']
931     end
932   end
933
934   [
935     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
936     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Uncommitted],
937     [{"partitions" => "fastcpu"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
938     [{"partitions" => "fastcpu"}, ContainerRequest::Uncommitted],
939     [{"partitions" => ["fastcpu","vfastcpu"]}, ContainerRequest::Committed],
940     [{"max_run_time" => "one day"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
941     [{"max_run_time" => "one day"}, ContainerRequest::Uncommitted],
942     [{"max_run_time" => -1}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
943     [{"max_run_time" => -1}, ContainerRequest::Uncommitted],
944     [{"max_run_time" => 86400}, ContainerRequest::Committed],
945   ].each do |sp, state, expected|
946     test "create container request with scheduling_parameters #{sp} in state #{state} and verify #{expected}" do
947       common_attrs = {cwd: "test",
948                       priority: 1,
949                       command: ["echo", "hello"],
950                       output_path: "test",
951                       scheduling_parameters: sp,
952                       mounts: {"test" => {"kind" => "json"}}}
953       set_user_from_auth :active
954
955       if expected == ActiveRecord::RecordInvalid
956         assert_raises(ActiveRecord::RecordInvalid) do
957           create_minimal_req!(common_attrs.merge({state: state}))
958         end
959       else
960         cr = create_minimal_req!(common_attrs.merge({state: state}))
961         assert_equal sp, cr.scheduling_parameters
962
963         if state == ContainerRequest::Committed
964           c = Container.find_by_uuid(cr.container_uuid)
965           assert_equal sp, c.scheduling_parameters
966         end
967       end
968     end
969   end
970
971   test "Having preemptible_instances=true create a committed child container request and verify the scheduling parameter of its container" do
972     common_attrs = {cwd: "test",
973                     priority: 1,
974                     command: ["echo", "hello"],
975                     output_path: "test",
976                     state: ContainerRequest::Committed,
977                     mounts: {"test" => {"kind" => "json"}}}
978     set_user_from_auth :active
979     Rails.configuration.preemptible_instances = true
980
981     cr = with_container_auth(Container.find_by_uuid 'zzzzz-dz642-runningcontainr') do
982       create_minimal_req!(common_attrs)
983     end
984     assert_equal 'zzzzz-dz642-runningcontainr', cr.requesting_container_uuid
985     assert_equal true, cr.scheduling_parameters["preemptible"]
986
987     c = Container.find_by_uuid(cr.container_uuid)
988     assert_equal true, c.scheduling_parameters["preemptible"]
989   end
990
991   [['Committed', true, {name: "foobar", priority: 123}],
992    ['Committed', false, {container_count: 2}],
993    ['Committed', false, {container_count: 0}],
994    ['Committed', false, {container_count: nil}],
995    ['Final', false, {state: ContainerRequest::Committed, name: "foobar"}],
996    ['Final', false, {name: "foobar", priority: 123}],
997    ['Final', false, {name: "foobar", output_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
998    ['Final', false, {name: "foobar", log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
999    ['Final', false, {log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1000    ['Final', false, {priority: 123}],
1001    ['Final', false, {mounts: {}}],
1002    ['Final', false, {container_count: 2}],
1003    ['Final', true, {name: "foobar"}],
1004    ['Final', true, {name: "foobar", description: "baz"}],
1005   ].each do |state, permitted, updates|
1006     test "state=#{state} can#{'not' if !permitted} update #{updates.inspect}" do
1007       act_as_user users(:active) do
1008         cr = create_minimal_req!(priority: 1,
1009                                  state: "Committed",
1010                                  container_count_max: 1)
1011         case state
1012         when 'Committed'
1013           # already done
1014         when 'Final'
1015           act_as_system_user do
1016             Container.find_by_uuid(cr.container_uuid).
1017               update_attributes!(state: Container::Cancelled)
1018           end
1019           cr.reload
1020         else
1021           raise 'broken test case'
1022         end
1023         assert_equal state, cr.state
1024         if permitted
1025           assert cr.update_attributes!(updates)
1026         else
1027           assert_raises(ActiveRecord::RecordInvalid) do
1028             cr.update_attributes!(updates)
1029           end
1030         end
1031       end
1032     end
1033   end
1034
1035   test "delete container_request and check its container's priority" do
1036     act_as_user users(:active) do
1037       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
1038
1039       # initially the cr's container has priority > 0
1040       c = Container.find_by_uuid(cr.container_uuid)
1041       assert_equal 1, c.priority
1042
1043       cr.destroy
1044
1045       # the cr's container now has priority of 0
1046       c = Container.find_by_uuid(cr.container_uuid)
1047       assert_equal 0, c.priority
1048     end
1049   end
1050
1051   test "delete container_request in final state and expect no error due to before_destroy callback" do
1052     act_as_user users(:active) do
1053       cr = ContainerRequest.find_by_uuid container_requests(:completed).uuid
1054       assert_nothing_raised {cr.destroy}
1055     end
1056   end
1057
1058   test "Container request valid priority" do
1059     set_user_from_auth :active
1060     cr = create_minimal_req!
1061
1062     assert_raises(ActiveRecord::RecordInvalid) do
1063       cr.priority = -1
1064       cr.save!
1065     end
1066
1067     cr.priority = 0
1068     cr.save!
1069
1070     cr.priority = 1
1071     cr.save!
1072
1073     cr.priority = 500
1074     cr.save!
1075
1076     cr.priority = 999
1077     cr.save!
1078
1079     cr.priority = 1000
1080     cr.save!
1081
1082     assert_raises(ActiveRecord::RecordInvalid) do
1083       cr.priority = 1001
1084       cr.save!
1085     end
1086   end
1087
1088   # Note: some of these tests might look redundant because they test
1089   # that out-of-order spellings of hashes are still considered equal
1090   # regardless of whether the existing (container) or new (container
1091   # request) hash needs to be re-ordered.
1092   secrets = {"/foo" => {"kind" => "text", "content" => "xyzzy"}}
1093   same_secrets = {"/foo" => {"content" => "xyzzy", "kind" => "text"}}
1094   different_secrets = {"/foo" => {"kind" => "text", "content" => "something completely different"}}
1095   [
1096     [true, nil, nil],
1097     [true, nil, {}],
1098     [true, {}, nil],
1099     [true, {}, {}],
1100     [true, secrets, same_secrets],
1101     [true, same_secrets, secrets],
1102     [false, nil, secrets],
1103     [false, {}, secrets],
1104     [false, secrets, {}],
1105     [false, secrets, nil],
1106     [false, secrets, different_secrets],
1107   ].each do |expect_reuse, sm1, sm2|
1108     test "container reuse secret_mounts #{sm1.inspect}, #{sm2.inspect}" do
1109       set_user_from_auth :active
1110       cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm1)
1111       cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm2)
1112       assert_not_nil cr1.container_uuid
1113       assert_not_nil cr2.container_uuid
1114       if expect_reuse
1115         assert_equal cr1.container_uuid, cr2.container_uuid
1116       else
1117         assert_not_equal cr1.container_uuid, cr2.container_uuid
1118       end
1119     end
1120   end
1121
1122   test "scrub secret_mounts but reuse container for request with identical secret_mounts" do
1123     set_user_from_auth :active
1124     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1125     cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1126     run_container(cr1)
1127     cr1.reload
1128
1129     # secret_mounts scrubbed from db
1130     c = Container.where(uuid: cr1.container_uuid).first
1131     assert_equal({}, c.secret_mounts)
1132     assert_equal({}, cr1.secret_mounts)
1133
1134     # can reuse container if secret_mounts match
1135     cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1136     assert_equal cr1.container_uuid, cr2.container_uuid
1137
1138     # don't reuse container if secret_mounts don't match
1139     cr3 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: {})
1140     assert_not_equal cr1.container_uuid, cr3.container_uuid
1141
1142     assert_no_secrets_logged
1143   end
1144
1145   test "conflicting key in mounts and secret_mounts" do
1146     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1147     set_user_from_auth :active
1148     cr = create_minimal_req!
1149     assert_equal false, cr.update_attributes(state: "Committed",
1150                                              priority: 1,
1151                                              mounts: cr.mounts.merge(sm),
1152                                              secret_mounts: sm)
1153     assert_equal [:secret_mounts], cr.errors.messages.keys
1154   end
1155
1156   test "using runtime_token" do
1157     set_user_from_auth :spectator
1158     spec = api_client_authorizations(:active)
1159     cr = create_minimal_req!(state: "Committed", runtime_token: spec.token, priority: 1)
1160     cr.save!
1161     c = Container.find_by_uuid cr.container_uuid
1162     lock_and_run c
1163     assert_nil c.auth_uuid
1164     assert_equal c.runtime_token, spec.token
1165
1166     assert_not_nil ApiClientAuthorization.find_by_uuid(spec.uuid)
1167
1168     act_as_system_user do
1169       c.update_attributes!(state: Container::Complete,
1170                            exit_code: 0,
1171                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1172                            log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
1173     end
1174
1175     cr.reload
1176     c.reload
1177     assert_nil cr.runtime_token
1178     assert_nil c.runtime_token
1179   end
1180
1181   test "invalid runtime_token" do
1182     set_user_from_auth :active
1183     spec = api_client_authorizations(:spectator)
1184     assert_raises(ArgumentError) do
1185       cr = create_minimal_req!(state: "Committed", runtime_token: "#{spec.token}xx")
1186       cr.save!
1187     end
1188   end
1189 end