Merge branch 'master' into 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         parameters: {
63           alt: {
64             type: "string",
65             description: "Data format for the response.",
66             default: "json",
67             enum: [
68                    "json"
69                   ],
70             enumDescriptions: [
71                                "Responses with Content-Type of application/json"
72                               ],
73             location: "query"
74           },
75           fields: {
76             type: "string",
77             description: "Selector specifying which fields to include in a partial response.",
78             location: "query"
79           },
80           key: {
81             type: "string",
82             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.",
83             location: "query"
84           },
85           oauth_token: {
86             type: "string",
87             description: "OAuth 2.0 token for the current user.",
88             location: "query"
89           }
90         },
91         auth: {
92           oauth2: {
93             scopes: {
94               "https://api.curoverse.com/auth/arvados" => {
95                 description: "View and manage objects"
96               },
97               "https://api.curoverse.com/auth/arvados.readonly" => {
98                 description: "View objects"
99               }
100             }
101           }
102         },
103         schemas: {},
104         resources: {}
105       }
106
107       ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
108         begin
109           ctl_class = "Arvados::V1::#{k.to_s.pluralize}Controller".constantize
110         rescue
111           # No controller -> no discovery.
112           next
113         end
114         object_properties = {}
115         k.columns.
116           select { |col| col.name != 'id' }.
117           collect do |col|
118           if k.serialized_attributes.has_key? col.name
119             object_properties[col.name] = {
120               type: k.serialized_attributes[col.name].object_class.to_s
121             }
122           else
123             object_properties[col.name] = {
124               type: col.type
125             }
126           end
127         end
128         discovery[:schemas][k.to_s + 'List'] = {
129           id: k.to_s + 'List',
130           description: k.to_s + ' list',
131           type: "object",
132           properties: {
133             kind: {
134               type: "string",
135               description: "Object type. Always arvados##{k.to_s.camelcase(:lower)}List.",
136               default: "arvados##{k.to_s.camelcase(:lower)}List"
137             },
138             etag: {
139               type: "string",
140               description: "List version."
141             },
142             items: {
143               type: "array",
144               description: "The list of #{k.to_s.pluralize}.",
145               items: {
146                 "$ref" => k.to_s
147               }
148             },
149             next_link: {
150               type: "string",
151               description: "A link to the next page of #{k.to_s.pluralize}."
152             },
153             next_page_token: {
154               type: "string",
155               description: "The page token for the next page of #{k.to_s.pluralize}."
156             },
157             selfLink: {
158               type: "string",
159               description: "A link back to this list."
160             }
161           }
162         }
163         discovery[:schemas][k.to_s] = {
164           id: k.to_s,
165           description: k.to_s,
166           type: "object",
167           uuidPrefix: (k.respond_to?(:uuid_prefix) ? k.uuid_prefix : nil),
168           properties: {
169             uuid: {
170               type: "string",
171               description: "Object ID."
172             },
173             etag: {
174               type: "string",
175               description: "Object version."
176             }
177           }.merge(object_properties)
178         }
179         discovery[:resources][k.to_s.underscore.pluralize] = {
180           methods: {
181             get: {
182               id: "arvados.#{k.to_s.underscore.pluralize}.get",
183               path: "#{k.to_s.underscore.pluralize}/{uuid}",
184               httpMethod: "GET",
185               description: "Gets a #{k.to_s}'s metadata by UUID.",
186               parameters: {
187                 uuid: {
188                   type: "string",
189                   description: "The UUID of the #{k.to_s} in question.",
190                   required: true,
191                   location: "path"
192                 }
193               },
194               parameterOrder: [
195                                "uuid"
196                               ],
197               response: {
198                 "$ref" => k.to_s
199               },
200               scopes: [
201                        "https://api.curoverse.com/auth/arvados",
202                        "https://api.curoverse.com/auth/arvados.readonly"
203                       ]
204             },
205             index: {
206               id: "arvados.#{k.to_s.underscore.pluralize}.index",
207               path: k.to_s.underscore.pluralize,
208               httpMethod: "GET",
209               description:
210                  %|Index #{k.to_s.pluralize}.
211
212                    The <code>index</code> method returns a
213                    <a href="/api/resources.html">resource list</a> of
214                    matching #{k.to_s.pluralize}. For example:
215
216                    <pre>
217                    {
218                     "kind":"arvados##{k.to_s.camelcase(:lower)}List",
219                     "etag":"",
220                     "self_link":"",
221                     "next_page_token":"",
222                     "next_link":"",
223                     "items":[
224                        ...
225                     ],
226                     "items_available":745,
227                     "_profile":{
228                      "request_time":0.157236317
229                     }
230                     </pre>|,
231               parameters: {
232               },
233               response: {
234                 "$ref" => "#{k.to_s}List"
235               },
236               scopes: [
237                        "https://api.curoverse.com/auth/arvados",
238                        "https://api.curoverse.com/auth/arvados.readonly"
239                       ]
240             },
241             create: {
242               id: "arvados.#{k.to_s.underscore.pluralize}.create",
243               path: "#{k.to_s.underscore.pluralize}",
244               httpMethod: "POST",
245               description: "Create a new #{k.to_s}.",
246               parameters: {},
247               request: {
248                 required: true,
249                 properties: {
250                   k.to_s.underscore => {
251                     "$ref" => k.to_s
252                   }
253                 }
254               },
255               response: {
256                 "$ref" => k.to_s
257               },
258               scopes: [
259                        "https://api.curoverse.com/auth/arvados"
260                       ]
261             },
262             update: {
263               id: "arvados.#{k.to_s.underscore.pluralize}.update",
264               path: "#{k.to_s.underscore.pluralize}/{uuid}",
265               httpMethod: "PUT",
266               description: "Update attributes of an existing #{k.to_s}.",
267               parameters: {
268                 uuid: {
269                   type: "string",
270                   description: "The UUID of the #{k.to_s} in question.",
271                   required: true,
272                   location: "path"
273                 }
274               },
275               request: {
276                 required: true,
277                 properties: {
278                   k.to_s.underscore => {
279                     "$ref" => k.to_s
280                   }
281                 }
282               },
283               response: {
284                 "$ref" => k.to_s
285               },
286               scopes: [
287                        "https://api.curoverse.com/auth/arvados"
288                       ]
289             },
290             delete: {
291               id: "arvados.#{k.to_s.underscore.pluralize}.delete",
292               path: "#{k.to_s.underscore.pluralize}/{uuid}",
293               httpMethod: "DELETE",
294               description: "Delete an existing #{k.to_s}.",
295               parameters: {
296                 uuid: {
297                   type: "string",
298                   description: "The UUID of the #{k.to_s} in question.",
299                   required: true,
300                   location: "path"
301                 }
302               },
303               response: {
304                 "$ref" => k.to_s
305               },
306               scopes: [
307                        "https://api.curoverse.com/auth/arvados"
308                       ]
309             }
310           }
311         }
312         # Check for Rails routes that don't match the usual actions
313         # listed above
314         d_methods = discovery[:resources][k.to_s.underscore.pluralize][:methods]
315         Rails.application.routes.routes.each do |route|
316           action = route.defaults[:action]
317           httpMethod = ['GET', 'POST', 'PUT', 'DELETE'].map { |method|
318             method if route.verb.match(method)
319           }.compact.first
320           if httpMethod and
321               route.defaults[:controller] == 'arvados/v1/' + k.to_s.underscore.pluralize and
322               ctl_class.action_methods.include? action
323             if !d_methods[action.to_sym]
324               method = {
325                 id: "arvados.#{k.to_s.underscore.pluralize}.#{action}",
326                 path: route.path.spec.to_s.sub('/arvados/v1/','').sub('(.:format)','').sub(/:(uu)?id/,'{uuid}'),
327                 httpMethod: httpMethod,
328                 description: "#{action} #{k.to_s.underscore.pluralize}",
329                 parameters: {},
330                 response: {
331                   "$ref" => (action == 'index' ? "#{k.to_s}List" : k.to_s)
332                 },
333                 scopes: [
334                          "https://api.curoverse.com/auth/arvados"
335                         ]
336               }
337               route.segment_keys.each do |key|
338                 if key != :format
339                   key = :uuid if key == :id
340                   method[:parameters][key] = {
341                     type: "string",
342                     description: "",
343                     required: true,
344                     location: "path"
345                   }
346                 end
347               end
348             else
349               # We already built a generic method description, but we
350               # might find some more required parameters through
351               # introspection.
352               method = d_methods[action.to_sym]
353             end
354             if ctl_class.respond_to? "_#{action}_requires_parameters".to_sym
355               ctl_class.send("_#{action}_requires_parameters".to_sym).each do |l, v|
356                 if v.is_a? Hash
357                   method[:parameters][l] = v
358                 else
359                   method[:parameters][l] = {}
360                 end
361                 if !method[:parameters][l][:default].nil?
362                   # The JAVA SDK is sensitive to all values being strings
363                   method[:parameters][l][:default] = method[:parameters][l][:default].to_s
364                 end
365                 method[:parameters][l][:type] ||= 'string'
366                 method[:parameters][l][:description] ||= ''
367                 method[:parameters][l][:location] = (route.segment_keys.include?(l) ? 'path' : 'query')
368                 if method[:parameters][l][:required].nil?
369                   method[:parameters][l][:required] = v != false
370                 end
371               end
372             end
373             d_methods[action.to_sym] = method
374
375             if action == 'index'
376               list_method = method.dup
377               list_method[:id].sub!('index', 'list')
378               list_method[:description].sub!('Index', 'List')
379               list_method[:description].sub!('index', 'list')
380               d_methods[:list] = list_method
381             end
382           end
383         end
384       end
385       Rails.configuration.disable_api_methods.each do |method|
386         ctrl, action = method.split('.', 2)
387         discovery[:resources][ctrl][:methods].delete(action.to_sym)
388       end
389       discovery
390     end
391   end
392 end