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.
15 # read authentication data from arvados configuration file if present
17 config_file = File.expand_path('~/.config/arvados/settings.conf')
18 if File.exist? config_file then
19 File.open(config_file, 'r').each do |line|
22 if line.match('^\s*#') then
25 var, val = line.chomp.split('=', 2)
26 # allow environment settings to override config files.
30 warn "#{config_file}: #{lineno}: could not parse `#{line}'"
39 if ['get', 'put', 'ls', 'normalize'].index @sub then
41 exec `which arv-#{@sub}`.strip, *ARGV
42 elsif ['less', 'check'].index @sub then
44 exec `which wh#{@sub}`.strip, *ARGV
57 if ['run'].index @sub then
58 exec `which arv-run-pipeline-instance`.strip, *ARGV
61 "#{$0} pipeline run [...]\n" +
62 "(see arv-run-pipeline-instance --help for details)\n"
67 exec `which arv-tag`.strip, *ARGV
70 ENV['ARVADOS_API_VERSION'] ||= 'v1'
72 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
74 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
81 require 'google/api_client'
87 require 'active_support/inflector'
92 Please install all required gems:
94 gem install activesupport andand curb google-api-client json oj trollop
99 ActiveSupport::Inflector.inflections do |inflect|
100 inflect.irregular 'specimen', 'specimens'
101 inflect.irregular 'human', 'humans'
105 def suppress_warnings
106 original_verbosity = $VERBOSE
109 $VERBOSE = original_verbosity
114 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
115 if ENV['ARVADOS_API_HOST_INSECURE']
116 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
119 class Google::APIClient
120 def discovery_document(api, version)
122 return @discovery_documents["#{api}:#{version}"] ||=
124 # fetch new API discovery doc if stale
125 cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
126 if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
127 response = self.execute!(:http_method => :get,
128 :uri => self.discovery_uri(api, version),
129 :authenticated => false)
130 FileUtils.makedirs(File.dirname cached_doc)
131 File.open(cached_doc, 'w') do |f|
136 File.open(cached_doc) { |f| JSON.load f }
141 class ArvadosClient < Google::APIClient
143 if args.last.is_a? Hash
144 args.last[:headers] ||= {}
145 args.last[:headers]['Accept'] ||= 'application/json'
152 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
153 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
154 rescue Exception => e
155 puts "Failed to connect to Arvados API server: #{e}"
160 !!(s =~ /^(true|t|yes|y|1)$/i)
163 def help_methods(discovery_document, resource, method=nil)
165 banner += "The #{resource} resource type supports the following methods:"
167 discovery_document["resources"][resource.pluralize]["methods"].
170 if v.include? "description"
171 # add only the first line of the discovery doc description
172 description = ' ' + v["description"].split("\n").first.chomp
174 banner += " #{sprintf("%20s",k)}#{description}\n"
179 if not method.nil? and method != '--help' then
180 Trollop::die ("Unknown method #{method.inspect} " +
181 "for resource #{resource.inspect}")
186 def help_resources(discovery_document, resource)
188 banner += "This Arvados instance supports the following resource types:"
190 discovery_document["resources"].each do |k,v|
192 resource_info = discovery_document["schemas"][k.singularize.capitalize]
193 if resource_info and resource_info.include?('description')
194 # add only the first line of the discovery doc description
195 description = ' ' + resource_info["description"].split("\n").first.chomp
197 banner += " #{sprintf("%30s",k.singularize)}#{description}\n"
202 if not resource.nil? and resource != '--help' then
203 Trollop::die "Unknown resource type #{resource.inspect}"
208 def parse_arguments(discovery_document)
209 resource_types = Array.new()
210 discovery_document["resources"].each do |k,v|
211 resource_types << k.singularize
214 global_opts = Trollop::options do
216 banner "arv: the Arvados CLI tool"
217 opt :dry_run, "Don't actually do anything", :short => "-n"
218 opt :verbose, "Print some things on stderr"
220 "Set the output format. Must be one of json (default), yaml or uuid.",
223 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
224 opt :resources, "Display list of resources known to this Arvados instance."
225 conflicts :short, :format
226 stop_on resource_types
229 unless %w(json yaml uuid).include?(global_opts[:format])
230 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
231 $stderr.puts "Use #{$0} --help for more information."
235 if global_opts[:short]
236 global_opts[:format] = 'uuid'
239 resource = ARGV.shift
240 if global_opts[:resources] or not resource_types.include?(resource)
241 help_resources(discovery_document, resource)
245 if not (discovery_document["resources"][resource.pluralize]["methods"].
247 help_methods(discovery_document, resource, method)
250 discovered_params = discovery_document\
251 ["resources"][resource.pluralize]\
252 ["methods"][method]["parameters"]
253 method_opts = Trollop::options do
254 discovered_params.each do |k,v|
256 opts[:type] = v["type"].to_sym if v.include?("type")
257 if [:datetime, :text, :object, :array].index opts[:type]
258 opts[:type] = :string # else trollop bork
260 opts[:default] = v["default"] if v.include?("default")
261 opts[:default] = v["default"].to_i if opts[:type] == :integer
262 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
263 opts[:required] = true if v.include?("required") and v["required"]
265 description = ' ' + v["description"] if v.include?("description")
266 opt k.to_sym, description, opts
268 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
269 if body_object and discovered_params[resource].nil?
271 if body_object["required"] == false
274 opt resource.to_sym, "#{resource} (request body)", {
275 required: is_required,
281 discovered_params.each do |k,v|
283 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
284 if method_opts[k].andand.match /^\//
285 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
289 return resource, method, method_opts, global_opts, ARGV
292 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
293 controller = resource_schema.pluralize
295 api_method = 'arvados.' + controller + '.' + method
297 if global_opts[:dry_run]
298 if global_opts[:verbose]
299 $stderr.puts "#{api_method} #{method_opts.inspect}"
304 request_parameters = {_profile:true}.merge(method_opts)
305 resource_body = request_parameters.delete(resource_schema.to_sym)
308 resource_schema => resource_body
316 'arvados.jobs.log_tail_follow'
318 # Special case for methods that respond with data streams rather
319 # than JSON (TODO: use the discovery document instead of a static
321 uri_s = eval(api_method).generate_uri(request_parameters)
322 Curl::Easy.perform(uri_s) do |curl|
323 curl.headers['Accept'] = 'text/plain'
324 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
325 if ENV['ARVADOS_API_HOST_INSECURE']
326 curl.ssl_verify_peer = false
327 curl.ssl_verify_host = false
329 if global_opts[:verbose]
330 curl.on_header { |data| $stderr.write data }
332 curl.on_body { |data| $stdout.write data }
336 result = client.execute(:api_method => eval(api_method),
337 :parameters => request_parameters,
338 :body => request_body,
339 :authenticated => false,
341 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
346 results = JSON.parse result.body
347 rescue JSON::ParserError => e
348 abort "Failed to parse server response:\n" + e.to_s
351 if results["errors"] then
352 abort "Error: #{results["errors"][0]}"
355 case global_opts[:format]
357 puts Oj.dump(results, :indent => 1)
361 if results["items"] and results["kind"].match /list$/i
362 results['items'].each do |i| puts i['uuid'] end
363 elsif results['uuid'].nil?
364 abort("Response did not include a uuid:\n" +
365 Oj.dump(results, :indent => 1) +