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 ~/.config/arvados if present
15 config_file = File.expand_path('~/.config/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 discovery_document["resources"].each do |k,v|
192 resource_types << k.singularize
195 global_opts = Trollop::options do
196 banner "arv: the Arvados CLI tool"
197 opt :dry_run, "Don't actually do anything", :short => "-n"
198 opt :verbose, "Print some things on stderr"
200 "Set the output format. Must be one of json (default), yaml or uuid.",
203 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
204 opt :resources, "Display list of resources known to this Arvados instance."
205 conflicts :short, :format
206 stop_on resource_types
209 unless %w(json yaml uuid).include?(global_opts[:format])
210 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
211 $stderr.puts "Use #{$0} --help for more information."
215 if global_opts[:short]
216 global_opts[:format] = 'uuid'
219 resource = ARGV.shift
220 if global_opts[:resources] or not resource_types.include?(resource)
221 help_resources(discovery_document, resource)
225 if not (discovery_document["resources"][resource.pluralize]["methods"].
227 help_methods(discovery_document, resource, method)
230 discovered_params = discovery_document\
231 ["resources"][resource.pluralize]\
232 ["methods"][method]["parameters"]
233 method_opts = Trollop::options do
234 discovered_params.each do |k,v|
236 opts[:type] = v["type"].to_sym if v.include?("type")
237 if [:datetime, :text, :object, :array].index opts[:type]
238 opts[:type] = :string # else trollop bork
240 opts[:default] = v["default"] if v.include?("default")
241 opts[:default] = v["default"].to_i if opts[:type] == :integer
242 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
243 opts[:required] = true if v.include?("required") and v["required"]
245 description = ' ' + v["description"] if v.include?("description")
246 opt k.to_sym, description, opts
248 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
249 if body_object and discovered_params[resource].nil?
251 if body_object["required"] == false
254 opt resource.to_sym, "#{resource} (request body)", {
255 required: is_required,
258 discovered_params[resource.to_sym] = body_object
262 discovered_params.each do |k,v|
264 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
265 if method_opts[k].andand.match /^\//
266 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
270 return resource, method, method_opts, global_opts, ARGV
273 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
274 controller = resource_schema.pluralize
276 api_method = 'arvados.' + controller + '.' + method
278 if global_opts[:dry_run]
279 if global_opts[:verbose]
280 $stderr.puts "#{api_method} #{method_opts.inspect}"
285 request_parameters = {}.merge(method_opts)
286 resource_body = request_parameters.delete(resource_schema.to_sym)
289 resource_schema => resource_body
297 'arvados.users.event_stream',
298 'arvados.jobs.log_stream',
299 'arvados.jobs.log_tail_follow'
301 # Special case for methods that respond with data streams rather
302 # than JSON (TODO: use the discovery document instead of a static
304 uri_s = eval(api_method).generate_uri(request_parameters)
305 Curl::Easy.perform(uri_s) do |curl|
306 curl.headers['Accept'] = 'text/plain'
307 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
308 if ENV['ARVADOS_API_HOST_INSECURE']
309 curl.ssl_verify_peer = false
310 curl.ssl_verify_host = false
312 if global_opts[:verbose]
313 curl.on_header { |data| $stderr.write data }
315 curl.on_body { |data| $stdout.write data }
319 request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
320 request_body[:_profile] = true
321 result = client.execute(:api_method => eval(api_method),
322 :parameters => request_parameters,
323 :body => request_body,
324 :authenticated => false)
328 results = JSON.parse result.body
329 rescue JSON::ParserError => e
330 abort "Failed to parse server response:\n" + e.to_s
333 if results["errors"] then
334 abort "Error: #{results["errors"][0]}"
337 case global_opts[:format]
339 puts Oj.dump(results, :indent => 1)
343 if results["items"] and results["kind"].match /list$/i
344 results['items'].each do |i| puts i['uuid'] end
345 elsif results['uuid'].nil?
346 abort("Response did not include a uuid:\n" +
347 Oj.dump(results, :indent => 1) +