+ def finalize_if_needed
+ if state == Committed && Container.find_by_uuid(container_uuid).final?
+ reload
+ act_as_system_user do
+ finalize!
+ end
+ end
+ end
+
+ # Finalize the container request after the container has
+ # finished/cancelled.
+ def finalize!
+ out_coll = nil
+ log_coll = nil
+ c = Container.find_by_uuid(container_uuid)
+ ['output', 'log'].each do |out_type|
+ pdh = c.send(out_type)
+ next if pdh.nil?
+ if self.output_name and out_type == 'output'
+ coll_name = self.output_name
+ else
+ coll_name = "Container #{out_type} for request #{uuid}"
+ end
+ manifest = Collection.where(portable_data_hash: pdh).first.manifest_text
+ begin
+ coll = Collection.create!(owner_uuid: owner_uuid,
+ manifest_text: manifest,
+ portable_data_hash: pdh,
+ name: coll_name,
+ properties: {
+ 'type' => out_type,
+ 'container_request' => uuid,
+ })
+ rescue ActiveRecord::RecordNotUnique => rn
+ # In case this is executed as part of a transaction: When a Postgres exception happens,
+ # the following statements on the same transaction become invalid, so a rollback is
+ # needed. One example are Unit Tests, every test is enclosed inside a transaction so
+ # that the database can be reverted before every new test starts.
+ # See: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#module-ActiveRecord::Transactions::ClassMethods-label-Exception+handling+and+rolling+back
+ ActiveRecord::Base.connection.execute 'ROLLBACK'
+ raise unless out_type == 'output' and self.output_name
+ # Postgres specific unique name check. See ApplicationController#create for
+ # a detailed explanation.
+ raise unless rn.original_exception.is_a? PG::UniqueViolation
+ err = rn.original_exception
+ detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
+ raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
+ # Output collection name collision detected: append a timestamp.
+ coll_name = "#{self.output_name} #{Time.now.getgm.strftime('%FT%TZ')}"
+ retry
+ end
+ if out_type == 'output'
+ out_coll = coll.uuid
+ else
+ log_coll = coll.uuid
+ end
+ end
+ update_attributes!(state: Final, output_uuid: out_coll, log_uuid: log_coll)