Class: CvpClient

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

Overview

Provide simplified RESTful methods to access Arista CloudVision Portal

Establish and maintain connections with Arista CloudVision Portal servers, providing basic RESTful methods which handle session, cookie, and reconnects behind the scenes.

Examples:

Basic usage

require 'cvprac'
cvp = CvpClient.new
cvp.connect(['cvp1', 'cvp2', 'cvp3'], 'cvpadmin', 'arista123')
result = cvp.get('/user/getUsers.do',
                 data: {queryparam: nil,
                        startIndex: 0,
                        endIndex: 0})
pp(result)
{"total"=>1,
 "users"=>
  [{"userId"=>"cvpadmin",
    "firstName"=>nil,
    "email"=>"[email protected]",
    "lastAccessed"=>1483726955950,
    "userStatus"=>"Enabled",
    "currentStatus"=>"Online",
    "contactNumber"=>nil,
    "factoryId"=>1,
    "lastName"=>nil,
    "password"=>nil,
    "id"=>28}],
 "roles"=>{"cvpadmin"=>["network-admin"]}}

cvp.post('/test/endpoint.do', body: '{"some":"data"}')

Author:

Constant Summary collapse

NUM_RETRY_REQUESTS =

Maximum number of times to retry a get or post to the same CVP node.

3

Instance Attribute Summary collapse

RESTful methods collapse

Instance Method Summary collapse

Constructor Details

#initialize(**opts) ⇒ CvpClient

Initialize a new CvpClient object

Parameters:

  • opts (Hash)

    Optional arguments

Options Hash (**opts):

  • :logger (String) — default: 'cvprac'

    Logging name for this service

  • :syslog (Bool) — default: false

    Log to the syslog service?

  • :filename (String) — default: nil

    A local logfile to use, if provided

  • :file_log_level (Logger::level) — default: Logger::INFO

    The default logging level which will be recorded in the logs. See the Logging rubygem for additional severity levels



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/cvprac/client.rb', line 146

def initialize(**opts)
  opts = { logger: 'cvprac',
           syslog: false,
           filename: nil,
           file_log_level: Logger::INFO }.merge(opts)
  @agent = File.basename($PROGRAM_NAME)
  @agent_full = "#{@agent} (#{RUBY_PLATFORM}) "\
                "cvprac-rb/#{Cvprac::VERSION}"
  @authdata = nil
  @connect_timeout = nil
  @cookies = HTTP::CookieJar.new
  @error_msg = nil
  @file_log_level = opts[:file_log_level]
  @headers = { 'Accept' => 'application/json',
               'Content-Type' => 'application/json',
               'User-agent' => @agent_full }
  @node_count = nil
  @node_pool = nil
  @nodes = nil
  @port = nil
  @protocol = nil
  @session = nil
  # OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER
  @ssl_verify_mode = OpenSSL::SSL::VERIFY_NONE
  @url_prefix = nil

  if opts[:filename] == 'STDOUT'
    @logstdout = Logger.new(STDOUT)
    @logstdout.level = @file_log_level
  else
    unless opts[:filename].nil?
      @logfile = Logger.new(opts[:filename])
      @logfile.level = @file_log_level
    end
  end
  @syslog = Syslog::Logger.new(opts[:filename]) if opts[:syslog]

  # Instantiate the CvpApi class
  @api = CvpApi.new(self)

  log(Logger::INFO, 'CvpClient initialized')
end

Instance Attribute Details

#agentString

Agent is the first part of the complete User-Agent

Examples:

User-Agent

"User-agent"=>"cvp_app (x86_64-darwin14) cvprac-rb/0.1.0"

Returns:

  • (String)

    Application name included in HTTP User-Agent passed to CloudVision Portal. (Default: $PROGRAM_NAME) The full User-Agent string includes the application name, system-OS, and cvprac version information.



118
119
120
# File 'lib/cvprac/client.rb', line 118

def agent
  @agent
end

#apiObject

An instance of CvpApi



118
119
# File 'lib/cvprac/client.rb', line 118

attr_accessor :agent, :connect_timeout, :headers,
:port, :protocol, :ssl_verify_mode, :file_log_level, :api

#connect_timeoutFixnum

Returns Max number of seconds before failing an HTTP connect.

Returns:

  • (Fixnum)

    Max number of seconds before failing an HTTP connect



118
119
# File 'lib/cvprac/client.rb', line 118

attr_accessor :agent, :connect_timeout, :headers,
:port, :protocol, :ssl_verify_mode, :file_log_level, :api

#cookiesHTTP::CookieJar (readonly)

request

Returns:

  • (HTTP::CookieJar)

    HTTP cookies sent with each authenticated



128
129
130
# File 'lib/cvprac/client.rb', line 128

def cookies
  @cookies
end

#file_log_levelObject

Returns the value of attribute file_log_level.



118
119
120
# File 'lib/cvprac/client.rb', line 118

def file_log_level
  @file_log_level
end

#headersHash

Returns HTTP headers sent with each request.

Returns:

  • (Hash)

    HTTP headers sent with each request



118
119
# File 'lib/cvprac/client.rb', line 118

attr_accessor :agent, :connect_timeout, :headers,
:port, :protocol, :ssl_verify_mode, :file_log_level, :api

#logger.levelObject

logger severity level: Logger::DEBUG < Logger::INFO < Logger::WARN < Logger::ERROR < Logger::FATAL. This allows the user to increase or decrease the logging level of the STDOUT log as needed throughout their application.



118
119
# File 'lib/cvprac/client.rb', line 118

attr_accessor :agent, :connect_timeout, :headers,
:port, :protocol, :ssl_verify_mode, :file_log_level, :api

#nodesObject (readonly)

Returns the value of attribute nodes.



128
# File 'lib/cvprac/client.rb', line 128

attr_reader :cookies, :headers, :nodes

#portFixnum

Returns TCP port used for connections.

Returns:

  • (Fixnum)

    TCP port used for connections



118
119
# File 'lib/cvprac/client.rb', line 118

attr_accessor :agent, :connect_timeout, :headers,
:port, :protocol, :ssl_verify_mode, :file_log_level, :api

#protocolString

Returns ‘http’ or ‘https’.

Returns:

  • (String)

    ‘http’ or ‘https’



118
119
# File 'lib/cvprac/client.rb', line 118

attr_accessor :agent, :connect_timeout, :headers,
:port, :protocol, :ssl_verify_mode, :file_log_level, :api

#ssl_verify_modeObject

OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER



118
119
# File 'lib/cvprac/client.rb', line 118

attr_accessor :agent, :connect_timeout, :headers,
:port, :protocol, :ssl_verify_mode, :file_log_level, :api

Instance Method Details

#connect(nodes, username, password, **opts) ⇒ Object

Connect to one or more CVP nodes.

Parameters:

  • nodes (Array)

    Hostnames or IPs of the CVP node or nodes

  • username (String)

    CVP username

  • password (String)

    CVP password

  • opts (Hash)

    Optional arguments

Options Hash (**opts):

  • :connect_timeout (Fixnum) — default: 10

    Seconds to wait before failing a connect. Default: 10

  • :protocol (String) — default: 'https'

    ‘http’ or ‘https’ to use when connecting to the CVP. Default: https

  • :port (Fixnum) — default: nil

    TCP port to which we should connect is not standard http/https port.

  • :verify_ssl (Bool) — default: false

    Verify CVP SSL certificate? Requires that a valid (non-self-signed) certificate be installed on the CloudVision Portal node(s).

Raises:



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/cvprac/client.rb', line 225

def connect(nodes, username, password, **opts)
  opts = { connect_timeout: 10,
           protocol: 'https',
           port: nil,
           verify_ssl: false }.merge(opts)
  connect_timeout = opts[:connect_timeout]
  protocol = opts[:protocol]
  port = opts[:port]

  @nodes = Array(nodes) # Ensure nodes is always an array
  @node_index = 0
  @node_count = nodes.length
  @node_last = @node_count - 1
  @node_pool = Enumerator.new do |y|
    loop do
      index = @node_index % @node_count
      if @node_index == @node_last
        @node_index = 0
      else
        @node_index += 1
      end
      y.yield @nodes[index]
    end
  end
  @authdata = { userId: username, password: password }
  @connect_timeout = connect_timeout
  @protocol = protocol

  if port.nil?
    if protocol == 'http'
      port = 80
    elsif protocol == 'https'
      port = 443
    else
      raise ArgumentError, "No default port for protocol: #{protocol}"
    end
  end
  @port = port

  @ssl_verify_mode = if opts[:verify_ssl]
                       OpenSSL::SSL::VERIFY_PEER
                     else
                       OpenSSL::SSL::VERIFY_NONE
                     end

  create_session(nil)
  raise CvpLoginError, @error_msg unless @session
end

#get(endpoint, **opts) ⇒ JSON

Send an HTTP GET request with session data and return the response.

Parameters:

  • endpoint (String)

    URL endpoint starting after ‘host:port/web`

  • opts (Hash)

    Optional parameters

Options Hash (**opts):

  • :data (Hash) — default: nil

    query parameters

Returns:

  • (JSON)

    parsed response body



285
286
287
288
# File 'lib/cvprac/client.rb', line 285

def get(endpoint, **opts)
  data = opts.key?(:data) ? opts[:data] : nil
  make_request(:get, endpoint, data: data)
end

#log(severity: Logger::INFO, msg: nil) ⇒ Object #log(severity: Logger::INFO) {|msg| ... } ⇒ Object

Log message to all configured loggers

Overloads:

  • #log(severity: Logger::INFO, msg: nil) ⇒ Object

    Parameters:

    • severity (Logger) (defaults to: Logger::INFO)

      Severity to log to: DEBUG < INFO < WARN < ERROR < FATAL

    • msg (String) (defaults to: nil)

      Message to log

  • #log(severity: Logger::INFO) {|msg| ... } ⇒ Object

    Parameters:

    • severity (Logger) (defaults to: Logger::INFO)

      Severity to log to: DEBUG < INFO < WARN < ERROR < FATAL

    Yields:

    • (msg)

      Messages can be passed as a block to delay evaluation



200
201
202
203
204
205
# File 'lib/cvprac/client.rb', line 200

def log(severity = Logger::INFO, msg = nil)
  msg = yield if block_given?
  @logstdout.add(severity, msg) if defined? @logstdout
  @logfile.add(severity, msg) if defined? @logfile
  @syslog.add(severity, msg) if defined? @syslog
end

#post(endpoint, **opts) ⇒ Net::HTTP Response

Send an HTTP POST request with session data and return the response.

Parameters:

  • endpoint (String)

    URL endpoint starting after ‘host:port/web`

  • opts (Hash)

    Optional parameters

Options Hash (**opts):

  • :body (JSON) — default: nil

    JSON body to post

  • :data (Hash) — default: nil

    query parameters

Returns:

  • (Net::HTTP Response)


298
299
300
301
302
# File 'lib/cvprac/client.rb', line 298

def post(endpoint, **opts)
  data = opts.key?(:data) ? opts[:data] : nil
  body = opts.key?(:body) ? opts[:body] : nil
  make_request(:post, endpoint, data: data, body: body)
end