Merge remote-tracking branch 'origin/master' into 1971-show-image-thumbnails
[arvados.git] / sdk / ruby / lib / arvados.rb
1 require 'rubygems'
2 require 'google/api_client'
3 require 'active_support/inflector'
4 require 'json'
5 require 'fileutils'
6 require 'andand'
7
8 ActiveSupport::Inflector.inflections do |inflect|
9   inflect.irregular 'specimen', 'specimens'
10   inflect.irregular 'human', 'humans'
11 end
12
13 module Kernel
14   def suppress_warnings
15     original_verbosity = $VERBOSE
16     $VERBOSE = nil
17     result = yield
18     $VERBOSE = original_verbosity
19     return result
20   end
21 end
22
23 class Arvados
24
25   class TransactionFailedError < StandardError
26   end
27
28   @@config = nil
29   @@debuglevel = 0
30   class << self
31     attr_accessor :debuglevel
32   end
33
34   def initialize(opts={})
35     @application_version ||= 0.0
36     @application_name ||= File.split($0).last
37
38     @arvados_api_version = opts[:api_version] ||
39       config['ARVADOS_API_VERSION'] ||
40       'v1'
41     @arvados_api_host = opts[:api_host] ||
42       config['ARVADOS_API_HOST'] or
43       raise "#{$0}: no :api_host or ENV[ARVADOS_API_HOST] provided."
44     @arvados_api_token = opts[:api_token] ||
45       config['ARVADOS_API_TOKEN'] or
46       raise "#{$0}: no :api_token or ENV[ARVADOS_API_TOKEN] provided."
47
48     if (opts[:suppress_ssl_warnings] or
49         config['ARVADOS_API_HOST_INSECURE'])
50       suppress_warnings do
51         OpenSSL::SSL.const_set 'VERIFY_PEER', OpenSSL::SSL::VERIFY_NONE
52       end
53     end
54
55     # Define a class and an Arvados instance method for each Arvados
56     # resource. After this, self.job will return Arvados::Job;
57     # self.job.new() and self.job.find() will do what you want.
58     _arvados = self
59     namespace_class = Arvados.const_set "A#{self.object_id}", Class.new
60     self.arvados_api.schemas.each do |classname, schema|
61       next if classname.match /List$/
62       klass = Class.new(Arvados::Model) do
63         def self.arvados
64           @arvados
65         end
66         def self.api_models_sym
67           @api_models_sym
68         end
69         def self.api_model_sym
70           @api_model_sym
71         end
72       end
73
74       # Define the resource methods (create, get, update, delete, ...)
75       self.
76         arvados_api.
77         send(classname.underscore.split('/').last.pluralize.to_sym).
78         discovered_methods.
79         each do |method|
80         class << klass; self; end.class_eval do
81           define_method method.name do |*params|
82             self.api_exec method, *params
83           end
84         end
85       end
86
87       # Give the new class access to the API
88       klass.instance_eval do
89         @arvados = _arvados
90         # TODO: Pull these from the discovery document instead.
91         @api_models_sym = classname.underscore.split('/').last.pluralize.to_sym
92         @api_model_sym = classname.underscore.split('/').last.to_sym
93       end
94
95       # Create the new class in namespace_class so it doesn't
96       # interfere with classes created by other Arvados objects. The
97       # result looks like Arvados::A26949680::Job.
98       namespace_class.const_set classname, klass
99
100       self.class.class_eval do
101         define_method classname.underscore do
102           klass
103         end
104       end
105     end
106   end
107
108   class Google::APIClient
109     def discovery_document(api, version)
110       api = api.to_s
111       return @discovery_documents["#{api}:#{version}"] ||=
112         begin
113           # fetch new API discovery doc if stale
114           cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
115           if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
116             response = self.execute!(:http_method => :get,
117                                      :uri => self.discovery_uri(api, version),
118                                      :authenticated => false)
119             FileUtils.makedirs(File.dirname cached_doc)
120             File.open(cached_doc, 'w') do |f|
121               f.puts response.body
122             end
123           end
124
125           File.open(cached_doc) { |f| JSON.load f }
126         end
127     end
128   end
129
130   def client
131     @client ||= Google::APIClient.
132       new(:host => @arvados_api_host,
133           :application_name => @application_name,
134           :application_version => @application_version.to_s)
135   end
136
137   def arvados_api
138     @arvados_api ||= self.client.discovered_api('arvados', @arvados_api_version)
139   end
140
141   def self.debuglog(message, verbosity=1)
142     $stderr.puts "#{File.split($0).last} #{$$}: #{message}" if @@debuglevel >= verbosity
143   end
144
145   def config(config_file_path="~/.config/arvados/settings.conf")
146     return @@config if @@config
147
148     # Initialize config settings with environment variables.
149     config = {}
150     config['ARVADOS_API_HOST']          = ENV['ARVADOS_API_HOST']
151     config['ARVADOS_API_TOKEN']         = ENV['ARVADOS_API_TOKEN']
152     config['ARVADOS_API_HOST_INSECURE'] = ENV['ARVADOS_API_HOST_INSECURE']
153     config['ARVADOS_API_VERSION']       = ENV['ARVADOS_API_VERSION']
154
155     expanded_path = File.expand_path config_file_path
156     if File.exist? expanded_path
157       # Load settings from the config file.
158       lineno = 0
159       File.open(expanded_path).each do |line|
160         lineno = lineno + 1
161         # skip comments and blank lines
162         next if line.match('^\s*#') or not line.match('\S')
163         var, val = line.chomp.split('=', 2)
164         # allow environment settings to override config files.
165         if var and val
166           config[var] ||= val
167         else
168           warn "#{expanded_path}: #{lineno}: could not parse `#{line}'"
169         end
170       end
171     end
172
173     @@config = config
174   end
175
176   class Model
177     def self.arvados_api
178       arvados.arvados_api
179     end
180     def self.client
181       arvados.client
182     end
183     def self.debuglog(*args)
184       arvados.class.debuglog *args
185     end
186     def debuglog(*args)
187       self.class.arvados.class.debuglog *args
188     end
189     def self.api_exec(method, parameters={})
190       api_method = arvados_api.send(api_models_sym).send(method.name.to_sym)
191       parameters = parameters.
192         merge(:api_token => arvados.config['ARVADOS_API_TOKEN'])
193       parameters.each do |k,v|
194         parameters[k] = v.to_json if v.is_a? Array or v.is_a? Hash
195       end
196       # Look for objects expected by request.properties.(key).$ref and
197       # move them from parameters (query string) to request body.
198       body = nil
199       method.discovery_document['request'].
200         andand['properties'].
201         andand.each do |k,v|
202         if v.is_a? Hash and v['$ref']
203           body ||= {}
204           body[k] = parameters.delete k.to_sym
205         end
206       end
207       result = client.
208         execute(:api_method => api_method,
209                 :authenticated => false,
210                 :parameters => parameters,
211                 :body => body)
212       resp = JSON.parse result.body, :symbolize_names => true
213       if resp[:errors]
214         raise Arvados::TransactionFailedError.new(resp[:errors])
215       elsif resp[:uuid] and resp[:etag]
216         self.new(resp)
217       elsif resp[:items].is_a? Array
218         resp.merge(items: resp[:items].collect do |i|
219                      self.new(i)
220                    end)
221       else
222         resp
223       end
224     end
225
226     def []=(x,y)
227       @attributes_to_update[x] = y
228       @attributes[x] = y
229     end
230     def [](x)
231       if @attributes[x].is_a? Hash or @attributes[x].is_a? Array
232         # We won't be notified via []= if these change, so we'll just
233         # assume they are going to get changed, and submit them if
234         # save() is called.
235         @attributes_to_update[x] = @attributes[x]
236       end
237       @attributes[x]
238     end
239     def save
240       @attributes_to_update.keys.each do |k|
241         @attributes_to_update[k] = @attributes[k]
242       end
243       j = self.class.api_exec :update, {
244         :uuid => @attributes[:uuid],
245         self.class.api_model_sym => @attributes_to_update.to_json
246       }
247       unless j.respond_to? :[] and j[:uuid]
248         debuglog "Failed to save #{self.to_s}: #{j[:errors] rescue nil}", 0
249         nil
250       else
251         @attributes_to_update = {}
252         @attributes = j
253       end
254     end
255
256     protected
257
258     def initialize(j)
259       @attributes_to_update = {}
260       @attributes = j
261     end
262   end
263 end