5 # Ward Vandewege <ward@clinicalfuture.com>
9 if RUBY_VERSION < '1.9.3' then
11 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
18 require 'google/api_client'
24 require 'active_support/inflector'
29 Please install all required gems:
31 gem install activesupport andand curb google-api-client json oj trollop yaml
36 # Search for 'ENTRY POINT' to see where things get going
38 ActiveSupport::Inflector.inflections do |inflect|
39 inflect.irregular 'specimen', 'specimens'
40 inflect.irregular 'human', 'humans'
45 original_verbosity = $VERBOSE
48 $VERBOSE = original_verbosity
53 class Google::APIClient
54 def discovery_document(api, version)
56 return @discovery_documents["#{api}:#{version}"] ||=
58 # fetch new API discovery doc if stale
59 cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
60 if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
61 response = self.execute!(:http_method => :get,
62 :uri => self.discovery_uri(api, version),
63 :authenticated => false)
64 FileUtils.makedirs(File.dirname cached_doc)
65 File.open(cached_doc, 'w') do |f|
70 File.open(cached_doc) { |f| JSON.load f }
75 class ArvadosClient < Google::APIClient
77 if args.last.is_a? Hash
78 args.last[:headers] ||= {}
79 args.last[:headers]['Accept'] ||= 'application/json'
86 # read authentication data from arvados configuration file if present
88 config_file = File.expand_path('~/.config/arvados/settings.conf')
89 if File.exist? config_file then
90 File.open(config_file, 'r').each do |line|
93 if line.match('^\s*#') then
96 var, val = line.chomp.split('=', 2)
97 # allow environment settings to override config files.
101 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
107 subcommands = %w(keep pipeline tag ws edit)
109 def check_subcommands client, arvados, subcommand, global_opts, remaining_opts
112 @sub = remaining_opts.shift
113 if ['get', 'put', 'ls', 'normalize'].index @sub then
115 exec `which arv-#{@sub}`.strip, *remaining_opts
116 elsif ['less', 'check'].index @sub then
118 exec `which wh#{@sub}`.strip, *remaining_opts
119 elsif @sub == 'docker'
120 exec `which arv-keepdocker`.strip, *remaining_opts
122 puts "Usage: arv keep [method] [--parameters]\n"
123 puts "Use 'arv keep [method] --help' to get more information about specific methods.\n\n"
124 puts "Available methods: ls, get, put, less, check, docker"
128 exec `which arv-run-pipeline-instance`.strip, *remaining_opts
130 exec `which arv-tag`.strip, *remaining_opts
132 exec `which arv-ws`.strip, *remaining_opts
134 arv_edit client, arvados, global_opts, remaining_opts
138 def arv_edit client, arvados, global_opts, remaining_opts
139 n = remaining_opts.shift
140 if n.nil? or n == "-h" or n == "--help"
142 puts "Usage: arv edit [uuid] [fields...]\n\n"
143 puts "Fetchs the specified Arvados object, select the specified fields, and\n"
144 puts "open an interactive text editor on a text representation (json or\n"
145 puts "yaml, use --format) and then updates the object. Will use 'nano'\n"
146 puts "by default, customize with the EDITOR or VISUAL environment variable.\n"
151 puts "Not connected to a TTY, cannot run interactive editor."
155 # determine controller
157 m = /([a-z0-9]{5})-([a-z0-9]{5})-([a-z0-9]{15})/.match n
159 abort puts "#{n} does not appear to be an arvados uuid"
163 arvados.discovery_document["resources"].each do |k,v|
164 klass = k.singularize.camelize
165 dig = Digest::MD5.hexdigest(klass).to_i(16).to_s(36)[-5..-1]
172 abort "Could not determine resource type #{m[2]}"
175 api_method = 'arvados.' + rsc + '.get'
177 result = client.execute(:api_method => eval(api_method),
178 :parameters => {"uuid" => n},
179 :authenticated => false,
181 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
184 results = JSON.parse result.body
185 rescue JSON::ParserError => e
186 abort "Failed to parse server response:\n" + e.to_s
189 if remaining_opts.length > 0
190 results.select! { |k, v| remaining_opts.include? k }
195 case global_opts[:format]
197 content = Oj.dump(results, :indent => 1)
199 content = results.to_yaml
204 tmp = Tempfile.new(n)
210 editor ||= ENV["VISUAL"]
211 editor ||= ENV["EDITOR"]
213 exec editor, tmp.path
218 if $?.exitstatus == 0
220 newcontent = tmp.read()
223 case global_opts[:format]
225 newobj = Oj.load(newcontent)
227 newobj = YAML.load(newcontent)
233 api_method = 'arvados.' + rsc + '.update'
234 result = client.execute(:api_method => eval(api_method),
235 :parameters => {"uuid" => n, rsc.singularize => Oj.dump(newobj)},
236 :authenticated => false,
238 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
242 results = JSON.parse result.body
243 rescue JSON::ParserError => e
244 abort "Failed to parse server response:\n" + e.to_s
247 if result.response.status != 200
248 puts "Update failed. Server responded #{result.response.status}: #{results['errors']} "
251 puts "Object is unchanged, did not update."
259 !!(s =~ /^(true|t|yes|y|1)$/i)
263 "Arvados command line client\n"
266 def help_methods(discovery_document, resource, method=nil)
268 banner += "Usage: arv #{resource} [method] [--parameters]\n"
269 banner += "Use 'arv #{resource} [method] --help' to get more information about specific methods.\n\n"
270 banner += "The #{resource} resource supports the following methods:"
272 discovery_document["resources"][resource.pluralize]["methods"].
275 if v.include? "description"
276 # add only the first line of the discovery doc description
277 description = ' ' + v["description"].split("\n").first.chomp
279 banner += " #{sprintf("%20s",k)}#{description}\n"
284 if not method.nil? and method != '--help' and method != '-h' then
285 abort "Unknown method #{method.inspect} " +
286 "for resource #{resource.inspect}"
291 def help_resources(option_parser, discovery_document, resource)
292 option_parser.educate
294 if not resource.nil? and resource != '--help' then
295 Trollop::die "Unknown resource type #{resource.inspect}"
300 def parse_arguments(discovery_document, subcommands)
301 resource_types = Array.new()
302 discovery_document["resources"].each do |k,v|
303 resource_types << k.singularize
306 resource_types += subcommands
308 option_parser = Trollop::Parser.new do
311 banner "Usage: arv [--flags] subcommand|resource [method] [--parameters]"
313 banner "Available flags:"
315 opt :dry_run, "Don't actually do anything", :short => "-n"
316 opt :verbose, "Print some things on stderr"
318 "Set the output format. Must be one of json (default), yaml or uuid.",
321 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
324 banner "Use 'arv subcommand|resource --help' to get more information about a particular command or resource."
326 banner "Available subcommands: #{subcommands.join(', ')}"
329 banner "Available resources: #{discovery_document['resources'].keys.map { |k| k.singularize }.join(', ')}"
332 banner "Additional options:"
334 conflicts :short, :format
335 stop_on resource_types
338 global_opts = Trollop::with_standard_exception_handling option_parser do
339 o = option_parser.parse ARGV
342 unless %w(json yaml uuid).include?(global_opts[:format])
343 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
344 $stderr.puts "Use #{$0} --help for more information."
348 if global_opts[:short]
349 global_opts[:format] = 'uuid'
352 resource = ARGV.shift
354 if not subcommands.include? resource
355 if global_opts[:resources] or not resource_types.include?(resource)
356 help_resources(option_parser, discovery_document, resource)
360 if not (discovery_document["resources"][resource.pluralize]["methods"].
362 help_methods(discovery_document, resource, method)
365 discovered_params = discovery_document\
366 ["resources"][resource.pluralize]\
367 ["methods"][method]["parameters"]
368 method_opts = Trollop::options do
370 banner "Usage: arv #{resource} #{method} [--parameters]"
372 banner "This method supports the following parameters:"
374 discovered_params.each do |k,v|
376 opts[:type] = v["type"].to_sym if v.include?("type")
377 if [:datetime, :text, :object, :array].index opts[:type]
378 opts[:type] = :string # else trollop bork
380 opts[:default] = v["default"] if v.include?("default")
381 opts[:default] = v["default"].to_i if opts[:type] == :integer
382 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
383 opts[:required] = true if v.include?("required") and v["required"]
385 description = ' ' + v["description"] if v.include?("description")
386 opt k.to_sym, description, opts
389 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
390 if body_object and discovered_params[resource].nil?
392 if body_object["required"] == false
395 opt resource.to_sym, "#{resource} (request body)", {
396 required: is_required,
402 discovered_params.each do |k,v|
404 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
405 if method_opts[k].andand.match /^\//
406 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
412 return resource, method, method_opts, global_opts, ARGV
421 ENV['ARVADOS_API_VERSION'] ||= 'v1'
423 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
425 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
429 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
430 if ENV['ARVADOS_API_HOST_INSECURE']
431 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
435 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
436 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
437 rescue Exception => e
438 puts "Failed to connect to Arvados API server: #{e}"
442 # Parse arguments here
443 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document, subcommands)
445 check_subcommands client, arvados, resource_schema, global_opts, remaining_opts
447 controller = resource_schema.pluralize
449 api_method = 'arvados.' + controller + '.' + method
451 if global_opts[:dry_run]
452 if global_opts[:verbose]
453 $stderr.puts "#{api_method} #{method_opts.inspect}"
458 request_parameters = {_profile:true}.merge(method_opts)
459 resource_body = request_parameters.delete(resource_schema.to_sym)
462 resource_schema => resource_body
470 'arvados.jobs.log_tail_follow'
472 # Special case for methods that respond with data streams rather
473 # than JSON (TODO: use the discovery document instead of a static
475 uri_s = eval(api_method).generate_uri(request_parameters)
476 Curl::Easy.perform(uri_s) do |curl|
477 curl.headers['Accept'] = 'text/plain'
478 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
479 if ENV['ARVADOS_API_HOST_INSECURE']
480 curl.ssl_verify_peer = false
481 curl.ssl_verify_host = false
483 if global_opts[:verbose]
484 curl.on_header { |data| $stderr.write data }
486 curl.on_body { |data| $stdout.write data }
490 result = client.execute(:api_method => eval(api_method),
491 :parameters => request_parameters,
492 :body => request_body,
493 :authenticated => false,
495 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
500 results = JSON.parse result.body
501 rescue JSON::ParserError => e
502 abort "Failed to parse server response:\n" + e.to_s
505 if results["errors"] then
506 abort "Error: #{results["errors"][0]}"
509 case global_opts[:format]
511 puts Oj.dump(results, :indent => 1)
515 if results["items"] and results["kind"].match /list$/i
516 results['items'].each do |i| puts i['uuid'] end
517 elsif results['uuid'].nil?
518 abort("Response did not include a uuid:\n" +
519 Oj.dump(results, :indent => 1) +