Merge branch '3720-big-manifest-performance-wip'
[arvados.git] / services / api / app / models / collection.rb
1 require 'arvados/keep'
2
3 class Collection < ArvadosModel
4   include HasUuid
5   include KindAndEtag
6   include CommonApiTemplate
7
8   before_validation :check_signatures
9   before_validation :strip_manifest_text
10   before_validation :set_portable_data_hash
11   validate :ensure_hash_matches_manifest_text
12
13   api_accessible :user, extend: :common do |t|
14     t.add :name
15     t.add :description
16     t.add :properties
17     t.add :portable_data_hash
18     t.add :manifest_text
19   end
20
21   def check_signatures
22     return false if self.manifest_text.nil?
23
24     return true if current_user.andand.is_admin
25
26     if self.manifest_text_changed?
27       # Check permissions on the collection manifest.
28       # If any signature cannot be verified, raise PermissionDeniedError
29       # which will return 403 Permission denied to the client.
30       api_token = current_api_client_authorization.andand.api_token
31       signing_opts = {
32         key: Rails.configuration.blob_signing_key,
33         api_token: api_token,
34         ttl: Rails.configuration.blob_signing_ttl,
35       }
36       self.manifest_text.lines.each do |entry|
37         entry.split[1..-1].each do |tok|
38           if /^[[:digit:]]+:[[:digit:]]+:/.match tok
39             # This is a filename token, not a blob locator. Note that we
40             # keep checking tokens after this, even though manifest
41             # format dictates that all subsequent tokens will also be
42             # filenames. Safety first!
43           elsif Blob.verify_signature tok, signing_opts
44             # OK.
45           elsif Keep::Locator.parse(tok).andand.signature
46             # Signature provided, but verify_signature did not like it.
47             logger.warn "Invalid signature on locator #{tok}"
48             raise ArvadosModel::PermissionDeniedError
49           elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
50             # No signature provided, but we are running in insecure mode.
51             logger.debug "Missing signature on locator #{tok} ignored"
52           elsif Blob.new(tok).empty?
53             # No signature provided -- but no data to protect, either.
54           else
55             logger.warn "Missing signature on locator #{tok}"
56             raise ArvadosModel::PermissionDeniedError
57           end
58         end
59       end
60     end
61     true
62   end
63
64   def strip_manifest_text
65     if self.manifest_text_changed?
66       # Remove any permission signatures from the manifest.
67       Collection.munge_manifest_locators(self[:manifest_text]) do |loc|
68         loc.without_signature.to_s
69       end
70     end
71     true
72   end
73
74   def set_portable_data_hash
75     if (self.portable_data_hash.nil? or (self.portable_data_hash == "") or (manifest_text_changed? and !portable_data_hash_changed?))
76       self.portable_data_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.length}"
77     elsif portable_data_hash_changed?
78       begin
79         loc = Keep::Locator.parse!(self.portable_data_hash)
80         loc.strip_hints!
81         if loc.size
82           self.portable_data_hash = loc.to_s
83         else
84           self.portable_data_hash = "#{loc.hash}+#{self.manifest_text.length}"
85         end
86       rescue ArgumentError => e
87         errors.add(:portable_data_hash, "#{e}")
88         return false
89       end
90     end
91     true
92   end
93
94   def ensure_hash_matches_manifest_text
95     if manifest_text_changed? or portable_data_hash_changed?
96       computed_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.length}"
97       unless computed_hash == portable_data_hash
98         logger.debug "(computed) '#{computed_hash}' != '#{portable_data_hash}' (provided)"
99         errors.add(:portable_data_hash, "does not match hash of manifest_text")
100         return false
101       end
102     end
103     true
104   end
105
106   def redundancy_status
107     if redundancy_confirmed_as.nil?
108       'unconfirmed'
109     elsif redundancy_confirmed_as < redundancy
110       'degraded'
111     else
112       if redundancy_confirmed_at.nil?
113         'unconfirmed'
114       elsif Time.now - redundancy_confirmed_at < 7.days
115         'OK'
116       else
117         'stale'
118       end
119     end
120   end
121
122   def self.munge_manifest_locators(manifest)
123     # Given a manifest text and a block, yield each locator,
124     # and replace it with whatever the block returns.
125     manifest.andand.gsub!(/ [[:xdigit:]]{32}(\+[[:digit:]]+)?(\+\S+)/) do |word|
126       if loc = Keep::Locator.parse(word.strip)
127         " " + yield(loc)
128       else
129         " " + word
130       end
131     end
132   end
133
134   def self.normalize_uuid uuid
135     hash_part = nil
136     size_part = nil
137     uuid.split('+').each do |token|
138       if token.match /^[0-9a-f]{32,}$/
139         raise "uuid #{uuid} has multiple hash parts" if hash_part
140         hash_part = token
141       elsif token.match /^\d+$/
142         raise "uuid #{uuid} has multiple size parts" if size_part
143         size_part = token
144       end
145     end
146     raise "uuid #{uuid} has no hash part" if !hash_part
147     [hash_part, size_part].compact.join '+'
148   end
149
150   # Return array of Collection objects
151   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
152     readers ||= [Thread.current[:user]]
153     base_search = Link.
154       readable_by(*readers).
155       readable_by(*readers, table_name: "collections").
156       joins("JOIN collections ON links.head_uuid = collections.uuid").
157       order("links.created_at DESC")
158
159     # If the search term is a Collection locator that contains one file
160     # that looks like a Docker image, return it.
161     if loc = Keep::Locator.parse(search_term)
162       loc.strip_hints!
163       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
164       if coll_match
165         # Check if the Collection contains exactly one file whose name
166         # looks like a saved Docker image.  We only take up to two
167         # files, because any number >1 means there's no match.
168         coll_files = Keep::Manifest.new(coll_match.manifest_text).each_file.take(2)
169         if (coll_files.size == 1) and
170             (coll_files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
171           return [coll_match]
172         end
173       end
174     end
175
176     if search_tag.nil? and (n = search_term.index(":"))
177       search_tag = search_term[n+1..-1]
178       search_term = search_term[0..n-1]
179     end
180
181     # Find Collections with matching Docker image repository+tag pairs.
182     matches = base_search.
183       where(link_class: "docker_image_repo+tag",
184             name: "#{search_term}:#{search_tag || 'latest'}")
185
186     # If that didn't work, find Collections with matching Docker image hashes.
187     if matches.empty?
188       matches = base_search.
189         where("link_class = ? and links.name LIKE ?",
190               "docker_image_hash", "#{search_term}%")
191     end
192
193     # Generate an order key for each result.  We want to order the results
194     # so that anything with an image timestamp is considered more recent than
195     # anything without; then we use the link's created_at as a tiebreaker.
196     uuid_timestamps = {}
197     matches.all.map do |link|
198       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
199        -link.created_at.to_i]
200     end
201     Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
202   end
203
204   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
205     find_all_for_docker_image(search_term, search_tag, readers).first
206   end
207 end