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
66 @signatures_checked = false
67 @computed_pdh_for_manifest_text = false
70 def self.attributes_required_columns
72 # If we don't list manifest_text explicitly, the
73 # params[:select] code gets confused by the way we
74 # expose signed_manifest_text as manifest_text in the
75 # API response, and never let clients select the
76 # manifest_text column.
78 # We need trash_at and is_trashed to determine the
79 # correct timestamp in signed_manifest_text.
80 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
81 'unsigned_manifest_text' => ['manifest_text'],
86 def self.ignored_select_attributes
87 super + ["updated_at", "file_names"]
90 def self.limit_index_columns_read
94 FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
96 throw(:abort) if self.manifest_text.nil?
98 return true if current_user.andand.is_admin
100 # Provided the manifest_text hasn't changed materially since an
101 # earlier validation, it's safe to pass this validation on
102 # subsequent passes without checking any signatures. This is
103 # important because the signatures have probably been stripped off
104 # by the time we get to a second validation pass!
105 if @signatures_checked && @signatures_checked == computed_pdh
109 if self.manifest_text_changed?
110 # Check permissions on the collection manifest.
111 # If any signature cannot be verified, raise PermissionDeniedError
112 # which will return 403 Permission denied to the client.
113 api_token = Thread.current[:token]
115 api_token: api_token,
116 now: @validation_timestamp.to_i,
118 self.manifest_text.each_line do |entry|
119 entry.split.each do |tok|
120 if tok == '.' or tok.starts_with? './'
122 elsif tok =~ FILE_TOKEN
123 # This is a filename token, not a blob locator. Note that we
124 # keep checking tokens after this, even though manifest
125 # format dictates that all subsequent tokens will also be
126 # filenames. Safety first!
127 elsif Blob.verify_signature tok, signing_opts
129 elsif Keep::Locator.parse(tok).andand.signature
130 # Signature provided, but verify_signature did not like it.
131 logger.warn "Invalid signature on locator #{tok}"
132 raise ArvadosModel::PermissionDeniedError
133 elsif !Rails.configuration.Collections.BlobSigning
134 # No signature provided, but we are running in insecure mode.
135 logger.debug "Missing signature on locator #{tok} ignored"
136 elsif Blob.new(tok).empty?
137 # No signature provided -- but no data to protect, either.
139 logger.warn "Missing signature on locator #{tok}"
140 raise ArvadosModel::PermissionDeniedError
145 @signatures_checked = computed_pdh
148 def strip_signatures_and_update_replication_confirmed
149 if self.manifest_text_changed?
151 if not self.replication_confirmed.nil?
152 self.class.each_manifest_locator(manifest_text_was) do |match|
153 in_old_manifest[match[1]] = true
157 stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
158 if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
159 # If the new manifest_text contains locators whose hashes
160 # weren't in the old manifest_text, storage replication is no
162 self.replication_confirmed_at = nil
163 self.replication_confirmed = nil
166 # Return the locator with all permission signatures removed,
167 # but otherwise intact.
168 match[0].gsub(/\+A[^+]*/, '')
171 if @computed_pdh_for_manifest_text == manifest_text
172 # If the cached PDH was valid before stripping, it is still
173 # valid after stripping.
174 @computed_pdh_for_manifest_text = stripped_manifest.dup
177 self[:manifest_text] = stripped_manifest
182 def ensure_pdh_matches_manifest_text
183 if not manifest_text_changed? and not portable_data_hash_changed?
185 elsif portable_data_hash.nil? or not portable_data_hash_changed?
186 self.portable_data_hash = computed_pdh
187 elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
188 errors.add(:portable_data_hash, "is not a valid locator")
190 elsif portable_data_hash[0..31] != computed_pdh[0..31]
191 errors.add(:portable_data_hash,
192 "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
195 # Ignore the client-provided size part: always store
196 # computed_pdh in the database.
197 self.portable_data_hash = computed_pdh
201 def name_null_if_empty
208 if self.manifest_text_changed?
209 self.file_names = manifest_files
214 def set_file_count_and_total_size
215 # Only update the file stats if the manifest changed
216 if self.manifest_text_changed?
217 m = Keep::Manifest.new(self.manifest_text)
218 self.file_size_total = m.files_size
219 self.file_count = m.files_count
220 # If the manifest didn't change but the attributes did, ignore the changes
221 elsif self.file_count_changed? || self.file_size_total_changed?
222 self.file_count = self.file_count_was
223 self.file_size_total = self.file_size_total_was
229 return '' if !self.manifest_text
233 self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
236 names << name.first.gsub('\040',' ') + "\n"
238 self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
239 next if done[stream_name]
240 done[stream_name] = true
241 names << stream_name.first.gsub('\040',' ') + "\n"
246 def default_empty_manifest
247 self.manifest_text ||= ''
250 def skip_uuid_existence_check
251 # Avoid checking the existence of current_version_uuid, as it's
252 # assigned on creation of a new 'current version' collection, so
253 # the collection's UUID only lives on memory when the validation check
255 ['current_version_uuid']
258 def manage_versioning
259 should_preserve_version = should_preserve_version? # Time sensitive, cache value
260 return(yield) unless (should_preserve_version || syncable_updates.any?)
262 # Put aside the changes because with_lock forces a record reload
263 changes = self.changes
266 # Copy the original state to save it as old version
267 if should_preserve_version
269 snapshot.uuid = nil # Reset UUID so it's created as a new record
270 snapshot.created_at = self.created_at
273 # Restore requested changes on the current version
274 changes.keys.each do |attr|
275 if attr == 'preserve_version' && changes[attr].last == false
276 next # Ignore false assignment, once true it'll be true until next version
278 self.attributes = {attr => changes[attr].last}
280 # Also update the current version reference
281 self.attributes = {'current_version_uuid' => changes[attr].last}
285 if should_preserve_version
287 self.preserve_version = false
292 sync_past_versions if syncable_updates.any?
294 snapshot.attributes = self.syncable_updates
295 leave_modified_by_user_alone do
296 act_as_system_user do
306 (syncable_attrs & self.changes.keys).each do |attr|
308 # Point old versions to current version's new UUID
309 updates['current_version_uuid'] = self.changes[attr].last
311 updates[attr] = self.changes[attr].last
317 def sync_past_versions
318 updates = self.syncable_updates
319 Collection.where('current_version_uuid = ? AND uuid != ?', self.uuid_was, self.uuid_was).each do |c|
320 c.attributes = updates
321 # Use a different validation context to skip the 'past_versions_cannot_be_updated'
322 # validator, as on this case it is legal to update some fields.
323 leave_modified_by_user_alone do
324 leave_modified_at_alone do
325 c.save(context: :update_old_versions)
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 (idle_threshold < 0 ||
353 (idle_threshold > 0 && self.modified_at_was > db_current_time-idle_threshold.seconds))
360 if !(manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?)
362 # If Ruby thinks the encoding is something else, like 7-bit
363 # ASCII, but its stored bytes are equal to the (valid) UTF-8
364 # encoding of the same string, we declare it to be a UTF-8
367 utf8.force_encoding Encoding::UTF_8
368 if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
369 self.manifest_text = utf8
374 errors.add :manifest_text, "must use UTF-8 encoding"
379 def check_manifest_validity
381 Keep::Manifest.validate! manifest_text
383 rescue ArgumentError => e
384 errors.add :manifest_text, e.message
389 def signed_manifest_text
390 if !has_attribute? :manifest_text
395 token = Thread.current[:token]
396 exp = [db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i,
397 trash_at].compact.map(&:to_i).min
398 self.class.sign_manifest manifest_text, token, exp
402 def self.sign_manifest manifest, token, exp=nil
404 exp = db_current_time.to_i + Rails.configuration.Collections.BlobSigningTTL.to_i
410 m = munge_manifest_locators(manifest) do |match|
411 Blob.sign_locator(match[0], signing_opts)
416 def self.munge_manifest_locators manifest
417 # Given a manifest text and a block, yield the regexp MatchData
418 # for each locator. Return a new manifest in which each locator
419 # has been replaced by the block's return value.
420 return nil if !manifest
421 return '' if manifest == ''
424 manifest.each_line do |line|
427 line.split(' ').each do |word|
430 elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
431 new_words << yield(match)
436 new_lines << new_words.join(' ')
438 new_lines.join("\n") + "\n"
441 def self.each_manifest_locator manifest
442 # Given a manifest text and a block, yield the regexp match object
444 manifest.each_line do |line|
445 # line will have a trailing newline, but the last token is never
446 # a locator, so it's harmless here.
447 line.split(' ').each do |word|
448 if match = Keep::Locator::LOCATOR_REGEXP.match(word)
455 def self.normalize_uuid uuid
458 uuid.split('+').each do |token|
459 if token.match(/^[0-9a-f]{32,}$/)
460 raise "uuid #{uuid} has multiple hash parts" if hash_part
462 elsif token.match(/^\d+$/)
463 raise "uuid #{uuid} has multiple size parts" if size_part
467 raise "uuid #{uuid} has no hash part" if !hash_part
468 [hash_part, size_part].compact.join '+'
471 def self.get_compatible_images(readers, pattern, collections)
472 if collections.empty?
477 Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
478 collections.map(&:portable_data_hash),
479 'docker_image_migration',
481 order('links.created_at asc').
483 [l.tail_uuid, l.head_uuid]
486 migrated_collections = Hash[
487 Collection.readable_by(*readers).
488 where('portable_data_hash in (?)', migrations.values).
490 [c.portable_data_hash, c]
493 collections.map { |c|
494 # Check if the listed image is compatible first, if not, then try the
496 manifest = Keep::Manifest.new(c.manifest_text)
497 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
499 elsif m = migrated_collections[migrations[c.portable_data_hash]]
500 manifest = Keep::Manifest.new(m.manifest_text)
501 if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
508 # Resolve a Docker repo+tag, hash, or collection PDH to an array of
509 # Collection objects, sorted by timestamp starting with the most recent
512 # If filter_compatible_format is true (the default), only return image
513 # collections which are support by the installation as indicated by
514 # Rails.configuration.Containers.SupportedDockerImageFormats. Will follow
515 # 'docker_image_migration' links if search_term resolves to an incompatible
516 # image, but an equivalent compatible image is available.
517 def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
518 readers ||= [Thread.current[:user]]
520 readable_by(*readers).
521 readable_by(*readers, table_name: "collections").
522 joins("JOIN collections ON links.head_uuid = collections.uuid").
523 order("links.created_at DESC")
525 docker_image_formats = Rails.configuration.Containers.SupportedDockerImageFormats.keys.map(&:to_s)
527 if (docker_image_formats.include? 'v1' and
528 docker_image_formats.include? 'v2') or filter_compatible_format == false
529 pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
530 elsif docker_image_formats.include? 'v2'
531 pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
532 elsif docker_image_formats.include? 'v1'
533 pattern = /^[0-9A-Fa-f]{64}\.tar$/
535 raise "Unrecognized configuration for docker_image_formats #{docker_image_formats}"
538 # If the search term is a Collection locator that contains one file
539 # that looks like a Docker image, return it.
540 if loc = Keep::Locator.parse(search_term)
542 coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
543 rc = Rails.configuration.RemoteClusters.select{ |k|
544 k != :"*" && k != Rails.configuration.ClusterID}
545 if coll_match.any? or rc.length == 0
546 return get_compatible_images(readers, pattern, coll_match)
548 # Allow bare pdh that doesn't exist in the local database so
549 # that federated container requests which refer to remotely
550 # stored containers will validate.
551 return [Collection.new(portable_data_hash: loc.to_s)]
555 if search_tag.nil? and (n = search_term.index(":"))
556 search_tag = search_term[n+1..-1]
557 search_term = search_term[0..n-1]
560 # Find Collections with matching Docker image repository+tag pairs.
561 matches = base_search.
562 where(link_class: "docker_image_repo+tag",
563 name: "#{search_term}:#{search_tag || 'latest'}")
565 # If that didn't work, find Collections with matching Docker image hashes.
567 matches = base_search.
568 where("link_class = ? and links.name LIKE ?",
569 "docker_image_hash", "#{search_term}%")
572 # Generate an order key for each result. We want to order the results
573 # so that anything with an image timestamp is considered more recent than
574 # anything without; then we use the link's created_at as a tiebreaker.
576 matches.each do |link|
577 uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
578 -link.created_at.to_i]
581 sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
582 uuid_timestamps[c.uuid]
584 compatible = get_compatible_images(readers, pattern, sorted)
585 if sorted.length > 0 and compatible.empty?
586 raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
591 def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
592 find_all_for_docker_image(search_term, search_tag, readers).first
595 def self.searchable_columns operator
596 super - ["manifest_text"]
599 def self.full_text_searchable_columns
600 super - ["manifest_text", "storage_classes_desired", "storage_classes_confirmed", "current_version_uuid"]
604 SweepTrashedObjects.sweep_if_stale
610 # Although the defaults for these columns is already set up on the schema,
611 # collection creation from an API client seems to ignore them, making the
612 # validation on empty desired storage classes return an error.
613 def default_storage_classes
614 if self.storage_classes_desired.nil? || self.storage_classes_desired.empty?
615 self.storage_classes_desired = ["default"]
617 self.storage_classes_confirmed ||= []
620 # Sets managed properties at creation time
621 def managed_properties
622 managed_props = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
623 if managed_props.empty?
626 (managed_props.keys - self.properties.keys).each do |key|
627 if managed_props[key]['Function'] == 'original_owner'
628 self.properties[key] = self.user_owner_uuid
629 elsif managed_props[key]['Value']
630 self.properties[key] = managed_props[key]['Value']
632 logger.warn "Unidentified default property definition '#{key}': #{managed_props[key].inspect}"
637 def portable_manifest_text
638 self.class.munge_manifest_locators(manifest_text) do |match|
648 portable_manifest = portable_manifest_text
649 (Digest::MD5.hexdigest(portable_manifest) +
651 portable_manifest.bytesize.to_s)
655 if @computed_pdh_for_manifest_text == manifest_text
658 @computed_pdh = compute_pdh
659 @computed_pdh_for_manifest_text = manifest_text.dup
663 def ensure_permission_to_save
664 if (not current_user.andand.is_admin)
665 if (replication_confirmed_at_changed? or replication_confirmed_changed?) and
666 not (replication_confirmed_at.nil? and replication_confirmed.nil?)
667 raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
669 if (storage_classes_confirmed_changed? or storage_classes_confirmed_at_changed?) and
670 not (storage_classes_confirmed == [] and storage_classes_confirmed_at.nil?)
671 raise ArvadosModel::PermissionDeniedError.new("storage_classes_confirmed and storage_classes_confirmed_at attributes cannot be changed, except by setting them to [] and nil respectively")
677 def ensure_storage_classes_desired_is_not_empty
678 if self.storage_classes_desired.empty?
679 raise ArvadosModel::InvalidStateTransitionError.new("storage_classes_desired shouldn't be empty")
683 def ensure_storage_classes_contain_non_empty_strings
684 (self.storage_classes_desired + self.storage_classes_confirmed).each do |c|
685 if !c.is_a?(String) || c == ''
686 raise ArvadosModel::InvalidStateTransitionError.new("storage classes should only be non-empty strings")
691 def past_versions_cannot_be_updated
693 errors.add(:base, "past versions cannot be updated")
698 def protected_managed_properties_updates
699 managed_properties = Rails.configuration.Collections.ManagedProperties.with_indifferent_access
700 if managed_properties.empty? || !properties_changed? || current_user.is_admin
703 protected_props = managed_properties.keys.select do |p|
704 Rails.configuration.Collections.ManagedProperties[p]['Protected']
706 # Pre-existent protected properties can't be updated
707 invalid_updates = properties_was.keys.select{|p| properties_was[p] != properties[p]} & protected_props
708 if !invalid_updates.empty?
709 invalid_updates.each do |p|
710 errors.add("protected property cannot be updated:", p)
712 raise PermissionDeniedError.new
717 def versioning_metadata_updates
719 if !is_past_version? && current_version_uuid_changed?
720 errors.add(:current_version_uuid, "cannot be updated")
724 errors.add(:version, "cannot be updated")
732 self.current_version_uuid ||= self.uuid