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.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"
66 if ['add', 'remove'].index @sub then
67 exec `which arv-tag`.strip, *ARGV
69 $stderr.puts "Usage: \n" +
70 "#{$0} tag add tag1 [tag2 ...] --objects object_uuid1 [object_uuid2...]\n" +
71 "#{$0} tag remove tag1 [tag2 ...] --objects object_uuid1 [object_uuid2...]\n" +
72 "#{$0} tag remove --all\n"
76 ENV['ARVADOS_API_VERSION'] ||= 'v1'
78 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
80 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
87 require 'google/api_client'
93 require 'active_support/inflector'
98 Please install all required gems:
100 gem install activesupport andand curb google-api-client json oj trollop
105 ActiveSupport::Inflector.inflections do |inflect|
106 inflect.irregular 'specimen', 'specimens'
107 inflect.irregular 'human', 'humans'
111 def suppress_warnings
112 original_verbosity = $VERBOSE
115 $VERBOSE = original_verbosity
120 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
121 if ENV['ARVADOS_API_HOST_INSECURE']
122 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
125 class Google::APIClient
126 def discovery_document(api, version)
128 return @discovery_documents["#{api}:#{version}"] ||= (begin
129 response = self.execute!(
130 :http_method => :get,
131 :uri => self.discovery_uri(api, version),
132 :authenticated => false
134 response.body.class == String ? JSON.parse(response.body) : response.body
139 class ArvadosClient < Google::APIClient
141 if args.last.is_a? Hash
142 args.last[:headers] ||= {}
143 args.last[:headers]['Accept'] ||= 'application/json'
149 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
150 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
153 !!(s =~ /^(true|t|yes|y|1)$/i)
156 def help_methods(discovery_document, resource, method=nil)
158 banner += "The #{resource} resource type supports the following methods:"
160 discovery_document["resources"][resource.pluralize]["methods"].
163 description = ' ' + v["description"] if v.include?("description")
164 banner += " #{sprintf("%20s",k)}#{description}\n"
169 if not method.nil? and method != '--help' then
170 Trollop::die ("Unknown method #{method.inspect} " +
171 "for resource #{resource.inspect}")
176 def help_resources(discovery_document, resource)
178 banner += "This Arvados instance supports the following resource types:"
180 discovery_document["resources"].each do |k,v|
182 if discovery_document["schemas"].include?(k.singularize.capitalize) and
183 discovery_document["schemas"][k.singularize.capitalize].include?('description') then
184 description = ' ' + discovery_document["schemas"][k.singularize.capitalize]["description"]
186 banner += " #{sprintf("%30s",k.singularize)}#{description}\n"
191 if not resource.nil? and resource != '--help' then
192 Trollop::die "Unknown resource type #{resource.inspect}"
197 def parse_arguments(discovery_document)
198 resource_types = Array.new()
199 resource_types << '--help'
200 discovery_document["resources"].each do |k,v|
201 resource_types << k.singularize
204 global_opts = Trollop::options do
205 banner "arvados cli client"
206 opt :dry_run, "Don't actually do anything", :short => "-n"
207 opt :verbose, "Print some things on stderr", :short => "-v"
208 opt :uuid, "Return the UUIDs of the objects in the response, one per line (default)", :short => nil
209 opt :json, "Return the entire response received from the API server, as a JSON object", :short => "-j"
210 opt :human, "Return the response received from the API server, as a JSON object with whitespace added for human consumption", :short => "-h"
211 opt :pretty, "Synonym of --human", :short => nil
212 opt :yaml, "Return the response received from the API server, in YAML format", :short => "-y"
213 stop_on resource_types
216 resource = ARGV.shift
217 if resource == '--help' or not resource_types.include?(resource)
218 help_resources(discovery_document, resource)
222 if not (discovery_document["resources"][resource.pluralize]["methods"].
224 help_methods(discovery_document, resource, method)
227 discovered_params = discovery_document\
228 ["resources"][resource.pluralize]\
229 ["methods"][method]["parameters"]
230 method_opts = Trollop::options do
231 discovered_params.each do |k,v|
233 opts[:type] = v["type"].to_sym if v.include?("type")
234 if [:datetime, :text, :object, :array].index opts[:type]
235 opts[:type] = :string # else trollop bork
237 opts[:default] = v["default"] if v.include?("default")
238 opts[:default] = v["default"].to_i if opts[:type] == :integer
239 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
240 opts[:required] = true if v.include?("required") and v["required"]
242 description = ' ' + v["description"] if v.include?("description")
243 opt k.to_sym, description, opts
245 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
246 if body_object and discovered_params[resource].nil?
248 if body_object["required"] == false
251 opt resource.to_sym, "#{resource} (request body)", {
252 required: is_required,
255 discovered_params[resource.to_sym] = body_object
259 discovered_params.each do |k,v|
261 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
262 if method_opts[k].match /^\//
263 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
267 return resource, method, method_opts, global_opts, ARGV
270 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
271 controller = resource_schema.pluralize
273 api_method = 'arvados.' + controller + '.' + method
275 if global_opts[:dry_run]
276 if global_opts[:verbose]
277 $stderr.puts "#{api_method} #{method_opts.inspect}"
282 request_parameters = {}.merge(method_opts)
283 resource_body = request_parameters.delete(resource_schema.to_sym)
286 resource_schema => JSON.parse(resource_body)
294 'arvados.users.event_stream',
295 'arvados.jobs.log_stream',
296 'arvados.jobs.log_tail_follow'
298 # Special case for methods that respond with data streams rather
299 # than JSON (TODO: use the discovery document instead of a static
301 uri_s = eval(api_method).generate_uri(request_parameters)
302 Curl::Easy.perform(uri_s) do |curl|
303 curl.headers['Accept'] = 'text/plain'
304 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
305 if ENV['ARVADOS_API_HOST_INSECURE']
306 curl.ssl_verify_peer = false
307 curl.ssl_verify_host = false
309 if global_opts[:verbose]
310 curl.on_header { |data| $stderr.write data }
312 curl.on_body { |data| $stdout.write data }
316 request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
317 result = client.execute(:api_method => eval(api_method),
318 :parameters => request_parameters,
319 :body => request_body,
320 :authenticated => false)
324 results = JSON.parse result.body
325 rescue JSON::ParserError => e
326 abort "Failed to parse server response:\n" + e.to_s
329 if results["errors"] then
330 abort "Error: #{results["errors"][0]}"
333 if global_opts[:human] or global_opts[:pretty] then
334 puts Oj.dump(results, :indent => 1)
335 elsif global_opts[:yaml] then
337 elsif global_opts[:json] then
338 puts Oj.dump(results)
339 elsif results["items"] and results["kind"].match /list$/i
340 results['items'].each do |i| puts i['uuid'] end
341 elsif results['uuid'].nil?
342 abort("Response did not include a uuid:\n" +
343 Oj.dump(results, :indent => 1) +