11453: Merge branch 'master' into 11453-federated-tokens
[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/docker_migration_helper'
7
8 class ContainerRequestTest < ActiveSupport::TestCase
9   include DockerMigrationHelper
10   include DbCurrentTime
11
12   def create_minimal_req! attrs={}
13     defaults = {
14       command: ["echo", "foo"],
15       container_image: links(:docker_image_collection_tag).name,
16       cwd: "/tmp",
17       environment: {},
18       mounts: {"/out" => {"kind" => "tmp", "capacity" => 1000000}},
19       output_path: "/out",
20       runtime_constraints: {"vcpus" => 1, "ram" => 2},
21       name: "foo",
22       description: "bar",
23     }
24     cr = ContainerRequest.create!(defaults.merge(attrs))
25     cr.reload
26     return cr
27   end
28
29   def check_bogus_states cr
30     [nil, "Flubber"].each do |state|
31       assert_raises(ActiveRecord::RecordInvalid) do
32         cr.state = state
33         cr.save!
34       end
35       cr.reload
36     end
37   end
38
39   test "Container request create" do
40     set_user_from_auth :active
41     cr = create_minimal_req!
42
43     assert_nil cr.container_uuid
44     assert_nil cr.priority
45
46     check_bogus_states cr
47
48     # Ensure we can modify all attributes
49     cr.command = ["echo", "foo3"]
50     cr.container_image = "img3"
51     cr.cwd = "/tmp3"
52     cr.environment = {"BUP" => "BOP"}
53     cr.mounts = {"BAR" => "BAZ"}
54     cr.output_path = "/tmp4"
55     cr.priority = 2
56     cr.runtime_constraints = {"vcpus" => 4}
57     cr.name = "foo3"
58     cr.description = "bar3"
59     cr.save!
60
61     assert_nil cr.container_uuid
62   end
63
64   [
65     {"vcpus" => 1},
66     {"vcpus" => 1, "ram" => nil},
67     {"vcpus" => 0, "ram" => 123},
68     {"vcpus" => "1", "ram" => "123"}
69   ].each do |invalid_constraints|
70     test "Create with #{invalid_constraints}" do
71       set_user_from_auth :active
72       assert_raises(ActiveRecord::RecordInvalid) do
73         cr = create_minimal_req!(state: "Committed",
74                                  priority: 1,
75                                  runtime_constraints: invalid_constraints)
76         cr.save!
77       end
78     end
79
80     test "Update with #{invalid_constraints}" do
81       set_user_from_auth :active
82       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
83       cr.save!
84       assert_raises(ActiveRecord::RecordInvalid) do
85         cr = ContainerRequest.find_by_uuid cr.uuid
86         cr.update_attributes!(state: "Committed",
87                               runtime_constraints: invalid_constraints)
88       end
89     end
90   end
91
92   test "Update from fixture" do
93     set_user_from_auth :active
94     cr = ContainerRequest.find_by_uuid(container_requests(:running).uuid)
95     cr.update_attributes!(description: "New description")
96     assert_equal "New description", cr.description
97   end
98
99   test "Update with valid runtime constraints" do
100       set_user_from_auth :active
101       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
102       cr.save!
103       cr = ContainerRequest.find_by_uuid cr.uuid
104       cr.update_attributes!(state: "Committed",
105                             runtime_constraints: {"vcpus" => 1, "ram" => 23})
106       assert_not_nil cr.container_uuid
107   end
108
109   test "Container request priority must be non-nil" do
110     set_user_from_auth :active
111     cr = create_minimal_req!(priority: nil)
112     cr.state = "Committed"
113     assert_raises(ActiveRecord::RecordInvalid) do
114       cr.save!
115     end
116   end
117
118   test "Container request commit" do
119     set_user_from_auth :active
120     cr = create_minimal_req!(runtime_constraints: {"vcpus" => 2, "ram" => 30})
121
122     assert_nil cr.container_uuid
123
124     cr.reload
125     cr.state = "Committed"
126     cr.priority = 1
127     cr.save!
128
129     cr.reload
130
131     assert_equal({"vcpus" => 2, "ram" => 30}, cr.runtime_constraints)
132
133     assert_not_nil cr.container_uuid
134     c = Container.find_by_uuid cr.container_uuid
135     assert_not_nil c
136     assert_equal ["echo", "foo"], c.command
137     assert_equal collections(:docker_image).portable_data_hash, c.container_image
138     assert_equal "/tmp", c.cwd
139     assert_equal({}, c.environment)
140     assert_equal({"/out" => {"kind"=>"tmp", "capacity"=>1000000}}, c.mounts)
141     assert_equal "/out", c.output_path
142     assert_equal({"keep_cache_ram"=>268435456, "vcpus" => 2, "ram" => 30}, c.runtime_constraints)
143     assert_equal 1, c.priority
144
145     assert_raises(ActiveRecord::RecordInvalid) do
146       cr.priority = nil
147       cr.save!
148     end
149
150     cr.priority = 0
151     cr.save!
152
153     cr.reload
154     c.reload
155     assert_equal 0, cr.priority
156     assert_equal 0, c.priority
157   end
158
159
160   test "Container request max priority" do
161     set_user_from_auth :active
162     cr = create_minimal_req!(priority: 5, state: "Committed")
163
164     c = Container.find_by_uuid cr.container_uuid
165     assert_equal 5, c.priority
166
167     cr2 = create_minimal_req!
168     cr2.priority = 10
169     cr2.state = "Committed"
170     cr2.container_uuid = cr.container_uuid
171     act_as_system_user do
172       cr2.save!
173     end
174
175     # cr and cr2 have priority 5 and 10, and are being satisfied by
176     # the same container c, so c's priority should be
177     # max(priority)=10.
178     c.reload
179     assert_equal 10, c.priority
180
181     cr2.update_attributes!(priority: 0)
182
183     c.reload
184     assert_equal 5, c.priority
185
186     cr.update_attributes!(priority: 0)
187
188     c.reload
189     assert_equal 0, c.priority
190   end
191
192
193   test "Independent container requests" do
194     set_user_from_auth :active
195     cr1 = create_minimal_req!(command: ["foo", "1"], priority: 5, state: "Committed")
196     cr2 = create_minimal_req!(command: ["foo", "2"], priority: 10, state: "Committed")
197
198     c1 = Container.find_by_uuid cr1.container_uuid
199     assert_equal 5, c1.priority
200
201     c2 = Container.find_by_uuid cr2.container_uuid
202     assert_equal 10, c2.priority
203
204     cr1.update_attributes!(priority: 0)
205
206     c1.reload
207     assert_equal 0, c1.priority
208
209     c2.reload
210     assert_equal 10, c2.priority
211   end
212
213   test "Request is finalized when its container is cancelled" do
214     set_user_from_auth :active
215     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 1)
216
217     act_as_system_user do
218       Container.find_by_uuid(cr.container_uuid).
219         update_attributes!(state: Container::Cancelled)
220     end
221
222     cr.reload
223     assert_equal "Final", cr.state
224   end
225
226   test "Request is finalized when its container is completed" do
227     set_user_from_auth :active
228     project = groups(:private)
229     cr = create_minimal_req!(owner_uuid: project.uuid,
230                              priority: 1,
231                              state: "Committed")
232
233     c = act_as_system_user do
234       c = Container.find_by_uuid(cr.container_uuid)
235       c.update_attributes!(state: Container::Locked)
236       c.update_attributes!(state: Container::Running)
237       c
238     end
239
240     cr.reload
241     assert_equal "Committed", cr.state
242
243     output_pdh = '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
244     log_pdh = 'fa7aeb5140e2848d39b416daeef4ffc5+45'
245     act_as_system_user do
246       c.update_attributes!(state: Container::Complete,
247                            output: output_pdh,
248                            log: log_pdh)
249     end
250
251     cr.reload
252     assert_equal "Final", cr.state
253     ['output', 'log'].each do |out_type|
254       pdh = Container.find_by_uuid(cr.container_uuid).send(out_type)
255       assert_equal(1, Collection.where(portable_data_hash: pdh,
256                                        owner_uuid: project.uuid).count,
257                    "Container #{out_type} should be copied to #{project.uuid}")
258     end
259     assert_not_nil cr.output_uuid
260     assert_not_nil cr.log_uuid
261     output = Collection.find_by_uuid cr.output_uuid
262     assert_equal output_pdh, output.portable_data_hash
263     log = Collection.find_by_uuid cr.log_uuid
264     assert_equal log_pdh, log.portable_data_hash
265   end
266
267   test "Container makes container request, then is cancelled" do
268     set_user_from_auth :active
269     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 1)
270
271     c = Container.find_by_uuid cr.container_uuid
272     assert_equal 5, c.priority
273
274     cr2 = create_minimal_req!
275     cr2.update_attributes!(priority: 10, state: "Committed", requesting_container_uuid: c.uuid, command: ["echo", "foo2"], container_count_max: 1)
276     cr2.reload
277
278     c2 = Container.find_by_uuid cr2.container_uuid
279     assert_equal 10, c2.priority
280
281     act_as_system_user do
282       c.state = "Cancelled"
283       c.save!
284     end
285
286     cr.reload
287     assert_equal "Final", cr.state
288
289     cr2.reload
290     assert_equal 0, cr2.priority
291
292     c2.reload
293     assert_equal 0, c2.priority
294   end
295
296
297   test "Container makes container request, then changes priority" do
298     set_user_from_auth :active
299     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 1)
300
301     c = Container.find_by_uuid cr.container_uuid
302     assert_equal 5, c.priority
303
304     cr2 = create_minimal_req!
305     cr2.update_attributes!(priority: 5, state: "Committed", requesting_container_uuid: c.uuid, command: ["echo", "foo2"], container_count_max: 1)
306     cr2.reload
307
308     c2 = Container.find_by_uuid cr2.container_uuid
309     assert_equal 5, c2.priority
310
311     act_as_system_user do
312       c.priority = 10
313       c.save!
314     end
315
316     cr.reload
317
318     cr2.reload
319     assert_equal 10, cr2.priority
320
321     c2.reload
322     assert_equal 10, c2.priority
323   end
324
325   [
326     ['running_container_auth', 'zzzzz-dz642-runningcontainr'],
327     ['active_no_prefs', nil],
328   ].each do |token, expected|
329     test "create as #{token} and expect requesting_container_uuid to be #{expected}" do
330       set_user_from_auth token
331       cr = ContainerRequest.create(container_image: "img", output_path: "/tmp", command: ["echo", "foo"])
332       assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
333       assert_equal expected, cr.requesting_container_uuid
334     end
335   end
336
337   [[{"vcpus" => [2, nil]},
338     lambda { |resolved| resolved["vcpus"] == 2 }],
339    [{"vcpus" => [3, 7]},
340     lambda { |resolved| resolved["vcpus"] == 3 }],
341    [{"vcpus" => 4},
342     lambda { |resolved| resolved["vcpus"] == 4 }],
343    [{"ram" => [1000000000, 2000000000]},
344     lambda { |resolved| resolved["ram"] == 1000000000 }],
345    [{"ram" => [1234234234]},
346     lambda { |resolved| resolved["ram"] == 1234234234 }],
347   ].each do |rc, okfunc|
348     test "resolve runtime constraint range #{rc} to values" do
349       resolved = Container.resolve_runtime_constraints(rc)
350       assert(okfunc.call(resolved),
351              "container runtime_constraints was #{resolved.inspect}")
352     end
353   end
354
355   [[{"/out" => {
356         "kind" => "collection",
357         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
358         "path" => "/foo"}},
359     lambda do |resolved|
360       resolved["/out"] == {
361         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
362         "kind" => "collection",
363         "path" => "/foo",
364       }
365     end],
366    [{"/out" => {
367         "kind" => "collection",
368         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
369         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
370         "path" => "/foo"}},
371     lambda do |resolved|
372       resolved["/out"] == {
373         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
374         "kind" => "collection",
375         "path" => "/foo",
376       }
377     end],
378   ].each do |mounts, okfunc|
379     test "resolve mounts #{mounts.inspect} to values" do
380       set_user_from_auth :active
381       resolved = Container.resolve_mounts(mounts)
382       assert(okfunc.call(resolved),
383              "Container.resolve_mounts returned #{resolved.inspect}")
384     end
385   end
386
387   test 'mount unreadable collection' do
388     set_user_from_auth :spectator
389     m = {
390       "/foo" => {
391         "kind" => "collection",
392         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
393         "path" => "/foo",
394       },
395     }
396     assert_raises(ArvadosModel::UnresolvableContainerError) do
397       Container.resolve_mounts(m)
398     end
399   end
400
401   test 'mount collection with mismatched UUID and PDH' do
402     set_user_from_auth :active
403     m = {
404       "/foo" => {
405         "kind" => "collection",
406         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
407         "portable_data_hash" => "fa7aeb5140e2848d39b416daeef4ffc5+45",
408         "path" => "/foo",
409       },
410     }
411     assert_raises(ArgumentError) do
412       Container.resolve_mounts(m)
413     end
414   end
415
416   ['arvados/apitestfixture:latest',
417    'arvados/apitestfixture',
418    'd8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678',
419   ].each do |tag|
420     test "Container.resolve_container_image(#{tag.inspect})" do
421       set_user_from_auth :active
422       resolved = Container.resolve_container_image(tag)
423       assert_equal resolved, collections(:docker_image).portable_data_hash
424     end
425   end
426
427   test "Container.resolve_container_image(pdh)" do
428     set_user_from_auth :active
429     [[:docker_image, 'v1'], [:docker_image_1_12, 'v2']].each do |coll, ver|
430       Rails.configuration.docker_image_formats = [ver]
431       pdh = collections(coll).portable_data_hash
432       resolved = Container.resolve_container_image(pdh)
433       assert_equal resolved, pdh
434     end
435   end
436
437   ['acbd18db4cc2f85cedef654fccc4a4d8+3',
438    'ENOEXIST',
439    'arvados/apitestfixture:ENOEXIST',
440   ].each do |img|
441     test "container_image_for_container(#{img.inspect}) => 422" do
442       set_user_from_auth :active
443       assert_raises(ArvadosModel::UnresolvableContainerError) do
444         Container.resolve_container_image(img)
445       end
446     end
447   end
448
449   test "migrated docker image" do
450     Rails.configuration.docker_image_formats = ['v2']
451     add_docker19_migration_link
452
453     # Test that it returns only v2 images even though request is for v1 image.
454
455     set_user_from_auth :active
456     cr = create_minimal_req!(command: ["true", "1"],
457                              container_image: collections(:docker_image).portable_data_hash)
458     assert_equal(Container.resolve_container_image(cr.container_image),
459                  collections(:docker_image_1_12).portable_data_hash)
460
461     cr = create_minimal_req!(command: ["true", "2"],
462                              container_image: links(:docker_image_collection_tag).name)
463     assert_equal(Container.resolve_container_image(cr.container_image),
464                  collections(:docker_image_1_12).portable_data_hash)
465   end
466
467   test "use unmigrated docker image" do
468     Rails.configuration.docker_image_formats = ['v1']
469     add_docker19_migration_link
470
471     # Test that it returns only supported v1 images even though there is a
472     # migration link.
473
474     set_user_from_auth :active
475     cr = create_minimal_req!(command: ["true", "1"],
476                              container_image: collections(:docker_image).portable_data_hash)
477     assert_equal(Container.resolve_container_image(cr.container_image),
478                  collections(:docker_image).portable_data_hash)
479
480     cr = create_minimal_req!(command: ["true", "2"],
481                              container_image: links(:docker_image_collection_tag).name)
482     assert_equal(Container.resolve_container_image(cr.container_image),
483                  collections(:docker_image).portable_data_hash)
484   end
485
486   test "incompatible docker image v1" do
487     Rails.configuration.docker_image_formats = ['v1']
488     add_docker19_migration_link
489
490     # Don't return unsupported v2 image even if we ask for it directly.
491     set_user_from_auth :active
492     cr = create_minimal_req!(command: ["true", "1"],
493                              container_image: collections(:docker_image_1_12).portable_data_hash)
494     assert_raises(ArvadosModel::UnresolvableContainerError) do
495       Container.resolve_container_image(cr.container_image)
496     end
497   end
498
499   test "incompatible docker image v2" do
500     Rails.configuration.docker_image_formats = ['v2']
501     # No migration link, don't return unsupported v1 image,
502
503     set_user_from_auth :active
504     cr = create_minimal_req!(command: ["true", "1"],
505                              container_image: collections(:docker_image).portable_data_hash)
506     assert_raises(ArvadosModel::UnresolvableContainerError) do
507       Container.resolve_container_image(cr.container_image)
508     end
509     cr = create_minimal_req!(command: ["true", "2"],
510                              container_image: links(:docker_image_collection_tag).name)
511     assert_raises(ArvadosModel::UnresolvableContainerError) do
512       Container.resolve_container_image(cr.container_image)
513     end
514   end
515
516   test "requestor can retrieve container owned by dispatch" do
517     assert_not_empty Container.readable_by(users(:admin)).where(uuid: containers(:running).uuid)
518     assert_not_empty Container.readable_by(users(:active)).where(uuid: containers(:running).uuid)
519     assert_empty Container.readable_by(users(:spectator)).where(uuid: containers(:running).uuid)
520   end
521
522   [
523     [{"var" => "value1"}, {"var" => "value1"}, nil],
524     [{"var" => "value1"}, {"var" => "value1"}, true],
525     [{"var" => "value1"}, {"var" => "value1"}, false],
526     [{"var" => "value1"}, {"var" => "value2"}, nil],
527   ].each do |env1, env2, use_existing|
528     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
529       common_attrs = {cwd: "test",
530                       priority: 1,
531                       command: ["echo", "hello"],
532                       output_path: "test",
533                       runtime_constraints: {"vcpus" => 4,
534                                             "ram" => 12000000000},
535                       mounts: {"test" => {"kind" => "json"}}}
536       set_user_from_auth :active
537       cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed,
538                                                     environment: env1}))
539       if use_existing.nil?
540         # Testing with use_existing default value
541         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
542                                                       environment: env2}))
543       else
544
545         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
546                                                       environment: env2,
547                                                       use_existing: use_existing}))
548       end
549       assert_not_nil cr1.container_uuid
550       assert_nil cr2.container_uuid
551
552       # Update cr2 to commited state and check for container equality on different cases:
553       # * When env1 and env2 are equal and use_existing is true, the same container
554       #   should be assigned.
555       # * When use_existing is false, a different container should be assigned.
556       # * When env1 and env2 are different, a different container should be assigned.
557       cr2.update_attributes!({state: ContainerRequest::Committed})
558       assert_equal (cr2.use_existing == true and (env1 == env2)),
559                    (cr1.container_uuid == cr2.container_uuid)
560     end
561   end
562
563   test "requesting_container_uuid at create is not allowed" do
564     set_user_from_auth :active
565     assert_raises(ActiveRecord::RecordNotSaved) do
566       create_minimal_req!(state: "Uncommitted", priority: 1, requesting_container_uuid: 'youcantdothat')
567     end
568   end
569
570   test "Retry on container cancelled" do
571     set_user_from_auth :active
572     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2)
573     cr2 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "baz"])
574     prev_container_uuid = cr.container_uuid
575
576     c = act_as_system_user do
577       c = Container.find_by_uuid(cr.container_uuid)
578       c.update_attributes!(state: Container::Locked)
579       c.update_attributes!(state: Container::Running)
580       c
581     end
582
583     cr.reload
584     cr2.reload
585     assert_equal "Committed", cr.state
586     assert_equal prev_container_uuid, cr.container_uuid
587     assert_not_equal cr2.container_uuid, cr.container_uuid
588     prev_container_uuid = cr.container_uuid
589
590     act_as_system_user do
591       c.update_attributes!(state: Container::Cancelled)
592     end
593
594     cr.reload
595     cr2.reload
596     assert_equal "Committed", cr.state
597     assert_not_equal prev_container_uuid, cr.container_uuid
598     assert_not_equal cr2.container_uuid, cr.container_uuid
599     prev_container_uuid = cr.container_uuid
600
601     c = act_as_system_user do
602       c = Container.find_by_uuid(cr.container_uuid)
603       c.update_attributes!(state: Container::Cancelled)
604       c
605     end
606
607     cr.reload
608     cr2.reload
609     assert_equal "Final", cr.state
610     assert_equal prev_container_uuid, cr.container_uuid
611     assert_not_equal cr2.container_uuid, cr.container_uuid
612   end
613
614   test "Output collection name setting using output_name with name collision resolution" do
615     set_user_from_auth :active
616     output_name = 'unimaginative name'
617     Collection.create!(name: output_name)
618
619     cr = create_minimal_req!(priority: 1,
620                              state: ContainerRequest::Committed,
621                              output_name: output_name)
622     run_container(cr)
623     cr.reload
624     assert_equal ContainerRequest::Final, cr.state
625     output_coll = Collection.find_by_uuid(cr.output_uuid)
626     # Make sure the resulting output collection name include the original name
627     # plus the date
628     assert_not_equal output_name, output_coll.name,
629                      "more than one collection with the same owner and name"
630     assert output_coll.name.include?(output_name),
631            "New name should include original name"
632     assert_match /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z/, output_coll.name,
633                  "New name should include ISO8601 date"
634   end
635
636   [[0, :check_output_ttl_0],
637    [1, :check_output_ttl_1s],
638    [365*86400, :check_output_ttl_1y],
639   ].each do |ttl, checker|
640     test "output_ttl=#{ttl}" do
641       act_as_user users(:active) do
642         cr = create_minimal_req!(priority: 1,
643                                  state: ContainerRequest::Committed,
644                                  output_name: 'foo',
645                                  output_ttl: ttl)
646         run_container(cr)
647         cr.reload
648         output = Collection.find_by_uuid(cr.output_uuid)
649         send(checker, db_current_time, output.trash_at, output.delete_at)
650       end
651     end
652   end
653
654   def check_output_ttl_0(now, trash, delete)
655     assert_nil(trash)
656     assert_nil(delete)
657   end
658
659   def check_output_ttl_1s(now, trash, delete)
660     assert_not_nil(trash)
661     assert_not_nil(delete)
662     assert_in_delta(trash, now + 1.second, 10)
663     assert_in_delta(delete, now + Rails.configuration.blob_signature_ttl.second, 10)
664   end
665
666   def check_output_ttl_1y(now, trash, delete)
667     year = (86400*365).second
668     assert_not_nil(trash)
669     assert_not_nil(delete)
670     assert_in_delta(trash, now + year, 10)
671     assert_in_delta(delete, now + year, 10)
672   end
673
674   def run_container(cr)
675     act_as_system_user do
676       c = Container.find_by_uuid(cr.container_uuid)
677       c.update_attributes!(state: Container::Locked)
678       c.update_attributes!(state: Container::Running)
679       c.update_attributes!(state: Container::Complete,
680                            exit_code: 0,
681                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
682                            log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
683       c
684     end
685   end
686
687   test "Finalize committed request when reusing a finished container" do
688     set_user_from_auth :active
689     cr = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
690     cr.reload
691     assert_equal ContainerRequest::Committed, cr.state
692     run_container(cr)
693     cr.reload
694     assert_equal ContainerRequest::Final, cr.state
695
696     cr2 = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
697     assert_equal cr.container_uuid, cr2.container_uuid
698     assert_equal ContainerRequest::Final, cr2.state
699
700     cr3 = create_minimal_req!(priority: 1, state: ContainerRequest::Uncommitted)
701     assert_equal ContainerRequest::Uncommitted, cr3.state
702     cr3.update_attributes!(state: ContainerRequest::Committed)
703     assert_equal cr.container_uuid, cr3.container_uuid
704     assert_equal ContainerRequest::Final, cr3.state
705   end
706
707   [
708     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
709     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Uncommitted],
710     [{"partitions" => "fastcpu"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
711     [{"partitions" => "fastcpu"}, ContainerRequest::Uncommitted],
712     [{"partitions" => ["fastcpu","vfastcpu"]}, ContainerRequest::Committed],
713   ].each do |sp, state, expected|
714     test "create container request with scheduling_parameters #{sp} in state #{state} and verify #{expected}" do
715       common_attrs = {cwd: "test",
716                       priority: 1,
717                       command: ["echo", "hello"],
718                       output_path: "test",
719                       scheduling_parameters: sp,
720                       mounts: {"test" => {"kind" => "json"}}}
721       set_user_from_auth :active
722
723       if expected == ActiveRecord::RecordInvalid
724         assert_raises(ActiveRecord::RecordInvalid) do
725           create_minimal_req!(common_attrs.merge({state: state}))
726         end
727       else
728         cr = create_minimal_req!(common_attrs.merge({state: state}))
729         assert_equal sp, cr.scheduling_parameters
730
731         if state == ContainerRequest::Committed
732           c = Container.find_by_uuid(cr.container_uuid)
733           assert_equal sp, c.scheduling_parameters
734         end
735       end
736     end
737   end
738
739   [['Committed', true, {name: "foobar", priority: 123}],
740    ['Committed', false, {container_count: 2}],
741    ['Committed', false, {container_count: 0}],
742    ['Committed', false, {container_count: nil}],
743    ['Final', false, {state: ContainerRequest::Committed, name: "foobar"}],
744    ['Final', false, {name: "foobar", priority: 123}],
745    ['Final', false, {name: "foobar", output_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
746    ['Final', false, {name: "foobar", log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
747    ['Final', false, {log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
748    ['Final', false, {priority: 123}],
749    ['Final', false, {mounts: {}}],
750    ['Final', false, {container_count: 2}],
751    ['Final', true, {name: "foobar"}],
752    ['Final', true, {name: "foobar", description: "baz"}],
753   ].each do |state, permitted, updates|
754     test "state=#{state} can#{'not' if !permitted} update #{updates.inspect}" do
755       act_as_user users(:active) do
756         cr = create_minimal_req!(priority: 1,
757                                  state: "Committed",
758                                  container_count_max: 1)
759         case state
760         when 'Committed'
761           # already done
762         when 'Final'
763           act_as_system_user do
764             Container.find_by_uuid(cr.container_uuid).
765               update_attributes!(state: Container::Cancelled)
766           end
767           cr.reload
768         else
769           raise 'broken test case'
770         end
771         assert_equal state, cr.state
772         if permitted
773           assert cr.update_attributes!(updates)
774         else
775           assert_raises(ActiveRecord::RecordInvalid) do
776             cr.update_attributes!(updates)
777           end
778         end
779       end
780     end
781   end
782
783   test "delete container_request and check its container's priority" do
784     act_as_user users(:active) do
785       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
786
787       # initially the cr's container has priority > 0
788       c = Container.find_by_uuid(cr.container_uuid)
789       assert_equal 1, c.priority
790
791       # destroy the cr
792       assert_nothing_raised {cr.destroy}
793
794       # the cr's container now has priority of 0
795       c = Container.find_by_uuid(cr.container_uuid)
796       assert_equal 0, c.priority
797     end
798   end
799
800   test "delete container_request in final state and expect no error due to before_destroy callback" do
801     act_as_user users(:active) do
802       cr = ContainerRequest.find_by_uuid container_requests(:completed).uuid
803       assert_nothing_raised {cr.destroy}
804     end
805   end
806 end