Class: Cisco::Client::GRPC

Inherits:
Cisco::Client show all
Defined in:
lib/cisco_node_utils/client/grpc.rb,
lib/cisco_node_utils/client/grpc/client.rb

Overview

Client implementation using gRPC API for IOS XR

Instance Attribute Summary collapse

Attributes inherited from Cisco::Client

#cache_auto, #data_formats, #platform

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Cisco::Client

#cache_auto?, #cache_enable=, #cache_enable?, clients, create, filter_cli, filter_data, find_subconfig, handle_errors, #inspect, #munge_to_array, munge_to_array, register_client, silence_warnings, #supports?, to_regexp, #to_s

Constructor Details

#initialize(**kwargs) ⇒ GRPC


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 36

def initialize(**kwargs)
  # Defaults for gRPC:
  kwargs[:host] ||= '127.0.0.1'
  kwargs[:port] ||= 57_400
  # rubocop:disable Style/HashSyntax
  super(data_formats: [:cli, :yang_json],
        platform:     :ios_xr,
        **kwargs)
  # rubocop:enable Style/HashSyntax
  @config = GRPCConfigOper::Stub.new(@address, :this_channel_is_insecure)
  @exec = GRPCExec::Stub.new(@address, :this_channel_is_insecure)

  # Make sure we can actually connect
  @timeout = 10
  begin
    base_msg = 'gRPC client creation failure: '
    get(command: 'show clock')
  rescue Cisco::ClientError => e
    error 'initial connect failed: ' + e.to_s
    if e.message[/deadline exceeded/i]
      raise Cisco::ConnectionRefused, \
            base_msg + 'timed out during initial connection: ' + e.message
    end
    raise e.class, base_msg + e.message
  end

  # Let commands in general take up to 2 minutes
  @timeout = 120
end

Instance Attribute Details

#timeoutObject

Returns the value of attribute timeout


34
35
36
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 34

def timeout
  @timeout
end

Class Method Details

.validate_args(**kwargs) ⇒ Object


66
67
68
69
70
71
72
73
74
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 66

def self.validate_args(**kwargs)
  super
  base_msg = 'gRPC client creation failure: '
  # Connection to remote system - username and password are required
  fail TypeError, base_msg + 'username must be specified' \
    if kwargs[:username].nil?
  fail TypeError, base_msg + 'password must be specified' \
    if kwargs[:password].nil?
end

Instance Method Details

#cache_flushObject


76
77
78
79
80
81
82
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 76

def cache_flush
  @cache_hash = {
    'cli_config'           => {},
    'show_cmd_text_output' => {},
    'show_cmd_json_output' => {},
  }
end

#get(data_format: :cli, command: nil, context: nil, value: nil, **kwargs) ⇒ Object


131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 131

def get(data_format: :cli,
        command:     nil,
        context:     nil,
        value:       nil,
        **kwargs)
  super
  fail ArgumentError if command.nil?

  if data_format == :yang_json
    mode = kwargs[:mode] || :get_config
    yang_req(@config, mode, ConfigGetArgs.new(yangpathjson: command))
  else
    args = ShowCmdArgs.new(cli: command)
    output = req(@exec, 'show_cmd_text_output', args)
    self.class.filter_cli(cli_output: output, context: context, value: value)
  end
end

#handle_errors(args, error_responses) ⇒ Object


298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 298

def handle_errors(args, error_responses)
  return if error_responses.empty?
  debug "#{error_responses.length} response(s) had errors:"
  error_responses.each { |r| debug "  error:\n#{r.errors}" }
  first_error = error_responses.first.errors
  # Conveniently for us, all *Reply protobufs in EMS have an errors field
  # Less conveniently, some are JSON and some are not.
  begin
    msg = JSON.parse(first_error)
    handle_json_error(msg)
  rescue JSON::ParserError
    handle_text_error(args, first_error)
  end
end

#handle_json_error(msg) ⇒ Object

Generate a CliError from a failed CliConfigReply


331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 331

def handle_json_error(msg)
  # {
  #   "cisco-grpc:errors": {
  #   "error": [
  #     {
  #       "error-type": "application",
  #       "error-tag": "operation-failed",
  #       "error-severity": "error",
  #       "error-message": "....",
  #     },
  #     {
  #       ...

  # {
  #   "cisco-grpc:errors": [
  #     {
  #       "error-type": "protocol",
  #       "error-message": "Failed authentication"
  #     }
  #   ]
  # }

  msg = msg['cisco-grpc:errors']
  msg = msg['error'] unless msg.is_a?(Array)
  msg.each do |m|
    type = m['error-type']
    message = m['error-message'] || m['error-tag']
    message += ': ' + m['error-path'] if m['error-path']
    if type == 'protocol' && message == 'Failed authentication'
      fail Cisco::AuthenticationFailed, message
    elsif type == 'application'
      # Example message:
      # !! SYNTAX/AUTHORIZATION ERRORS: This configuration failed due to
      # !! one or more of the following reasons:
      # !!  - the entered commands do not exist,
      # !!  - the entered commands have errors in their syntax,
      # !!  - the software packages containing the commands are not active,
      # !!  - the current user is not a member of a task-group that has
      # !!    permissions to use the commands.
      #
      # foo
      # bar
      #
      if m['error-path']
        fail Cisco::YangError.new( # rubocop:disable Style/RaiseArgs
          message
        )
      else
        match = /\n\n(.*)\n\n\Z/m.match(message)
        if match.nil?
          rejected = '(unknown, see error message)'
        else
          rejected = match[1].split("\n")
        end
        fail Cisco::CliError.new( # rubocop:disable Style/RaiseArgs
          rejected_input: rejected,
          clierror:       message,
        )
      end
    else
      fail Cisco::ClientError, message
    end
  end
end

#handle_response(args, replies) ⇒ Object


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
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 236

def handle_response(args, replies)
  klass = replies[0].class
  unless replies.all? { |r| r.class == klass }
    fail Cisco::ClientError, 'reply class inconsistent: ' +
      replies.map(&:class).join(', ')
  end
  debug "Handling #{replies.length} '#{klass}' reply(s):"
  case klass.to_s
  when /ShowCmdTextReply/
    replies.each { |r| debug "  output:\n#{r.output}" }
    output = replies.map(&:output).join('')
    output = handle_text_output(args, output)
  when /ShowCmdJSONReply/
    # TODO: not yet supported by server to test against
    replies.each { |r| debug "  jsonoutput:\n#{r.jsonoutput}" }
    output = replies.map(&:jsonoutput).join("\n---\n")
  when /CliConfigReply/
    # nothing to process
    output = ''
  when /ConfigGetReply/
    replies.each { |r| debug "  yangjson:\n#{r.yangjson}" }
    output = replies.map(&:yangjson).join('')
  when /GetOperReply/
    replies.each { |r| debug "  yangjson:\n#{r.yangjson}" }
    output = replies.map(&:yangjson).join('')
  when /ConfigReply/
    # nothing to process
    output = ''
  else
    fail Cisco::ClientError, "unsupported reply class #{klass}"
  end
  debug "Success with output:\n#{output}"
  output
end

#handle_text_error(args, msg) ⇒ Object

Generate an error from a failed request


314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 314

def handle_text_error(args, msg)
  if /^Disallowed commands:/ =~ msg
    fail Cisco::RequestNotSupported, msg
  elsif args.is_a?(ConfigGetArgs) || args.is_a?(ConfigArgs)
    fail Cisco::YangError.new( # rubocop:disable Style/RaiseArgs
      rejected_input: args.yangpathjson,
      error:          msg,
    )
  else
    fail Cisco::CliError.new( # rubocop:disable Style/RaiseArgs
      rejected_input: args.cli,
      clierror:       msg,
    )
  end
end

#handle_text_output(args, output) ⇒ Object


271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 271

def handle_text_output(args, output)
  # For a successful show command, gRPC presents the output as:
  # \n--------- <cmd> ----------
  # \n<output of command>
  # \n\n

  # For an invalid CLI, gRPC presents the output as:
  # \n--------- <cmd> --------
  # \n<cmd>
  # \n<error output>
  # \n\n

  # Discard the leading whitespace, header, and trailing whitespace
  output = output.split("\n").drop(2)
  return '' if output.nil? || output.empty?

  # Now we have either [<output_line_1>, <output_line_2>, ...] or
  # [<cmd>, <error_line_1>, <error_line_2>, ...]
  if output[0].strip == args.cli.strip
    fail Cisco::CliError.new( # rubocop:disable Style/RaiseArgs
      rejected_input: args.cli,
      clierror:       output.join("\n"),
    )
  end
  output.join("\n")
end

#req(stub, type, args) ⇒ Object


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
188
189
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 149

def req(stub, type, args)
  if cache_enable? && @cache_hash[type] && @cache_hash[type][args.cli]
    return @cache_hash[type][args.cli]
  end

  debug "Sending '#{type}' request:"
  if args.is_a?(ShowCmdArgs) || args.is_a?(CliConfigArgs)
    debug "  with cli: '#{args.cli}'"
  end
  output = Cisco::Client.silence_warnings do
    response = stub.send(type, args,
                         timeout:  @timeout,
                         username: @username,
                         password: @password)
    # gRPC server may split the response into multiples
    response = response.is_a?(Enumerator) ? response.to_a : [response]
    debug "Got responses: #{response.map(&:class).join(', ')}"
    # Check for errors first
    handle_errors(args, response.select { |r| !r.errors.empty? })

    # If we got here, no errors occurred
    handle_response(args, response)
  end

  @cache_hash[type][args.cli] = output if cache_enable? && !output.empty?
  return output
rescue ::GRPC::BadStatus => e
  warn "gRPC error '#{e.code}' during '#{type}' request: "
  if args.is_a?(ShowCmdArgs) || args.is_a?(CliConfigArgs)
    warn "  with cli: '#{args.cli}'"
  end
  warn "  '#{e.details}'"
  case e.code
  when ::GRPC::Core::StatusCodes::UNAVAILABLE
    raise Cisco::ConnectionRefused, "Connection refused: #{e.details}"
  when ::GRPC::Core::StatusCodes::UNAUTHENTICATED
    raise Cisco::AuthenticationFailed, e.details
  else
    raise Cisco::ClientError, e.details
  end
end

#set(data_format: :cli, context: nil, values: nil, **kwargs) ⇒ Object

Configure the given CLI command(s) on the device.


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 92

def set(data_format: :cli,
        context:     nil,
        values:      nil,
        **kwargs)
  context = munge_to_array(context)
  values = munge_to_array(values)
  super
  if data_format == :yang_json
    mode = kwargs[:mode] || :merge_config
    fail ArgumentError unless Cisco::YANG_SET_MODE.include? mode
    values.each do |yang|
      yang_req(@config, mode.to_s, ConfigArgs.new(yangjson: yang))
    end
  else
    # IOS XR lets us concatenate submode commands together.
    # This makes it possible to guarantee we are in the correct context:
    #   context: ['foo', 'bar'], values: ['baz', 'bat']
    #   ---> values: ['foo bar baz', 'foo bar bat']
    # However, there's a special case for 'no' commands:
    #   context: ['foo', 'bar'], values: ['no baz']
    #   ---> values: ['no foo bar baz'] ---- the 'no' goes at the start
    context = context.join(' ')
    unless context.empty?
      values.map! do |cmd|
        match = cmd[/^\s*no\s+(.*)/, 1]
        if match
          cmd = "no #{context} #{match}"
        else
          cmd = "#{context} #{cmd}"
        end
        cmd
      end
    end
    # CliConfigArgs wants a newline-separated string of commands
    args = CliConfigArgs.new(cli: values.join("\n"))
    req(@config, 'cli_config', args)
  end
end

#yang_req(stub, type, args) ⇒ Object

Send a YANG request via gRPC


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 192

def yang_req(stub, type, args)
  debug "Sending '#{type}' request:"
  if args.is_a?(ConfigGetArgs)
    debug "  with yangpathjson: #{args.yangpathjson}"
  elsif args.is_a?(ConfigArgs)
    debug " with yangjson: #{args.yangjson}"
  end

  output = Cisco::Client.silence_warnings do
    response = stub.send(type, args,
                         timeout:  @timeout,
                         username: @username,
                         password: @password)
    # gRPC server may split the response into multiples
    response = response.is_a?(Enumerator) ? response.to_a : [response]
    debug "Got responses: #{response.map(&:class).join(', ')}"
    debug "response: #{response}"
    # Check for errors first
    handle_errors(args, response.select { |r| !r.errors.empty? })

    # If we got here, no errors occurred
    handle_response(args, response)
  end
  return output

rescue ::GRPC::BadStatus => e
  warn "gRPC error '#{e.code}' during '#{type}' request: "
  if args.is_a?(ConfigGetArgs)
    debug "  with yangpathjson: #{args.yangpathjson}"
  elsif args.is_a?(ConfigArgs)
    debug " with yangjson: #{args.yangjson}"
  end

  warn "  '#{e.details}'"
  case e.code
  when ::GRPC::Core::StatusCodes::UNAVAILABLE
    raise Cisco::ConnectionRefused, "Connection refused: #{e.details}"
  when ::GRPC::Core::StatusCodes::UNAUTHENTICATED
    raise Cisco::AuthenticationFailed, e.details
  else
    raise Cisco::ClientError, e.details
  end
end