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