Project

General

Profile

Hacking API server » History » Version 4

Tom Clegg, 04/23/2014 12:05 PM

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
SDKs really want your server to offer SSL. One way is to generate a self-signed certificate.
27
28
 openssl req -new -x509 -nodes -out ~/self-signed.pem -keyout ~/self-signed.key -days 3650 -subj '/CN=arvados.example.com'
29
30
Save something like this at @~/bin/apiserver@, make it executable, make sure ~/bin is in your path:
31
32
 #!/bin/sh
33
set -e
34
cd ~/arvados/services/api
35
export RAILS_ENV=development
36
rvm-exec 2.0.0 bundle install
37
exec rvm-exec 2.0.0 bundle exec passenger start --ssl --ssl-certificate ~/self-signed.pem --ssl-certificate-key ~/self-signed.key
38
39
h2. Headaches to avoid
40
41
If you make a change that affects the discovery document, you need to clear a few caches before your client will see the change.
42
* Restart API server or: @touch tmp/restart.txt@
43
* Clear API server disk cache: @rake tmp:cache:clear@
44
* Clear SDK discovery doc cache on client side: @rm -r ~/.cache/arvados/@
45
46 4 Tom Clegg
Do not store symbol keys (or values) in serialized attributes.
47
* 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.
48
* 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.
49
* There is no validation (yet!) to check for this.
50
51
52 1 Tom Clegg
h2. Features
53
54
h3. Authentication
55
56
Involves
57
* UserSessionsController (in app/controllers/, not .../arvados/v1): this is an exceptional case where we actually talk to a browser.
58
59
h3. Permissions
60
61
Object-level permissions, aka ownership and sharing
62
* Models have their own idea of create/update permissions. Controllers don't worry about this.
63
* ArvadosModel updates/enforces modified_by_* and owner_uuid
64
* Lookups are not (yet) permission-restricted in the default scope, though. Controllers need to use Model.readable_by(user).
65
* 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@.
66
* Unusual cases: KeepDisks and Collections can be looked up by inactive users (otherwise they wouldn't be able to read & clickthrough user agreements).
67
68
Controller-level permissions
69
* ApplicationController#require_auth_scope_all checks token scopes: currently, unless otherwise specified by a subclass controller, nothing is allowed unless scopes includes "all".
70
* ApplicationController has an admin_required filter available (not used by default)
71
72
h3. Error handling
73
74
* "Look up object by uuid, and send 404 if not found" is enabled by default, except for index/create actions.
75
76
h3. Routing
77
78
* API routes are in the @:arvados@ → @:v1@ namespace.
79
* 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.)
80
* We use the standard Rails routes like @/jobs/:id@ but then we move params[:id] to params[:uuid] in our before_filters.
81
82
h3. Tests
83
84
* Run tests with @rvm-exec 2.0.0 bundle exec rake test RAILS_ENV=test@
85
* Functional tests need to authenticate themselves with @authorize_with :active@ (where @:active@ refers to an ApiClientAuthorization fixture)
86
* Big deficit of tests, especially unit tests. This is a bug! It doesn't mean we don't want to test things.
87
88
h3. Discovery document
89
90
* 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").
91
* Handled by Arvados::V1::SchemaController#index (used to be in #discovery_document before #1750). See @config/routes.rb@
92
* Must be available to anonymous clients.
93
* Has no tests! We test it by trying all of our SDKs against it.
94
95
h2. Development patterns
96
97
h3. Add a model
98
99
In shell:
100
* @rails g model FizzBuzz@
101
102
In @app/models/fizzbuzz.rb@:
103
* Change base class from @ActiveRecord::Base@ to @ArvadosModel@.
104
* Add some more standard behavior.
105
106
<pre><code class="ruby">
107
include AssignUuid
108
include KindAndEtag
109
include CommonApiTemplate
110
</code></pre>
111
112
In @db/migrate/{timestamp}_create_fizzbuzzes.rb@:
113
* Add the generic attribute columns.
114
* Run @t.timestamps@ and add (at least!) a @:uuid@ index.
115
116
<pre><code class="ruby">
117
class CreateFizzBuzz < ActiveRecord::Migration
118
  def change
119
    create_table :fizzbuzzes do |t|
120
      t.string :uuid, :null => false
121
      t.string :owner_uuid, :null => false
122
      t.string :modified_by_client_uuid
123
      t.string :modified_by_user_uuid
124
      t.datetime :modified_at
125
      t.text :properties
126
127
      t.timestamps
128
    end
129
    add_index :humans, :uuid, :unique => true
130
  end
131
end
132
</code></pre>
133
134
Apply the migration:
135
* @rake db:migrate@
136
* @RAILS_ENV=test rake db:migrate@ (to migrate your test database too)
137
* Inspect the resulting @db/schema.rb@ and include it in your commit.
138
* Don't forget to @git add@ the new migration and model files.
139
140
h3. Add an attribute to a model
141
142
* Generate migration as usual
143
<pre>
144
rails g migration AddBazQuxToFooBar baz_qux:column_type_goes_here
145
</pre>
146
* 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@:
147
<pre><code class="ruby">, null: false, default: false</code></pre>
148
* Consider adding an index
149
* 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 ...@
150
* Sometimes it's only visible to privileged users; see @ping_secret@ in @app/models/keep_disk.rb@
151
* If it's a serialized attribute, add @serialize :the_attribute_name, Hash@ to the model. Always specify Hash or Array!
152
* 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.
153 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.
154 1 Tom Clegg
155
156
h3. Add a controller
157
158
* @rails g controller Arvados::V1::FizzBuzzesController@
159
* Avoid adding top-level controllers like @app/controllers/fizz_buzzes_controller.rb@.
160
* Avoid adding top-level routes. Everything should be in @namespace :arvados@ &rarr; @namespace :v1@ except oddballs like login/logout actions.
161
162
h3. Add a controller action
163
164
Add a route in @config/routes.rb@.
165
* Choose an appropriate HTTP method: GET has no side effects. POST creates something. PUT replaces/updates something.
166
* Use the block form:
167
<pre><code class="ruby">
168
resources :fizz_buzzes do
169
  # If the action operates on an object, i.e., a uuid is required,
170
  # this generates a route /arvados/v1/fizz_buzzes/{uuid}/blurfl
171
  post 'blurfl', on: :member
172
  # If not, this generates a route /arvados/v1/fizz_buzzes/flurbl
173
  get 'flurbl', on: :collection
174
end
175
</code></pre>
176
177
In @app/controllers/arvados/v1/fizz_buzzes_controller.rb@:
178
179
* Add a method to the controller class.
180
* Skip the "find_object" before_filters if it's a collection action.
181
* Specify required/optional parameters using a class method @_action_requires_parameters@.
182
<pre><code class="ruby">
183
skip_before_filter :find_object_by_uuid, only: [:flurbl]
184
skip_before_filter :render_404_if_no_object, only: [:flurbl]
185
186
def blurfl
187
  @object.do_whatever_blurfl_does!
188
  show
189
end
190
191
def self._flurbl_requires_parameters
192
  {
193
    qux: { type: 'integer', required: true, description: 'First flurbl qux must match this qux.' }
194
  }
195
end
196
def flurbl
197
  @object = model_class.where('qux = ?', params[:qux]).first
198
  show
199
end
200
</code></pre>
201
202
h3. Add a configuration parameter
203
204
* Add it to @config/application.default.yml@ with a sensible default value.
205
* 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.
206
* 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!
207
* 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.
208 2 Tom Clegg
209
h3. Add a test fixture
210
211
Generate last part of uuid from command line:
212
<pre><code class="ruby">ruby -e 'puts rand(2**512).to_s(36)[0..14]'
213
j0wqrlny07k1u12</code></pre>
214
Generate uuid from @rails console@:
215
<pre><code class="ruby">Group.generate_uuid
216
=> "xyzzy-j7d0g-8nw4r6gnnkixw1i"
217
</code></pre>