Class: Vra::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/vra/client.rb

Overview

rubocop:disable ClassLength

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Client

Returns a new instance of Client.



28
29
30
31
32
33
34
35
36
37
# File 'lib/vra/client.rb', line 28

def initialize(opts)
  @base_url     = opts[:base_url]
  @username     = opts[:username]
  @password     = PasswordMasker.new(opts[:password])
  @tenant       = opts[:tenant]
  @verify_ssl   = opts.fetch(:verify_ssl, true)
  @bearer_token = PasswordMasker.new(nil)

  validate_client_options!
end

Instance Attribute Details

#bearer_tokenObject

Returns the value of attribute bearer_token.



26
27
28
# File 'lib/vra/client.rb', line 26

def bearer_token
  @bearer_token
end

Instance Method Details

#authorize!Object



77
78
79
80
81
# File 'lib/vra/client.rb', line 77

def authorize!
  generate_bearer_token unless authorized?

  raise Vra::Exception::Unauthorized, 'Unable to authorize against vRA' unless authorized?
end

#authorized?Boolean

Returns:

  • (Boolean)


83
84
85
86
87
88
89
90
91
92
# File 'lib/vra/client.rb', line 83

def authorized?
  return false if @bearer_token.value.nil?

  response = http_head("/identity/api/tokens/#{@bearer_token.value}", :skip_auth)
  if response.code == 204
    true
  else
    false
  end
end

#bearer_token_request_bodyObject

client methods



61
62
63
64
65
66
67
# File 'lib/vra/client.rb', line 61

def bearer_token_request_body
  {
    'username' => @username,
    'password' => @password.value,
    'tenant'   => @tenant
  }
end

#catalogObject

methods to other classes



44
45
46
# File 'lib/vra/client.rb', line 44

def catalog
  Vra::Catalog.new(self)
end

#full_url(path) ⇒ Object



106
107
108
# File 'lib/vra/client.rb', line 106

def full_url(path)
  "#{@base_url}#{path}"
end

#generate_bearer_tokenObject



94
95
96
97
98
99
100
101
102
103
104
# File 'lib/vra/client.rb', line 94

def generate_bearer_token
  @bearer_token.value = nil
  validate_client_options!

  response = http_post('/identity/api/tokens', bearer_token_request_body.to_json, :skip_auth)
  if response.code != 200
    raise Vra::Exception::Unauthorized, "Unable to get bearer token: #{response.body}"
  end

  @bearer_token.value = FFI_Yajl::Parser.parse(response.body)['id']
end

#http_get(path, skip_auth = nil) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/vra/client.rb', line 123

def http_get(path, skip_auth=nil)
  authorize! unless skip_auth

  response = RestClient::Request.execute(method: :get,
                                         url: full_url(path),
                                         headers: request_headers,
                                         verify_ssl: @verify_ssl)
rescue => e
  raise_http_exception(e, path)
else
  response
end

#http_get!(path) ⇒ Object



136
137
138
139
# File 'lib/vra/client.rb', line 136

def http_get!(path)
  response = http_get(path)
  response.body
end

#http_get_paginated_array!(path, limit = 20) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/vra/client.rb', line 141

def http_get_paginated_array!(path, limit=20)
  items = []
  page = 1
  base_path = path + "?limit=#{limit}"

  loop do
    response = FFI_Yajl::Parser.parse(http_get!("#{base_path}&page=#{page}"))
    items += response['content']

    break if page >= response['metadata']['totalPages']
    page += 1
  end

  items
end

#http_head(path, skip_auth = nil) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/vra/client.rb', line 110

def http_head(path, skip_auth=nil)
  authorize! unless skip_auth

  response = RestClient::Request.execute(method: :head,
                                         url: full_url(path),
                                         headers: request_headers,
                                         verify_ssl: @verify_ssl)
rescue => e
  raise Vra::Exception::HTTPError, "head #{path} failed: #{e.class}: #{e.message}"
else
  response
end

#http_post(path, payload, skip_auth = nil) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/vra/client.rb', line 157

def http_post(path, payload, skip_auth=nil)
  authorize! unless skip_auth

  response = RestClient::Request.execute(method: :post,
                                         url: full_url(path),
                                         headers: request_headers,
                                         payload: payload,
                                         verify_ssl: @verify_ssl)
rescue => e
  raise_http_exception(e, path)
else
  response
end

#http_post!(path, payload) ⇒ Object



171
172
173
174
# File 'lib/vra/client.rb', line 171

def http_post!(path, payload)
  response = http_post(path, payload)
  response.body
end

#raise_http_exception(caught_exception, path) ⇒ Object

Raises:

  • (exception)


176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/vra/client.rb', line 176

def raise_http_exception(caught_exception, path)
  raise unless caught_exception.respond_to?(:http_code)

  if caught_exception.http_code == 404
    klass = Vra::Exception::HTTPNotFound
  else
    klass = Vra::Exception::HTTPError
  end

  exception = klass.new(code: caught_exception.http_code,
                        body: caught_exception.response,
                        klass: caught_exception.class,
                        path: path)

  message = exception.errors.empty? ? caught_exception.message : exception.errors.join(', ')
  raise exception, message
end

#request_headersObject



69
70
71
72
73
74
75
# File 'lib/vra/client.rb', line 69

def request_headers
  headers = {}
  headers['Accept']        = 'application/json'
  headers['Content-Type']  = 'application/json'
  headers['Authorization'] = "Bearer #{@bearer_token.value}" unless @bearer_token.value.nil?
  headers
end

#requests(*args) ⇒ Object



48
49
50
# File 'lib/vra/client.rb', line 48

def requests(*args)
  Vra::Requests.new(self, *args)
end

#resources(*args) ⇒ Object



52
53
54
# File 'lib/vra/client.rb', line 52

def resources(*args)
  Vra::Resources.new(self, *args)
end

#valid_uri?(uri) ⇒ Boolean

Returns:

  • (Boolean)


201
202
203
204
205
206
# File 'lib/vra/client.rb', line 201

def valid_uri?(uri)
  uri = URI.parse(uri)
  uri.is_a?(URI::HTTP)
rescue URI::InvalidURIError
  false
end

#validate_client_options!Object

Raises:

  • (ArgumentError)


194
195
196
197
198
199
# File 'lib/vra/client.rb', line 194

def validate_client_options!
  raise ArgumentError, 'Username and password are required' if @username.nil? || @password.value.nil?
  raise ArgumentError, 'A tenant is required' if @tenant.nil?
  raise ArgumentError, 'A base URL is required' if @base_url.nil?
  raise ArgumentError, "Base URL #{@base_url} is not a valid URI." unless valid_uri?(@base_url)
end