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