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