1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
8 class Collection < ArvadosModel
9 extend CurrentApiClient
13 include CommonApiTemplate
16 # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
17 # already know how to properly treat them.
18 attribute :properties, :jsonbHash, default: {}
19 attribute :storage_classes_desired, :jsonbArray, default: lambda { Rails.configuration.DefaultStorageClasses }
20 attribute :storage_classes_confirmed, :jsonbArray, default: []
22 before_validation :default_empty_manifest
23 before_validation :default_storage_classes, on: :create
24 before_validation :managed_properties, on: :create
25 before_validation :check_encoding
26 before_validation :check_manifest_validity
27 before_validation :check_signatures
28 before_validation :strip_signatures_and_update_replication_confirmed
29 before_validation :name_null_if_empty
30 validate :ensure_filesystem_compatible_name
31 validate :ensure_pdh_matches_manifest_text
32 validate :ensure_storage_classes_desired_is_not_empty
33 validate :ensure_storage_classes_contain_non_empty_strings
34 validate :versioning_metadata_updates, on: :update
35 validate :past_versions_cannot_be_updated, on: :update
36 validate :protected_managed_properties_updates, on: :update
37 after_validation :set_file_count_and_total_size
38 before_save :set_file_names
39 around_update :manage_versioning, unless: :is_past_version?
41 api_accessible :user, extend: :common do |t|
42 t.add lambda { |x| x.name || "" }, as: :name
45 t.add :portable_data_hash
46 t.add :manifest_text, as: :unsigned_manifest_text
47 t.add :manifest_text, as: :manifest_text
48 t.add :replication_desired
49 t.add :replication_confirmed
50 t.add :replication_confirmed_at
51 t.add :storage_classes_desired
52 t.add :storage_classes_confirmed
53 t.add :storage_classes_confirmed_at
58 t.add :current_version_uuid
59 t.add :preserve_version
61 t.add :file_size_total
64 UNLOGGED_CHANGES = ['preserve_version', 'updated_at']
67 @signatures_checked = false
68 @computed_pdh_for_manifest_text = false
71 def self.attributes_required_columns
73 # If we don't list unsigned_manifest_text explicitly,
74 # the params[:select] code gets confused by the way we
75 # expose manifest_text as unsigned_manifest_text in
76 # the API response, and never let clients select the
77 # unsigned_manifest_text column.
78 'unsigned_manifest_text' => ['manifest_text'],
83 def self.ignored_select_attributes
84 super + ["updated_at", "file_names"]
87 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
89 throw(:abort) if self.manifest_text.nil?
91 return true if current_user.andand.is_admin
93 # Provided the manifest_text hasn't changed materially since an
94 # earlier validation, it's safe to pass this validation on
95 # subsequent passes without checking any signatures. This is
96 # important because the signatures have probably been stripped off
97 # by the time we get to a second validation pass!
98 if @signatures_checked && @signatures_checked == computed_pdh
102 if self.manifest_text_changed?
103 # Check permissions on the collection manifest.
104 # If any signature cannot be verified, raise PermissionDeniedError
105 # which will return 403 Permission denied to the client.
106 api_token = Thread.current[:token]
108 api_token: api_token,
109 now: @validation_timestamp.to_i,
111 self.manifest_text.each_line do |entry|
112 entry.split.each do |tok|
113 if tok == '.' or tok.starts_with? './'
115 elsif tok =~ FILE_TOKEN
116 # This is a filename token, not a blob locator. Note that we
117 # keep checking tokens after this, even though manifest
118 # format dictates that all subsequent tokens will also be
119 # filenames. Safety first!
120 elsif Blob.verify_signature tok, signing_opts
122 elsif Keep::Locator.parse(tok).andand.signature
123 # Signature provided, but verify_signature did not like it.
124 logger.warn "Invalid signature on locator #{tok}"
125 raise ArvadosModel::PermissionDeniedError
126 elsif !Rails.configuration.Collections.BlobSigning
127 # No signature provided, but we are running in insecure mode.
128 logger.debug "Missing signature on locator #{tok} ignored"
129 elsif Blob.new(tok).empty?
130 # No signature provided -- but no data to protect, either.
132 logger.warn "Missing signature on locator #{tok}"
133 raise ArvadosModel::PermissionDeniedError
138 @signatures_checked = computed_pdh
141 def strip_signatures_and_update_replication_confirmed
142 if self.manifest_text_changed?
144 # manifest_text_was could be nil when dealing with a freshly created snapshot,
145 # so we skip this case because there was no real manifest change. (Bug #18005)
146 if (not self.replication_confirmed.nil?) and (not self.manifest_text_was.nil?)
147 self.class.each_manifest_locator(manifest_text_was) do |match|
148 in_old_manifest[match[1]] = true
152 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
153 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
154 # If the new manifest_text contains locators whose hashes
155 # weren't in the old manifest_text, storage replication is no
157 self.replication_confirmed_at = nil
158 self.replication_confirmed = nil
161 # Return the locator with all permission signatures removed,
162 # but otherwise intact.
163 match[0].gsub(/\+A[^+]*/, '')
166 if @computed_pdh_for_manifest_text == manifest_text
167 # If the cached PDH was valid before stripping, it is still
168 # valid after stripping.
169 @computed_pdh_for_manifest_text = stripped_manifest.dup
172 self[:manifest_text] = stripped_manifest
177 def ensure_pdh_matches_manifest_text
178 if not manifest_text_changed? and not portable_data_hash_changed?
180 elsif portable_data_hash.nil? or not portable_data_hash_changed?
181 self.portable_data_hash = computed_pdh
182 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
183 errors.add(:portable_data_hash, "is not a valid locator")
185 elsif portable_data_hash[0..31] != computed_pdh[0..31]
186 errors.add(:portable_data_hash,
187 "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
190 # Ignore the client-provided size part: always store
191 # computed_pdh in the database.
192 self.portable_data_hash = computed_pdh
196 def name_null_if_empty
203 if self.manifest_text_changed?
204 self.file_names = manifest_files
209 def set_file_count_and_total_size
210 # Only update the file stats if the manifest changed
211 if self.manifest_text_changed?
212 m = Keep::Manifest.new(self.manifest_text)
213 self.file_size_total = m.files_size
214 self.file_count = m.files_count
215 # If the manifest didn't change but the attributes did, ignore the changes
216 elsif self.file_count_changed? || self.file_size_total_changed?
217 self.file_count = self.file_count_was
218 self.file_size_total = self.file_size_total_was
224 return '' if !self.manifest_text
228 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
231 names << name.first.gsub('\040',' ') + "\n"
233 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
234 next if done[stream_name]
235 done[stream_name] = true
236 names << stream_name.first.gsub('\040',' ') + "\n"
241 def default_empty_manifest
242 self.manifest_text ||= ''
245 def skip_uuid_existence_check
246 # Avoid checking the existence of current_version_uuid, as it's
247 # assigned on creation of a new 'current version' collection, so
248 # the collection's UUID only lives on memory when the validation check
250 ['current_version_uuid']
253 def manage_versioning
254 should_preserve_version = should_preserve_version? # Time sensitive, cache value
255 return(yield) unless (should_preserve_version || syncable_updates.any?)
257 # Put aside the changes because with_lock does a record reload
258 changes = self.changes
262 # Copy the original state to save it as old version
263 if should_preserve_version
265 snapshot.uuid = nil # Reset UUID so it's created as a new record
266 snapshot.created_at = self.created_at
267 snapshot.modified_at = self.modified_at_was
270 # Restore requested changes on the current version
271 changes.keys.each do |attr|
272 if attr == 'preserve_version' && changes[attr].last == false && !should_preserve_version
273 next # Ignore false assignment, once true it'll be true until next version
275 self.attributes = {attr => changes[attr].last}
277 # Also update the current version reference
278 self.attributes = {'current_version_uuid' => changes[attr].last}
282 if should_preserve_version
288 sync_past_versions if syncable_updates.any?
290 snapshot.attributes = self.syncable_updates
291 leave_modified_by_user_alone do
292 leave_modified_at_alone do
293 act_as_system_user do
302 def maybe_update_modified_by_fields
303 if !(self.changes.keys - ['updated_at', 'preserve_version']).empty?
311 changes = self.changes
313 # If called after save...
314 changes = self.saved_changes
316 (syncable_attrs & changes.keys).each do |attr|
318 # Point old versions to current version's new UUID
319 updates['current_version_uuid'] = changes[attr].last
321 updates[attr] = changes[attr].last
327 def sync_past_versions
328 Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_before_last_save, self.uuid_before_last_save).update_all self.syncable_updates
331 def versionable_updates?(attrs)
332 (['manifest_text', 'description', 'properties', 'name'] & attrs).any?
336 ['uuid', 'owner_uuid', 'delete_at', 'trash_at', 'is_trashed', 'replication_desired', 'storage_classes_desired']
340 # Check for the '_was' values just in case the update operation
341 # includes a change on current_version_uuid or uuid.
342 !(new_record? || self.current_version_uuid_was == self.uuid_was)
345 def should_preserve_version?
346 return false unless (Rails.configuration.Collections.CollectionVersioning && versionable_updates?(self.changes.keys))
348 return false if self.is_trashed
350 idle_threshold = Rails.configuration.Collections.PreserveVersionIfIdle
351 if !self.preserve_version_was &&
352 !self.preserve_version &&
353 (idle_threshold < 0 ||
354 (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
361 if !(manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?)
363 # If Ruby thinks the encoding is something else, like 7-bit
364 # ASCII, but its stored bytes are equal to the (valid) UTF-8
365 # encoding of the same string, we declare it to be a UTF-8
368 utf8.force_encoding Encoding::UTF_8
369 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
370 self.manifest_text = utf8
375 errors.add :manifest_text, "must use UTF-8 encoding"
380 def check_manifest_validity
382 Keep::Manifest.validate! manifest_text
384 rescue ArgumentError => e
385 errors.add :manifest_text, e.message
390 def signed_manifest_text_only_for_tests
391 if !has_attribute? :manifest_text
396 token = Thread.current[:token]
397 exp = [db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i,
398 trash_at].compact.map(&:to_i).min
399 self.class.sign_manifest_only_for_tests manifest_text, token, exp
403 def self.sign_manifest_only_for_tests manifest, token, exp=nil
405 exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
411 m = munge_manifest_locators(manifest) do |match|
412 Blob.sign_locator(match[0], signing_opts)
417 def self.munge_manifest_locators manifest
418 # Given a manifest text and a block, yield the regexp MatchData
419 # for each locator. Return a new manifest in which each locator
420 # has been replaced by the block's return value.
421 return nil if !manifest
422 return '' if manifest == ''
425 manifest.each_line do |line|
428 line.split(' ').each do |word|
431 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
432 new_words << yield(match)
437 new_lines << new_words.join(' ')
439 new_lines.join("\n") + "\n"
442 def self.each_manifest_locator manifest
443 # Given a manifest text and a block, yield the regexp match object
445 manifest.each_line do |line|
446 # line will have a trailing newline, but the last token is never
447 # a locator, so it's harmless here.
448 line.split(' ').each do |word|
449 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
456 def self.normalize_uuid uuid
459 uuid.split('+').each do |token|
460 if token.match(/^[0-9a-f]{32,}$/)
461 raise "uuid #{uuid} has multiple hash parts" if hash_part
463 elsif token.match(/^\d+$/)
464 raise "uuid #{uuid} has multiple size parts" if size_part
468 raise "uuid #{uuid} has no hash part" if !hash_part
469 [hash_part, size_part].compact.join '+'
472 def self.get_compatible_images(readers, pattern, collections)
473 if collections.empty?
478 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
479 collections.map(&:portable_data_hash),
480 'docker_image_migration',
482 order('links.created_at asc').
484 [l.tail_uuid, l.head_uuid]
487 migrated_collections = Hash[
488 Collection.readable_by(*readers).
489 where('portable_data_hash in (?)', migrations.values).
491 [c.portable_data_hash, c]
494 collections.map { |c|
495 # Check if the listed image is compatible first, if not, then try the
497 manifest = Keep::Manifest.new(c.manifest_text)
498 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
500 elsif m = migrated_collections[migrations[c.portable_data_hash]]
501 manifest = Keep::Manifest.new(m.manifest_text)
502 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
509 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
510 # Collection objects, sorted by timestamp starting with the most recent
513 # If filter_compatible_format is true (the default), only return image
514 # collections which are support by the installation as indicated by
515 # Rails.configuration.Containers.SupportedDockerImageFormats. Will follow
516 # 'docker_image_migration' links if search_term resolves to an incompatible
517 # image, but an equivalent compatible image is available.
518 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
519 readers ||= [Thread.current[:user]]
521 readable_by(*readers).
522 readable_by(*readers, table_name: "collections").
523 joins("JOIN collections ON links.head_uuid = collections.uuid").
524 order("links.created_at DESC")
526 docker_image_formats = Rails.configuration.Containers.SupportedDockerImageFormats.keys.map(&:to_s)
528 if (docker_image_formats.include? 'v1' and
529 docker_image_formats.include? 'v2') or filter_compatible_format == false
530 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
531 elsif docker_image_formats.include? 'v2'
532 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
533 elsif docker_image_formats.include? 'v1'
534 pattern = /^[0-9A-Fa-f]{64}\.tar$/
536 raise "Unrecognized configuration for docker_image_formats #{docker_image_formats}"
539 # If the search term is a Collection locator that contains one file
540 # that looks like a Docker image, return it.
541 if loc = Keep::Locator.parse(search_term)
543 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
544 rc = Rails.configuration.RemoteClusters.select{ |k|
545 k != :"*" && k != Rails.configuration.ClusterID}
546 if coll_match.any? or rc.length == 0
547 return get_compatible_images(readers, pattern, coll_match)
549 # Allow bare pdh that doesn't exist in the local database so
550 # that federated container requests which refer to remotely
551 # stored containers will validate.
552 return [Collection.new(portable_data_hash: loc.to_s)]
556 if search_tag.nil? and (n = search_term.index(":"))
557 search_tag = search_term[n+1..-1]
558 search_term = search_term[0..n-1]
561 # Find Collections with matching Docker image repository+tag pairs.
562 matches = base_search.
563 where(link_class: "docker_image_repo+tag",
564 name: "#{search_term}:#{search_tag || 'latest'}")
566 # If that didn't work, find Collections with matching Docker image hashes.
568 matches = base_search.
569 where("link_class = ? and links.name LIKE ?",
570 "docker_image_hash", "#{search_term}%")
573 # Generate an order key for each result. We want to order the results
574 # so that anything with an image timestamp is considered more recent than
575 # anything without; then we use the link's created_at as a tiebreaker.
577 matches.each do |link|
578 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
579 -link.created_at.to_i]
582 sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
583 uuid_timestamps[c.uuid]
585 compatible = get_compatible_images(readers, pattern, sorted)
586 if sorted.length > 0 and compatible.empty?
587 raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
592 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
593 find_all_for_docker_image(search_term, search_tag, readers).first
596 def self.searchable_columns operator
597 super - ["manifest_text"]
600 def self.full_text_searchable_columns
601 super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
606 # Although the defaults for these columns is already set up on the schema,
607 # collection creation from an API client seems to ignore them, making the
608 # validation on empty desired storage classes return an error.
609 def default_storage_classes
610 if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
611 self.storage_classes_desired = Rails.configuration.DefaultStorageClasses
613 self.storage_classes_confirmed ||= []
616 # Sets managed properties at creation time
617 def managed_properties
618 managed_props = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
619 if managed_props.empty?
622 (managed_props.keys - self.properties.keys).each do |key|
623 if managed_props[key]['Function'] == 'original_owner'
624 self.properties[key] = self.user_owner_uuid
625 elsif managed_props[key]['Value']
626 self.properties[key] = managed_props[key]['Value']
628 logger.warn "Unidentified default property definition '#{key}': #{managed_props[key].inspect}"
633 def portable_manifest_text
634 self.class.munge_manifest_locators(manifest_text) do |match|
644 portable_manifest = portable_manifest_text
645 (Digest::MD5.hexdigest(portable_manifest) +
647 portable_manifest.bytesize.to_s)
651 if @computed_pdh_for_manifest_text == manifest_text
654 @computed_pdh = compute_pdh
655 @computed_pdh_for_manifest_text = manifest_text.dup
659 def ensure_permission_to_save
660 if (not current_user.andand.is_admin)
661 if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
662 not (replication_confirmed_at.nil? and replication_confirmed.nil?)
663 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
665 if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
666 not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
667 raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
673 def ensure_storage_classes_desired_is_not_empty
674 if self.storage_classes_desired.empty?
675 raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
679 def ensure_storage_classes_contain_non_empty_strings
680 (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
681 if !c.is_a?(String) || c == ''
682 raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
687 def past_versions_cannot_be_updated
689 errors.add(:base, "past versions cannot be updated")
694 def protected_managed_properties_updates
695 managed_properties = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
696 if managed_properties.empty? || !properties_changed? || current_user.is_admin
699 protected_props = managed_properties.keys.select do |p|
700 Rails.configuration.Collections.ManagedProperties[p]['Protected']
702 # Pre-existent protected properties can't be updated
703 invalid_updates = properties_was.keys.select{|p| properties_was[p] != properties[p]} & protected_props
704 if !invalid_updates.empty?
705 invalid_updates.each do |p|
706 errors.add("protected property cannot be updated:", p)
708 raise PermissionDeniedError.new
713 def versioning_metadata_updates
715 if !is_past_version? && current_version_uuid_changed?
716 errors.add(:current_version_uuid, "cannot be updated")
720 errors.add(:version, "cannot be updated")
728 self.current_version_uuid ||= self.uuid
733 super unless (saved_changes.keys - UNLOGGED_CHANGES).empty?