1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
6 require 'sweep_trashed_objects'
9 class Collection < ArvadosModel
10 extend CurrentApiClient
14 include CommonApiTemplate
17 # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
18 # already know how to properly treat them.
19 attribute :properties, :jsonbHash, default: {}
20 attribute :storage_classes_desired, :jsonbArray, default: ["default"]
21 attribute :storage_classes_confirmed, :jsonbArray, default: []
23 before_validation :default_empty_manifest
24 before_validation :default_storage_classes, on: :create
25 before_validation :managed_properties, on: :create
26 before_validation :check_encoding
27 before_validation :check_manifest_validity
28 before_validation :check_signatures
29 before_validation :strip_signatures_and_update_replication_confirmed
30 before_validation :name_null_if_empty
31 validate :ensure_filesystem_compatible_name
32 validate :ensure_pdh_matches_manifest_text
33 validate :ensure_storage_classes_desired_is_not_empty
34 validate :ensure_storage_classes_contain_non_empty_strings
35 validate :versioning_metadata_updates, on: :update
36 validate :past_versions_cannot_be_updated, on: :update
37 validate :protected_managed_properties_updates, on: :update
38 after_validation :set_file_count_and_total_size
39 before_save :set_file_names
40 around_update :manage_versioning, unless: :is_past_version?
42 api_accessible :user, extend: :common do |t|
43 t.add lambda { |x| x.name || "" }, as: :name
46 t.add :portable_data_hash
47 t.add :signed_manifest_text, as: :manifest_text
48 t.add :manifest_text, as: :unsigned_manifest_text
49 t.add :replication_desired
50 t.add :replication_confirmed
51 t.add :replication_confirmed_at
52 t.add :storage_classes_desired
53 t.add :storage_classes_confirmed
54 t.add :storage_classes_confirmed_at
59 t.add :current_version_uuid
60 t.add :preserve_version
62 t.add :file_size_total
65 UNLOGGED_CHANGES = ['preserve_version', 'updated_at']
68 @signatures_checked = false
69 @computed_pdh_for_manifest_text = false
72 def self.attributes_required_columns
74 # If we don't list manifest_text explicitly, the
75 # params[:select] code gets confused by the way we
76 # expose signed_manifest_text as manifest_text in the
77 # API response, and never let clients select the
78 # manifest_text column.
80 # We need trash_at and is_trashed to determine the
81 # correct timestamp in signed_manifest_text.
82 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
83 'unsigned_manifest_text' => ['manifest_text'],
88 def self.ignored_select_attributes
89 super + ["updated_at", "file_names"]
92 def self.limit_index_columns_read
96 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
98 throw(:abort) if self.manifest_text.nil?
100 return true if current_user.andand.is_admin
102 # Provided the manifest_text hasn't changed materially since an
103 # earlier validation, it's safe to pass this validation on
104 # subsequent passes without checking any signatures. This is
105 # important because the signatures have probably been stripped off
106 # by the time we get to a second validation pass!
107 if @signatures_checked && @signatures_checked == computed_pdh
111 if self.manifest_text_changed?
112 # Check permissions on the collection manifest.
113 # If any signature cannot be verified, raise PermissionDeniedError
114 # which will return 403 Permission denied to the client.
115 api_token = Thread.current[:token]
117 api_token: api_token,
118 now: @validation_timestamp.to_i,
120 self.manifest_text.each_line do |entry|
121 entry.split.each do |tok|
122 if tok == '.' or tok.starts_with? './'
124 elsif tok =~ FILE_TOKEN
125 # This is a filename token, not a blob locator. Note that we
126 # keep checking tokens after this, even though manifest
127 # format dictates that all subsequent tokens will also be
128 # filenames. Safety first!
129 elsif Blob.verify_signature tok, signing_opts
131 elsif Keep::Locator.parse(tok).andand.signature
132 # Signature provided, but verify_signature did not like it.
133 logger.warn "Invalid signature on locator #{tok}"
134 raise ArvadosModel::PermissionDeniedError
135 elsif !Rails.configuration.Collections.BlobSigning
136 # No signature provided, but we are running in insecure mode.
137 logger.debug "Missing signature on locator #{tok} ignored"
138 elsif Blob.new(tok).empty?
139 # No signature provided -- but no data to protect, either.
141 logger.warn "Missing signature on locator #{tok}"
142 raise ArvadosModel::PermissionDeniedError
147 @signatures_checked = computed_pdh
150 def strip_signatures_and_update_replication_confirmed
151 if self.manifest_text_changed?
153 if not self.replication_confirmed.nil?
154 self.class.each_manifest_locator(manifest_text_was) do |match|
155 in_old_manifest[match[1]] = true
159 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
160 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
161 # If the new manifest_text contains locators whose hashes
162 # weren't in the old manifest_text, storage replication is no
164 self.replication_confirmed_at = nil
165 self.replication_confirmed = nil
168 # Return the locator with all permission signatures removed,
169 # but otherwise intact.
170 match[0].gsub(/\+A[^+]*/, '')
173 if @computed_pdh_for_manifest_text == manifest_text
174 # If the cached PDH was valid before stripping, it is still
175 # valid after stripping.
176 @computed_pdh_for_manifest_text = stripped_manifest.dup
179 self[:manifest_text] = stripped_manifest
184 def ensure_pdh_matches_manifest_text
185 if not manifest_text_changed? and not portable_data_hash_changed?
187 elsif portable_data_hash.nil? or not portable_data_hash_changed?
188 self.portable_data_hash = computed_pdh
189 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
190 errors.add(:portable_data_hash, "is not a valid locator")
192 elsif portable_data_hash[0..31] != computed_pdh[0..31]
193 errors.add(:portable_data_hash,
194 "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
197 # Ignore the client-provided size part: always store
198 # computed_pdh in the database.
199 self.portable_data_hash = computed_pdh
203 def name_null_if_empty
210 if self.manifest_text_changed?
211 self.file_names = manifest_files
216 def set_file_count_and_total_size
217 # Only update the file stats if the manifest changed
218 if self.manifest_text_changed?
219 m = Keep::Manifest.new(self.manifest_text)
220 self.file_size_total = m.files_size
221 self.file_count = m.files_count
222 # If the manifest didn't change but the attributes did, ignore the changes
223 elsif self.file_count_changed? || self.file_size_total_changed?
224 self.file_count = self.file_count_was
225 self.file_size_total = self.file_size_total_was
231 return '' if !self.manifest_text
235 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
238 names << name.first.gsub('\040',' ') + "\n"
240 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
241 next if done[stream_name]
242 done[stream_name] = true
243 names << stream_name.first.gsub('\040',' ') + "\n"
248 def default_empty_manifest
249 self.manifest_text ||= ''
252 def skip_uuid_existence_check
253 # Avoid checking the existence of current_version_uuid, as it's
254 # assigned on creation of a new 'current version' collection, so
255 # the collection's UUID only lives on memory when the validation check
257 ['current_version_uuid']
260 def manage_versioning
261 should_preserve_version = should_preserve_version? # Time sensitive, cache value
262 return(yield) unless (should_preserve_version || syncable_updates.any?)
264 # Put aside the changes because with_lock does a record reload
265 changes = self.changes
269 # Copy the original state to save it as old version
270 if should_preserve_version
272 snapshot.uuid = nil # Reset UUID so it's created as a new record
273 snapshot.created_at = self.created_at
274 snapshot.modified_at = self.modified_at_was
277 # Restore requested changes on the current version
278 changes.keys.each do |attr|
279 if attr == 'preserve_version' && changes[attr].last == false && !should_preserve_version
280 next # Ignore false assignment, once true it'll be true until next version
282 self.attributes = {attr => changes[attr].last}
284 # Also update the current version reference
285 self.attributes = {'current_version_uuid' => changes[attr].last}
289 if should_preserve_version
295 sync_past_versions if syncable_updates.any?
297 snapshot.attributes = self.syncable_updates
298 leave_modified_by_user_alone do
299 leave_modified_at_alone do
300 act_as_system_user do
309 def maybe_update_modified_by_fields
310 if !(self.changes.keys - ['updated_at', 'preserve_version']).empty?
318 changes = self.changes
320 # If called after save...
321 changes = self.saved_changes
323 (syncable_attrs & changes.keys).each do |attr|
325 # Point old versions to current version's new UUID
326 updates['current_version_uuid'] = changes[attr].last
328 updates[attr] = changes[attr].last
334 def sync_past_versions
335 updates = self.syncable_updates
336 Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_before_last_save, self.uuid_before_last_save).each do |c|
337 c.attributes = updates
338 # Use a different validation context to skip the 'past_versions_cannot_be_updated'
339 # validator, as on this case it is legal to update some fields.
340 leave_modified_by_user_alone do
341 leave_modified_at_alone do
342 c.save(context: :update_old_versions)
348 def versionable_updates?(attrs)
349 (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
353 ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
357 # Check for the '_was' values just in case the update operation
358 # includes a change on current_version_uuid or uuid.
359 !(new_record? || self.current_version_uuid_was == self.uuid_was)
362 def should_preserve_version?
363 return false unless (Rails.configuration.Collections.CollectionVersioning && versionable_updates?(self.changes.keys))
365 return false if self.is_trashed
367 idle_threshold = Rails.configuration.Collections.PreserveVersionIfIdle
368 if !self.preserve_version_was &&
369 !self.preserve_version &&
370 (idle_threshold < 0 ||
371 (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
378 if !(manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?)
380 # If Ruby thinks the encoding is something else, like 7-bit
381 # ASCII, but its stored bytes are equal to the (valid) UTF-8
382 # encoding of the same string, we declare it to be a UTF-8
385 utf8.force_encoding Encoding::UTF_8
386 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
387 self.manifest_text = utf8
392 errors.add :manifest_text, "must use UTF-8 encoding"
397 def check_manifest_validity
399 Keep::Manifest.validate! manifest_text
401 rescue ArgumentError => e
402 errors.add :manifest_text, e.message
407 def signed_manifest_text
408 if !has_attribute? :manifest_text
413 token = Thread.current[:token]
414 exp = [db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i,
415 trash_at].compact.map(&:to_i).min
416 self.class.sign_manifest manifest_text, token, exp
420 def self.sign_manifest manifest, token, exp=nil
422 exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
428 m = munge_manifest_locators(manifest) do |match|
429 Blob.sign_locator(match[0], signing_opts)
434 def self.munge_manifest_locators manifest
435 # Given a manifest text and a block, yield the regexp MatchData
436 # for each locator. Return a new manifest in which each locator
437 # has been replaced by the block's return value.
438 return nil if !manifest
439 return '' if manifest == ''
442 manifest.each_line do |line|
445 line.split(' ').each do |word|
448 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
449 new_words << yield(match)
454 new_lines << new_words.join(' ')
456 new_lines.join("\n") + "\n"
459 def self.each_manifest_locator manifest
460 # Given a manifest text and a block, yield the regexp match object
462 manifest.each_line do |line|
463 # line will have a trailing newline, but the last token is never
464 # a locator, so it's harmless here.
465 line.split(' ').each do |word|
466 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
473 def self.normalize_uuid uuid
476 uuid.split('+').each do |token|
477 if token.match(/^[0-9a-f]{32,}$/)
478 raise "uuid #{uuid} has multiple hash parts" if hash_part
480 elsif token.match(/^\d+$/)
481 raise "uuid #{uuid} has multiple size parts" if size_part
485 raise "uuid #{uuid} has no hash part" if !hash_part
486 [hash_part, size_part].compact.join '+'
489 def self.get_compatible_images(readers, pattern, collections)
490 if collections.empty?
495 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
496 collections.map(&:portable_data_hash),
497 'docker_image_migration',
499 order('links.created_at asc').
501 [l.tail_uuid, l.head_uuid]
504 migrated_collections = Hash[
505 Collection.readable_by(*readers).
506 where('portable_data_hash in (?)', migrations.values).
508 [c.portable_data_hash, c]
511 collections.map { |c|
512 # Check if the listed image is compatible first, if not, then try the
514 manifest = Keep::Manifest.new(c.manifest_text)
515 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
517 elsif m = migrated_collections[migrations[c.portable_data_hash]]
518 manifest = Keep::Manifest.new(m.manifest_text)
519 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
526 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
527 # Collection objects, sorted by timestamp starting with the most recent
530 # If filter_compatible_format is true (the default), only return image
531 # collections which are support by the installation as indicated by
532 # Rails.configuration.Containers.SupportedDockerImageFormats. Will follow
533 # 'docker_image_migration' links if search_term resolves to an incompatible
534 # image, but an equivalent compatible image is available.
535 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
536 readers ||= [Thread.current[:user]]
538 readable_by(*readers).
539 readable_by(*readers, table_name: "collections").
540 joins("JOIN collections ON links.head_uuid = collections.uuid").
541 order("links.created_at DESC")
543 docker_image_formats = Rails.configuration.Containers.SupportedDockerImageFormats.keys.map(&:to_s)
545 if (docker_image_formats.include? 'v1' and
546 docker_image_formats.include? 'v2') or filter_compatible_format == false
547 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
548 elsif docker_image_formats.include? 'v2'
549 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
550 elsif docker_image_formats.include? 'v1'
551 pattern = /^[0-9A-Fa-f]{64}\.tar$/
553 raise "Unrecognized configuration for docker_image_formats #{docker_image_formats}"
556 # If the search term is a Collection locator that contains one file
557 # that looks like a Docker image, return it.
558 if loc = Keep::Locator.parse(search_term)
560 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
561 rc = Rails.configuration.RemoteClusters.select{ |k|
562 k != :"*" && k != Rails.configuration.ClusterID}
563 if coll_match.any? or rc.length == 0
564 return get_compatible_images(readers, pattern, coll_match)
566 # Allow bare pdh that doesn't exist in the local database so
567 # that federated container requests which refer to remotely
568 # stored containers will validate.
569 return [Collection.new(portable_data_hash: loc.to_s)]
573 if search_tag.nil? and (n = search_term.index(":"))
574 search_tag = search_term[n+1..-1]
575 search_term = search_term[0..n-1]
578 # Find Collections with matching Docker image repository+tag pairs.
579 matches = base_search.
580 where(link_class: "docker_image_repo+tag",
581 name: "#{search_term}:#{search_tag || 'latest'}")
583 # If that didn't work, find Collections with matching Docker image hashes.
585 matches = base_search.
586 where("link_class = ? and links.name LIKE ?",
587 "docker_image_hash", "#{search_term}%")
590 # Generate an order key for each result. We want to order the results
591 # so that anything with an image timestamp is considered more recent than
592 # anything without; then we use the link's created_at as a tiebreaker.
594 matches.each do |link|
595 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
596 -link.created_at.to_i]
599 sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
600 uuid_timestamps[c.uuid]
602 compatible = get_compatible_images(readers, pattern, sorted)
603 if sorted.length > 0 and compatible.empty?
604 raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
609 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
610 find_all_for_docker_image(search_term, search_tag, readers).first
613 def self.searchable_columns operator
614 super - ["manifest_text"]
617 def self.full_text_searchable_columns
618 super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
622 SweepTrashedObjects.sweep_if_stale
628 # Although the defaults for these columns is already set up on the schema,
629 # collection creation from an API client seems to ignore them, making the
630 # validation on empty desired storage classes return an error.
631 def default_storage_classes
632 if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
633 self.storage_classes_desired = ["default"]
635 self.storage_classes_confirmed ||= []
638 # Sets managed properties at creation time
639 def managed_properties
640 managed_props = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
641 if managed_props.empty?
644 (managed_props.keys - self.properties.keys).each do |key|
645 if managed_props[key]['Function'] == 'original_owner'
646 self.properties[key] = self.user_owner_uuid
647 elsif managed_props[key]['Value']
648 self.properties[key] = managed_props[key]['Value']
650 logger.warn "Unidentified default property definition '#{key}': #{managed_props[key].inspect}"
655 def portable_manifest_text
656 self.class.munge_manifest_locators(manifest_text) do |match|
666 portable_manifest = portable_manifest_text
667 (Digest::MD5.hexdigest(portable_manifest) +
669 portable_manifest.bytesize.to_s)
673 if @computed_pdh_for_manifest_text == manifest_text
676 @computed_pdh = compute_pdh
677 @computed_pdh_for_manifest_text = manifest_text.dup
681 def ensure_permission_to_save
682 if (not current_user.andand.is_admin)
683 if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
684 not (replication_confirmed_at.nil? and replication_confirmed.nil?)
685 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
687 if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
688 not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
689 raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
695 def ensure_storage_classes_desired_is_not_empty
696 if self.storage_classes_desired.empty?
697 raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
701 def ensure_storage_classes_contain_non_empty_strings
702 (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
703 if !c.is_a?(String) || c == ''
704 raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
709 def past_versions_cannot_be_updated
711 errors.add(:base, "past versions cannot be updated")
716 def protected_managed_properties_updates
717 managed_properties = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
718 if managed_properties.empty? || !properties_changed? || current_user.is_admin
721 protected_props = managed_properties.keys.select do |p|
722 Rails.configuration.Collections.ManagedProperties[p]['Protected']
724 # Pre-existent protected properties can't be updated
725 invalid_updates = properties_was.keys.select{|p| properties_was[p] != properties[p]} & protected_props
726 if !invalid_updates.empty?
727 invalid_updates.each do |p|
728 errors.add("protected property cannot be updated:", p)
730 raise PermissionDeniedError.new
735 def versioning_metadata_updates
737 if !is_past_version? && current_version_uuid_changed?
738 errors.add(:current_version_uuid, "cannot be updated")
742 errors.add(:version, "cannot be updated")
750 self.current_version_uuid ||= self.uuid
755 super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?