Merge branch '11453-federated-tokens'
[arvados.git] / services / api / app / controllers / arvados / v1 / schema_controller.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 class Arvados::V1::SchemaController < ApplicationController
6   skip_before_filter :catch_redirect_hint
7   skip_before_filter :find_objects_for_index
8   skip_before_filter :find_object_by_uuid
9   skip_before_filter :load_filters_param
10   skip_before_filter :load_limit_offset_order_params
11   skip_before_filter :load_read_auths
12   skip_before_filter :load_where_param
13   skip_before_filter :render_404_if_no_object
14   skip_before_filter :require_auth_scope
15
16   include DbCurrentTime
17
18   def index
19     expires_in 24.hours, public: true
20     send_json discovery_doc
21   end
22
23   protected
24
25   def discovery_doc
26     Rails.cache.fetch 'arvados_v1_rest_discovery' do
27       Rails.application.eager_load!
28       discovery = {
29         kind: "discovery#restDescription",
30         discoveryVersion: "v1",
31         id: "arvados:v1",
32         name: "arvados",
33         version: "v1",
34         revision: "20131114",
35         source_version: AppVersion.hash,
36         generatedAt: db_current_time.iso8601,
37         title: "Arvados API",
38         description: "The API to interact with Arvados.",
39         documentationLink: "http://doc.arvados.org/api/index.html",
40         defaultCollectionReplication: Rails.configuration.default_collection_replication,
41         protocol: "rest",
42         baseUrl: root_url + "arvados/v1/",
43         basePath: "/arvados/v1/",
44         rootUrl: root_url,
45         servicePath: "arvados/v1/",
46         batchPath: "batch",
47         defaultTrashLifetime: Rails.application.config.default_trash_lifetime,
48         blobSignatureTtl: Rails.application.config.blob_signature_ttl,
49         maxRequestSize: Rails.application.config.max_request_size,
50         dockerImageFormats: Rails.application.config.docker_image_formats,
51         crunchLogBytesPerEvent: Rails.application.config.crunch_log_bytes_per_event,
52         crunchLogSecondsBetweenEvents: Rails.application.config.crunch_log_seconds_between_events,
53         crunchLogThrottlePeriod: Rails.application.config.crunch_log_throttle_period,
54         crunchLogThrottleBytes: Rails.application.config.crunch_log_throttle_bytes,
55         crunchLogThrottleLines: Rails.application.config.crunch_log_throttle_lines,
56         crunchLimitLogBytesPerJob: Rails.application.config.crunch_limit_log_bytes_per_job,
57         crunchLogPartialLineThrottlePeriod: Rails.application.config.crunch_log_partial_line_throttle_period,
58         remoteHosts: Rails.configuration.remote_hosts,
59         remoteHostsViaDNS: Rails.configuration.remote_hosts_via_dns,
60         websocketUrl: Rails.application.config.websocket_address,
61         workbenchUrl: Rails.application.config.workbench_address,
62         keepWebServiceUrl: Rails.application.config.keep_web_service_url,
63         parameters: {
64           alt: {
65             type: "string",
66             description: "Data format for the response.",
67             default: "json",
68             enum: [
69                    "json"
70                   ],
71             enumDescriptions: [
72                                "Responses with Content-Type of application/json"
73                               ],
74             location: "query"
75           },
76           fields: {
77             type: "string",
78             description: "Selector specifying which fields to include in a partial response.",
79             location: "query"
80           },
81           key: {
82             type: "string",
83             description: "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.",
84             location: "query"
85           },
86           oauth_token: {
87             type: "string",
88             description: "OAuth 2.0 token for the current user.",
89             location: "query"
90           }
91         },
92         auth: {
93           oauth2: {
94             scopes: {
95               "https://api.curoverse.com/auth/arvados" => {
96                 description: "View and manage objects"
97               },
98               "https://api.curoverse.com/auth/arvados.readonly" => {
99                 description: "View objects"
100               }
101             }
102           }
103         },
104         schemas: {},
105         resources: {}
106       }
107
108       ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
109         begin
110           ctl_class = "Arvados::V1::#{k.to_s.pluralize}Controller".constantize
111         rescue
112           # No controller -> no discovery.
113           next
114         end
115         object_properties = {}
116         k.columns.
117           select { |col| col.name != 'id' }.
118           collect do |col|
119           if k.serialized_attributes.has_key? col.name
120             object_properties[col.name] = {
121               type: k.serialized_attributes[col.name].object_class.to_s
122             }
123           else
124             object_properties[col.name] = {
125               type: col.type
126             }
127           end
128         end
129         discovery[:schemas][k.to_s + 'List'] = {
130           id: k.to_s + 'List',
131           description: k.to_s + ' list',
132           type: "object",
133           properties: {
134             kind: {
135               type: "string",
136               description: "Object type. Always arvados##{k.to_s.camelcase(:lower)}List.",
137               default: "arvados##{k.to_s.camelcase(:lower)}List"
138             },
139             etag: {
140               type: "string",
141               description: "List version."
142             },
143             items: {
144               type: "array",
145               description: "The list of #{k.to_s.pluralize}.",
146               items: {
147                 "$ref" => k.to_s
148               }
149             },
150             next_link: {
151               type: "string",
152               description: "A link to the next page of #{k.to_s.pluralize}."
153             },
154             next_page_token: {
155               type: "string",
156               description: "The page token for the next page of #{k.to_s.pluralize}."
157             },
158             selfLink: {
159               type: "string",
160               description: "A link back to this list."
161             }
162           }
163         }
164         discovery[:schemas][k.to_s] = {
165           id: k.to_s,
166           description: k.to_s,
167           type: "object",
168           uuidPrefix: (k.respond_to?(:uuid_prefix) ? k.uuid_prefix : nil),
169           properties: {
170             uuid: {
171               type: "string",
172               description: "Object ID."
173             },
174             etag: {
175               type: "string",
176               description: "Object version."
177             }
178           }.merge(object_properties)
179         }
180         discovery[:resources][k.to_s.underscore.pluralize] = {
181           methods: {
182             get: {
183               id: "arvados.#{k.to_s.underscore.pluralize}.get",
184               path: "#{k.to_s.underscore.pluralize}/{uuid}",
185               httpMethod: "GET",
186               description: "Gets a #{k.to_s}'s metadata by UUID.",
187               parameters: {
188                 uuid: {
189                   type: "string",
190                   description: "The UUID of the #{k.to_s} in question.",
191                   required: true,
192                   location: "path"
193                 }
194               },
195               parameterOrder: [
196                                "uuid"
197                               ],
198               response: {
199                 "$ref" => k.to_s
200               },
201               scopes: [
202                        "https://api.curoverse.com/auth/arvados",
203                        "https://api.curoverse.com/auth/arvados.readonly"
204                       ]
205             },
206             index: {
207               id: "arvados.#{k.to_s.underscore.pluralize}.index",
208               path: k.to_s.underscore.pluralize,
209               httpMethod: "GET",
210               description:
211                  %|Index #{k.to_s.pluralize}.
212
213                    The <code>index</code> method returns a
214                    <a href="/api/resources.html">resource list</a> of
215                    matching #{k.to_s.pluralize}. For example:
216
217                    <pre>
218                    {
219                     "kind":"arvados##{k.to_s.camelcase(:lower)}List",
220                     "etag":"",
221                     "self_link":"",
222                     "next_page_token":"",
223                     "next_link":"",
224                     "items":[
225                        ...
226                     ],
227                     "items_available":745,
228                     "_profile":{
229                      "request_time":0.157236317
230                     }
231                     </pre>|,
232               parameters: {
233               },
234               response: {
235                 "$ref" => "#{k.to_s}List"
236               },
237               scopes: [
238                        "https://api.curoverse.com/auth/arvados",
239                        "https://api.curoverse.com/auth/arvados.readonly"
240                       ]
241             },
242             create: {
243               id: "arvados.#{k.to_s.underscore.pluralize}.create",
244               path: "#{k.to_s.underscore.pluralize}",
245               httpMethod: "POST",
246               description: "Create a new #{k.to_s}.",
247               parameters: {},
248               request: {
249                 required: true,
250                 properties: {
251                   k.to_s.underscore => {
252                     "$ref" => k.to_s
253                   }
254                 }
255               },
256               response: {
257                 "$ref" => k.to_s
258               },
259               scopes: [
260                        "https://api.curoverse.com/auth/arvados"
261                       ]
262             },
263             update: {
264               id: "arvados.#{k.to_s.underscore.pluralize}.update",
265               path: "#{k.to_s.underscore.pluralize}/{uuid}",
266               httpMethod: "PUT",
267               description: "Update attributes of an existing #{k.to_s}.",
268               parameters: {
269                 uuid: {
270                   type: "string",
271                   description: "The UUID of the #{k.to_s} in question.",
272                   required: true,
273                   location: "path"
274                 }
275               },
276               request: {
277                 required: true,
278                 properties: {
279                   k.to_s.underscore => {
280                     "$ref" => k.to_s
281                   }
282                 }
283               },
284               response: {
285                 "$ref" => k.to_s
286               },
287               scopes: [
288                        "https://api.curoverse.com/auth/arvados"
289                       ]
290             },
291             delete: {
292               id: "arvados.#{k.to_s.underscore.pluralize}.delete",
293               path: "#{k.to_s.underscore.pluralize}/{uuid}",
294               httpMethod: "DELETE",
295               description: "Delete an existing #{k.to_s}.",
296               parameters: {
297                 uuid: {
298                   type: "string",
299                   description: "The UUID of the #{k.to_s} in question.",
300                   required: true,
301                   location: "path"
302                 }
303               },
304               response: {
305                 "$ref" => k.to_s
306               },
307               scopes: [
308                        "https://api.curoverse.com/auth/arvados"
309                       ]
310             }
311           }
312         }
313         # Check for Rails routes that don't match the usual actions
314         # listed above
315         d_methods = discovery[:resources][k.to_s.underscore.pluralize][:methods]
316         Rails.application.routes.routes.each do |route|
317           action = route.defaults[:action]
318           httpMethod = ['GET', 'POST', 'PUT', 'DELETE'].map { |method|
319             method if route.verb.match(method)
320           }.compact.first
321           if httpMethod and
322               route.defaults[:controller] == 'arvados/v1/' + k.to_s.underscore.pluralize and
323               ctl_class.action_methods.include? action
324             if !d_methods[action.to_sym]
325               method = {
326                 id: "arvados.#{k.to_s.underscore.pluralize}.#{action}",
327                 path: route.path.spec.to_s.sub('/arvados/v1/','').sub('(.:format)','').sub(/:(uu)?id/,'{uuid}'),
328                 httpMethod: httpMethod,
329                 description: "#{action} #{k.to_s.underscore.pluralize}",
330                 parameters: {},
331                 response: {
332                   "$ref" => (action == 'index' ? "#{k.to_s}List" : k.to_s)
333                 },
334                 scopes: [
335                          "https://api.curoverse.com/auth/arvados"
336                         ]
337               }
338               route.segment_keys.each do |key|
339                 if key != :format
340                   key = :uuid if key == :id
341                   method[:parameters][key] = {
342                     type: "string",
343                     description: "",
344                     required: true,
345                     location: "path"
346                   }
347                 end
348               end
349             else
350               # We already built a generic method description, but we
351               # might find some more required parameters through
352               # introspection.
353               method = d_methods[action.to_sym]
354             end
355             if ctl_class.respond_to? "_#{action}_requires_parameters".to_sym
356               ctl_class.send("_#{action}_requires_parameters".to_sym).each do |l, v|
357                 if v.is_a? Hash
358                   method[:parameters][l] = v
359                 else
360                   method[:parameters][l] = {}
361                 end
362                 if !method[:parameters][l][:default].nil?
363                   # The JAVA SDK is sensitive to all values being strings
364                   method[:parameters][l][:default] = method[:parameters][l][:default].to_s
365                 end
366                 method[:parameters][l][:type] ||= 'string'
367                 method[:parameters][l][:description] ||= ''
368                 method[:parameters][l][:location] = (route.segment_keys.include?(l) ? 'path' : 'query')
369                 if method[:parameters][l][:required].nil?
370                   method[:parameters][l][:required] = v != false
371                 end
372               end
373             end
374             d_methods[action.to_sym] = method
375
376             if action == 'index'
377               list_method = method.dup
378               list_method[:id].sub!('index', 'list')
379               list_method[:description].sub!('Index', 'List')
380               list_method[:description].sub!('index', 'list')
381               d_methods[:list] = list_method
382             end
383           end
384         end
385       end
386       Rails.configuration.disable_api_methods.each do |method|
387         ctrl, action = method.split('.', 2)
388         discovery[:resources][ctrl][:methods].delete(action.to_sym)
389       end
390       discovery
391     end
392   end
393 end