0abd976fc54363e008a6dfdad20dbdfe60918586
[arvados.git] / sdk / cli / bin / arv
1 #!/usr/bin/env ruby
2
3 # Arvados cli client
4 #
5 # Ward Vandewege <ward@clinicalfuture.com>
6
7 if RUBY_VERSION < '1.9.3' then
8   abort <<-EOS
9 #{$0.gsub(/^\.\//,'')} requires Ruby version 1.9.3 or higher.
10   EOS
11 end
12
13 if ARGV[0] == 'keep'
14   ARGV.shift
15   @sub = ARGV.shift
16   if ['ls', 'get', 'put', 'less', 'check'].index @sub then
17     exec `which wh#{@sub}`.strip, *ARGV
18   else
19     puts "Usage: \n" +
20       "#{$0} keep ls\n" +
21       "#{$0} keep get\n" +
22       "#{$0} keep put\n" +
23       "#{$0} keep less\n" +
24       "#{$0} keep check\n"
25   end
26   abort
27 end
28
29 if ARGV[0] == 'pipeline'
30   ARGV.shift
31   @sub = ARGV.shift
32   if ['run'].index @sub then
33     exec `which arv-run-pipeline-instance`.strip, *ARGV
34   else
35     puts "Usage: \n" +
36       "#{$0} pipeline run [...]\n" +
37       "(see arv-run-pipeline-instance --help for details)\n"
38   end
39   abort
40 end
41
42 ENV['ARVADOS_API_VERSION'] ||= 'v1'
43
44 if not ENV.include?('ARVADOS_API_HOST') or not ENV.include?('ARVADOS_API_TOKEN') then
45   abort <<-EOS
46 ARVADOS_API_HOST and ARVADOS_API_TOKEN need to be defined as environment variables.
47   EOS
48 end
49
50 begin
51   require 'rubygems'
52   require 'google/api_client'
53   require 'json'
54   require 'pp'
55   require 'trollop'
56   require 'andand'
57   require 'oj'
58   require 'active_support/inflector'
59 rescue LoadError
60   abort <<-EOS
61
62 Please install all required gems: 
63
64   gem install google-api-client json trollop andand oj activesupport
65
66   EOS
67 end
68
69 ActiveSupport::Inflector.inflections do |inflect|
70   inflect.irregular 'specimen', 'specimens'
71   inflect.irregular 'human', 'humans'
72 end
73
74 module Kernel
75   def suppress_warnings
76     original_verbosity = $VERBOSE
77     $VERBOSE = nil
78     result = yield
79     $VERBOSE = original_verbosity
80     return result
81   end
82 end
83
84 # do this if you're testing with a dev server and you don't care about SSL certificate checks:
85 if ENV['ARVADOS_API_HOST_INSECURE']
86   suppress_warnings { OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE }
87 end
88
89 class Google::APIClient
90  def discovery_document(api, version)
91   api = api.to_s
92   return @discovery_documents["#{api}:#{version}"] ||= (begin
93     response = self.execute!(
94       :http_method => :get,
95       :uri => self.discovery_uri(api, version),
96       :authenticated => false
97     )
98     response.body.class == String ? JSON.parse(response.body) : response.body
99   end)
100  end
101 end
102
103 class ArvadosClient < Google::APIClient
104   def execute(*args)
105     if args.last.is_a? Hash
106       args.last[:headers] ||= {}
107       args.last[:headers]['Accept'] ||= 'application/json'
108     end
109     super(*args)
110   end
111 end
112
113 client = ArvadosClient.new(:host => ENV['ARVADOS_API_HOST'], :application_name => 'arvados-cli', :application_version => '1.0')
114 arvados = client.discovered_api('arvados', ENV['ARVADOS_API_VERSION'])
115
116 def to_boolean(s)
117   !!(s =~ /^(true|t|yes|y|1)$/i)
118 end
119
120 def parse_arguments(discovery_document)
121   resource_types = Array.new()
122   resource_types << '--help'
123   discovery_document["resources"].each do |k,v|
124     resource_types << k.singularize
125   end
126
127   global_opts = Trollop::options do
128     banner "arvados cli client"
129     opt :dry_run, "Don't actually do anything", :short => "-n"
130     opt :verbose, "Print some things on stderr", :short => "-v"
131     opt :uuid, "Return the UUIDs of the objects in the response, one per line (default)", :short => nil
132     opt :json, "Return the entire response received from the API server, as a JSON object", :short => "-j"
133     opt :human, "Return the response received from the API server, as a JSON object with whitespace added for human consumption", :short => "-h"
134     opt :pretty, "Synonym of --human", :short => nil
135     stop_on resource_types
136   end
137   
138   # get the subcommand
139   resource_arg = ARGV.shift
140   if resource_types.include?(resource_arg) and resource_arg != '--help' then
141     # subcommand exists
142     # Now see if the method supplied exists
143     method = ARGV.shift
144     if discovery_document["resources"][resource_arg.pluralize]["methods"].include?(method) then
145       # method exists. Collect arguments.
146       discovered_params = discovery_document["resources"][resource_arg.pluralize]["methods"][method]["parameters"]
147       method_opts = Trollop::options do
148         discovered_params.each do |k,v|
149           opts = Hash.new()
150           opts[:type] = v["type"].to_sym if v.include?("type")
151           if [:datetime, :text, :object, :array].index opts[:type]
152             opts[:type] = :string                       # else trollop bork
153           end
154           opts[:default] = v["default"] if v.include?("default")
155           opts[:default] = v["default"].to_i if opts[:type] == :integer
156           opts[:default] = to_boolean(v["default"]) if opts[:type] == :boolean
157           opts[:required] = true if v.include?("required") and v["required"]
158           description = ''
159           description = '  ' + v["description"] if v.include?("description")
160           opt k.to_sym, description, opts
161         end
162         body_object = discovery_document["resources"][resource_arg.pluralize]["methods"][method]["request"]
163         if body_object and discovered_params[resource_arg].nil?
164           is_required = true
165           if body_object["required"] == false
166             is_required = false
167           end
168           opt resource_arg.to_sym, "#{resource_arg} (request body)", required: is_required, type: :string
169         end
170       end
171       discovered_params.each do |k,v|
172         if ['object', 'array'].index(v["type"]) and method_opts.has_key? k
173           method_opts[k] = JSON.parse method_opts[k]
174         end
175       end
176     else
177       banner = "\nThis resource type supports the following methods:\n\n"
178       discovery_document["resources"][resource_arg.pluralize]["methods"].each do |k,v|
179         description = ''
180         description = '  ' + v["description"] if v.include?("description")
181         banner += "   #{sprintf("%20s",k)}#{description}\n"
182       end
183       banner += "\n"
184
185       STDERR.puts banner
186   
187       if not method.nil? and method != '--help' then 
188         Trollop::die "Unknown method #{method.to_s} for command #{resource_arg.to_s}"
189       else
190         exit 255
191       end
192
193     end
194     
195   else
196     banner = "\nThis Arvados instance supports the following resource types:\n\n"
197     discovery_document["resources"].each do |k,v|
198       description = ''
199       if discovery_document["schemas"].include?(k.singularize.capitalize) and 
200          discovery_document["schemas"][k.singularize.capitalize].include?('description') then
201         description = '  ' + discovery_document["schemas"][k.singularize.capitalize]["description"]
202       end
203       banner += "   #{sprintf("%30s",k.singularize)}#{description}\n"
204     end
205     banner += "\n"
206
207     STDERR.puts banner
208
209     if not resource_arg.nil? and resource_arg != '--help' then 
210       Trollop::die "Unknown resource type #{resource_arg.inspect}"
211     else
212       exit 255
213     end
214   end
215
216   return resource_arg, method, method_opts, global_opts, ARGV
217 end
218
219 resource_schema, method, method_opts, global_opts, remaining_opts = parse_arguments(arvados.discovery_document)
220 controller = resource_schema.pluralize
221
222 api_method = 'arvados.' + controller + '.' + method
223
224 if global_opts[:dry_run]
225   if global_opts[:verbose]
226     $stderr.puts "#{api_method} #{method_opts.inspect}"
227   end
228   exit
229 end
230
231 request_parameters = {}.merge(method_opts)
232 resource_body = request_parameters.delete(resource_schema.to_sym)
233 if resource_body
234   request_body = {
235     resource_schema => JSON.parse(resource_body)
236   }
237 else
238   request_body = {}
239 end
240 request_body[:api_token] = ENV['ARVADOS_API_TOKEN']
241 result = client.execute(:api_method => eval(api_method),
242                         :parameters => request_parameters,
243                         :body => request_body,
244                         :authenticated => false)
245 results = JSON.parse result.body
246
247 if results["errors"] then
248   abort "Error: #{results["errors"][0]}"
249 end
250
251 if global_opts[:human] or global_opts[:pretty] then
252   puts Oj.dump(results, :indent => 1)
253 elsif global_opts[:json] then
254   puts Oj.dump(results)
255 elsif results["items"] and results["kind"].match /list$/i
256   results['items'].each do |i| puts i['uuid'] end
257 else
258   puts results['uuid']
259 end