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