class MibInstrumController(object):
class DataIndexInstrumController(object):
    def __init__(self, data_file):
    def __str__(self):
    def _get_call_context(self, ac_info, next_flag=False, set_flag=False):
    def readVars(self, var_binds, acInfo=None):
    def readNextVars(self, var_binds, acInfo=None):
    def writeVars(self, var_binds, acInfo=None):
    def __init__(self, base_oid=(1, 3, 6, 1, 4, 1, 20408, 999)):
    def __str__(self):
    def readVars(self, var_binds, acInfo=None):
    def _get_next_val(self, key, default):
    def readNextVars(self, var_binds, acInfo=None):
    def writeVars(self, var_binds, acInfo=None):
    def add_data_file(self, *args):
MIB_CONTROLLERS = {
    datafile.DataFile.layout: MibInstrumController
} def daemonize(pidfile):
    def __init__(self, *args, **kwargs):
    def __enter__(self):
    def __exit__(self, *args):
def daemonize(pidfile):
    def signal_cb(s, f):
    def atexit_cb():
    def __init__(self, uname, gname, final=False):
    def __enter__(self):
    def __exit__(self, *args):
class PrivilegesOf(object):
class PrivilegesOf(object): SELF_LABEL = 'self'
class AbstractLayout(object):
class DataFile(AbstractLayout):
    def __init__(self, textFile, textParser, variationModules):
    def index_text(self, forceIndexBuild=False, validateData=False):
    def close(self):
    def get_handles(self):
    def process_var_binds(self, var_binds, **context):
    def __str__(self):
def get_data_files(tgt_dir, top_len=None):
def probe_context(transport_domain, transport_address,
                  context_engine_id, context_name): class TransportEndpointsBase(object):
class IPv4TransportEndpoints(TransportEndpointsBase):
class IPv6TransportEndpoints(TransportEndpointsBase):
    def __init__(self):
    def add(self, addr):
    def _addEndpoint(self, addr):
    def __len__(self):
    def __getitem__(self, i):
    def _addEndpoint(self, addr):
    def _addEndpoint(self, addr):
def parse_endpoint(arg, ipv6=False): LOG_DEBUG = 0
LOG_INFO = 1
LOG_ERROR = 2
    SYSLOG_SOCKET_PATHS = (
        '/dev/log',
        '/var/run/syslog'
    )
METHODS_MAP = {
    'syslog': SyslogLogger,
    'file': FileLogger,
    'stdout': StdoutLogger,
    'stderr': StderrLogger,
    'null': NullLogger
}
LEVELS_MAP = {
    'debug': LOG_DEBUG,
    'info': LOG_INFO,
    'error': LOG_ERROR,
}
class AbstractLogger(object):
class SyslogLogger(AbstractLogger):
class FileLogger(AbstractLogger):
    class TimedRotatingFileHandler(handlers.TimedRotatingFileHandler):
class StreamLogger(AbstractLogger):
class StdoutLogger(StreamLogger):
class StderrLogger(StreamLogger):
class NullLogger(AbstractLogger):
    def __init__(self, progId, *priv):
    def __call__(self, s):
    def inc_ident(self, amount=2):
    def dec_ident(self, amount=2):
    def init(self, *priv):
    def init(self, *priv):
        def __init__(self, *args, **kwargs):
        def _filename(self):
        def doRollover(self):
    def init(self, *priv):
    def __call__(self, s):
    def init(self, *priv):
    def init(self, *priv):
    def __call__(self, s):
def error(message, ctx=''):
def info(message, ctx=''):
def debug(message, ctx=''):
def set_level(level):
def set_logger(progId, *priv, **options): TITLE = """\
SNMP Simulator version %s, written by Ilya Etingof <etingof@gmail.com>
Using foundation libraries: pysmi %s, pysnmp %s, pyasn1 %s.
Python interpreter: %s
Documentation and support at http://snmplabs.com/snmpsim
""" % (snmpsim.__version__, pysmi.__version__, pysnmp.__version__,
       pyasn1.__version__, sys.version)
def try_load(module, package=None):
def split(val, sep): RECORD_TYPES = {
    dump.DumpRecord.ext: dump.DumpRecord(),
    mvc.MvcRecord.ext: mvc.MvcRecord(),
    sap.SapRecord.ext: sap.SapRecord(),
    walk.WalkRecord.ext: walk.WalkRecord(),
}
class SnmprecRecordMixIn(object):
class SnmprecRecord(SnmprecRecordMixIn, snmprec.SnmprecRecord):
class CompressedSnmprecRecord(
        SnmprecRecordMixIn, snmprec.CompressedSnmprecRecord):
    def evaluate_value(self, oid, tag, value, **context):
    def evaluate(self, line, **context):
    def format_value(self, oid, value, **context):
def load_variation_modules(search_path, modules_options):
def initialize_variation_modules(variation_modules, mode):
def parse_modules_options(options): class NoDataNotification(SnmpsimError):
    pass class SnmpsimError(Exception):
    pass class ReportingManager(object):
    """Maintain activity metrics.

    Accumulates and periodically dumps activity metrics reflecting
    SNMP command responder activity.

    These counters are accumulated in memory for some time, then get
    written down as a JSON file indexed by time. Consumers are expected
    to process each of these files and are free to remove them.
    """

    REPORTERS = {
        'null': null.NullReporter,
        'fulljson': alljson.FullJsonReporter,
        'minimaljson': alljson.MinimalJsonReporter,
    }

    _reporter = null.NullReporter()

    @classmethod
    def configure(cls, fmt, *args):
        try:
            reporter = cls.REPORTERS[fmt]

        except KeyError:
            raise error.SnmpsimError('Unsupported reporting format: %s' % fmt)

        cls._reporter = reporter(*args)

        log.info('Using "%s" activity reporting method with '
                 'params %s' % (cls._reporter, ', '.join(args)))

    @classmethod
    def update_metrics(cls, **kwargs):

        cls._reporter.update_metrics(**kwargs)
        cls._reporter.flush()
import argparse
import functools
import os
import sys
import traceback
from hashlib import md5
from pyasn1 import debug as pyasn1_debug
from pyasn1.compat.octets import null
from pyasn1.type import univ
from pysnmp import debug as pysnmp_debug
from pysnmp import error
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.carrier.asyncore.dgram import udp6
from pysnmp.carrier.asyncore.dispatch import AsyncoreDispatcher
from pysnmp.entity import config
from pysnmp.entity import engine
from pysnmp.entity.rfc3413 import cmdrsp
from pysnmp.entity.rfc3413 import context
from snmpsim import confdir
from snmpsim import controller
from snmpsim import daemon
from snmpsim import datafile
from snmpsim import endpoints
from snmpsim import log
from snmpsim import utils
from snmpsim import variation
from snmpsim.error import NoDataNotification
from snmpsim.error import SnmpsimError
from snmpsim.reporting.manager import ReportingManager
    v3_group.add_argument(
        '--v3-auth-key', type=_parse_sized_string,
        help='SNMPv3 USM authentication key (must be > 8 chars)')

    v3_group.add_argument(
        '--v3-auth-proto', choices=AUTH_PROTOCOLS,
        type=lambda x: x.upper(), default='NONE',
        help='SNMPv3 USM authentication protocol')

    v3_group.add_argument(
        '--v3-priv-key', type=_parse_sized_string,
        help='SNMPv3 USM privacy (encryption) key (must be > 8 chars)')

    v3_group.add_argument(
        '--v3-priv-proto', choices=PRIV_PROTOCOLS,
        type=lambda x: x.upper(), default='NONE',
        help='SNMPv3 USM privacy (encryption) protocol')

    v3_group.add_argument(
        '--v3-context-engine-id',
        type=lambda x: univ.OctetString(hexValue=x[2:]),
        help='SNMPv3 context engine ID')

    v3_group.add_argument(
        '--v3-context-name', type=str, default='',
        help='SNMPv3 context engine ID')

    v3_group.add_argument(
        '--agent-udpv4-endpoint', type=endpoints.parse_endpoint,
        metavar='<[X.X.X.X]:NNNNN>',
        help='SNMP agent UDP/IPv4 address to listen on (name:port)')

    v3_group.add_argument(
        '--agent-udpv6-endpoint',
        type=functools.partial(endpoints.parse_endpoint, ipv6=True),
        metavar='<[X:X:..X]:NNNNN>',
        help='SNMP agent UDP/IPv6 address to listen on ([name]:port)')

    v3_group.add_argument(
        '--data-dir',
        type=str, metavar='<DIR>',
        help='SNMP simulation data recordings directory.')

    args, unparsed_args = parser.parse_known_args()

    if args.usage:
        snmp_helper.print_usage(sys.stderr)
        return 1

    if args.help:
        snmp_helper.print_help(sys.stderr)
        return 1

    _, unknown_args = snmp_helper.parse_known_args(unparsed_args)
    if unknown_args:
        sys.stderr.write(
            'ERROR: Unknown command-line parameter(s) '
            '%s\r\n' % ' '.join(unknown_args))
        snmp_helper.print_usage(sys.stderr)
        return 1

    # Reformat unparsed args into a list of (option, value) tuples
    snmp_args = []
    name = None

    for opt in unparsed_args:
        if '=' in opt:
            snmp_args.append(opt.split('='))

        elif name:
            snmp_args.append((name, opt))
            name = None

        else:
            name = opt

    if name:
        sys.stderr.write(
            'ERROR: Non-paired command-line key-value parameter '
            '%s\r\n' % name)
        snmp_helper.print_usage(sys.stderr)
        return 1

    if args.cache_dir:
        confdir.cache = args.cache_dir

    if args.variation_modules_dir:
        confdir.variation = args.variation_modules_dir

    variation_modules_options = variation.parse_modules_options(
        args.variation_module_options)

    if args.args_from_file:
        try:
            with open(args.args_from_file) as fl:
                snmp_args.extend([handler.split('=', 1) for handler in fl.read().split()])

        except Exception as exc:
            sys.stderr.write(
                'ERROR: file %s opening failure: '
                '%s\r\n' % (args.args_from_file, exc))
            snmp_helper.print_usage(sys.stderr)
            return 1

    with daemon.PrivilegesOf(args.process_user, args.process_group):

        proc_name = os.path.basename(sys.argv[0])

        try:
            log.set_logger(proc_name, *args.logging_method, force=True)

            if args.log_level:
                log.set_level(args.log_level)

        except SnmpsimError as exc:
            sys.stderr.write('%s\r\n' % exc)
            snmp_helper.print_usage(sys.stderr)
            return 1

        try:

            ReportingManager.configure(*args.reporting_method)