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