Module snmputils
[hide private]

Source Code for Module snmputils

  1  #coding=utf-8 
  2  """ 
  3  Utilities for managing Simple Network Management connections 
  4  """ 
  5   
  6  from appilog.common.system.types import ObjectStateHolder 
  7  from appilog.common.system.types import AttributeStateHolder 
  8  #from appilog.common.system.types.vectors import ObjectStateHolderVector 
  9  from java.util import Comparator 
 10  from java.util import TreeSet 
 11   
 12  import logger 
 13   
 14   
15 -class Converter:
16 - def convert(self, originalValue):
17 raise NotImplementedError()
18 19
20 -class NoopConverter(Converter):
21 - def convert(self, originalValue):
22 return originalValue
23 24 NOOP_CONVERTER = NoopConverter() 25 26
27 -class ByMapConverter(Converter):
28 - def __init__(self, map_):
29 self.map = map_
30
31 - def convert(self, originalValue):
32 if self.map.has_key(originalValue): 33 return self.map[originalValue] 34 else: 35 raise UnmappedValueException(originalValue)
36 37
38 -class ResultItem:
39 - def __str__(self):
40 return str(self.__dict__)
41 42
43 -class OffsetBasedComparator(Comparator):
44 - def compare(self, element1, element2):
45 return cmp(element1.offset, element2.offset)
46 47
48 -class QueryElement:
49 - def __init__(self, offset, name, type_):
50 self.offset = offset 51 self.name = name 52 self.type = type_
53 54
55 -def defineRangeQuery(snmpQueryProducer, rangeStart, rangeEnd):
56 for i in range(rangeStart, rangeEnd + 1): 57 snmpQueryProducer.addQueryElement(i, str(i))
58 59
60 -class SnmpQueryBuilder:
61 - def __init__(self, tableOidOffset):
62 self.queryElements = TreeSet(OffsetBasedComparator()) 63 self.tableOidOffset = tableOidOffset
64
65 - def addQueryElement(self, offset, name, type='string'):
66 queryElement = QueryElement(offset, name, type) 67 self.queryElements.add(queryElement)
68
69 - def __buildQueryParts(self, productOidBase, queryElements):
70 ''' Build query parts and returns base query part and parts for each 71 query element (OID) 72 @types: str, java.util.TreeSet -> tuple(str, list(str))''' 73 if productOidBase: 74 tableOidBase = self.__glue_(productOidBase, self.tableOidOffset, '.') 75 else: 76 tableOidBase = self.tableOidOffset 77 78 iterator = self.queryElements.iterator() 79 queryElement = iterator.next() 80 oidNoType = self.__glue_(tableOidBase, queryElement.offset, '.') 81 surrogateOid = self.__glue_(tableOidBase, queryElement.offset + 1, '.') 82 oidNoType = self.__glue_(oidNoType, surrogateOid) 83 queryBase = self.__glue_(oidNoType, queryElement.type) 84 85 oidParts = [] 86 while iterator.hasNext(): 87 queryElement = iterator.next() 88 oidNoType = self.__glue_(tableOidBase, queryElement.offset, '.') 89 oid = self.__glue_(oidNoType, queryElement.type) 90 oidParts.append(oid) 91 return queryBase, oidParts
92
93 - def produceQuery(self, productOidBase):
94 '@types: str -> str' 95 queryBase, oidParts = self.__buildQueryParts(productOidBase, 96 self.queryElements) 97 # make single query where query base is joined with parts related to 98 # each query element 99 return reduce(self.__glue_, (queryBase,) + tuple(oidParts))
100
101 - def producePartialQueries(self, productOidBase):
102 queryBase, oidParts = self.__buildQueryParts(productOidBase, 103 self.queryElements) 104 # zi = zip(queryBase * len(oidParts), oidParts) 105 # return map(lambda pair, _ = self: _.__glue_(pair[0], pair[1]), zi) 106 queries = [] 107 for elementPart in oidParts: 108 queries.append(self.__glue_(queryBase, elementPart)) 109 return queries
110
111 - def parseResults(self, resultSet):
112 table = resultSet.asTable() 113 return self.produceResults(table)
114
115 - def produceResults(self, table):
116 resultItems = [] 117 for rowIndex in range(len(table)): 118 columnIndex = 1 119 resultItem = ResultItem() 120 iterator = self.queryElements.iterator() 121 while iterator.hasNext(): 122 queryElement = iterator.next() 123 name = queryElement.name 124 setattr(resultItem, name, table[rowIndex][columnIndex]) 125 columnIndex += 1 126 resultItems.append(resultItem) 127 128 return resultItems
129
130 - def mergeAndParseResults(self, resultSets):
131 resultTable = [] 132 numberOfResults = len(resultSets) 133 if numberOfResults > 0: 134 firstTable = resultSets[0].asTable() 135 numberOfRows = len(firstTable) 136 for rowIndex in xrange(numberOfRows): 137 resultTable.append([firstTable[rowIndex][0], 138 firstTable[rowIndex][1], 139 firstTable[rowIndex][2]]) 140 if numberOfResults > 1: 141 for i in xrange(1, numberOfResults): 142 table = resultSets[i].asTable() 143 for rowIndex in xrange(numberOfRows): 144 resultTable[rowIndex].append(table[rowIndex][2]) 145 146 return self.produceResults(resultTable)
147
148 - def __glue_(self, base, offset, separator=','):
149 return ('%s%s%s') % (base, separator, offset)
150 151
152 -class SnmpAgent:
153 - def __init__(self, productOidBase, snmpClient, Framework=None):
154 '@types: str, SnmpClient' 155 self.productOidBase = productOidBase 156 self.snmpClient = snmpClient
157
158 - def getSnmpData(self, queryBuilder):
159 '@types: snmputils.SnmpQueryBuilder -> list(snmputils.ResultItem)' 160 return (self.getSnmpDataUsingSingleQuery(queryBuilder) 161 or self.getSnmpDataUsingPartialQueries(queryBuilder))
162
163 - def getSnmpDataUsingSingleQuery(self, queryBuilder):
164 '@types: snmputils.SnmpQueryBuilder -> list(snmputils.ResultItem)' 165 query = queryBuilder.produceQuery(self.productOidBase) 166 resultSet = self.snmpClient.executeQuery(query) 167 return queryBuilder.parseResults(resultSet)
168
169 - def getSnmpDataUsingPartialQueries(self, queryBuilder):
170 '@types: snmputils.SnmpQueryBuilder -> list(snmputils.ResultItem)' 171 queries = queryBuilder.producePartialQueries(self.productOidBase) 172 resultSets = [] 173 for query in queries: 174 resultSets.append(self.snmpClient.executeQuery(query)) 175 return queryBuilder.mergeAndParseResults(resultSets)
176 177
178 -class AttributeMapping:
179 - def __init__(self, attributeName, sourceAttributeName, type_, converter):
180 self.attributeName = attributeName 181 182 if sourceAttributeName: 183 self.sourceAttributeName = sourceAttributeName 184 else: 185 self.sourceAttributeName = attributeName 186 187 self.type = type_ 188 self.converter = converter
189
190 - def setAttribute(self, osh, sourceElement):
191 sourceValue = getattr(sourceElement, self.sourceAttributeName) 192 193 try: 194 convertedValue = self.converter.convert(sourceValue) 195 except ConversionException: 196 raise AttributeMappingException(self.attributeName) 197 198 osh.setAttribute(AttributeStateHolder(self.attributeName, 199 convertedValue, self.type))
200 201
202 -class OSHMapping:
203 - def __init__(self, oshName):
204 self.oshName = oshName 205 self.attributeMappings = []
206
207 - def defineMapping(self, attributeName, sourceAttributeName=None, 208 type='string', converter=NOOP_CONVERTER):
209 attributeMapping = AttributeMapping(attributeName, sourceAttributeName, 210 type, converter) 211 self.attributeMappings.append(attributeMapping)
212
213 - def createOSHs(self, sourceElements):
214 oshs = [] 215 for sourceElement in sourceElements: 216 osh = self.createOSH(sourceElement) 217 oshs.append(osh) 218 return oshs
219
220 - def fillOSH(self, osh, sourceElement):
221 for attributeMapping in self.attributeMappings: 222 attributeMapping.setAttribute(osh, sourceElement)
223
224 - def createOSH(self, sourceElement):
225 osh = ObjectStateHolder(self.oshName) 226 self.fillOSH(osh, sourceElement) 227 return osh
228 229
230 -class SimpleTableWorker:
231 - def __init__(self, tableOidOffset, oshName, snmpTableWorker):
232 self.queryProducer = SnmpQueryBuilder(tableOidOffset) 233 self.oshMapping = OSHMapping(oshName) 234 self.snmpTableWorker = snmpTableWorker
235
236 - def defineMappingByMap(self, oidOffset, oshAttributeName, map_, 237 oshAttributeType='string'):
238 self.defineMapping(oidOffset, oshAttributeName, oshAttributeType, 239 ByMapConverter(map_))
240
241 - def defineMapping(self, oidOffset, oshAttributeName, 242 oshAttributeType='string', converter=NOOP_CONVERTER):
243 self.queryProducer.addQueryElement(oidOffset, oshAttributeName) 244 self.oshMapping.defineMapping(oshAttributeName, oshAttributeName, 245 oshAttributeType, converter)
246
247 - def createOSHs(self):
248 snmpData = self.snmpTableWorker.getSnmpData(self.queryProducer) 249 return self.oshMapping.createOSHs(snmpData)
250 251
252 -class SnmpWrapperException(Exception):
253 - def __init__(self, *args):
254 Exception.__init__(self, *args) 255 # (self.rootClass, self.rootValue, self.rootStacktrace) = sys.exc_info() 256 self.rootStacktrace = logger.prepareFullStackTrace('')
257
258 - def __str__(self):
259 message = Exception.__str__(self) 260 261 if self.rootStacktrace: 262 message += ('\nCaused by\n%s') % (self.rootStacktrace) 263 264 return message
265 266
267 -class ConversionException(SnmpWrapperException):
268 - def __init__(self, *args):
270 271
272 -class UnmappedValueException(ConversionException):
273 - def __init__(self, *args):
274 ConversionException.__init__(self, *args)
275 276
277 -class AttributeMappingException(SnmpWrapperException):
278 - def __init__(self, *args):
280