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