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/settings.conf')
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 if v.include? "description"
156 # add only the first line of the discovery doc description
157 description = ' ' + v["description"].split("\n").first.chomp
159 banner += " #{sprintf("%20s",k)}#{description}\n"
164 if not method.nil? and method != '--help' then
165 Trollop::die ("Unknown method #{method.inspect} " +
166 "for resource #{resource.inspect}")
171 def help_resources(discovery_document, resource)
173 banner += "This Arvados instance supports the following resource types:"
175 discovery_document["resources"].each do |k,v|
177 resource_info = discovery_document["schemas"][k.singularize.capitalize]
178 if resource_info and resource_info.include?('description')
179 # add only the first line of the discovery doc description
180 description = ' ' + resource_info["description"].split("\n").first.chomp
182 banner += " #{sprintf("%30s",k.singularize)}#{description}\n"
187 if not resource.nil? and resource != '--help' then
188 Trollop::die "Unknown resource type #{resource.inspect}"
193 def parse_arguments(discovery_document)
194 resource_types = Array.new()
195 discovery_document["resources"].each do |k,v|
196 resource_types << k.singularize
199 global_opts = Trollop::options do
200 banner "arv: the Arvados CLI tool"
201 opt :dry_run, "Don't actually do anything", :short => "-n"
202 opt :verbose, "Print some things on stderr"
204 "Set the output format. Must be one of json (default), yaml or uuid.",
207 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
208 opt :resources, "Display list of resources known to this Arvados instance."
209 conflicts :short, :format
210 stop_on resource_types
213 unless %w(json yaml uuid).include?(global_opts[:format])
214 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
215 $stderr.puts "Use #{$0} --help for more information."
219 if global_opts[:short]
220 global_opts[:format] = 'uuid'
223 resource = ARGV.shift
224 if global_opts[:resources] or not resource_types.include?(resource)
225 help_resources(discovery_document, resource)
229 if not (discovery_document["resources"][resource.pluralize]["methods"].
231 help_methods(discovery_document, resource, method)
234 discovered_params = discovery_document\
235 ["resources"][resource.pluralize]\
236 ["methods"][method]["parameters"]
237 method_opts = Trollop::options do
238 discovered_params.each do |k,v|
240 opts[:type] = v["type"].to_sym if v.include?("type")
241 if [:datetime, :text, :object, :array].index opts[:type]
242 opts[:type] = :string # else trollop bork
244 opts[:default] = v["default"] if v.include?("default")
245 opts[:default] = v["default"].to_i if opts[:type] == :integer
246 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
247 opts[:required] = true if v.include?("required") and v["required"]
249 description = ' ' + v["description"] if v.include?("description")
250 opt k.to_sym, description, opts
252 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
253 if body_object and discovered_params[resource].nil?
255 if body_object["required"] == false
258 opt resource.to_sym, "#{resource} (request body)", {
259 required: is_required,
262 discovered_params[resource.to_sym] = body_object
266 discovered_params.each do |k,v|
268 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
269 if method_opts[k].andand.match /^\//
270 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
274 return resource, method, method_opts, global_opts, ARGV
277 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
278 controller = resource_schema.pluralize
280 api_method = 'arvados.' + controller + '.' + method
282 if global_opts[:dry_run]
283 if global_opts[:verbose]
284 $stderr.puts "#{api_method} #{method_opts.inspect}"
289 request_parameters = {}.merge(method_opts)
290 resource_body = request_parameters.delete(resource_schema.to_sym)
293 resource_schema => resource_body
301 'arvados.users.event_stream',
302 'arvados.jobs.log_stream',
303 'arvados.jobs.log_tail_follow'
305 # Special case for methods that respond with data streams rather
306 # than JSON (TODO: use the discovery document instead of a static
308 uri_s = eval(api_method).generate_uri(request_parameters)
309 Curl::Easy.perform(uri_s) do |curl|
310 curl.headers['Accept'] = 'text/plain'
311 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
312 if ENV['ARVADOS_API_HOST_INSECURE']
313 curl.ssl_verify_peer = false
314 curl.ssl_verify_host = false
316 if global_opts[:verbose]
317 curl.on_header { |data| $stderr.write data }
319 curl.on_body { |data| $stdout.write data }
323 request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
324 request_body[:_profile] = true
325 result = client.execute(:api_method => eval(api_method),
326 :parameters => request_parameters,
327 :body => request_body,
328 :authenticated => false)
332 results = JSON.parse result.body
333 rescue JSON::ParserError => e
334 abort "Failed to parse server response:\n" + e.to_s
337 if results["errors"] then
338 abort "Error: #{results["errors"][0]}"
341 case global_opts[:format]
343 puts Oj.dump(results, :indent => 1)
347 if results["items"] and results["kind"].match /list$/i
348 results['items'].each do |i| puts i['uuid'] end
349 elsif results['uuid'].nil?
350 abort("Response did not include a uuid:\n" +
351 Oj.dump(results, :indent => 1) +