File: multiplex.py

package info (click to toggle)
snmpsim 0.2.4-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,536 kB
  • ctags: 461
  • sloc: python: 4,257; makefile: 9
file content (223 lines) | stat: -rw-r--r-- 9,225 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#
# SNMP Simulator, http://snmpsim.sourceforge.net
#
# Managed value variation module: simulate a live Agent using
# a series of snapshots.
#
import os, sys, time, bisect
from pyasn1.compat.octets import str2octs
from pysnmp.proto import rfc1902
from snmpsim.record.snmprec import SnmprecRecord
from snmpsim.record.search.file import searchRecordByOid
from snmpsim.record.search.database import RecordIndex
from snmpsim import confdir
from snmpsim import log
from snmpsim import error

def init(**context):
    if context['options']:
        for k,v in [x.split(':') for x in context['options'].split(',')]:
            if k == 'addon':
                if k in moduleContext:
                    moduleContext[k].append(v)
                else:
                    moduleContext[k] = [v]
            else:
                moduleContext[k] = v
    if context['mode'] == 'variating':
        moduleContext['booted'] = time.time()
    elif context['mode'] == 'recording':
        if 'dir' not in moduleContext:
            raise error.SnmpsimError('SNMP snapshots directory not specified')
        if not os.path.exists(moduleContext['dir']):
            log.msg('multiplex: creating %s...' % moduleContext['dir'])
            os.makedirs(moduleContext['dir'])
        if 'iterations' in moduleContext:
            moduleContext['iterations'] = int(moduleContext['iterations'])
        if 'period' in moduleContext:
            moduleContext['period'] = float(moduleContext['period'])
        else:
            moduleContext['period'] = 10.0

    moduleContext['ready'] = True

def variate(oid, tag, value, **context):
    if 'settings' not in recordContext:
        recordContext['settings'] = dict([ x.split('=') for x in value.split(',') ])
        if 'dir' not in recordContext['settings']:
            log.msg('multiplex: snapshot directory not specified')
            return context['origOid'], tag, context['errorStatus']

        recordContext['settings']['dir'] = recordContext['settings']['dir'].replace(
            '/', os.path.sep
        )
        if recordContext['settings']['dir'][0] != os.path.sep:
            for x in confdir.data:
                d = os.path.join(x, recordContext['settings']['dir'])
                if os.path.exists(d):
                    break
            else:
                log.msg('multiplex: directory %s not found' % recordContext['settings']['dir'])
                return context['origOid'], tag, context['errorStatus']
        else:
            d = recordContext['settings']['dir']
        recordContext['dirmap'] = dict(
            [ (int(os.path.basename(x).split(os.path.extsep)[0]), os.path.join(d, x)) for x in os.listdir(d) if x[-7:] == 'snmprec' ]
        )
        recordContext['keys'] = list(
            recordContext['dirmap'].keys()
        )
        recordContext['bounds'] = (
            min(recordContext['keys']), max(recordContext['keys'])
        )
        if 'period' in recordContext['settings']:
            recordContext['settings']['period'] = float(recordContext['settings']['period'])
        else:
            recordContext['settings']['period'] = 60.0
        if 'wrap' in recordContext['settings']:
            recordContext['settings']['wrap'] = bool(recordContext['settings']['wrap'])
        else:
            recordContext['settings']['wrap'] = False
        if 'control' in recordContext['settings']:
            recordContext['settings']['control'] = rfc1902.ObjectName(
                recordContext['settings']['control']
            )
            log.msg('multiplex: using control OID %s for subtree %s, time-based multiplexing disabled' % (recordContext['settings']['control'], oid))

        recordContext['ready'] = True

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

    if oid not in moduleContext:
        moduleContext[oid] = {}

    if context['setFlag']:
        if 'control' in recordContext['settings'] and \
                recordContext['settings']['control'] == context['origOid']:
            fileno = int(context['origValue'])
            if fileno >= len(recordContext['keys']):
                log.msg('multiplex: .snmprec file number %s over limit of %s' % (fileno, len(recordContext['keys'])))
                return context['origOid'], tag, context['errorStatus']
            moduleContext[oid]['fileno'] = fileno
            log.msg('multiplex: switched to file #%s (%s)' % (recordContext['keys'][fileno], recordContext['dirmap'][recordContext['keys'][fileno]]))
            return context['origOid'], tag, context['origValue']
        else:
            return context['origOid'], tag, context['errorStatus']

    if 'control' in recordContext['settings']:
        if 'fileno' not in moduleContext[oid]:
            moduleContext[oid]['fileno'] = 0
        if not context['nextFlag'] and \
                recordContext['settings']['control'] == context['origOid']:
            return context['origOid'], tag, rfc1902.Integer32(moduleContext[oid]['fileno'])
    else:
        timeslot = (time.time() - moduleContext['booted']) % (recordContext['settings']['period'] * len(recordContext['dirmap']))
        fileslot = int(timeslot / recordContext['settings']['period']) + recordContext['bounds'][0]

        fileno = bisect.bisect(recordContext['keys'], fileslot) - 1

        if 'fileno' not in moduleContext[oid] or \
                moduleContext[oid]['fileno'] < fileno or \
                recordContext['settings']['wrap']:
            moduleContext[oid]['fileno'] = fileno

    datafile = recordContext['dirmap'][
        recordContext['keys'][moduleContext[oid]['fileno']]
    ]

    if 'datafile' not in moduleContext[oid] or \
            moduleContext[oid]['datafile'] != datafile:
        if 'datafileobj' in moduleContext[oid]:
            moduleContext[oid]['datafileobj'].close()
        moduleContext[oid]['datafileobj'] = RecordIndex(
            datafile, SnmprecRecord()
        ).create()
        moduleContext[oid]['datafile'] = datafile

        log.msg('multiplex: switching to data file %s for %s' % (datafile, context['origOid']))
        
    text, db = moduleContext[oid]['datafileobj'].getHandles()

    textOid = str(rfc1902.OctetString('.'.join([ '%s' % x for x in context['origOid']])))

    try:
        line = moduleContext[oid]['datafileobj'].lookup(textOid)
    except KeyError:
        offset = searchRecordByOid(context['origOid'], text, SnmprecRecord())
        exactMatch = False
    else:
        offset, subtreeFlag, prevOffset = line.split(str2octs(','))
        exactMatch = True

    text.seek(int(offset))

    line = text.readline()  # matched line

    if context['nextFlag']:
        if exactMatch:
            line = text.readline()
    else:
        if not exactMatch:
            return context['origOid'], tag, context['errorStatus']

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

    try:
        oid, value = SnmprecRecord().evaluate(line)
    except error.SnmpsimError:
        oid, value = context['origOid'], tag, context['errorStatus']

    return oid, tag, value

def record(oid, tag, value, **context):
    if 'ready' not in moduleContext:
        raise error.SnmpsimError('module not initialized')
    if 'started' not in moduleContext:
        moduleContext['started'] = time.time()
    if context['stopFlag']:
        if 'file' in moduleContext:
            moduleContext['file'].close()
            del moduleContext['file']
        else:
            moduleContext['filenum'] = 0
        if 'iterations' in moduleContext and moduleContext['iterations']:
            log.msg('multiplex: %s iterations remaining' % moduleContext['iterations'])
            moduleContext['started'] = time.time()
            moduleContext['iterations'] -= 1
            moduleContext['filenum'] += 1
            wait = max(0, moduleContext['period'] - (time.time() - moduleContext['started']))
            raise error.MoreDataNotification(period=wait)
        else:
            raise error.NoDataNotification()

    if 'file' not in moduleContext:
        if 'filenum' not in moduleContext:
            moduleContext['filenum'] = 0
        snmprecfile = os.path.join(moduleContext['dir'],
                                   '%.5d%ssnmprec' % (moduleContext['filenum'],
                                                      os.path.extsep))
        moduleContext['file'] = open(snmprecfile, 'wb')
        log.msg('multiplex: writing into %s file...' % snmprecfile)

    moduleContext['file'].write(
        SnmprecRecord().format(context['origOid'], context['origValue'])
    )

    if not context['total']:
        settings = {
            'dir': moduleContext['dir'].replace(os.path.sep, '/')
        }
        if 'period' in moduleContext:
            settings['period'] = '%.2f' % float(moduleContext['period'])
        if 'addon' in moduleContext:
            settings.update(
                dict([x.split('=') for x in moduleContext['addon']])
            )
        value = ','.join([ '%s=%s' % (k,v) for k,v in settings.items() ])
        return str(context['startOID']), ':multiplex', value
    else:
        raise error.NoDataNotification()

def shutdown(**context): pass