Propagate API errors as exceptions
[arvados.git] / sdk / ruby / lib / arvados.rb
1 require 'rubygems'
2 require 'google/api_client'
3 require 'active_support/inflector'
4 require 'json'
5
6 ActiveSupport::Inflector.inflections do |inflect|
7   inflect.irregular 'specimen', 'specimens'
8   inflect.irregular 'human', 'humans'
9 end
10
11 module Kernel
12   def suppress_warnings
13     original_verbosity = $VERBOSE
14     $VERBOSE = nil
15     result = yield
16     $VERBOSE = original_verbosity
17     return result
18   end
19 end
20
21 class Arvados
22
23   class TransactionFailedError < StandardError
24   end
25
26   @@debuglevel = 0
27   class << self
28     attr_accessor :debuglevel
29   end
30
31   def initialize(opts={})
32     @application_version ||= 0.0
33     @application_name ||= File.split($0).last
34
35     @arvados_api_version = opts[:api_version] ||
36       ENV['ARVADOS_API_VERSION'] ||
37       'v1'
38     @arvados_api_host = opts[:api_host] ||
39       ENV['ARVADOS_API_HOST'] or
40       raise "#{$0}: no :api_host or ENV[ARVADOS_API_HOST] provided."
41     @arvados_api_token = opts[:api_token] ||
42       ENV['ARVADOS_API_TOKEN'] or
43       raise "#{$0}: no :api_token or ENV[ARVADOS_API_TOKEN] provided."
44
45     if (opts[:api_host] ? opts[:suppress_ssl_warnings] :
46         ENV['ARVADOS_API_HOST_INSECURE'])
47       suppress_warnings do
48         OpenSSL::SSL.const_set 'VERIFY_PEER', OpenSSL::SSL::VERIFY_NONE
49       end
50     end
51
52     # Define a class and an Arvados instance method for each Arvados
53     # resource. After this, self.job will return Arvados::Job;
54     # self.job.new() and self.job.find() will do what you want.
55     _arvados = self
56     self.arvados_api.schemas.each do |classname, schema|
57       next if classname.match /List$/
58       klass = Class.new(Arvados::Model) do
59         def self.arvados
60           @arvados
61         end
62         def self.api_models_sym
63           @api_models_sym
64         end
65         def self.api_model_sym
66           @api_model_sym
67         end
68       end
69
70       # Define the resource methods (create, get, update, delete, ...)
71       self.
72         arvados_api.
73         send(classname.underscore.split('/').last.pluralize.to_sym).
74         discovered_methods.
75         collect(&:name).
76         each do |method_name|
77         class << klass; self; end.class_eval do
78           define_method method_name do |*params|
79             self.api_exec(method_name.to_sym, *params)
80           end
81         end
82       end
83
84       # Give the new class access to the API
85       klass.instance_eval do
86         @arvados = _arvados
87         # These should be pulled from the discovery document instead:
88         @api_models_sym = classname.underscore.split('/').last.pluralize.to_sym
89         @api_model_sym = classname.underscore.split('/').last.to_sym
90       end
91
92       # This might produce confusing results when using multiple
93       # Arvados instances.
94       Arvados.const_set classname, klass
95
96       self.class.class_eval do
97         define_method classname.underscore do
98           klass
99         end
100       end
101     end
102   end
103
104   class Google::APIClient
105     def discovery_document(api, version)
106       api = api.to_s
107       return @discovery_documents["#{api}:#{version}"] ||=
108         begin
109           response = self.execute!(
110                                    :http_method => :get,
111                                    :uri => self.discovery_uri(api, version),
112                                    :authenticated => false
113                                    )
114           response.body.class == String ? JSON.parse(response.body) : response.body
115         end
116     end
117   end
118
119   def client
120     @client ||= Google::APIClient.
121       new(:host => @arvados_api_host,
122           :application_name => @application_name,
123           :application_version => @application_version.to_s)
124   end
125
126   def arvados_api
127     @arvados_api ||= self.client.discovered_api('arvados', @arvados_api_version)
128   end
129
130   def self.debuglog(message, verbosity=1)
131     $stderr.puts "#{File.split($0).last} #{$$}: #{message}" if @@debuglevel >= verbosity
132   end
133
134   class Model
135     def self.arvados_api
136       arvados.arvados_api
137     end
138     def self.client
139       arvados.client
140     end
141     def self.debuglog(*args)
142       arvados.class.debuglog *args
143     end
144     def debuglog(*args)
145       self.class.arvados.class.debuglog *args
146     end
147     def self.api_exec(method, parameters={})
148       parameters = parameters.
149         merge(:api_token => ENV['ARVADOS_API_TOKEN'])
150       parameters.each do |k,v|
151         parameters[k] = v.to_json if v.is_a? Array or v.is_a? Hash
152       end
153       result = client.
154         execute(:api_method => arvados_api.send(api_models_sym).send(method),
155                 :authenticated => false,
156                 :parameters => parameters)
157       resp = JSON.parse result.body, :symbolize_names => true
158       if resp[:errors]
159         raise Arvados::TransactionFailedError.new(resp[:errors])
160       end
161       resp
162     end
163
164     def []=(x,y)
165       @attributes_to_update[x] = y
166       @attributes[x] = y
167     end
168     def [](x)
169       if @attributes[x].is_a? Hash or @attributes[x].is_a? Array
170         # We won't be notified via []= if these change, so we'll just
171         # assume they are going to get changed, and submit them if
172         # save() is called.
173         @attributes_to_update[x] = @attributes[x]
174       end
175       @attributes[x]
176     end
177     def save
178       @attributes_to_update.keys.each do |k|
179         @attributes_to_update[k] = @attributes[k]
180       end
181       j = self.class.api_exec :update, {
182         :uuid => @attributes[:uuid],
183         self.class.api_model_sym => @attributes_to_update.to_json
184       }
185       unless j.is_a? Hash and j[:uuid]
186         debuglog "Failed to save #{self.to_s}: #{j[:errors] rescue nil}", 0
187         nil
188       else
189         @attributes_to_update = {}
190         @attributes = j
191       end
192     end
193
194     protected
195
196     def initialize(j)
197       @attributes_to_update = {}
198       @attributes = j
199     end
200   end
201 end