lib/snmp/open/parser.rb in snmp-open-0.3.1 vs lib/snmp/open/parser.rb in snmp-open-0.4.0
- old
+ new
@@ -1,7 +1,9 @@
require 'set'
require 'shellwords'
+require 'snmp/open/parser/constants'
+require 'snmp/open/parser/value_parser'
module SNMP
class Open
Value = Struct.new(:oid, :type, :value) do
def id_after(path)
@@ -9,25 +11,23 @@
end
end
# convert SNMP command output into arrays
class Parser
- NOSUCHOBJECT_STR =
- 'No Such Object available on this agent at this OID'.freeze
- NOSUCHINSTANCE_STR =
- 'No Such Instance currently exists at this OID'.freeze
+ include SNMP::Open::Parser::Constants
def initialize(oids)
@oids = oids
end
def parse(texts)
columns = texts.map do |text|
tokenized =
text
- .gsub(NOSUCHOBJECT_STR, %("#{NOSUCHOBJECT_STR}"))
- .gsub(NOSUCHINSTANCE_STR, %("#{NOSUCHINSTANCE_STR}"))
+ .gsub(/^([0-9\.]+) = (Opaque|STRING): ((?!")[^\n]*)\n/,
+ %(\\1 = \\2: "\\3"\n))
+ .gsub(Static::ANY_MESSAGE, Static::QUOTED_MESSAGES)
.shellsplit
parse_tokens(tokenized)
end
table(columns)
@@ -80,28 +80,15 @@
type, value = parse_type(tokens)
Value.new(oid, type, value)
end
def parse_type(tokens)
- next_token = tokens.next
- type = next_token.match(/\A([A-Z]+):\z/) { |md| md[1] }
- type, value = parse_value(tokens, next_token, type)
- [type, Conversions.convert_value(type, value)]
+ token = tokens.next
+ type = token.match(/\A([-A-Za-z]+[0-9]*):\z/) { |md| md[1] }
+ ValueParser.find(type, token).parse(tokens)
end
- def parse_value(tokens, token, type)
- if token == NOSUCHOBJECT_STR
- ['No Such Object', nil]
- elsif token == NOSUCHINSTANCE_STR
- ['No Such Instance', nil]
- elsif !type
- ['STRING', token]
- else
- [type, tokens.next]
- end
- end
-
def table(columns)
if columns.size == 1 && columns.all? { |column| column.size == 1 }
columns
else
align(columns)
@@ -122,28 +109,27 @@
def fill_gaps(columns)
indexes = indexes(columns)
@oids.zip(columns).map do |oid, column|
indexes.map do |index|
id = (oid == index ? index : "#{oid}.#{index}")
- column.find { |o| o.oid == id } || Conversions.absent_value(id)
+ column.find { |o| o.oid == id } || Value.new(id, 'absent', nil)
end
end
end
- # functions to generate value objects
- module Conversions
- module_function def convert_value(type, value)
- case type
- when 'INTEGER'
- value.to_i
- else
- value
- end
- end
+ # static messages from net-snmp commands
+ module Static
+ include SNMP::Open::Parser::Constants
- module_function def absent_value(id)
- Value.new(id, 'absent', nil)
- end
+ MESSAGES = [
+ NOSUCHOBJECT_STR,
+ NOSUCHINSTANCE_STR,
+ NOMOREVARIABLES_STR
+ ].freeze
+
+ ANY_MESSAGE = Regexp.union(*MESSAGES)
+
+ QUOTED_MESSAGES = MESSAGES.map { |v| [v, %("#{v}")] }.to_h.freeze
end
end # class Parser
end # class Open
end # module SNMP