Project

General

Profile

Hacking API server » History » Version 6

Tom Clegg, 05/09/2014 01:43 AM

1 1 Tom Clegg
h1. Hacking API server
2
3
{{toc}}
4
5
h2. Source tree layout
6
7
Everything is in @/services/api@.
8
9
Key pieces to know about before going much further:
10
11
|/|Usual Rails project layout|
12
|/app/controllers/application_controller.rb|Controller superclass with most of the generic API features like CRUD, authentication|
13
|/app/controllers/arvados/v1/|API methods other than generic CRUD (users#current, jobs#queue, ...)|
14
|/app/models/arvados_model.rb|Default Arvados model behavior: permissions, etag, uuid|
15
16
h2. Unlike a typical Rails project...
17
18
* Most responses are JSON. Very few HTML views. We don't normally talk to browsers, except during authentication.
19
* We assign UUID strings (see lib/assign_uuid.rb and app/models/arvados_model.rb)
20
* The @Links@ table emulates a graph database a la "RDF":http://www.rdfabout.com/quickintro.xpd. Much of the interesting information in Arvados is recorded as a Link between two other entities.
21
* For the most part, relations among objects are not expressed with the usual ActiveRelation features like belongs_to and has_many.
22
* Permissions: see below.
23
24
h2. Running in development mode
25
26
Save something like this at @~/bin/apiserver@, make it executable, make sure ~/bin is in your path:
27
28
 #!/bin/sh
29
set -e
30
cd ~/arvados/services/api
31
export RAILS_ENV=development
32
rvm-exec 2.0.0 bundle install
33 5 Tom Clegg
exec rvm-exec 2.0.0 bundle exec rails server --port=3030
34 1 Tom Clegg
35
h2. Headaches to avoid
36
37
If you make a change that affects the discovery document, you need to clear a few caches before your client will see the change.
38
* Restart API server or: @touch tmp/restart.txt@
39
* Clear API server disk cache: @rake tmp:cache:clear@
40
* Clear SDK discovery doc cache on client side: @rm -r ~/.cache/arvados/@
41
42 4 Tom Clegg
Do not store symbol keys (or values) in serialized attributes.
43
* Rails supplies @params@ as a HashWithIndifferentAccess so @params['foo']@ and @params[:foo]@ are equivalent. This is usually convenient. However, here we often copy arrays and hashes from @params@ to the database, and from there to API responses. JSON does not have HashWithIndifferentAccess (or symbols) and we want these serialized attributes to behave predictably everywhere.
44
* API server's policy is that serialized attributes (like @properties@ on a link) always have strings instead of symbols: these attributes look the same in the database, in the API server Rails application, in the JSON response sent to clients, and in the JSON objects received from clients.
45
* There is no validation (yet!) to check for this.
46
47
48 1 Tom Clegg
h2. Features
49
50
h3. Authentication
51
52
Involves
53
* UserSessionsController (in app/controllers/, not .../arvados/v1): this is an exceptional case where we actually talk to a browser.
54
55
h3. Permissions
56
57
Object-level permissions, aka ownership and sharing
58
* Models have their own idea of create/update permissions. Controllers don't worry about this.
59
* ArvadosModel updates/enforces modified_by_* and owner_uuid
60
* Lookups are not (yet) permission-restricted in the default scope, though. Controllers need to use Model.readable_by(user).
61
* ApplicationController uses an around_filter that verifies the supplied api_token and makes current_user available everywhere. If you need to override create/update permissions, use @act_as_system_user do ... end@.
62
* Unusual cases: KeepDisks and Collections can be looked up by inactive users (otherwise they wouldn't be able to read & clickthrough user agreements).
63
64
Controller-level permissions
65
* ApplicationController#require_auth_scope_all checks token scopes: currently, unless otherwise specified by a subclass controller, nothing is allowed unless scopes includes "all".
66
* ApplicationController has an admin_required filter available (not used by default)
67
68
h3. Error handling
69
70
* "Look up object by uuid, and send 404 if not found" is enabled by default, except for index/create actions.
71
72
h3. Routing
73
74
* API routes are in the @:arvados@ → @:v1@ namespace.
75
* Routes like @/jobs/queue@ have to come before @resources :jobs@ (otherwise @/jobs/queue@ will match @jobs#get(id=queue)@ first). (Better, we should rearrange these to use @resources :jobs do ...@ like in Workbench.)
76
* We use the standard Rails routes like @/jobs/:id@ but then we move params[:id] to params[:uuid] in our before_filters.
77
78
h3. Tests
79
80
* Run tests with @rvm-exec 2.0.0 bundle exec rake test RAILS_ENV=test@
81
* Functional tests need to authenticate themselves with @authorize_with :active@ (where @:active@ refers to an ApiClientAuthorization fixture)
82
* Big deficit of tests, especially unit tests. This is a bug! It doesn't mean we don't want to test things.
83
84
h3. Discovery document
85
86
* Mostly, but not yet completely, generated by introspection (descendants of ArvadosModel are inspected at run time). But some controllers/actions are skipped, and some actions are renamed (e.g., Rails calls it "show" but everyone else calls it "get").
87
* Handled by Arvados::V1::SchemaController#index (used to be in #discovery_document before #1750). See @config/routes.rb@
88
* Must be available to anonymous clients.
89
* Has no tests! We test it by trying all of our SDKs against it.
90
91
h2. Development patterns
92
93
h3. Add a model
94
95
In shell:
96
* @rails g model FizzBuzz@
97
98
In @app/models/fizzbuzz.rb@:
99
* Change base class from @ActiveRecord::Base@ to @ArvadosModel@.
100
* Add some more standard behavior.
101
102
<pre><code class="ruby">
103
include AssignUuid
104
include KindAndEtag
105
include CommonApiTemplate
106
</code></pre>
107
108
In @db/migrate/{timestamp}_create_fizzbuzzes.rb@:
109
* Add the generic attribute columns.
110
* Run @t.timestamps@ and add (at least!) a @:uuid@ index.
111
112
<pre><code class="ruby">
113
class CreateFizzBuzz < ActiveRecord::Migration
114
  def change
115
    create_table :fizzbuzzes do |t|
116
      t.string :uuid, :null => false
117
      t.string :owner_uuid, :null => false
118
      t.string :modified_by_client_uuid
119
      t.string :modified_by_user_uuid
120
      t.datetime :modified_at
121
      t.text :properties
122
123
      t.timestamps
124
    end
125
    add_index :humans, :uuid, :unique => true
126
  end
127
end
128
</code></pre>
129
130
Apply the migration:
131
* @rake db:migrate@
132
* @RAILS_ENV=test rake db:migrate@ (to migrate your test database too)
133
* Inspect the resulting @db/schema.rb@ and include it in your commit.
134
* Don't forget to @git add@ the new migration and model files.
135
136
h3. Add an attribute to a model
137
138
* Generate migration as usual
139
<pre>
140
rails g migration AddBazQuxToFooBar baz_qux:column_type_goes_here
141
</pre>
142
* Consider adding null constraints and a default value to the @add_column@ statement in the migration in @db/migrate/timestamp_add_baz_qux_to_foo_bar.rb@:
143
<pre><code class="ruby">, null: false, default: false</code></pre>
144
* Consider adding an index
145
* You probably want to add it to the API response template so clients can see it: @app/models/model_name.rb@ &rarr; @api_accessible :user ...@
146
* Sometimes it's only visible to privileged users; see @ping_secret@ in @app/models/keep_disk.rb@
147
* If it's a serialized attribute, add @serialize :the_attribute_name, Hash@ to the model. Always specify Hash or Array!
148
* Run @rake db:migrate@ and inspect your @db/schema.rb@ and include the new @schema.rb@ in the *same commit* as your @db/migrate/*.rb@ migration script.
149 3 Tom Clegg
* Run @rake tmp:cache:clear@ and @touch tmp/restart.txt@ in your dev apiserver, to force it to generate a new REST discovery document.
150 1 Tom Clegg
151
152
h3. Add a controller
153
154
* @rails g controller Arvados::V1::FizzBuzzesController@
155
* Avoid adding top-level controllers like @app/controllers/fizz_buzzes_controller.rb@.
156
* Avoid adding top-level routes. Everything should be in @namespace :arvados@ &rarr; @namespace :v1@ except oddballs like login/logout actions.
157
158
h3. Add a controller action
159
160
Add a route in @config/routes.rb@.
161
* Choose an appropriate HTTP method: GET has no side effects. POST creates something. PUT replaces/updates something.
162
* Use the block form:
163
<pre><code class="ruby">
164
resources :fizz_buzzes do
165
  # If the action operates on an object, i.e., a uuid is required,
166
  # this generates a route /arvados/v1/fizz_buzzes/{uuid}/blurfl
167
  post 'blurfl', on: :member
168
  # If not, this generates a route /arvados/v1/fizz_buzzes/flurbl
169
  get 'flurbl', on: :collection
170
end
171
</code></pre>
172
173
In @app/controllers/arvados/v1/fizz_buzzes_controller.rb@:
174
175
* Add a method to the controller class.
176
* Skip the "find_object" before_filters if it's a collection action.
177
* Specify required/optional parameters using a class method @_action_requires_parameters@.
178
<pre><code class="ruby">
179
skip_before_filter :find_object_by_uuid, only: [:flurbl]
180
skip_before_filter :render_404_if_no_object, only: [:flurbl]
181
182
def blurfl
183
  @object.do_whatever_blurfl_does!
184
  show
185
end
186
187
def self._flurbl_requires_parameters
188
  {
189
    qux: { type: 'integer', required: true, description: 'First flurbl qux must match this qux.' }
190
  }
191
end
192
def flurbl
193
  @object = model_class.where('qux = ?', params[:qux]).first
194
  show
195
end
196
</code></pre>
197
198
h3. Add a configuration parameter
199
200 6 Tom Clegg
* Add it to @config/application.default.yml@ with a sensible default value. (Don't fall back to default values at time of use, or define defaults in other places!)
201 1 Tom Clegg
* If there is no sensible default value, like @secret_token@: specify @~@ (i.e., nil) in @application.default.yml@ *and* put a default value in the @test@ section of @config/application.yml.example@ that will make tests pass.
202
* If there is a sensible default value for development/test but not for production, like return address for notification email messages, specify the test/dev default in the @common@ section @application.default.yml@ but specify @~@ (nil) in the @production@ section. This prevents someone from installing or *updating a production server* with defaults that don't make sense in production!
203
* Use @Rails.configuration.config_setting_name@ to retrieve the configured value. There is no need to check whether it is nil or missing: in those cases, "rake config:check" would have failed and the application would have refused to start.
204 6 Tom Clegg
205 2 Tom Clegg
206
h3. Add a test fixture
207
208
Generate last part of uuid from command line:
209
<pre><code class="ruby">ruby -e 'puts rand(2**512).to_s(36)[0..14]'
210
j0wqrlny07k1u12</code></pre>
211
Generate uuid from @rails console@:
212
<pre><code class="ruby">Group.generate_uuid
213
=> "xyzzy-j7d0g-8nw4r6gnnkixw1i"
214
</code></pre>