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