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
45 elsif @sub == 'docker'
46 exec `which arv-keepdocker`.strip, *ARGV
53 "#{$0} keep check\n" +
60 if ['run'].index @sub then
61 exec `which arv-run-pipeline-instance`.strip, *ARGV
64 "#{$0} pipeline run [...]\n" +
65 "(see arv-run-pipeline-instance --help for details)\n"
70 exec `which arv-tag`.strip, *ARGV
73 ENV['ARVADOS_API_VERSION'] ||= 'v1'
75 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
77 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
84 require 'google/api_client'
90 require 'active_support/inflector'
95 Please install all required gems:
97 gem install activesupport andand curb google-api-client json oj trollop
102 ActiveSupport::Inflector.inflections do |inflect|
103 inflect.irregular 'specimen', 'specimens'
104 inflect.irregular 'human', 'humans'
108 def suppress_warnings
109 original_verbosity = $VERBOSE
112 $VERBOSE = original_verbosity
117 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
118 if ENV['ARVADOS_API_HOST_INSECURE']
119 suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
122 class Google::APIClient
123 def discovery_document(api, version)
125 return @discovery_documents["#{api}:#{version}"] ||=
127 # fetch new API discovery doc if stale
128 cached_doc = File.expand_path '~/.cache/arvados/discovery_uri.json'
129 if not File.exist?(cached_doc) or (Time.now - File.mtime(cached_doc)) > 86400
130 response = self.execute!(:http_method => :get,
131 :uri => self.discovery_uri(api, version),
132 :authenticated => false)
133 FileUtils.makedirs(File.dirname cached_doc)
134 File.open(cached_doc, 'w') do |f|
139 File.open(cached_doc) { |f| JSON.load f }
144 class ArvadosClient < Google::APIClient
146 if args.last.is_a? Hash
147 args.last[:headers] ||= {}
148 args.last[:headers]['Accept'] ||= 'application/json'
155 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
156 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
157 rescue Exception => e
158 puts "Failed to connect to Arvados API server: #{e}"
163 !!(s =~ /^(true|t|yes|y|1)$/i)
166 def help_methods(discovery_document, resource, method=nil)
168 banner += "The #{resource} resource type supports the following methods:"
170 discovery_document["resources"][resource.pluralize]["methods"].
173 if v.include? "description"
174 # add only the first line of the discovery doc description
175 description = ' ' + v["description"].split("\n").first.chomp
177 banner += " #{sprintf("%20s",k)}#{description}\n"
182 if not method.nil? and method != '--help' then
183 Trollop::die ("Unknown method #{method.inspect} " +
184 "for resource #{resource.inspect}")
189 def help_resources(discovery_document, resource)
191 banner += "This Arvados instance supports the following resource types:"
193 discovery_document["resources"].each do |k,v|
195 resource_info = discovery_document["schemas"][k.singularize.capitalize]
196 if resource_info and resource_info.include?('description')
197 # add only the first line of the discovery doc description
198 description = ' ' + resource_info["description"].split("\n").first.chomp
200 banner += " #{sprintf("%30s",k.singularize)}#{description}\n"
205 if not resource.nil? and resource != '--help' then
206 Trollop::die "Unknown resource type #{resource.inspect}"
211 def parse_arguments(discovery_document)
212 resource_types = Array.new()
213 discovery_document["resources"].each do |k,v|
214 resource_types << k.singularize
217 global_opts = Trollop::options do
219 banner "arv: the Arvados CLI tool"
220 opt :dry_run, "Don't actually do anything", :short => "-n"
221 opt :verbose, "Print some things on stderr"
223 "Set the output format. Must be one of json (default), yaml or uuid.",
226 opt :short, "Return only UUIDs (equivalent to --format=uuid)"
227 opt :resources, "Display list of resources known to this Arvados instance."
228 conflicts :short, :format
229 stop_on resource_types
232 unless %w(json yaml uuid).include?(global_opts[:format])
233 $stderr.puts "#{$0}: --format must be one of json, yaml or uuid."
234 $stderr.puts "Use #{$0} --help for more information."
238 if global_opts[:short]
239 global_opts[:format] = 'uuid'
242 resource = ARGV.shift
243 if global_opts[:resources] or not resource_types.include?(resource)
244 help_resources(discovery_document, resource)
248 if not (discovery_document["resources"][resource.pluralize]["methods"].
250 help_methods(discovery_document, resource, method)
253 discovered_params = discovery_document\
254 ["resources"][resource.pluralize]\
255 ["methods"][method]["parameters"]
256 method_opts = Trollop::options do
257 discovered_params.each do |k,v|
259 opts[:type] = v["type"].to_sym if v.include?("type")
260 if [:datetime, :text, :object, :array].index opts[:type]
261 opts[:type] = :string # else trollop bork
263 opts[:default] = v["default"] if v.include?("default")
264 opts[:default] = v["default"].to_i if opts[:type] == :integer
265 opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
266 opts[:required] = true if v.include?("required") and v["required"]
268 description = ' ' + v["description"] if v.include?("description")
269 opt k.to_sym, description, opts
271 body_object = discovery_document["resources"][resource.pluralize]["methods"][method]["request"]
272 if body_object and discovered_params[resource].nil?
274 if body_object["required"] == false
277 opt resource.to_sym, "#{resource} (request body)", {
278 required: is_required,
284 discovered_params.each do |k,v|
286 if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
287 if method_opts[k].andand.match /^\//
288 method_opts[k] = File.open method_opts[k], 'rb' do |f| f.read end
292 return resource, method, method_opts, global_opts, ARGV
295 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
296 controller = resource_schema.pluralize
298 api_method = 'arvados.' + controller + '.' + method
300 if global_opts[:dry_run]
301 if global_opts[:verbose]
302 $stderr.puts "#{api_method} #{method_opts.inspect}"
307 request_parameters = {_profile:true}.merge(method_opts)
308 resource_body = request_parameters.delete(resource_schema.to_sym)
311 resource_schema => resource_body
319 'arvados.jobs.log_tail_follow'
321 # Special case for methods that respond with data streams rather
322 # than JSON (TODO: use the discovery document instead of a static
324 uri_s = eval(api_method).generate_uri(request_parameters)
325 Curl::Easy.perform(uri_s) do |curl|
326 curl.headers['Accept'] = 'text/plain'
327 curl.headers['Authorization'] = "OAuth2 #{ENV['ARVADOS_API_TOKEN']}"
328 if ENV['ARVADOS_API_HOST_INSECURE']
329 curl.ssl_verify_peer = false
330 curl.ssl_verify_host = false
332 if global_opts[:verbose]
333 curl.on_header { |data| $stderr.write data }
335 curl.on_body { |data| $stdout.write data }
339 result = client.execute(:api_method => eval(api_method),
340 :parameters => request_parameters,
341 :body => request_body,
342 :authenticated => false,
344 authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
349 results = JSON.parse result.body
350 rescue JSON::ParserError => e
351 abort "Failed to parse server response:\n" + e.to_s
354 if results["errors"] then
355 abort "Error: #{results["errors"][0]}"
358 case global_opts[:format]
360 puts Oj.dump(results, :indent => 1)
364 if results["items"] and results["kind"].match /list$/i
365 results['items'].each do |i| puts i['uuid'] end
366 elsif results['uuid'].nil?
367 abort("Response did not include a uuid:\n" +
368 Oj.dump(results, :indent => 1) +