5 # Ward Vandewege <ward@clinicalfuture.com>
7 if RUBY_VERSION < '1.9.3' then
9 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
13 # read authentication data from ~/.arvados if present
15 config_file = File.expand_path('~/.arvados')
16 if File.exist? config_file then
17 File.open(config_file, 'r').each do |line|
20 if line.match('^\s*#') then
23 var, val = line.chomp.split('=', 2)
24 # allow environment settings to override config files.
28 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
37 if ['get', 'put'].index @sub then
39 exec `which arv-#{@sub}`.strip, *ARGV
40 elsif ['ls', 'less', 'check'].index @sub then
42 exec `which wh#{@sub}`.strip, *ARGV
55 if ['run'].index @sub then
56 exec `which arv-run-pipeline-instance`.strip, *ARGV
59 "#{$0} pipeline run [...]\n" +
60 "(see arv-run-pipeline-instance --help for details)\n"
65 exec `which arv-tag`.strip, *ARGV
68 ENV['ARVADOS_API_VERSION'] ||= 'v1'
70 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
72 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
79 require 'google/api_client'
85 require 'active_support/inflector'
90 Please install all required gems:
92 gem install activesupport andand curb google-api-client json oj trollop
97 ActiveSupport::Inflector.inflections do |inflect|
98 inflect.irregular 'specimen', 'specimens'
99 inflect.irregular 'human', 'humans'
103 def suppress_warnings
104 original_verbosity = $VERBOSE
107 $VERBOSE = original_verbosity
112 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
113 if ENV['ARVADOS_API_HOST_INSECURE']
114 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
117 class Google::APIClient
118 def discovery_document(api, version)
120 return @discovery_documents["#{api}:#{version}"] ||= (begin
121 response = self.execute!(
122 :http_method => :get,
123 :uri => self.discovery_uri(api, version),
124 :authenticated => false
126 response.body.class == String ? JSON.parse(response.body) : response.body
131 class ArvadosClient < Google::APIClient
133 if args.last.is_a? Hash
134 args.last[:headers] ||= {}
135 args.last[:headers]['Accept'] ||= 'application/json'
141 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
142 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
145 !!(s =~ /^(true|t|yes|y|1)$/i)
148 def help_methods(discovery_document, resource, method=nil)
150 banner += "The #{resource} resource type supports the following methods:"
152 discovery_document["resources"][resource.pluralize]["methods"].
155 description = ' ' + v["description"] if v.include?("description")
156 banner += " #{sprintf("%20s",k)}#{description}\n"
161 if not method.nil? and method != '--help' then
162 Trollop::die ("Unknown method #{method.inspect} " +
163 "for resource #{resource.inspect}")
168 def help_resources(discovery_document, resource)
170 banner += "This Arvados instance supports the following resource types:"
172 discovery_document["resources"].each do |k,v|
174 if discovery_document["schemas"].include?(k.singularize.capitalize) and
175 discovery_document["schemas"][k.singularize.capitalize].include?('description') then
176 description = ' ' + discovery_document["schemas"][k.singularize.capitalize]["description"]
178 banner += " #{sprintf("%30s",k.singularize)}#{description}\n"
183 if not resource.nil? and resource != '--help' then
184 Trollop::die "Unknown resource type #{resource.inspect}"
189 def parse_arguments(discovery_document)
190 resource_types = Array.new()
191 resource_types << '--help'
192 discovery_document["resources"].each do |k,v|
193 resource_types << k.singularize
196 global_opts = Trollop::options do
197 banner "arvados cli client"
198 opt :dry_run, "Don't actually do anything", :short => "-n"
199 opt :verbose, "Print some things on stderr", :short => "-v"
200 opt :uuid, "Return the UUIDs of the objects in the response, one per line (default)", :short => nil
201 opt :json, "Return the entire response received from the API server, as a JSON object", :short => "-j"
202 opt :human, "Return the response received from the API server, as a JSON object with whitespace added for human consumption", :short => "-h"
203 opt :pretty, "Synonym of --human", :short => nil
204 opt :yaml, "Return the response received from the API server, in YAML format", :short => "-y"
205 stop_on resource_types
208 resource = ARGV.shift
209 if resource == '--help' or not resource_types.include?(resource)
210 help_resources(discovery_document, resource)
214 if not (discovery_document["resources"][resource.pluralize]["methods"].
216 help_methods(discovery_document, resource, method)
219 discovered_params = discovery_document\
220 ["resources"][resource.pluralize]\
221 ["methods"][method]["parameters"]
222 method_opts = Trollop::options do
223 discovered_params.each do |k,v|
225 opts[:type] = v["type"].to_sym if v.include?("type")
226 if [:datetime, :text, :object, :array].index opts[:type]
227 opts[:type] = :string # else trollop bork
229 opts[:default] = v["default"] if v.include?("default")
230 opts[:default] = v["default"].to_i if opts[:type] == :integer
231 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
232 opts[:required] = true if v.include?("required") and v["required"]
234 description = ' ' + v["description"] if v.include?("description")
235 opt k.to_sym, description, opts
237 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
238 if body_object and discovered_params[resource].nil?
240 if body_object["required"] == false
243 opt resource.to_sym, "#{resource} (request body)", {
244 required: is_required,
247 discovered_params[resource.to_sym] = body_object
251 discovered_params.each do |k,v|
253 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
254 if method_opts[k].andand.match /^\//
255 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
259 return resource, method, method_opts, global_opts, ARGV
262 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
263 controller = resource_schema.pluralize
265 api_method = 'arvados.' + controller + '.' + method
267 if global_opts[:dry_run]
268 if global_opts[:verbose]
269 $stderr.puts "#{api_method} #{method_opts.inspect}"
274 request_parameters = {}.merge(method_opts)
275 resource_body = request_parameters.delete(resource_schema.to_sym)
278 resource_schema => JSON.parse(resource_body)
286 'arvados.users.event_stream',
287 'arvados.jobs.log_stream',
288 'arvados.jobs.log_tail_follow'
290 # Special case for methods that respond with data streams rather
291 # than JSON (TODO: use the discovery document instead of a static
293 uri_s = eval(api_method).generate_uri(request_parameters)
294 Curl::Easy.perform(uri_s) do |curl|
295 curl.headers['Accept'] = 'text/plain'
296 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
297 if ENV['ARVADOS_API_HOST_INSECURE']
298 curl.ssl_verify_peer = false
299 curl.ssl_verify_host = false
301 if global_opts[:verbose]
302 curl.on_header { |data| $stderr.write data }
304 curl.on_body { |data| $stdout.write data }
308 request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
309 request_body[:_profile] = true
310 result = client.execute(:api_method => eval(api_method),
311 :parameters => request_parameters,
312 :body => request_body,
313 :authenticated => false)
317 results = JSON.parse result.body
318 rescue JSON::ParserError => e
319 abort "Failed to parse server response:\n" + e.to_s
322 if results["errors"] then
323 abort "Error: #{results["errors"][0]}"
326 if global_opts[:human] or global_opts[:pretty] then
327 puts Oj.dump(results, :indent => 1)
328 elsif global_opts[:yaml] then
330 elsif global_opts[:json] then
331 puts Oj.dump(results)
332 elsif results["items"] and results["kind"].match /list$/i
333 results['items'].each do |i| puts i['uuid'] end
334 elsif results['uuid'].nil?
335 abort("Response did not include a uuid:\n" +
336 Oj.dump(results, :indent => 1) +