12430: Drop non-matching files from output if output_glob specified.
[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!(state: Container::Locked)
38         ctr.update!(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" => -1}},
111     {"mounts" => {"FOO" => "BAR"}},
112     {"mounts" => {"FOO" => {}}},
113     {"mounts" => {"FOO" => {"kind" => "tmp", "capacity" => 42.222}}},
114     {"command" => ["echo", 55]},
115     {"environment" => {"FOO" => 55}},
116     {"output_glob" => [false]},
117     {"output_glob" => [["bad"]]},
118     {"output_glob" => "bad"},
119     {"output_glob" => ["nope", -1]},
120   ].each do |value|
121     test "Create with invalid #{value}" do
122       set_user_from_auth :active
123       assert_raises(ActiveRecord::RecordInvalid, Serializer::TypeMismatch) do
124         cr = create_minimal_req!({state: "Committed",
125                priority: 1}.merge(value))
126         cr.save!
127       end
128     end
129
130     test "Update with invalid #{value}" do
131       set_user_from_auth :active
132       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
133       cr.save!
134       assert_raises(ActiveRecord::RecordInvalid, Serializer::TypeMismatch) do
135         cr = ContainerRequest.find_by_uuid cr.uuid
136         cr.update!({state: "Committed",
137                                priority: 1}.merge(value))
138       end
139     end
140   end
141
142   test "Update from fixture" do
143     set_user_from_auth :active
144     cr = ContainerRequest.find_by_uuid(container_requests(:running).uuid)
145     cr.update!(description: "New description")
146     assert_equal "New description", cr.description
147   end
148
149   test "Update with valid runtime constraints" do
150       set_user_from_auth :active
151       cr = create_minimal_req!(state: "Uncommitted", priority: 1)
152       cr.save!
153       cr = ContainerRequest.find_by_uuid cr.uuid
154       cr.update!(state: "Committed",
155                             runtime_constraints: {"vcpus" => 1, "ram" => 23})
156       assert_not_nil cr.container_uuid
157   end
158
159   test "Container request priority must be non-nil" do
160     set_user_from_auth :active
161     cr = create_minimal_req!
162     cr.priority = nil
163     cr.state = "Committed"
164     assert_raises(ActiveRecord::RecordInvalid) do
165       cr.save!
166     end
167   end
168
169   test "Container request commit" do
170     set_user_from_auth :active
171     cr = create_minimal_req!(runtime_constraints: {"vcpus" => 2, "ram" => 300000000})
172
173     assert_nil cr.container_uuid
174
175     cr.reload
176     cr.state = "Committed"
177     cr.priority = 1
178     cr.save!
179
180     cr.reload
181
182     assert_empty({"vcpus" => 2, "ram" => 300000000}.to_a - cr.runtime_constraints.to_a)
183
184     assert_equal 0, Rails.configuration.Containers.DefaultKeepCacheRAM
185
186     assert_not_nil cr.container_uuid
187     c = Container.find_by_uuid cr.container_uuid
188     assert_not_nil c
189     assert_equal ["echo", "foo"], c.command
190     assert_equal collections(:docker_image).portable_data_hash, c.container_image
191     assert_equal "/tmp", c.cwd
192     assert_equal({}, c.environment)
193     assert_equal({"/out" => {"kind"=>"tmp", "capacity"=>1000000}}, c.mounts)
194     assert_equal "/out", c.output_path
195     assert ({"keep_cache_disk" => 2<<30, "keep_cache_ram" => 0, "vcpus" => 2, "ram" => 300000000}.to_a - c.runtime_constraints.to_a).empty?
196     assert_operator 0, :<, c.priority
197
198     assert_raises(ActiveRecord::RecordInvalid) do
199       cr.priority = nil
200       cr.save!
201     end
202
203     cr.priority = 0
204     cr.save!
205
206     cr.reload
207     c.reload
208     assert_equal 0, cr.priority
209     assert_equal 0, c.priority
210   end
211
212   test "Independent container requests" do
213     set_user_from_auth :active
214     cr1 = create_minimal_req!(command: ["foo", "1"], priority: 5, state: "Committed")
215     cr2 = create_minimal_req!(command: ["foo", "2"], priority: 10, state: "Committed")
216
217     c1 = Container.find_by_uuid cr1.container_uuid
218     assert_operator 0, :<, c1.priority
219
220     c2 = Container.find_by_uuid cr2.container_uuid
221     assert_operator c1.priority, :<, c2.priority
222     c2priority_was = c2.priority
223
224     cr1.update!(priority: 0)
225
226     c1.reload
227     assert_equal 0, c1.priority
228
229     c2.reload
230     assert_equal c2priority_was, c2.priority
231   end
232
233   test "Request is finalized when its container is cancelled" do
234     set_user_from_auth :active
235     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 1)
236     assert_equal users(:active).uuid, cr.modified_by_user_uuid
237
238     act_as_system_user do
239       Container.find_by_uuid(cr.container_uuid).
240         update!(state: Container::Cancelled, cost: 1.25)
241     end
242
243     cr.reload
244     assert_equal "Final", cr.state
245     assert_equal 1.25, cr.cumulative_cost
246     assert_equal users(:active).uuid, cr.modified_by_user_uuid
247   end
248
249   test "Request is finalized when its container is completed" do
250     set_user_from_auth :active
251     project = groups(:private)
252     cr = create_minimal_req!(owner_uuid: project.uuid,
253                              priority: 1,
254                              state: "Committed")
255     assert_equal users(:active).uuid, cr.modified_by_user_uuid
256
257     c = act_as_system_user do
258       c = Container.find_by_uuid(cr.container_uuid)
259       c.update!(state: Container::Locked)
260       c.update!(state: Container::Running)
261       c
262     end
263
264     cr.reload
265     assert_equal "Committed", cr.state
266
267     output_pdh = '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
268     log_pdh = 'fa7aeb5140e2848d39b416daeef4ffc5+45'
269     act_as_system_user do
270       c.update!(state: Container::Complete,
271                            cost: 1.25,
272                            output: output_pdh,
273                            log: log_pdh)
274     end
275
276     cr.reload
277     assert_equal "Final", cr.state
278     assert_equal 1.25, cr.cumulative_cost
279     assert_equal users(:active).uuid, cr.modified_by_user_uuid
280
281     assert_not_nil cr.output_uuid
282     assert_not_nil cr.log_uuid
283     output = Collection.find_by_uuid cr.output_uuid
284     assert_equal output_pdh, output.portable_data_hash
285     assert_equal output.owner_uuid, project.uuid, "Container output should be copied to #{project.uuid}"
286     assert_not_nil output.modified_at
287
288     log = Collection.find_by_uuid cr.log_uuid
289     assert_equal log.manifest_text, ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
290 ./log\\040for\\040container\\040#{cr.container_uuid} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n"
291
292     assert_equal log.owner_uuid, project.uuid, "Container log should be copied to #{project.uuid}"
293   end
294
295   # This tests bug report #16144
296   test "Request is finalized when its container is completed even when log & output don't exist" do
297     set_user_from_auth :active
298     project = groups(:private)
299     cr = create_minimal_req!(owner_uuid: project.uuid,
300                              priority: 1,
301                              state: "Committed")
302     assert_equal users(:active).uuid, cr.modified_by_user_uuid
303
304     output_pdh = '1f4b0bc7583c2a7f9102c395f4ffc5e3+45'
305     log_pdh = 'fa7aeb5140e2848d39b416daeef4ffc5+45'
306
307     c = act_as_system_user do
308       c = Container.find_by_uuid(cr.container_uuid)
309       c.update!(state: Container::Locked)
310       c.update!(state: Container::Running,
311                            output: output_pdh,
312                            log: log_pdh)
313       c
314     end
315
316     cr.reload
317     assert_equal "Committed", cr.state
318
319     act_as_system_user do
320       Collection.where(portable_data_hash: output_pdh).delete_all
321       Collection.where(portable_data_hash: log_pdh).delete_all
322       c.update!(state: Container::Complete)
323     end
324
325     cr.reload
326     assert_equal "Final", cr.state
327   end
328
329   # This tests bug report #16144
330   test "Can destroy CR even if its container doesn't exist" do
331     set_user_from_auth :active
332     project = groups(:private)
333     cr = create_minimal_req!(owner_uuid: project.uuid,
334                              priority: 1,
335                              state: "Committed")
336     assert_equal users(:active).uuid, cr.modified_by_user_uuid
337
338     c = act_as_system_user do
339       c = Container.find_by_uuid(cr.container_uuid)
340       c.update!(state: Container::Locked)
341       c.update!(state: Container::Running)
342       c
343     end
344
345     cr.reload
346     assert_equal "Committed", cr.state
347
348     cr_uuid = cr.uuid
349     act_as_system_user do
350       Container.find_by_uuid(cr.container_uuid).destroy
351       cr.destroy
352     end
353     assert_nil ContainerRequest.find_by_uuid(cr_uuid)
354   end
355
356   test "Container makes container request, then is cancelled" do
357     set_user_from_auth :active
358     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 1)
359
360     c = Container.find_by_uuid cr.container_uuid
361     assert_operator 0, :<, c.priority
362     lock_and_run(c)
363
364     cr2 = with_container_auth(c) do
365       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
366     end
367     assert_equal c.uuid, cr2.requesting_container_uuid
368     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
369
370     c2 = Container.find_by_uuid cr2.container_uuid
371     assert_operator 0, :<, c2.priority
372
373     act_as_system_user do
374       c.state = "Cancelled"
375       c.save!
376     end
377
378     cr.reload
379     assert_equal "Final", cr.state
380
381     cr2.reload
382     assert_equal 0, cr2.priority
383     assert_equal users(:active).uuid, cr2.modified_by_user_uuid
384
385     c2.reload
386     assert_equal 0, c2.priority
387   end
388
389   test "child container priority follows same ordering as corresponding top-level ancestors" do
390     findctr = lambda { |cr| Container.find_by_uuid(cr.container_uuid) }
391
392     set_user_from_auth :active
393
394     toplevel_crs = [
395       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "0"}),
396       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "1"}),
397       create_minimal_req!(priority: 5, state: "Committed", environment: {"workflow" => "2"}),
398     ]
399     parents = toplevel_crs.map(&findctr)
400
401     children_crs = parents.map do |parent|
402       lock_and_run(parent)
403       with_container_auth(parent) do
404         create_minimal_req!(state: "Committed",
405                             priority: 1,
406                             environment: {"child" => parent.environment["workflow"]})
407       end
408     end
409     children = children_crs.map(&findctr)
410
411     grandchildren = children.reverse.map do |child|
412       lock_and_run(child)
413       with_container_auth(child) do
414         create_minimal_req!(state: "Committed",
415                             priority: 1,
416                             environment: {"grandchild" => child.environment["child"]})
417       end
418     end.reverse.map(&findctr)
419
420     shared_grandchildren = children.map do |child|
421       with_container_auth(child) do
422         create_minimal_req!(state: "Committed",
423                             priority: 1,
424                             environment: {"grandchild" => "shared"})
425       end
426     end.map(&findctr)
427
428     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[1].uuid
429     assert_equal shared_grandchildren[0].uuid, shared_grandchildren[2].uuid
430     shared_grandchild = shared_grandchildren[0]
431
432     set_user_from_auth :active
433
434     # parents should be prioritized by submit time.
435     assert_operator parents[0].priority, :>, parents[1].priority
436     assert_operator parents[1].priority, :>, parents[2].priority
437
438     # children should be prioritized in same order as their respective
439     # parents.
440     assert_operator children[0].priority, :>, children[1].priority
441     assert_operator children[1].priority, :>, children[2].priority
442
443     # grandchildren should also be prioritized in the same order,
444     # despite having been submitted in the opposite order.
445     assert_operator grandchildren[0].priority, :>, grandchildren[1].priority
446     assert_operator grandchildren[1].priority, :>, grandchildren[2].priority
447
448     # shared grandchild container should be prioritized above
449     # everything that isn't needed by parents[0], but not above
450     # earlier-submitted descendants of parents[0]
451     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
452     assert_operator shared_grandchild.priority, :>, children[1].priority
453     assert_operator shared_grandchild.priority, :>, parents[1].priority
454     assert_operator shared_grandchild.priority, :<=, grandchildren[0].priority
455     assert_operator shared_grandchild.priority, :<=, children[0].priority
456     assert_operator shared_grandchild.priority, :<=, parents[0].priority
457
458     # increasing priority of the most recent toplevel container should
459     # reprioritize all of its descendants (including the shared
460     # grandchild) above everything else.
461     toplevel_crs[2].update!(priority: 72)
462     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
463     assert_operator shared_grandchild.priority, :>, grandchildren[0].priority
464     assert_operator shared_grandchild.priority, :>, children[0].priority
465     assert_operator shared_grandchild.priority, :>, parents[0].priority
466     assert_operator shared_grandchild.priority, :>, grandchildren[1].priority
467     assert_operator shared_grandchild.priority, :>, children[1].priority
468     assert_operator shared_grandchild.priority, :>, parents[1].priority
469     # ...but the shared container should not have higher priority than
470     # the earlier-submitted descendants of the high-priority workflow.
471     assert_operator shared_grandchild.priority, :<=, grandchildren[2].priority
472     assert_operator shared_grandchild.priority, :<=, children[2].priority
473     assert_operator shared_grandchild.priority, :<=, parents[2].priority
474
475     # cancelling the most recent toplevel container should
476     # reprioritize all of its descendants (except the shared
477     # grandchild) to zero
478     toplevel_crs[2].update!(priority: 0)
479     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
480     assert_operator 0, :==, parents[2].priority
481     assert_operator 0, :==, children[2].priority
482     assert_operator 0, :==, grandchildren[2].priority
483     assert_operator shared_grandchild.priority, :==, grandchildren[0].priority
484
485     # cancel a child request, the parent should be > 0 but
486     # the child and grandchild go to 0.
487     children_crs[1].update!(priority: 0)
488     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
489     assert_operator 0, :<, parents[1].priority
490     assert_operator parents[0].priority, :>, parents[1].priority
491     assert_operator 0, :==, children[1].priority
492     assert_operator 0, :==, grandchildren[1].priority
493     assert_operator shared_grandchild.priority, :==, grandchildren[0].priority
494
495     # update the parent, it should get a higher priority but the children and
496     # grandchildren should remain at 0
497     toplevel_crs[1].update!(priority: 6)
498     (parents + children + grandchildren + [shared_grandchild]).map(&:reload)
499     assert_operator 0, :<, parents[1].priority
500     assert_operator parents[0].priority, :<, parents[1].priority
501     assert_operator 0, :==, children[1].priority
502     assert_operator 0, :==, grandchildren[1].priority
503     assert_operator shared_grandchild.priority, :==, grandchildren[0].priority
504   end
505
506   [
507     ['running_container_auth', 'zzzzz-dz642-runningcontainr', 501],
508     ['active_no_prefs', nil, 0]
509   ].each do |token, expected, expected_priority|
510     test "create as #{token} and expect requesting_container_uuid to be #{expected}" do
511       set_user_from_auth token
512       cr = create_minimal_req!
513       assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
514       assert_equal expected, cr.requesting_container_uuid
515       assert_equal expected_priority, cr.priority
516     end
517   end
518
519   [
520     [:admin, 0, "output"],
521     [:admin, 19, "output"],
522     [:admin, nil, "output"],
523     [:running_container_auth, 0, "intermediate"],
524     [:running_container_auth, 29, "intermediate"],
525     [:running_container_auth, nil, "intermediate"],
526   ].each do |token, exit_code, expect_output_type|
527     test "container with exit_code #{exit_code} has collection types set with output type #{expect_output_type}" do
528       final_state = if exit_code.nil?
529                       Container::Cancelled
530                     else
531                       Container::Complete
532                     end
533       set_user_from_auth token
534       request = create_minimal_req!(
535         container_count_max: 1,
536         priority: 500,
537         state: ContainerRequest::Committed,
538       )
539       run_container(request, final_state: final_state, exit_code: exit_code)
540       request.reload
541       assert_equal(ContainerRequest::Final, request.state)
542
543       output = Collection.find_by_uuid(request.output_uuid)
544       assert_not_nil(output)
545       assert_equal(request.uuid, output.properties["container_request"])
546       assert_equal(expect_output_type, output.properties["type"])
547
548       log = Collection.find_by_uuid(request.log_uuid)
549       assert_not_nil(log)
550       assert_equal(request.uuid, log.properties["container_request"])
551       assert_equal("log", log.properties["type"])
552     end
553   end
554
555   test "create as container_runtime_token and expect requesting_container_uuid to be zzzzz-dz642-20isqbkl8xwnsao" do
556     set_user_from_auth :container_runtime_token
557     Thread.current[:token] = "#{Thread.current[:token]}/zzzzz-dz642-20isqbkl8xwnsao"
558     cr = ContainerRequest.create(container_image: "img", output_path: "/tmp", command: ["echo", "foo"])
559     assert_not_nil cr.uuid, 'uuid should be set for newly created container_request'
560     assert_equal 'zzzzz-dz642-20isqbkl8xwnsao', cr.requesting_container_uuid
561     assert_equal 1, cr.priority
562   end
563
564   [[{"vcpus" => [2, nil]},
565     lambda { |resolved| resolved["vcpus"] == 2 }],
566    [{"vcpus" => [3, 7]},
567     lambda { |resolved| resolved["vcpus"] == 3 }],
568    [{"vcpus" => 4},
569     lambda { |resolved| resolved["vcpus"] == 4 }],
570    [{"ram" => [1000000000, 2000000000]},
571     lambda { |resolved| resolved["ram"] == 1000000000 }],
572    [{"ram" => [1234234234]},
573     lambda { |resolved| resolved["ram"] == 1234234234 }],
574   ].each do |rc, okfunc|
575     test "resolve runtime constraint range #{rc} to values" do
576       resolved = Container.resolve_runtime_constraints(rc)
577       assert(okfunc.call(resolved),
578              "container runtime_constraints was #{resolved.inspect}")
579     end
580   end
581
582   [[{"/out" => {
583         "kind" => "collection",
584         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
585         "path" => "/foo"}},
586     lambda do |resolved|
587       resolved["/out"] == {
588         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
589         "kind" => "collection",
590         "path" => "/foo",
591       }
592     end],
593    [{"/out" => {
594         "kind" => "collection",
595         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
596         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
597         "path" => "/foo"}},
598     lambda do |resolved|
599       resolved["/out"] == {
600         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
601         "kind" => "collection",
602         "path" => "/foo",
603       }
604     end],
605    [{"/out" => {
606       "kind" => "collection",
607       "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
608       "path" => "/foo"}},
609     lambda do |resolved|
610       resolved["/out"] == {
611         "portable_data_hash" => "1f4b0bc7583c2a7f9102c395f4ffc5e3+45",
612         "kind" => "collection",
613         "path" => "/foo",
614       }
615     end],
616     # Empty collection
617     [{"/out" => {
618       "kind" => "collection",
619       "path" => "/foo"}},
620     lambda do |resolved|
621       resolved["/out"] == {
622         "kind" => "collection",
623         "path" => "/foo",
624       }
625     end],
626   ].each do |mounts, okfunc|
627     test "resolve mounts #{mounts.inspect} to values" do
628       set_user_from_auth :active
629       resolved = Container.resolve_mounts(mounts)
630       assert(okfunc.call(resolved),
631              "Container.resolve_mounts returned #{resolved.inspect}")
632     end
633   end
634
635   test 'mount unreadable collection' do
636     set_user_from_auth :spectator
637     m = {
638       "/foo" => {
639         "kind" => "collection",
640         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
641         "path" => "/foo",
642       },
643     }
644     assert_raises(ArvadosModel::UnresolvableContainerError) do
645       Container.resolve_mounts(m)
646     end
647   end
648
649   test 'mount collection with mismatched UUID and PDH' do
650     set_user_from_auth :active
651     m = {
652       "/foo" => {
653         "kind" => "collection",
654         "uuid" => "zzzzz-4zz18-znfnqtbbv4spc3w",
655         "portable_data_hash" => "fa7aeb5140e2848d39b416daeef4ffc5+45",
656         "path" => "/foo",
657       },
658     }
659     resolved_mounts = Container.resolve_mounts(m)
660     assert_equal m['portable_data_hash'], resolved_mounts['portable_data_hash']
661   end
662
663   ['arvados/apitestfixture:latest',
664    'arvados/apitestfixture',
665    'd8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678',
666   ].each do |tag|
667     test "Container.resolve_container_image(#{tag.inspect})" do
668       set_user_from_auth :active
669       resolved = Container.resolve_container_image(tag)
670       assert_equal resolved, collections(:docker_image).portable_data_hash
671     end
672   end
673
674   test "Container.resolve_container_image(pdh)" do
675     set_user_from_auth :active
676     [[:docker_image, 'v1'], [:docker_image_1_12, 'v2']].each do |coll, ver|
677       Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({ver=>{}})
678       pdh = collections(coll).portable_data_hash
679       resolved = Container.resolve_container_image(pdh)
680       assert_equal resolved, pdh
681     end
682   end
683
684   ['acbd18db4cc2f85cedef654fccc4a4d8+3',
685    'ENOEXIST',
686    'arvados/apitestfixture:ENOEXIST',
687   ].each do |img|
688     test "container_image_for_container(#{img.inspect}) => 422" do
689       set_user_from_auth :active
690       assert_raises(ArvadosModel::UnresolvableContainerError) do
691         Container.resolve_container_image(img)
692       end
693     end
694   end
695
696   test "allow unrecognized container when there are remote_hosts" do
697     set_user_from_auth :active
698     Rails.configuration.RemoteClusters = Rails.configuration.RemoteClusters.merge({foooo: ActiveSupport::InheritableOptions.new({Host: "bar.com"})})
699     Container.resolve_container_image('acbd18db4cc2f85cedef654fccc4a4d8+3')
700   end
701
702   test "migrated docker image" do
703     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v2'=>{}})
704     add_docker19_migration_link
705
706     # Test that it returns only v2 images even though request is for v1 image.
707
708     set_user_from_auth :active
709     cr = create_minimal_req!(command: ["true", "1"],
710                              container_image: collections(:docker_image).portable_data_hash)
711     assert_equal(Container.resolve_container_image(cr.container_image),
712                  collections(:docker_image_1_12).portable_data_hash)
713
714     cr = create_minimal_req!(command: ["true", "2"],
715                              container_image: links(:docker_image_collection_tag).name)
716     assert_equal(Container.resolve_container_image(cr.container_image),
717                  collections(:docker_image_1_12).portable_data_hash)
718   end
719
720   test "use unmigrated docker image" do
721     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v1'=>{}})
722     add_docker19_migration_link
723
724     # Test that it returns only supported v1 images even though there is a
725     # migration link.
726
727     set_user_from_auth :active
728     cr = create_minimal_req!(command: ["true", "1"],
729                              container_image: collections(:docker_image).portable_data_hash)
730     assert_equal(Container.resolve_container_image(cr.container_image),
731                  collections(:docker_image).portable_data_hash)
732
733     cr = create_minimal_req!(command: ["true", "2"],
734                              container_image: links(:docker_image_collection_tag).name)
735     assert_equal(Container.resolve_container_image(cr.container_image),
736                  collections(:docker_image).portable_data_hash)
737   end
738
739   test "incompatible docker image v1" do
740     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v1'=>{}})
741     add_docker19_migration_link
742
743     # Don't return unsupported v2 image even if we ask for it directly.
744     set_user_from_auth :active
745     cr = create_minimal_req!(command: ["true", "1"],
746                              container_image: collections(:docker_image_1_12).portable_data_hash)
747     assert_raises(ArvadosModel::UnresolvableContainerError) do
748       Container.resolve_container_image(cr.container_image)
749     end
750   end
751
752   test "incompatible docker image v2" do
753     Rails.configuration.Containers.SupportedDockerImageFormats = ConfigLoader.to_OrderedOptions({'v2'=>{}})
754     # No migration link, don't return unsupported v1 image,
755
756     set_user_from_auth :active
757     cr = create_minimal_req!(command: ["true", "1"],
758                              container_image: collections(:docker_image).portable_data_hash)
759     assert_raises(ArvadosModel::UnresolvableContainerError) do
760       Container.resolve_container_image(cr.container_image)
761     end
762     cr = create_minimal_req!(command: ["true", "2"],
763                              container_image: links(:docker_image_collection_tag).name)
764     assert_raises(ArvadosModel::UnresolvableContainerError) do
765       Container.resolve_container_image(cr.container_image)
766     end
767   end
768
769   test "requestor can retrieve container owned by dispatch" do
770     assert_not_empty Container.readable_by(users(:admin)).where(uuid: containers(:running).uuid)
771     assert_not_empty Container.readable_by(users(:active)).where(uuid: containers(:running).uuid)
772     assert_empty Container.readable_by(users(:spectator)).where(uuid: containers(:running).uuid)
773   end
774
775   [
776     [{"var" => "value1"}, {"var" => "value1"}, nil],
777     [{"var" => "value1"}, {"var" => "value1"}, true],
778     [{"var" => "value1"}, {"var" => "value1"}, false],
779     [{"var" => "value1"}, {"var" => "value2"}, nil],
780   ].each do |env1, env2, use_existing|
781     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
782       common_attrs = {cwd: "test",
783                       priority: 1,
784                       command: ["echo", "hello"],
785                       output_path: "test",
786                       runtime_constraints: {"vcpus" => 4,
787                                             "ram" => 12000000000},
788                       mounts: {"test" => {"kind" => "json"}}}
789       set_user_from_auth :active
790       cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed,
791                                                     environment: env1}))
792       run_container(cr1)
793       cr1.reload
794       if use_existing.nil?
795         # Testing with use_existing default value
796         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
797                                                       environment: env2}))
798       else
799
800         cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
801                                                       environment: env2,
802                                                       use_existing: use_existing}))
803       end
804       assert_not_nil cr1.container_uuid
805       assert_nil cr2.container_uuid
806
807       # Update cr2 to commited state and check for container equality on different cases:
808       # * When env1 and env2 are equal and use_existing is true, the same container
809       #   should be assigned.
810       # * When use_existing is false, a different container should be assigned.
811       # * When env1 and env2 are different, a different container should be assigned.
812       cr2.update!({state: ContainerRequest::Committed})
813       assert_equal (cr2.use_existing == true and (env1 == env2)),
814                    (cr1.container_uuid == cr2.container_uuid)
815     end
816   end
817
818   test "requesting_container_uuid at create is not allowed" do
819     set_user_from_auth :active
820     assert_raises(ActiveRecord::RecordInvalid) do
821       create_minimal_req!(state: "Uncommitted", priority: 1, requesting_container_uuid: 'youcantdothat')
822     end
823   end
824
825   test "Retry on container cancelled" do
826     set_user_from_auth :active
827     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2)
828     cr2 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "baz"])
829     prev_container_uuid = cr.container_uuid
830
831     c = act_as_system_user do
832       c = Container.find_by_uuid(cr.container_uuid)
833       c.update!(state: Container::Locked)
834       c.update!(state: Container::Running)
835       c
836     end
837
838     cr.reload
839     cr2.reload
840     assert_equal "Committed", cr.state
841     assert_equal prev_container_uuid, cr.container_uuid
842     assert_not_equal cr2.container_uuid, cr.container_uuid
843     prev_container_uuid = cr.container_uuid
844
845     act_as_system_user do
846       c.update!(cost: 0.5, subrequests_cost: 1.25)
847       c.update!(state: Container::Cancelled)
848     end
849
850     cr.reload
851     cr2.reload
852     assert_equal "Committed", cr.state
853     assert_not_equal prev_container_uuid, cr.container_uuid
854     assert_not_equal cr2.container_uuid, cr.container_uuid
855     prev_container_uuid = cr.container_uuid
856
857     c = act_as_system_user do
858       c = Container.find_by_uuid(cr.container_uuid)
859       c.update!(state: Container::Locked)
860       c.update!(state: Container::Running)
861       c.update!(cost: 0.125)
862       c.update!(state: Container::Cancelled)
863       c
864     end
865
866     cr.reload
867     cr2.reload
868     assert_equal "Final", cr.state
869     assert_equal prev_container_uuid, cr.container_uuid
870     assert_not_equal cr2.container_uuid, cr.container_uuid
871     assert_equal 1.875, cr.cumulative_cost
872   end
873
874   test "Retry on container cancelled with runtime_token" do
875     set_user_from_auth :spectator
876     spec = api_client_authorizations(:active)
877     cr = create_minimal_req!(priority: 1, state: "Committed",
878                              runtime_token: spec.token,
879                              container_count_max: 2)
880     prev_container_uuid = cr.container_uuid
881
882     c = act_as_system_user do
883       c = Container.find_by_uuid(cr.container_uuid)
884       assert_equal spec.token, c.runtime_token
885       c.update!(state: Container::Locked)
886       c.update!(state: Container::Running)
887       c
888     end
889
890     cr.reload
891     assert_equal "Committed", cr.state
892     assert_equal prev_container_uuid, cr.container_uuid
893     prev_container_uuid = cr.container_uuid
894
895     act_as_system_user do
896       c.update!(state: Container::Cancelled)
897     end
898
899     cr.reload
900     assert_equal "Committed", cr.state
901     assert_not_equal prev_container_uuid, cr.container_uuid
902     prev_container_uuid = cr.container_uuid
903
904     c = act_as_system_user do
905       c = Container.find_by_uuid(cr.container_uuid)
906       assert_equal spec.token, c.runtime_token
907       c.update!(state: Container::Cancelled)
908       c
909     end
910
911     cr.reload
912     assert_equal "Final", cr.state
913     assert_equal prev_container_uuid, cr.container_uuid
914   end
915
916
917   test "Retry saves logs from previous attempts" do
918     set_user_from_auth :active
919     cr = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 3)
920
921     c = act_as_system_user do
922       c = Container.find_by_uuid(cr.container_uuid)
923       c.update!(state: Container::Locked)
924       c.update!(state: Container::Running)
925       c
926     end
927
928     container_uuids = []
929
930     [0, 1, 2].each do
931       cr.reload
932       assert_equal "Committed", cr.state
933       container_uuids << cr.container_uuid
934
935       c = act_as_system_user do
936         logc = Collection.new(manifest_text: ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar\n")
937         logc.save!
938         c = Container.find_by_uuid(cr.container_uuid)
939         c.update!(state: Container::Cancelled, log: logc.portable_data_hash)
940         c
941       end
942     end
943
944     container_uuids.sort!
945
946     cr.reload
947     assert_equal "Final", cr.state
948     assert_equal 3, cr.container_count
949     assert_equal ". 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
950 ./log\\040for\\040container\\040#{container_uuids[0]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
951 ./log\\040for\\040container\\040#{container_uuids[1]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
952 ./log\\040for\\040container\\040#{container_uuids[2]} 37b51d194a7513e45b56f6524f2d51f2+3 0:3:bar
953 " , Collection.find_by_uuid(cr.log_uuid).manifest_text
954
955   end
956
957   test "Retry sub-request on error" do
958     set_user_from_auth :active
959     cr1 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "foo1"])
960     c1 = Container.find_by_uuid(cr1.container_uuid)
961     act_as_system_user do
962       c1.update!(state: Container::Locked)
963       c1.update!(state: Container::Running)
964     end
965
966     cr2 = with_container_auth(c1) do
967       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo2"])
968     end
969     c2 = Container.find_by_uuid(cr2.container_uuid)
970     act_as_system_user do
971       c2.update!(state: Container::Locked)
972       c2.update!(state: Container::Running)
973     end
974
975     cr3 = with_container_auth(c2) do
976       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo3"])
977     end
978     c3 = Container.find_by_uuid(cr3.container_uuid)
979
980     act_as_system_user do
981       c3.update!(state: Container::Locked)
982       c3.update!(state: Container::Running)
983     end
984
985     # All the containers are in running state
986
987     c3.reload
988     cr3.reload
989
990     # c3 still running
991     assert_equal 'Running', c3.state
992     assert_equal 1, cr3.container_count
993     assert_equal 'Committed', cr3.state
994
995     # c3 goes to cancelled state
996     act_as_system_user do
997       c3.state = "Cancelled"
998       c3.save!
999     end
1000
1001     cr3.reload
1002
1003     # Because the parent request is still live, it should
1004     # be retried.
1005     assert_equal 2, cr3.container_count
1006     assert_equal 'Committed', cr3.state
1007   end
1008
1009   test "Do not retry sub-request when process tree is cancelled" do
1010     set_user_from_auth :active
1011     cr1 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "foo1"])
1012     c1 = Container.find_by_uuid(cr1.container_uuid)
1013     act_as_system_user do
1014       c1.update!(state: Container::Locked)
1015       c1.update!(state: Container::Running)
1016     end
1017
1018     cr2 = with_container_auth(c1) do
1019       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo2"])
1020     end
1021     c2 = Container.find_by_uuid(cr2.container_uuid)
1022     act_as_system_user do
1023       c2.update!(state: Container::Locked)
1024       c2.update!(state: Container::Running)
1025     end
1026
1027     cr3 = with_container_auth(c2) do
1028       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo3"])
1029     end
1030     c3 = Container.find_by_uuid(cr3.container_uuid)
1031
1032     act_as_system_user do
1033       c3.update!(state: Container::Locked)
1034       c3.update!(state: Container::Running)
1035     end
1036
1037     # All the containers are in running state
1038
1039     # Now cancel the toplevel container request
1040     act_as_system_user do
1041       cr1.priority = 0
1042       cr1.save!
1043     end
1044
1045     c3.reload
1046     cr3.reload
1047
1048     # c3 still running
1049     assert_equal 'Running', c3.state
1050     assert_equal 1, cr3.container_count
1051     assert_equal 'Committed', cr3.state
1052
1053     # c3 goes to cancelled state
1054     act_as_system_user do
1055       assert_equal 0, c3.priority
1056       c3.state = "Cancelled"
1057       c3.save!
1058     end
1059
1060     cr3.reload
1061
1062     # Because the parent process was cancelled, it _should not_ be
1063     # retried.
1064     assert_equal 1, cr3.container_count
1065     assert_equal 'Final', cr3.state
1066   end
1067
1068   test "Retry process tree on error" do
1069     set_user_from_auth :active
1070     cr1 = create_minimal_req!(priority: 1, state: "Committed", container_count_max: 2, command: ["echo", "foo1"])
1071     c1 = Container.find_by_uuid(cr1.container_uuid)
1072     act_as_system_user do
1073       c1.update!(state: Container::Locked)
1074       c1.update!(state: Container::Running)
1075     end
1076
1077     cr2 = with_container_auth(c1) do
1078       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo2"])
1079     end
1080     c2 = Container.find_by_uuid(cr2.container_uuid)
1081     act_as_system_user do
1082       c2.update!(state: Container::Locked)
1083       c2.update!(state: Container::Running)
1084     end
1085
1086     cr3 = with_container_auth(c2) do
1087       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 2, command: ["echo", "foo3"])
1088     end
1089     c3 = Container.find_by_uuid(cr3.container_uuid)
1090
1091     act_as_system_user do
1092       c3.update!(state: Container::Locked)
1093       c3.update!(state: Container::Running)
1094     end
1095
1096     # All the containers are in running state
1097
1098     c1.reload
1099
1100     # c1 goes to cancelled state
1101     act_as_system_user do
1102       c1.state = "Cancelled"
1103       c1.save!
1104     end
1105
1106     cr1.reload
1107     cr2.reload
1108     cr3.reload
1109
1110     # Because the root request is still live, it should be retried.
1111     # Assumes the root is something like arvados-cwl-runner where
1112     # container reuse enables it to more or less pick up where it left
1113     # off.
1114     assert_equal 2, cr1.container_count
1115     assert_equal 'Committed', cr1.state
1116
1117     # These keep running.
1118     assert_equal 1, cr2.container_count
1119     assert_equal 'Committed', cr2.state
1120
1121     assert_equal 1, cr3.container_count
1122     assert_equal 'Committed', cr3.state
1123   end
1124
1125   test "Output collection name setting using output_name with name collision resolution" do
1126     set_user_from_auth :active
1127     output_name = 'unimaginative name'
1128     Collection.create!(name: output_name)
1129
1130     cr = create_minimal_req!(priority: 1,
1131                              state: ContainerRequest::Committed,
1132                              output_name: output_name)
1133     run_container(cr)
1134     cr.reload
1135     assert_equal ContainerRequest::Final, cr.state
1136     output_coll = Collection.find_by_uuid(cr.output_uuid)
1137     # Make sure the resulting output collection name include the original name
1138     # plus the last 15 characters of uuid
1139     assert_not_equal output_name, output_coll.name,
1140                      "more than one collection with the same owner and name"
1141     assert output_coll.name.include?(output_name),
1142            "New name should include original name"
1143     assert_match /#{output_coll.uuid[-15..-1]}/, output_coll.name,
1144                  "New name should include last 15 characters of uuid"
1145   end
1146
1147   [[0, :check_output_ttl_0],
1148    [1, :check_output_ttl_1s],
1149    [365*86400, :check_output_ttl_1y],
1150   ].each do |ttl, checker|
1151     test "output_ttl=#{ttl}" do
1152       act_as_user users(:active) do
1153         cr = create_minimal_req!(priority: 1,
1154                                  state: ContainerRequest::Committed,
1155                                  output_name: 'foo',
1156                                  output_ttl: ttl)
1157         run_container(cr)
1158         cr.reload
1159         output = Collection.find_by_uuid(cr.output_uuid)
1160         send(checker, db_current_time, output.trash_at, output.delete_at)
1161       end
1162     end
1163   end
1164
1165   def check_output_ttl_0(now, trash, delete)
1166     assert_nil(trash)
1167     assert_nil(delete)
1168   end
1169
1170   def check_output_ttl_1s(now, trash, delete)
1171     assert_not_nil(trash)
1172     assert_not_nil(delete)
1173     assert_in_delta(trash, now + 1.second, 10)
1174     assert_in_delta(delete, now + Rails.configuration.Collections.BlobSigningTTL, 10)
1175   end
1176
1177   def check_output_ttl_1y(now, trash, delete)
1178     year = (86400*365).second
1179     assert_not_nil(trash)
1180     assert_not_nil(delete)
1181     assert_in_delta(trash, now + year, 10)
1182     assert_in_delta(delete, now + year, 10)
1183   end
1184
1185   def run_container(cr, final_state: Container::Complete, exit_code: 0)
1186     act_as_system_user do
1187       logc = Collection.new(owner_uuid: system_user_uuid,
1188                             manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
1189       logc.save!
1190
1191       c = Container.find_by_uuid(cr.container_uuid)
1192       c.update!(state: Container::Locked)
1193       c.update!(state: Container::Running)
1194       c.update!(state: final_state,
1195                            exit_code: exit_code,
1196                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1197                            log: logc.portable_data_hash)
1198       logc.destroy
1199       c
1200     end
1201   end
1202
1203   test "Finalize committed request when reusing a finished container" do
1204     set_user_from_auth :active
1205     cr = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
1206     cr.reload
1207     assert_equal ContainerRequest::Committed, cr.state
1208     run_container(cr)
1209     cr.reload
1210     assert_equal ContainerRequest::Final, cr.state
1211
1212     cr2 = create_minimal_req!(priority: 1, state: ContainerRequest::Committed)
1213     assert_equal cr.container_uuid, cr2.container_uuid
1214     assert_equal ContainerRequest::Final, cr2.state
1215
1216     cr3 = create_minimal_req!(priority: 1, state: ContainerRequest::Uncommitted)
1217     assert_equal ContainerRequest::Uncommitted, cr3.state
1218     cr3.update!(state: ContainerRequest::Committed)
1219     assert_equal cr.container_uuid, cr3.container_uuid
1220     assert_equal ContainerRequest::Final, cr3.state
1221   end
1222
1223   [
1224     # client requests preemptible, but types are not configured
1225     [false, false, false, true, ActiveRecord::RecordInvalid],
1226     [true, false, false, true, ActiveRecord::RecordInvalid],
1227     # client requests preemptible, types are configured
1228     [false, true, false, true, true],
1229     [true, true, false, true, true],
1230     # client requests non-preemptible for top-level container
1231     [false, false, false, false, false],
1232     [true, false, false, false, false],
1233     [false, true, false, false, false],
1234     [true, true, false, false, false],
1235     # client requests non-preemptible for child container, preemptible
1236     # is enabled anyway if AlwaysUsePreemptibleInstances and instance types
1237     # are configured.
1238     [false, false, true, false, false],
1239     [true, false, true, false, false],
1240     [false, true, true, false, false],
1241     [true, true, true, false, true],
1242   ].each do |use_preemptible, have_preemptible, is_child, ask, expect|
1243     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
1244       Rails.configuration.Containers.AlwaysUsePreemptibleInstances = use_preemptible
1245       if have_preemptible
1246         configure_preemptible_instance_type
1247       end
1248       common_attrs = {
1249         cwd: "test",
1250         priority: 1,
1251         command: ["echo", "hello"],
1252         output_path: "test",
1253         scheduling_parameters: {"preemptible" => ask},
1254         mounts: {"test" => {"kind" => "json"}},
1255       }
1256       set_user_from_auth :active
1257
1258       if is_child
1259         cr = with_container_auth(containers(:running)) do
1260           create_minimal_req!(common_attrs)
1261         end
1262       else
1263         cr = create_minimal_req!(common_attrs)
1264       end
1265
1266       cr.reload
1267       cr.state = ContainerRequest::Committed
1268
1269       if expect == true || expect == false
1270         cr.save!
1271         assert_equal expect, cr.scheduling_parameters["preemptible"]
1272       else
1273         assert_raises(expect) do
1274           cr.save!
1275         end
1276       end
1277     end
1278   end
1279
1280   test "config update does not flip preemptible flag on already-committed container requests" do
1281     parent = containers(:running_container_with_logs)
1282     attrs_p = {
1283       scheduling_parameters: {"preemptible" => true},
1284       "state" => "Committed",
1285       "priority" => 1,
1286     }
1287     attrs_nonp = {
1288       scheduling_parameters: {"preemptible" => false},
1289       "state" => "Committed",
1290       "priority" => 1,
1291     }
1292     expect = {false => [], true => []}
1293
1294     with_container_auth(parent) do
1295       configure_preemptible_instance_type
1296       Rails.configuration.Containers.AlwaysUsePreemptibleInstances = false
1297
1298       expect[true].push create_minimal_req!(attrs_p)
1299       expect[false].push create_minimal_req!(attrs_nonp)
1300
1301       Rails.configuration.Containers.AlwaysUsePreemptibleInstances = true
1302
1303       expect[true].push create_minimal_req!(attrs_p)
1304       expect[true].push create_minimal_req!(attrs_nonp)
1305       commit_later = create_minimal_req!()
1306
1307       Rails.configuration.InstanceTypes = ConfigLoader.to_OrderedOptions({})
1308
1309       expect[false].push create_minimal_req!(attrs_nonp)
1310
1311       # Even though preemptible is not allowed, we should be able to
1312       # commit a CR that was created earlier when preemptible was the
1313       # default.
1314       commit_later.update!(priority: 1, state: "Committed")
1315       expect[false].push commit_later
1316     end
1317
1318     set_user_from_auth :active
1319     [false, true].each do |pflag|
1320       expect[pflag].each do |cr|
1321         cr.reload
1322         assert_equal pflag, cr.scheduling_parameters['preemptible']
1323       end
1324     end
1325
1326     act_as_system_user do
1327       # Cancelling the parent used to fail while updating the child
1328       # containers' priority, because the child containers' unchanged
1329       # preemptible fields caused validation to fail.
1330       parent.update!(state: 'Cancelled')
1331
1332       [false, true].each do |pflag|
1333         expect[pflag].each do |cr|
1334           cr.reload
1335           assert_equal 0, cr.priority, "unexpected non-zero priority #{cr.priority} for #{cr.uuid}"
1336         end
1337       end
1338     end
1339   end
1340
1341   [
1342     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1343     [{"partitions" => ["fastcpu","vfastcpu", 100]}, ContainerRequest::Uncommitted],
1344     [{"partitions" => "fastcpu"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1345     [{"partitions" => "fastcpu"}, ContainerRequest::Uncommitted],
1346     [{"partitions" => ["fastcpu","vfastcpu"]}, ContainerRequest::Committed],
1347     [{"max_run_time" => "one day"}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1348     [{"max_run_time" => "one day"}, ContainerRequest::Uncommitted],
1349     [{"max_run_time" => -1}, ContainerRequest::Committed, ActiveRecord::RecordInvalid],
1350     [{"max_run_time" => -1}, ContainerRequest::Uncommitted],
1351     [{"max_run_time" => 86400}, ContainerRequest::Committed],
1352   ].each do |sp, state, expected|
1353     test "create container request with scheduling_parameters #{sp} in state #{state} and verify #{expected}" do
1354       common_attrs = {cwd: "test",
1355                       priority: 1,
1356                       command: ["echo", "hello"],
1357                       output_path: "test",
1358                       scheduling_parameters: sp,
1359                       mounts: {"test" => {"kind" => "json"}}}
1360       set_user_from_auth :active
1361
1362       if expected == ActiveRecord::RecordInvalid
1363         assert_raises(ActiveRecord::RecordInvalid) do
1364           create_minimal_req!(common_attrs.merge({state: state}))
1365         end
1366       else
1367         cr = create_minimal_req!(common_attrs.merge({state: state}))
1368         assert (sp.to_a - cr.scheduling_parameters.to_a).empty?
1369
1370         if state == ContainerRequest::Committed
1371           c = Container.find_by_uuid(cr.container_uuid)
1372           assert (sp.to_a - c.scheduling_parameters.to_a).empty?
1373         end
1374       end
1375     end
1376   end
1377
1378   test "AlwaysUsePreemptibleInstances makes child containers preemptible" do
1379     Rails.configuration.Containers.AlwaysUsePreemptibleInstances = true
1380     common_attrs = {cwd: "test",
1381                     priority: 1,
1382                     command: ["echo", "hello"],
1383                     output_path: "test",
1384                     state: ContainerRequest::Committed,
1385                     mounts: {"test" => {"kind" => "json"}}}
1386     set_user_from_auth :active
1387     configure_preemptible_instance_type
1388
1389     cr = with_container_auth(Container.find_by_uuid 'zzzzz-dz642-runningcontainr') do
1390       create_minimal_req!(common_attrs)
1391     end
1392     assert_equal 'zzzzz-dz642-runningcontainr', cr.requesting_container_uuid
1393     assert_equal true, cr.scheduling_parameters["preemptible"]
1394
1395     c = Container.find_by_uuid(cr.container_uuid)
1396     assert_equal true, c.scheduling_parameters["preemptible"]
1397   end
1398
1399   [['Committed', true, {name: "foobar", priority: 123}],
1400    ['Committed', false, {container_count: 2}],
1401    ['Committed', false, {container_count: 0}],
1402    ['Committed', false, {container_count: nil}],
1403    ['Committed', true, {priority: 0, mounts: {"/out" => {"kind" => "tmp", "capacity" => 1000000}}}],
1404    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp"}}}],
1405    # Addition of default values for mounts / runtime_constraints /
1406    # scheduling_parameters, as happens in a round-trip through
1407    # controller, does not have any real effect and should be
1408    # accepted/ignored rather than causing an error when the CR state
1409    # dictates those attributes are not allowed to change.
1410    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 0, "kind" => "tmp"}}}, {mounts: {"/out" => {"kind" => "tmp"}}}],
1411    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "exclude_from_output": false}}}],
1412    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "repository_name": ""}}}],
1413    ['Committed', true, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "content": nil}}}],
1414    ['Committed', false, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "content": {}}}}],
1415    ['Committed', false, {priority: 0, mounts: {"/out" => {"capacity" => 1000000, "kind" => "tmp", "repository_name": "foo"}}}],
1416    ['Committed', false, {priority: 0, mounts: {"/out" => {"kind" => "tmp", "capacity" => 1234567}}}],
1417    ['Committed', false, {priority: 0, mounts: {}}],
1418    ['Committed', true, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2}}],
1419    ['Committed', true, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "keep_cache_ram" => 0}}],
1420    ['Committed', true, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "API" => false}}],
1421    ['Committed', false, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "keep_cache_ram" => 1}}],
1422    ['Committed', false, {priority: 0, runtime_constraints: {"vcpus" => 1, "ram" => 2, "API" => true}}],
1423    ['Committed', true, {priority: 0, scheduling_parameters: {"preemptible" => false}}],
1424    ['Committed', true, {priority: 0, scheduling_parameters: {"partitions" => []}}],
1425    ['Committed', true, {priority: 0, scheduling_parameters: {"max_run_time" => 0}}],
1426    ['Committed', false, {priority: 0, scheduling_parameters: {"preemptible" => true}}],
1427    ['Committed', false, {priority: 0, scheduling_parameters: {"partitions" => ["foo"]}}],
1428    ['Committed', false, {priority: 0, scheduling_parameters: {"max_run_time" => 1}}],
1429    ['Final', false, {state: ContainerRequest::Committed, name: "foobar"}],
1430    ['Final', false, {name: "foobar", priority: 123}],
1431    ['Final', false, {name: "foobar", output_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1432    ['Final', false, {name: "foobar", log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1433    ['Final', false, {log_uuid: "zzzzz-4zz18-znfnqtbbv4spc3w"}],
1434    ['Final', false, {priority: 123}],
1435    ['Final', false, {mounts: {}}],
1436    ['Final', false, {container_count: 2}],
1437    ['Final', true, {name: "foobar"}],
1438    ['Final', true, {name: "foobar", description: "baz"}],
1439   ].each do |state, permitted, updates, create_attrs|
1440     test "state=#{state} can#{'not' if !permitted} update #{updates.inspect}" do
1441       act_as_user users(:active) do
1442         attrs = {
1443           priority: 1,
1444           state: "Committed",
1445           container_count_max: 1
1446         }
1447         if !create_attrs.nil?
1448           attrs.merge!(create_attrs)
1449         end
1450         cr = create_minimal_req!(attrs)
1451         case state
1452         when 'Committed'
1453           # already done
1454         when 'Final'
1455           act_as_system_user do
1456             Container.find_by_uuid(cr.container_uuid).
1457               update!(state: Container::Cancelled)
1458           end
1459           cr.reload
1460         else
1461           raise 'broken test case'
1462         end
1463         assert_equal state, cr.state
1464         if permitted
1465           assert cr.update!(updates)
1466         else
1467           assert_raises(ActiveRecord::RecordInvalid) do
1468             cr.update!(updates)
1469           end
1470         end
1471       end
1472     end
1473   end
1474
1475   test "delete container_request and check its container's priority" do
1476     act_as_user users(:active) do
1477       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
1478
1479       # initially the cr's container has priority > 0
1480       c = Container.find_by_uuid(cr.container_uuid)
1481       assert_equal 1, c.priority
1482
1483       cr.destroy
1484
1485       # the cr's container now has priority of 0
1486       c.reload
1487       assert_equal 0, c.priority
1488     end
1489   end
1490
1491   test "trash the project containing a container_request and check its container's priority" do
1492     act_as_user users(:active) do
1493       cr = ContainerRequest.find_by_uuid container_requests(:running_to_be_deleted).uuid
1494
1495       # initially the cr's container has priority > 0
1496       c = Container.find_by_uuid(cr.container_uuid)
1497       assert_equal 1, c.priority
1498
1499       prj = Group.find_by_uuid cr.owner_uuid
1500       prj.update!(trash_at: db_current_time)
1501
1502       # the cr's container now has priority of 0
1503       c.reload
1504       assert_equal 0, c.priority
1505
1506       assert_equal c.state, 'Running'
1507       assert_equal cr.state, 'Committed'
1508
1509       # mark the container as cancelled, this should cause the
1510       # container request to go to final state and run the finalize
1511       # function
1512       act_as_system_user do
1513         c.update!(state: 'Cancelled', log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
1514       end
1515       c.reload
1516       cr.reload
1517
1518       assert_equal c.state, 'Cancelled'
1519       assert_equal cr.state, 'Final'
1520       assert_equal nil, cr.log_uuid
1521     end
1522   end
1523
1524   test "delete container_request in final state and expect no error due to before_destroy callback" do
1525     act_as_user users(:active) do
1526       cr = ContainerRequest.find_by_uuid container_requests(:completed).uuid
1527       assert_nothing_raised {cr.destroy}
1528     end
1529   end
1530
1531   test "Container request valid priority" do
1532     set_user_from_auth :active
1533     cr = create_minimal_req!
1534
1535     assert_raises(ActiveRecord::RecordInvalid) do
1536       cr.priority = -1
1537       cr.save!
1538     end
1539
1540     cr.priority = 0
1541     cr.save!
1542
1543     cr.priority = 1
1544     cr.save!
1545
1546     cr.priority = 500
1547     cr.save!
1548
1549     cr.priority = 999
1550     cr.save!
1551
1552     cr.priority = 1000
1553     cr.save!
1554
1555     assert_raises(ActiveRecord::RecordInvalid) do
1556       cr.priority = 1001
1557       cr.save!
1558     end
1559   end
1560
1561   # Note: some of these tests might look redundant because they test
1562   # that out-of-order spellings of hashes are still considered equal
1563   # regardless of whether the existing (container) or new (container
1564   # request) hash needs to be re-ordered.
1565   secrets = {"/foo" => {"kind" => "text", "content" => "xyzzy"}}
1566   same_secrets = {"/foo" => {"content" => "xyzzy", "kind" => "text"}}
1567   different_secrets = {"/foo" => {"kind" => "text", "content" => "something completely different"}}
1568   [
1569     [true, nil, nil],
1570     [true, nil, {}],
1571     [true, {}, nil],
1572     [true, {}, {}],
1573     [true, secrets, same_secrets],
1574     [true, same_secrets, secrets],
1575     [false, nil, secrets],
1576     [false, {}, secrets],
1577     [false, secrets, {}],
1578     [false, secrets, nil],
1579     [false, secrets, different_secrets],
1580   ].each do |expect_reuse, sm1, sm2|
1581     test "container reuse secret_mounts #{sm1.inspect}, #{sm2.inspect}" do
1582       set_user_from_auth :active
1583       cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm1)
1584       cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm2)
1585       assert_not_nil cr1.container_uuid
1586       assert_not_nil cr2.container_uuid
1587       if expect_reuse
1588         assert_equal cr1.container_uuid, cr2.container_uuid
1589       else
1590         assert_not_equal cr1.container_uuid, cr2.container_uuid
1591       end
1592     end
1593   end
1594
1595   test "scrub secret_mounts but reuse container for request with identical secret_mounts" do
1596     set_user_from_auth :active
1597     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1598     cr1 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1599     run_container(cr1)
1600     cr1.reload
1601
1602     # secret_mounts scrubbed from db
1603     c = Container.where(uuid: cr1.container_uuid).first
1604     assert_equal({}, c.secret_mounts)
1605     assert_equal({}, cr1.secret_mounts)
1606
1607     # can reuse container if secret_mounts match
1608     cr2 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: sm.dup)
1609     assert_equal cr1.container_uuid, cr2.container_uuid
1610
1611     # don't reuse container if secret_mounts don't match
1612     cr3 = create_minimal_req!(state: "Committed", priority: 1, secret_mounts: {})
1613     assert_not_equal cr1.container_uuid, cr3.container_uuid
1614
1615     assert_no_secrets_logged
1616   end
1617
1618   test "conflicting key in mounts and secret_mounts" do
1619     sm = {'/secret/foo' => {'kind' => 'text', 'content' => secret_string}}
1620     set_user_from_auth :active
1621     cr = create_minimal_req!
1622     assert_equal false, cr.update(state: "Committed",
1623                                              priority: 1,
1624                                              mounts: cr.mounts.merge(sm),
1625                                              secret_mounts: sm)
1626     assert_equal [:secret_mounts], cr.errors.messages.keys
1627   end
1628
1629   test "using runtime_token" do
1630     set_user_from_auth :spectator
1631     spec = api_client_authorizations(:active)
1632     cr = create_minimal_req!(state: "Committed", runtime_token: spec.token, priority: 1)
1633     cr.save!
1634     c = Container.find_by_uuid cr.container_uuid
1635     lock_and_run c
1636     assert_nil c.auth_uuid
1637     assert_equal c.runtime_token, spec.token
1638
1639     assert_not_nil ApiClientAuthorization.find_by_uuid(spec.uuid)
1640
1641     act_as_system_user do
1642       c.update!(state: Container::Complete,
1643                            exit_code: 0,
1644                            output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1645                            log: 'fa7aeb5140e2848d39b416daeef4ffc5+45')
1646     end
1647
1648     cr.reload
1649     c.reload
1650     assert_nil cr.runtime_token
1651     assert_nil c.runtime_token
1652   end
1653
1654   test "invalid runtime_token" do
1655     set_user_from_auth :active
1656     spec = api_client_authorizations(:spectator)
1657     assert_raises(ArgumentError) do
1658       cr = create_minimal_req!(state: "Committed", runtime_token: "#{spec.token}xx")
1659       cr.save!
1660     end
1661   end
1662
1663   test "default output_storage_classes" do
1664     saved = Rails.configuration.DefaultStorageClasses
1665     Rails.configuration.DefaultStorageClasses = ["foo"]
1666     begin
1667       act_as_user users(:active) do
1668         cr = create_minimal_req!(priority: 1,
1669                                  state: ContainerRequest::Committed,
1670                                  output_name: 'foo')
1671         run_container(cr)
1672         cr.reload
1673         output = Collection.find_by_uuid(cr.output_uuid)
1674         assert_equal ["foo"], output.storage_classes_desired
1675       end
1676     ensure
1677       Rails.configuration.DefaultStorageClasses = saved
1678     end
1679   end
1680
1681   test "setting output_storage_classes" do
1682     act_as_user users(:active) do
1683       cr = create_minimal_req!(priority: 1,
1684                                state: ContainerRequest::Committed,
1685                                output_name: 'foo',
1686                                output_storage_classes: ["foo_storage_class", "bar_storage_class"])
1687       run_container(cr)
1688       cr.reload
1689       output = Collection.find_by_uuid(cr.output_uuid)
1690       assert_equal ["foo_storage_class", "bar_storage_class"], output.storage_classes_desired
1691       log = Collection.find_by_uuid(cr.log_uuid)
1692       assert_equal ["foo_storage_class", "bar_storage_class"], log.storage_classes_desired
1693     end
1694   end
1695
1696   test "reusing container with different container_request.output_storage_classes" do
1697     common_attrs = {cwd: "test",
1698                     priority: 1,
1699                     command: ["echo", "hello"],
1700                     output_path: "test",
1701                     runtime_constraints: {"vcpus" => 4,
1702                                           "ram" => 12000000000},
1703                     mounts: {"test" => {"kind" => "json"}},
1704                     environment: {"var" => "value1"},
1705                     output_storage_classes: ["foo_storage_class"]}
1706     set_user_from_auth :active
1707     cr1 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Committed}))
1708     cont1 = run_container(cr1)
1709     cr1.reload
1710
1711     output1 = Collection.find_by_uuid(cr1.output_uuid)
1712
1713     # Testing with use_existing default value
1714     cr2 = create_minimal_req!(common_attrs.merge({state: ContainerRequest::Uncommitted,
1715                                                   output_storage_classes: ["bar_storage_class"]}))
1716
1717     assert_not_nil cr1.container_uuid
1718     assert_nil cr2.container_uuid
1719
1720     # Update cr2 to commited state, check for reuse, then run it
1721     cr2.update!({state: ContainerRequest::Committed})
1722     assert_equal cr1.container_uuid, cr2.container_uuid
1723
1724     cr2.reload
1725     output2 = Collection.find_by_uuid(cr2.output_uuid)
1726
1727     # the original CR output has the original storage class,
1728     # but the second CR output has the new storage class.
1729     assert_equal ["foo_storage_class"], cont1.output_storage_classes
1730     assert_equal ["foo_storage_class"], output1.storage_classes_desired
1731     assert_equal ["bar_storage_class"], output2.storage_classes_desired
1732   end
1733
1734   [
1735     [{},               {},           {"type": "output"}],
1736     [{"a1": "b1"},     {},           {"type": "output", "a1": "b1"}],
1737     [{},               {"a1": "b1"}, {"type": "output", "a1": "b1"}],
1738     [{"a1": "b1"},     {"a1": "c1"}, {"type": "output", "a1": "b1"}],
1739     [{"a1": "b1"},     {"a2": "c2"}, {"type": "output", "a1": "b1", "a2": "c2"}],
1740     [{"type": "blah"}, {},           {"type": "blah"}],
1741   ].each do |cr_prop, container_prop, expect_prop|
1742     test "setting output_properties #{cr_prop} #{container_prop} on current container" do
1743       act_as_user users(:active) do
1744         cr = create_minimal_req!(priority: 1,
1745                                  state: ContainerRequest::Committed,
1746                                  output_name: 'foo',
1747                                  output_properties: cr_prop)
1748
1749         act_as_system_user do
1750           logc = Collection.new(owner_uuid: system_user_uuid,
1751                                 manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
1752           logc.save!
1753
1754           c = Container.find_by_uuid(cr.container_uuid)
1755           c.update!(state: Container::Locked)
1756           c.update!(state: Container::Running)
1757
1758           c.update!(output_properties: container_prop)
1759
1760           c.update!(state: Container::Complete,
1761                                exit_code: 0,
1762                                output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1763                                log: logc.portable_data_hash)
1764           logc.destroy
1765         end
1766
1767         cr.reload
1768         expect_prop["container_request"] = cr.uuid
1769         output = Collection.find_by_uuid(cr.output_uuid)
1770         assert_equal expect_prop.symbolize_keys, output.properties.symbolize_keys
1771       end
1772     end
1773   end
1774
1775   test "Cumulative cost includes retried attempts but not reused containers" do
1776     set_user_from_auth :active
1777     cr = create_minimal_req!(priority: 5, state: "Committed", container_count_max: 3)
1778     c = Container.find_by_uuid cr.container_uuid
1779     act_as_system_user do
1780       c.update!(state: Container::Locked)
1781       c.update!(state: Container::Running)
1782       c.update!(state: Container::Cancelled, cost: 3)
1783     end
1784     cr.reload
1785     assert_equal 3, cr.cumulative_cost
1786
1787     c = Container.find_by_uuid cr.container_uuid
1788     lock_and_run c
1789     c.reload
1790     assert_equal 0, c.subrequests_cost
1791
1792     # cr2 is a child/subrequest
1793     cr2 = with_container_auth(c) do
1794       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
1795     end
1796     assert_equal c.uuid, cr2.requesting_container_uuid
1797     c2 = Container.find_by_uuid cr2.container_uuid
1798     act_as_system_user do
1799       c2.update!(state: Container::Locked)
1800       c2.update!(state: Container::Running)
1801       logc = Collection.new(owner_uuid: system_user_uuid,
1802                             manifest_text: ". ef772b2f28e2c8ca84de45466ed19ee9+7815 0:0:arv-mount.txt\n")
1803       logc.save!
1804       c2.update!(state: Container::Complete,
1805                             exit_code: 0,
1806                             output: '1f4b0bc7583c2a7f9102c395f4ffc5e3+45',
1807                             log: logc.portable_data_hash,
1808                             cost: 7)
1809     end
1810     c.reload
1811     assert_equal 7, c.subrequests_cost
1812
1813     # cr3 is an identical child/subrequest, will reuse c2
1814     cr3 = with_container_auth(c) do
1815       create_minimal_req!(priority: 10, state: "Committed", container_count_max: 1, command: ["echo", "foo2"])
1816     end
1817     assert_equal c.uuid, cr3.requesting_container_uuid
1818     c3 = Container.find_by_uuid cr3.container_uuid
1819     assert_equal c2.uuid, c3.uuid
1820     assert_equal Container::Complete, c3.state
1821     c.reload
1822     assert_equal 7, c.subrequests_cost
1823
1824     act_as_system_user do
1825       c.update!(state: Container::Complete, exit_code: 0, cost: 9)
1826     end
1827
1828     c.reload
1829     assert_equal 7, c.subrequests_cost
1830     cr.reload
1831     assert_equal 3+7+9, cr.cumulative_cost
1832   end
1833
1834 end