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