2 require 'active_support/inflector'
7 require 'arvados/google_api_client'
9 ActiveSupport::Inflector.inflections do |inflect|
10 inflect.irregular 'specimen', 'specimens'
11 inflect.irregular 'human', 'humans'
16 original_verbosity = $VERBOSE
19 $VERBOSE = original_verbosity
26 class TransactionFailedError < StandardError
32 attr_accessor :debuglevel
35 def initialize(opts={})
36 @application_version ||= 0.0
37 @application_name ||= File.split($0).last
39 @arvados_api_version = opts[:api_version] || '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."
48 if (opts[:suppress_ssl_warnings] or
49 %w(1 true yes).index(config['ARVADOS_API_HOST_INSECURE'].
52 OpenSSL::SSL.const_set 'VERIFY_PEER', OpenSSL::SSL::VERIFY_NONE
56 # Define a class and an Arvados instance method for each Arvados
57 # resource. After this, self.job will return Arvados::Job;
58 # self.job.new() and self.job.find() will do what you want.
60 namespace_class = Arvados.const_set "A#{self.object_id}", Class.new
61 self.arvados_api.schemas.each do |classname, schema|
62 next if classname.match /List$/
63 klass = Class.new(Arvados::Model) do
67 def self.api_models_sym
70 def self.api_model_sym
75 # Define the resource methods (create, get, update, delete, ...)
78 send(classname.underscore.split('/').last.pluralize.to_sym).
81 class << klass; self; end.class_eval do
82 define_method method.name do |*params|
83 self.api_exec method, *params
88 # Give the new class access to the API
89 klass.instance_eval do
91 # TODO: Pull these from the discovery document instead.
92 @api_models_sym = classname.underscore.split('/').last.pluralize.to_sym
93 @api_model_sym = classname.underscore.split('/').last.to_sym
96 # Create the new class in namespace_class so it doesn't
97 # interfere with classes created by other Arvados objects. The
98 # result looks like Arvados::A26949680::Job.
99 namespace_class.const_set classname, klass
101 self.class.class_eval do
102 define_method classname.underscore do
110 @client ||= Google::APIClient.
111 new(:host => @arvados_api_host,
112 :application_name => @application_name,
113 :application_version => @application_version.to_s)
117 @arvados_api ||= self.client.discovered_api('arvados', @arvados_api_version)
120 def self.debuglog(message, verbosity=1)
121 $stderr.puts "#{File.split($0).last} #{$$}: #{message}" if @@debuglevel >= verbosity
125 self.class.debuglog *args
128 def config(config_file_path="~/.config/arvados/settings.conf")
129 return @@config if @@config
131 # Initialize config settings with environment variables.
133 config['ARVADOS_API_HOST'] = ENV['ARVADOS_API_HOST']
134 config['ARVADOS_API_TOKEN'] = ENV['ARVADOS_API_TOKEN']
135 config['ARVADOS_API_HOST_INSECURE'] = ENV['ARVADOS_API_HOST_INSECURE']
137 if config['ARVADOS_API_HOST'] and config['ARVADOS_API_TOKEN']
138 # Environment variables take precedence over the config file, so
139 # there is no point reading the config file. If the environment
140 # specifies a _HOST without asking for _INSECURE, we certainly
141 # shouldn't give the config file a chance to create a
142 # system-wide _INSECURE state for this user.
144 # Note: If we start using additional configuration settings from
145 # this file in the future, we might have to read the file anyway
146 # instead of returning here.
147 return (@@config = config)
151 expanded_path = File.expand_path config_file_path
152 if File.exist? expanded_path
153 # Load settings from the config file.
155 File.open(expanded_path).each do |line|
157 # skip comments and blank lines
158 next if line.match('^\s*#') or not line.match('\S')
159 var, val = line.chomp.split('=', 2)
162 # allow environment settings to override config files.
163 if !var.empty? and val
166 debuglog "#{expanded_path}: #{lineno}: could not parse `#{line}'", 0
170 rescue StandardError => e
171 debuglog "Ignoring error reading #{config_file_path}: #{e}", 0
184 def self.debuglog(*args)
185 arvados.class.debuglog *args
188 self.class.arvados.class.debuglog *args
190 def self.api_exec(method, parameters={})
191 api_method = arvados_api.send(api_models_sym).send(method.name.to_sym)
192 parameters.each do |k,v|
193 parameters[k] = v.to_json if v.is_a? Array or v.is_a? Hash
195 # Look for objects expected by request.properties.(key).$ref and
196 # move them from parameters (query string) to request body.
198 method.discovery_document['request'].
199 andand['properties'].
201 if v.is_a? Hash and v['$ref']
203 body[k] = parameters.delete k.to_sym
207 execute(:api_method => api_method,
208 :authenticated => false,
209 :parameters => parameters,
210 :body_object => body,
212 :authorization => 'OAuth2 '+arvados.config['ARVADOS_API_TOKEN']
214 resp = JSON.parse result.body, :symbolize_names => true
216 raise Arvados::TransactionFailedError.new(resp[:errors])
217 elsif resp[:uuid] and resp[:etag]
219 elsif resp[:items].is_a? Array
220 resp.merge(:items => resp[:items].collect do |i|
229 @attributes_to_update[x] = y
233 if @attributes[x].is_a? Hash or @attributes[x].is_a? Array
234 # We won't be notified via []= if these change, so we'll just
235 # assume they are going to get changed, and submit them if
237 @attributes_to_update[x] = @attributes[x]
242 @attributes_to_update.keys.each do |k|
243 @attributes_to_update[k] = @attributes[k]
245 j = self.class.api_exec :update, {
246 :uuid => @attributes[:uuid],
247 self.class.api_model_sym => @attributes_to_update.to_json
249 unless j.respond_to? :[] and j[:uuid]
250 debuglog "Failed to save #{self.to_s}: #{j[:errors] rescue nil}", 0
253 @attributes_to_update = {}
261 @attributes_to_update = {}