Class: Cisco::Client::GRPC
- Inherits:
-
Cisco::Client
- Object
- Cisco::Client
- Cisco::Client::GRPC
- 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
-
#timeout ⇒ Object
Returns the value of attribute timeout.
Attributes inherited from Cisco::Client
#cache_auto, #data_formats, #platform
Class Method Summary collapse
Instance Method Summary collapse
- #cache_flush ⇒ Object
- #get(data_format: :cli, command: nil, context: nil, value: nil) ⇒ Object
- #handle_errors(args, error_responses) ⇒ Object
-
#handle_json_error(msg) ⇒ Object
Generate a CliError from a failed CliConfigReply.
- #handle_response(args, replies) ⇒ Object
-
#handle_text_error(args, msg) ⇒ Object
Generate an error from a failed request.
- #handle_text_output(args, output) ⇒ Object
-
#initialize(**kwargs) ⇒ GRPC
constructor
A new instance of GRPC.
- #req(stub, type, args) ⇒ Object
-
#set(data_format: :cli, context: nil, values: nil) ⇒ Object
Configure the given CLI command(s) on the device.
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
Returns a new instance of GRPC.
35 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 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 35 def initialize(**kwargs) # Defaults for gRPC: kwargs[:host] ||= '127.0.0.1' kwargs[:port] ||= 57_400 # rubocop:disable Style/HashSyntax super(data_formats: [:cli], 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.[/deadline exceeded/i] raise Cisco::ConnectionRefused, \ base_msg + 'timed out during initial connection: ' + e. end raise e.class, base_msg + e. end # Let commands in general take up to 2 minutes @timeout = 120 end |
Instance Attribute Details
#timeout ⇒ Object
Returns the value of attribute timeout.
33 34 35 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 33 def timeout @timeout end |
Class Method Details
.validate_args(**kwargs) ⇒ Object
65 66 67 68 69 70 71 72 73 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 65 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_flush ⇒ Object
75 76 77 78 79 80 81 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 75 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) ⇒ Object
120 121 122 123 124 125 126 127 128 129 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 120 def get(data_format: :cli, command: nil, context: nil, value: nil) super fail ArgumentError if command.nil? 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 |
#handle_errors(args, error_responses) ⇒ Object
226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 226 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
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 254 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'] = m['error-message'] if type == 'protocol' && == 'Failed authentication' fail Cisco::AuthenticationFailed, 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 # match = /\n\n(.*)\n\n\Z/m.match() 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: , ) else fail Cisco::ClientError, end end end |
#handle_response(args, replies) ⇒ Object
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 173 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 = '' 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
242 243 244 245 246 247 248 249 250 251 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 242 def handle_text_error(args, msg) if /^Disallowed commands:/ =~ msg fail Cisco::RequestNotSupported, msg else fail Cisco::CliError.new( # rubocop:disable Style/RaiseArgs rejected_input: args.cli, clierror: msg, ) end end |
#handle_text_output(args, output) ⇒ Object
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 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 199 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
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 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 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 131 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) ⇒ Object
Configure the given CLI command(s) on the device.
90 91 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 |
# File 'lib/cisco_node_utils/client/grpc/client.rb', line 90 def set(data_format: :cli, context: nil, values: nil) context = munge_to_array(context) values = munge_to_array(values) super # 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 |