Merge branch '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     begin
156       expanded_path = File.expand_path config_file_path
157       if File.exist? expanded_path
158         # Load settings from the config file.
159         lineno = 0
160         File.open(expanded_path).each do |line|
161           lineno = lineno + 1
162           # skip comments and blank lines
163           next if line.match('^\s*#') or not line.match('\S')
164           var, val = line.chomp.split('=', 2)
165           # allow environment settings to override config files.
166           if var and val
167             config[var] ||= val
168           else
169             warn "#{expanded_path}: #{lineno}: could not parse `#{line}'"
170           end
171         end
172       end
173     rescue
174       debuglog "HOME environment variable (#{ENV['HOME']}) not set, not using #{config_file_path}", 0
175     end
176
177     @@config = config
178   end
179
180   class Model
181     def self.arvados_api
182       arvados.arvados_api
183     end
184     def self.client
185       arvados.client
186     end
187     def self.debuglog(*args)
188       arvados.class.debuglog *args
189     end
190     def debuglog(*args)
191       self.class.arvados.class.debuglog *args
192     end
193     def self.api_exec(method, parameters={})
194       api_method = arvados_api.send(api_models_sym).send(method.name.to_sym)
195       parameters = parameters.
196         merge(:api_token => arvados.config['ARVADOS_API_TOKEN'])
197       parameters.each do |k,v|
198         parameters[k] = v.to_json if v.is_a? Array or v.is_a? Hash
199       end
200       # Look for objects expected by request.properties.(key).$ref and
201       # move them from parameters (query string) to request body.
202       body = nil
203       method.discovery_document['request'].
204         andand['properties'].
205         andand.each do |k,v|
206         if v.is_a? Hash and v['$ref']
207           body ||= {}
208           body[k] = parameters.delete k.to_sym
209         end
210       end
211       result = client.
212         execute(:api_method => api_method,
213                 :authenticated => false,
214                 :parameters => parameters,
215                 :body => body)
216       resp = JSON.parse result.body, :symbolize_names => true
217       if resp[:errors]
218         raise Arvados::TransactionFailedError.new(resp[:errors])
219       elsif resp[:uuid] and resp[:etag]
220         self.new(resp)
221       elsif resp[:items].is_a? Array
222         resp.merge(items: resp[:items].collect do |i|
223                      self.new(i)
224                    end)
225       else
226         resp
227       end
228     end
229
230     def []=(x,y)
231       @attributes_to_update[x] = y
232       @attributes[x] = y
233     end
234     def [](x)
235       if @attributes[x].is_a? Hash or @attributes[x].is_a? Array
236         # We won't be notified via []= if these change, so we'll just
237         # assume they are going to get changed, and submit them if
238         # save() is called.
239         @attributes_to_update[x] = @attributes[x]
240       end
241       @attributes[x]
242     end
243     def save
244       @attributes_to_update.keys.each do |k|
245         @attributes_to_update[k] = @attributes[k]
246       end
247       j = self.class.api_exec :update, {
248         :uuid => @attributes[:uuid],
249         self.class.api_model_sym => @attributes_to_update.to_json
250       }
251       unless j.respond_to? :[] and j[:uuid]
252         debuglog "Failed to save #{self.to_s}: #{j[:errors] rescue nil}", 0
253         nil
254       else
255         @attributes_to_update = {}
256         @attributes = j
257       end
258     end
259
260     protected
261
262     def initialize(j)
263       @attributes_to_update = {}
264       @attributes = j
265     end
266   end
267 end