Beispiel #1
0
def record(oid, tag, value, **context):
    if 'dbConn' in moduleContext:
        db_conn = moduleContext['dbConn']

    else:
        raise error.SnmpsimError('variation module not initialized')

    db_table = moduleContext['dbTable']

    if context['stopFlag']:
        raise error.NoDataNotification()

    sql_oid = '.'.join(['%10s' % x for x in oid.split('.')])
    if 'hexvalue' in context:
        text_tag = context['hextag']
        text_value = context['hexvalue']

    else:
        text_tag = SnmprecGrammar().get_tag_by_type(context['origValue'])
        text_value = str(context['origValue'])

    cursor = db_conn.cursor()

    cursor.execute('select oid from %s where oid=\'%s\' '
                   'limit 1' % (db_table, sql_oid))

    if cursor.fetchone():
        cursor.execute('update %s set tag=\'%s\',value=\'%s\' where '
                       'oid=\'%s\'' %
                       (db_table, text_tag, text_value, sql_oid))

    else:
        cursor.execute('insert into %s values (\'%s\', \'%s\', \'%s\', '
                       '\'read-write\')' %
                       (db_table, sql_oid, text_tag, text_value))

    cursor.close()

    if not context['count']:
        return str(context['startOID']), ':sql', db_table

    else:
        raise error.NoDataNotification()
Beispiel #2
0
def variate(oid, tag, value, **context):
    if 'dbConn' in moduleContext:
        dbConn = moduleContext['dbConn']

    else:
        raise error.SnmpsimError('variation module not initialized')

    if 'settings' not in recordContext:
        settings = recordContext['settings'] = dict(
            [split(x, '=') for x in split(value, ',')])

        if 'key-spaces-id' not in settings:
            log.msg('redis:mandatory key-spaces-id option is missing')
            return context['origOid'], tag, context['errorStatus']

        settings['period'] = float(settings.get('period', 60))

        if 'evalsha' in settings:
            if not dbConn.script_exists(settings['evalsha']):
                log.msg('redis: lua script %s does not exist '
                        'at Redis' % settings['evalsha'])
                return context['origOid'], tag, context['errorStatus']

        recordContext['ready'] = True

    if 'ready' not in recordContext:
        return context['origOid'], tag, context['errorStatus']

    redisScript = recordContext['settings'].get('evalsha')

    keySpacesId = recordContext['settings']['key-spaces-id']

    if recordContext['settings']['period']:
        booted = time.time() - moduleContext['booted']
        slot = int(
            dbConn.llen(keySpacesId)) // recordContext['settings']['period']
        keySpaceIdx = int(booted) % (recordContext['settings']['period'] *
                                     slot)

    else:
        keySpaceIdx = 0

    keySpace = dbConn.lindex(keySpacesId, keySpaceIdx)

    if ('current-keyspace' not in recordContext
            or recordContext['current-keyspace'] != keySpace):
        log.msg(
            'redis: now using keyspace %s (cycling period'
            ' %s)' %
            (keySpace, recordCoentext['settings']['period'] or '<disabled>'))

        recordContext['current-keyspace'] = keySpace

    if keySpace is None:
        return origOid, tag, context['errorStatus']

    origOid = context['origOid']
    dbOid = '.'.join(['%10s' % x for x in str(origOid).split('.')])

    if context['setFlag']:
        if 'hexvalue' in context:
            textTag = context['hextag']
            textValue = context['hexvalue']

        else:
            textTag = SnmprecGrammar().getTagByType(context['origValue'])
            textValue = str(context['origValue'])

        if redisScript:
            prevTagAndValue = dbConn.evalsha(redisScript, 1,
                                             keySpace + '-' + dbOid)

        else:
            prevTagAndValue = dbConn.get(keySpace + '-' + dbOid)

        if prevTagAndValue:
            prevTag, prevValue = prevTagAndValue.split('|')

            if unpackTag(prevTag)[0] != unpackTag(textTag)[0]:
                idx = max(0,
                          context['varsTotal'] - context['varsRemaining'] - 1)
                raise WrongValueError(name=origOid, idx=idx)

        else:
            dbConn.linsert(keySpace + '-oids_ordering', 'after',
                           getNextOid(dbConn, keySpace, dbOid), dbOid)

        if redisScript:
            dbConn.evalsha(redisScript, 1, keySpace + '-' + dbOid,
                           textTag + '|' + textValue)

        else:
            dbConn.set(keySpace + '-' + dbOid, textTag + '|' + textValue)

        return origOid, textTag, context['origValue']

    else:
        if context['nextFlag']:
            textOid = dbConn.lindex(
                keySpace + '-oids_ordering',
                getNextOid(dbConn, keySpace, dbOid, index=True))

        else:
            textOid = keySpace + '-' + dbOid

        if redisScript:
            tagAndValue = dbConn.evalsha(redisScript, 1, textOid)

        else:
            tagAndValue = dbConn.get(textOid)

        if not tagAndValue:
            return origOid, tag, context['errorStatus']

        textOid = '.'.join(
            [x.strip() for x in textOid.split('-', 1)[1].split('.')])
        textTag, textValue = tagAndValue.split('|', 1)

        return textOid, textTag, textValue
Beispiel #3
0
def record(oid, tag, value, **context):
    if 'ready' not in moduleContext:
        raise error.SnmpsimError('module not initialized')

    if 'dbConn' in moduleContext:
        dbConn = moduleContext['dbConn']

    else:
        raise error.SnmpsimError('variation module not initialized')

    if 'started' not in moduleContext:
        moduleContext['started'] = time.time()

    redisScript = moduleContext.get('evalsha')

    keySpace = '%.10d' % (moduleContext['key-spaces-id'] +
                          moduleContext.get('iterations', 0))

    if context['stopFlag']:
        dbConn.sort(keySpace + '-' + 'temp_oids_ordering',
                    store=keySpace + '-' + 'oids_ordering',
                    alpha=True)

        dbConn.delete(keySpace + '-' + 'temp_oids_ordering')
        dbConn.rpush(moduleContext['key-spaces-id'], keySpace)

        log.msg('redis: done with key-space %s' % keySpace)

        if 'iterations' in moduleContext and moduleContext['iterations']:
            log.msg('redis: %s iterations remaining' %
                    moduleContext['iterations'])

            moduleContext['started'] = time.time()
            moduleContext['iterations'] -= 1

            runtime = time.time() - moduleContext['started']
            wait = max(0, moduleContext['period'] - runtime)

            raise error.MoreDataNotification(period=wait)

        else:
            raise error.NoDataNotification()

    dbOid = '.'.join(['%10s' % x for x in oid.split('.')])

    if 'hexvalue' in context:
        textTag = context['hextag']
        textValue = context['hexvalue']

    else:
        textTag = SnmprecGrammar().getTagByType(context['origValue'])
        textValue = str(context['origValue'])

    dbConn.lpush(keySpace + '-temp_oids_ordering', keySpace + '-' + dbOid)

    if redisScript:
        dbConn.evalsha(redisScript, 1, keySpace + '-' + dbOid,
                       textTag + '|' + textValue)

    else:
        dbConn.set(keySpace + '-' + dbOid, textTag + '|' + textValue)

    if not context['count']:
        settings = {'key-spaces-id': moduleContext['key-spaces-id']}

        if 'period' in moduleContext:
            settings['period'] = '%.2f' % float(moduleContext['period'])

        if 'addon' in moduleContext:
            settings.update(
                dict([split(x, '=') for x in moduleContext['addon']]))

        value = ','.join(['%s=%s' % (k, v) for k, v in settings.items()])

        return str(context['startOID']), ':redis', value

    else:
        raise error.NoDataNotification()
Beispiel #4
0
def variate(oid, tag, value, **context):
    if 'dbConn' in moduleContext:
        dbConn = moduleContext['dbConn']
    else:
        raise error.SnmpsimError('variation module not initialized')

    cursor = dbConn.cursor()

    try:
        cursor.execute('set session transaction isolation level %s' %
                       moduleContext['isolationLevel'])
        cursor.fetchall()
    except:  # non-MySQL/Postgres
        pass

    if value:
        dbTable = value.split(',').pop(0)
    elif 'dbTable' in moduleContext:
        dbTable = moduleContext['dbTable']
    else:
        log.msg('SQL table not specified for OID %s' % (context['origOid'], ))
        return context['origOid'], tag, context['errorStatus']

    origOid = context['origOid']
    sqlOid = '.'.join(['%10s' % x for x in str(origOid).split('.')])
    if context['setFlag']:
        if 'hexvalue' in context:
            textTag = context['hextag']
            textValue = context['hexvalue']
        else:
            textTag = SnmprecGrammar().getTagByType(context['origValue'])
            textValue = str(context['origValue'])
        cursor.execute(
            'select maxaccess,tag,value from %s where oid=\'%s\' limit 1' %
            (dbTable, sqlOid))
        resultset = cursor.fetchone()
        if resultset:
            maxaccess = resultset[0]
            if maxaccess != 'read-write':
                return origOid, tag, context['errorStatus']

            value_written = textValue
            try:
                value_settings = {}
                value_settings = dict(
                    [split(x, '=') for x in split(resultset[2], ',')])
                print value_settings
                # if detected error mode, raise an error
                if 'mode' in value_settings and \
                        value_settings['mode'] == 'error':
                    raise Error.WrongValueError(
                        name=origOid,
                        idx=max(
                            0, context['varsTotal'] -
                            context['varsRemaining'] - 1))
                elif 'mode' in value_settings and \
                    value_settings['mode'] == 'normal':
                    value_written = "mode=" + value_settings['mode'] + \
                        ",value=" + textValue
                else:
                    return origOid, tag, context['errorStatus']
            except Error.WrongValueError:
                cursor.close()
                raise Error.WrongValueError(name=origOid,
                                            idx=max(
                                                0, context['varsTotal'] -
                                                context['varsRemaining'] - 1))
            except:
                pass

            cursor.execute(
                'update %s set tag=\'%s\',value=\'%s\' where oid=\'%s\'' %
                (dbTable, textTag, value_written, sqlOid))

            inform = moduleContext.get('inform')
            try:
                value = str(origOid) + " " + textValue
                written_len = os.write(inform, value)
                if written_len != len(value):
                    log.msg(
                        "--->Infrasim: Expected length %d, actual length %d\n"
                        % (len(str(origOid)), written_len))
                    cursor.close()
                    return origOid, tag, context['errorStatus']
            except Exception, ex:
                log.msg("--->Infrasim: {0}".format(ex))
                cursor.close()
                return origOid, tag, context['errorStatus']

        else:
            cursor.close()
            raise Error.NoSuchInstanceError(
                name=origOid,
                idx=max(0,
                        context['varsTotal'] - context['varsRemaining'] - 1))

        if context['varsRemaining'] == 0:  # last OID in PDU
            dbConn.commit()
        cursor.close()
        return origOid, textTag, context['origValue']
Beispiel #5
0
def variate(oid, tag, value, **context):
    if not context['nextFlag'] and not context['exactMatch']:
        return context['origOid'], tag, context['errorStatus']

    if 'settings' not in recordContext:
        recordContext['settings'] = dict(
            [split(x, '=') for x in split(value, ',')])

        if 'vlist' in recordContext['settings']:
            vlist = {}
            recordContext['settings']['vlist'] = split(
                recordContext['settings']['vlist'], ':')
            while recordContext['settings']['vlist']:
                o, v, e = recordContext['settings']['vlist'][:3]
                recordContext['settings']['vlist'] = recordContext['settings'][
                    'vlist'][3:]
                v = SnmprecGrammar.tagMap[tag](v)
                if o not in vlist:
                    vlist[o] = {}
                if o == 'eq':
                    vlist[o][v] = e
                elif o in ('lt', 'gt'):
                    vlist[o] = v, e
                else:
                    log.msg('writecache: bad vlist syntax: %s' %
                            recordContext['settings']['vlist'])

            recordContext['settings']['vlist'] = vlist

        if 'status' in recordContext['settings']:
            recordContext['settings']['status'] = recordContext['settings'][
                'status'].lower()

    if oid not in moduleContext:
        moduleContext[oid] = {}
        moduleContext[oid]['type'] = SnmprecGrammar().tagMap[tag]()

    textOid = str(oid)

    if context['setFlag']:
        if 'vlist' in recordContext['settings']:
            if ('eq' in recordContext['settings']['vlist']
                    and context['origValue']
                    in recordContext['settings']['vlist']['eq']):
                e = recordContext['settings']['vlist']['eq'][
                    context['origValue']]
            elif ('lt' in recordContext['settings']['vlist']
                  and context['origValue'] <
                  recordContext['settings']['vlist']['lt'][0]):
                e = recordContext['settings']['vlist']['lt'][1]
            elif ('gt' in recordContext['settings']['vlist']
                  and context['origValue'] >
                  recordContext['settings']['vlist']['gt'][0]):
                e = recordContext['settings']['vlist']['gt'][1]
            else:
                e = None

            if e in errorTypes:
                raise errorTypes[e](name=oid,
                                    idx=max(
                                        0, context['varsTotal'] -
                                        context['varsRemaining'] - 1))

        if moduleContext[oid]['type'].isSameTypeWith(context['origValue']):
            moduleContext['cache'][textOid] = context['origValue']
        else:
            return context['origOid'], tag, context['errorStatus']

    if 'status' in recordContext['settings']:
        if ('op' not in recordContext['settings']
                or recordContext['settings']['op'] == 'any' or
                recordContext['settings']['op'] == 'set' and context['setFlag']
                or recordContext['settings']['op'] == 'get'
                and not context['setFlag']):
            e = recordContext['settings']['status']
            if e in errorTypes:
                raise errorTypes[e](name=oid,
                                    idx=max(
                                        0, context['varsTotal'] -
                                        context['varsRemaining'] - 1))

    if textOid in moduleContext['cache']:
        return oid, tag, moduleContext['cache'][textOid]
    elif 'hexvalue' in recordContext['settings']:
        return oid, tag, moduleContext[oid]['type'].clone(
            hexValue=recordContext['settings']['hexvalue'])
    elif 'value' in recordContext['settings']:
        return oid, tag, moduleContext[oid]['type'].clone(
            recordContext['settings']['value'])
    else:
        return oid, tag, context['errorStatus']
Beispiel #6
0
def variate(oid, tag, value, **context):
    if 'dbConn' in moduleContext:
        dbConn = moduleContext['dbConn']
    else:
        raise error.SnmpsimError('variation module not initialized')

    cursor = dbConn.cursor()

    try:
        cursor.execute(
            'set session transaction isolation level %s' % isolationLevels[moduleContext['isolationLevel']]
        )
        cursor.fetchall()
    except:  # non-MySQL/Postgres
        pass

    if value:
        dbTable = value.split(',').pop(0)
    elif 'dbTable' in moduleContext:
        dbTable = moduleContext['dbTable']
    else:
        log.msg('SQL table not specified for OID %s' % (context['origOid'],))
        return context['origOid'], tag, context['errorStatus']

    origOid = context['origOid']
    sqlOid = '.'.join(['%10s' % x for x in str(origOid).split('.')])

    if context['setFlag']:
        if 'hexvalue' in context:
            textTag = context['hextag']
            textValue = context['hexvalue']
        else:
            textTag = SnmprecGrammar().getTagByType(context['origValue'])
            textValue = str(context['origValue'])
        cursor.execute(
            'select maxaccess,tag from %s where oid=\'%s\' limit 1' % (dbTable, sqlOid)
        )
        resultset = cursor.fetchone()
        if resultset:
            maxaccess = resultset[0]
            if maxaccess != 'read-write':
                return origOid, tag, context['errorStatus']
            cursor.execute(
                'update %s set tag=\'%s\',value=\'%s\' where oid=\'%s\'' % (dbTable, textTag, textValue, sqlOid)
            )
        else:
            cursor.execute(
                'insert into %s values (\'%s\', \'%s\', \'%s\', \'read-write\')' % (dbTable, sqlOid, textTag, textValue)
            )
        if context['varsRemaining'] == 0:  # last OID in PDU
            dbConn.commit()
        cursor.close()
        return origOid, textTag, context['origValue']
    else:
        if context['nextFlag']:
            cursor.execute('select oid from %s where oid>\'%s\' order by oid limit 1' % (dbTable, sqlOid))
            resultset = cursor.fetchone()
            if resultset:
                origOid = origOid.clone(
                    '.'.join([x.strip() for x in str(resultset[0]).split('.')])
                )
                sqlOid = '.'.join(['%10s' % x for x in str(origOid).split('.')])
            else:
                cursor.close()
                return origOid, tag, context['errorStatus']

        cursor.execute('select tag, value from %s where oid=\'%s\' limit 1' % (dbTable, sqlOid))
        resultset = cursor.fetchone()
        cursor.close()

        if resultset:
            return origOid, str(resultset[0]), str(resultset[1])
        else:
            return origOid, tag, context['errorStatus']