def parse_endpoint(arg, ipv6=False): address = arg # IPv6 notation if ipv6 and address.startswith('['): address = address.replace('[', '').replace(']', '') try: if ':' in address: address, port = address.split(':', 1) port = int(port) else: port = 161 except Exception as exc: raise SnmpsimError('Malformed network endpoint address %s: %s' % (arg, exc)) try: address, port = socket.getaddrinfo( address, port, socket.AF_INET6 if ipv6 else socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] except socket.gaierror as exc: raise SnmpsimError('Unknown hostname %s: %s' % (address, exc)) return address, port
def init(self, *priv): if not priv: raise SnmpsimError('Bad log file params, need filename') if sys.platform[:3] == 'win': # fix possibly corrupted absolute windows path if len(priv[0]) == 1 and priv[0].isalpha() and len(priv) > 1: priv = [priv[0] + ':' + priv[1]] + list(priv[2:]) maxsize = 0 maxage = None if len(priv) > 1 and priv[1]: try: if priv[1][-1] == 'k': maxsize = int(priv[1][:-1]) * 1024 elif priv[1][-1] == 'm': maxsize = int(priv[1][:-1]) * 1024 * 1024 elif priv[1][-1] == 'g': maxsize = int(priv[1][:-1]) * 1024 * 1024 * 1024 elif priv[1][-1] == 'S': maxage = ('S', int(priv[1][:-1])) elif priv[1][-1] == 'M': maxage = ('M', int(priv[1][:-1])) elif priv[1][-1] == 'H': maxage = ('H', int(priv[1][:-1])) elif priv[1][-1] == 'D': maxage = ('D', int(priv[1][:-1])) else: raise ValueError('Unknown log rotation criterion: %s' % priv[1][-1]) except ValueError: raise SnmpsimError( 'Error in timed log rotation specification. Use <NNN>k,m,g ' 'for size or <NNN>S,M,H,D for time limits') try: if maxsize: handler = handlers.RotatingFileHandler(priv[0], backupCount=30, maxBytes=maxsize) elif maxage: handler = self.TimedRotatingFileHandler(priv[0], backupCount=30, when=maxage[0], interval=maxage[1]) else: handler = handlers.WatchedFileHandler(priv[0]) except Exception: raise SnmpsimError('Failure configure logging: %s' % sys.exc_info()[1]) handler.setFormatter(logging.Formatter('%(message)s')) self._logger.addHandler(handler) self('Log file %s, rotation rules: %s' % (priv[0], maxsize and '> %sKB' % (maxsize / 1024) or maxage and '%s%s' % (maxage[1], maxage[0]) or '<none>'))
def parse_modules_options(options): variation_modules_options = {} for option in options: args = option.split(':', 1) try: mod_name, args = args[0], args[1] except Exception as exc: raise SnmpsimError( 'ERROR: improper variation module options %s: %s\r\n', exc) if '=' in mod_name: mod_name, alias = mod_name.split('=', 1) else: alias = os.path.splitext(os.path.basename(mod_name))[0] if mod_name not in variation_modules_options: variation_modules_options[mod_name] = [] variation_modules_options[mod_name].append((alias, args)) return variation_modules_options
def _parse_range(arg): try: minimum, maximum = [int(x) for x in arg.split(',')] except Exception as exc: raise SnmpsimError('Malformed integer range %s: %s' % (arg, exc)) return minimum, maximum
def setLevel(level): global logLevel try: logLevel = LEVELS_MAP[level] except KeyError: raise SnmpsimError('Unknown log level "%s", known levels are: %s' % (level, ', '.join(LEVELS_MAP)))
def init(self, *priv): if len(priv) < 1: raise SnmpsimError( 'Bad syslog params, need at least facility, also accept ' 'host, port, socktype (tcp|udp)') if len(priv) < 2: priv = [priv[0], 'debug'] if len(priv) < 3: # search for syslog local socket for dev in self.SYSLOG_SOCKET_PATHS: if os.path.exists(dev): priv = [priv[0], priv[1], dev] break else: priv = [priv[0], priv[1], 'localhost', 514, 'udp'] if not priv[2].startswith('/'): if len(priv) < 4: priv = [priv[0], priv[1], priv[2], 514, 'udp'] if len(priv) < 5: priv = [priv[0], priv[1], priv[2], 514, 'udp'] priv = [priv[0], priv[1], priv[2], int(priv[3]), priv[4]] try: handler = handlers.SysLogHandler( address=(priv[2].startswith('/') and priv[2] or (priv[2], int(priv[3]))), facility=priv[0].lower(), socktype=(len(priv) > 4 and priv[4] == 'tcp' and socket.SOCK_STREAM or socket.SOCK_DGRAM)) except Exception: raise SnmpsimError('Bad syslog option(s): %s' % sys.exc_info()[1]) handler.setFormatter( logging.Formatter('%(asctime)s %(name)s: %(message)s')) self._logger.addHandler(handler)
def init(self, *priv): try: handler = logging.StreamHandler(self.stream) except AttributeError: raise SnmpsimError('Stream logger failure: %s' % sys.exc_info()[1]) handler.setFormatter(logging.Formatter('%(message)s')) self._logger.addHandler(handler)
def setLogger(progId, *priv, **options): global msg try: if (not isinstance(msg, AbstractLogger) or options.get('force')): msg = METHODS_MAP[priv[0]](progId, *priv[1:]) except KeyError: raise SnmpsimError('Unknown logging method "%s", known methods are: ' '%s' % (priv[0], ', '.join(METHODS_MAP)))
def _addEndpoint(self, addr): f = lambda h, p=161: (h, int(p)) try: h, p = f(*addr.split(':')) except Exception: raise SnmpsimError('improper IPv4/UDP endpoint %s' % addr) return udp.UdpTransport().openServerMode((h, p)), addr
def evaluate(self, line, **context): oid, tag, value = self.grammar.parse(line) oid = self.evaluateOid(oid) if context.get('oidOnly'): value = None else: try: oid, tag, value = self.evaluateValue(oid, tag, value, **context) except PyAsn1Error: raise SnmpsimError('value evaluation for %s = %r failed: %s\r\n' % (oid, value, sys.exc_info()[1])) return oid, value
def _addEndpoint(self, addr): if not udp6: raise SnmpsimError('This system does not support UDP/IP6') if addr.find(']:') != -1 and addr[0] == '[': h, p = addr.split(']:') try: h, p = h[1:], int(p) except Exception: raise SnmpsimError('improper IPv6/UDP endpoint %s' % addr) elif addr[0] == '[' and addr[-1] == ']': h, p = addr[1:-1], 161 else: h, p = addr, 161 return udp6.Udp6Transport().openServerMode((h, p)), addr
def evaluateValue(self, oid, tag, value, **context): try: value = self.grammar.tagMap[tag](value) except: raise SnmpsimError('value evaluation error for tag %r, value %r' % (tag, value)) # not all callers supply the context - just ignore it try: if (not context['nextFlag'] and not context['exactMatch'] or context['setFlag']): return context['origOid'], tag, context['errorStatus'] except KeyError: pass return oid, tag, value
def evaluate(self, line, **context): oid, tag, value = self.grammar.parse(line) oid = self.evaluate_oid(oid) if context.get('oidOnly'): value = None else: try: oid, tag, value = self.evaluate_value( oid, tag, value, **context) except PyAsn1Error as exc: raise SnmpsimError( 'value evaluation for %s = %r failed: ' '%s\r\n' % (oid, value, exc)) return oid, value
def format(self, oid, value, **context): raise SnmpsimError('Method not implemented at %s' % self.__class__.__name__)
def formatOid(self, oid): raise SnmpsimError('Method not implemented at %s' % self.__class__.__name__)
def evaluate(self, line, **context): raise SnmpsimError('Method not implemented at %s' % self.__class__.__name__)
def evaluate_value(self, oid, tag, value, **context): raise SnmpsimError('Method not implemented at ' '%s' % self.__class__.__name__)
def evaluate_oid(self, oid): raise SnmpsimError('Method not implemented at ' '%s' % self.__class__.__name__)
def evaluate_value(self, oid, tag, value, **context): # Variation module reference if ':' in tag: mod_name, tag = tag[tag.index(':')+1:], tag[:tag.index(':')] else: mod_name = None if mod_name: if ('variationModules' in context and mod_name in context['variationModules']): if 'dataValidation' in context: return oid, tag, univ.Null else: if context['setFlag']: hexvalue = self.grammar.hexify_value( context['origValue']) if hexvalue is not None: context['hexvalue'] = hexvalue context['hextag'] = self.grammar.get_tag_by_type( context['origValue']) context['hextag'] += 'x' # prepare agent and record contexts on first reference (variation_module, agent_contexts, record_contexts) = context['variationModules'][mod_name] if context['dataFile'] not in agent_contexts: agent_contexts[context['dataFile']] = {} if context['dataFile'] not in record_contexts: record_contexts[context['dataFile']] = {} variation_module['agentContext'] = agent_contexts[context['dataFile']] record_contexts = record_contexts[context['dataFile']] if oid not in record_contexts: record_contexts[oid] = {} variation_module['recordContext'] = record_contexts[oid] handler = variation_module['variate'] # invoke variation module oid, tag, value = handler(oid, tag, value, **context) ReportingManager.update_metrics( variation=mod_name, variation_call_count=1, **context) else: ReportingManager.update_metrics( variation=mod_name, variation_failure_count=1, **context) raise SnmpsimError( 'Variation module "%s" referenced but not ' 'loaded\r\n' % mod_name) if not mod_name: if 'dataValidation' in context: snmprec.SnmprecRecord.evaluate_value( self, oid, tag, value, **context) if (not context['nextFlag'] and not context['exactMatch'] or context['setFlag']): return context['origOid'], tag, context['errorStatus'] if not hasattr(value, 'tagSet'): # not already a pyasn1 object return snmprec.SnmprecRecord.evaluate_value( self, oid, tag, value, **context) return oid, tag, value
def evaluateValue(self, oid, tag, value, **context): try: return oid, tag, self.grammar.tagMap[tag](value) except: raise SnmpsimError('value evaluation error for tag %r, value %r' % (tag, value))