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