File: numeric.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 (220 lines) | stat: -rw-r--r-- 8,567 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
# SNMP Simulator, http://snmpsim.sourceforge.net
# Managed value variation module
# Simulate a numeric value
# Valid values in module options are:
#   2  - Integer
#   65 - Counter32
#   66 - Gauge32
#   67 - TimeTicks
#   70 - Counter64
import sys
import math
import time
import random
from pysnmp.proto import rfc1902, rfc1905
from snmpsim import log
from snmpsim import error

tboot = time.time()

def init(**context):
    if context['mode'] == 'variating':
        random.seed()
    if context['mode'] == 'recording':
        moduleContext['settings'] = {}
        if context['options']:
            for k,v in [x.split(':') for x in context['options'].split(',')]:
                if k == 'addon':
                    if k in moduleContext['settings']:
                        moduleContext['settings'][k].append(v)
                    else:
                        moduleContext['settings'][k] = [v]
                else:
                    moduleContext['settings'][k] = v
            if 'iterations' in moduleContext['settings']:
                moduleContext['settings']['iterations'] = int(moduleContext['settings']['iterations'])
                if moduleContext['settings']['iterations']:
                    moduleContext['settings']['iterations'] = 1  # no reason for more
            if 'period' in moduleContext['settings']:
                moduleContext['settings']['period'] = float(moduleContext['settings']['period'])
            else:
                moduleContext['settings']['period'] = 10.0

            if 'taglist' not in moduleContext['settings']:
                moduleContext['settings']['taglist'] = '2-65-66-67-70'

def variate(oid, tag, value, **context):
    if not context['nextFlag'] and not context['exactMatch']:
        return context['origOid'], tag, context['errorStatus']
    if context['setFlag']:
        return context['origOid'], tag, context['errorStatus']

    if 'settings' not in recordContext:
        recordContext['settings'] = dict([ x.split('=') for x in value.split(',') ])
        for k in recordContext['settings']:
            if k != 'function':
                recordContext['settings'][k] = float(recordContext['settings'][k])
        if 'min' not in recordContext['settings']:
            recordContext['settings']['min'] = 0
        if 'max' not in recordContext['settings']:
            if tag == '70':
                recordContext['settings']['max'] = 0xffffffffffffffff
            else:
                recordContext['settings']['max'] = 0xffffffff
        if 'rate' not in recordContext['settings']:
            recordContext['settings']['rate'] = 1
        if 'function' in recordContext['settings']:
            recordContext['settings']['function'] = getattr(
                math, recordContext['settings']['function']
            )
        else:
            recordContext['settings']['function'] = lambda x: x

    vold, told = recordContext['settings'].get('initial', recordContext['settings']['min']), tboot

    if 'cumulative' in recordContext['settings']:
        if 'value' not in recordContext:
            recordContext['value'] = vold, told
        vold, told = recordContext['value']

    tnow = time.time()

    if 'atime' in recordContext['settings']:
        t = tnow
    else:
        t = tnow - tboot

    v = recordContext['settings']['function'](
        t * recordContext['settings']['rate']
    )
    
    if 'scale' in recordContext['settings']:
        v *= recordContext['settings']['scale']

    if 'offset' in recordContext['settings']:
        if 'cumulative' in recordContext['settings']:
            v += recordContext['settings']['offset'] * (tnow - told) * recordContext['settings']['rate']
        else:
            v += recordContext['settings']['offset']

    if 'deviation' in recordContext['settings'] and recordContext['settings']['deviation']:
        v += random.randrange(-recordContext['settings']['deviation'], recordContext['settings']['deviation'])

    if 'cumulative' in recordContext['settings']:
        v = max(v, 0)

    v += vold

    if v < recordContext['settings']['min']:
        v = recordContext['settings']['min']
    elif v > recordContext['settings']['max']:
        if 'wrap' in recordContext['settings']:
            v %= recordContext['settings']['max']
        else:
            v = recordContext['settings']['max']

    if 'cumulative' in recordContext['settings']:
        recordContext['value'] = v, tnow

    return oid, tag, v

def record(oid, tag, value, **context):
    if 'started' not in moduleContext:
        moduleContext['started'] = time.time()

    if 'iterations' not in moduleContext:
        moduleContext['iterations'] = min(1, moduleContext['settings'].get('iterations',0))

    # single-run recording

    if 'iterations' not in moduleContext['settings'] or not moduleContext['settings']['iterations']:
        if context['origValue'].tagSet not in (
                    rfc1902.Counter32.tagSet,
                    rfc1902.Counter64.tagSet,
                    rfc1902.TimeTicks.tagSet,
                    rfc1902.Gauge32.tagSet,
                    rfc1902.Integer.tagSet):
            if 'hextag' in context:
                tag = context['hextag']
            if 'hexvalue' in context:
                value = context['hexvalue']
            return oid, tag, value

        if 'taglist' not in moduleContext['settings'] or \
                tag not in moduleContext['settings']['taglist']:
            return oid, tag, value

        value = 'initial=%s' % value 

        if context['origValue'].tagSet == rfc1902.TimeTicks.tagSet:
            value += ',rate=100'
        elif context['origValue'].tagSet == rfc1902.Integer.tagSet:
            value += ',rate=0'
 
        return oid, tag + ':numeric', value
            
    # multiple-iteration recording

    if oid not in moduleContext:
        settings = {
            'initial': value
        }
        if context['origValue'].tagSet == rfc1902.TimeTicks.tagSet:
            settings['rate'] = 100
        elif context['origValue'].tagSet == rfc1902.Integer.tagSet:
            settings['rate'] = 0  # may be constants
        if 'addon' in moduleContext['settings']:
            settings.update(
                dict([x.split('=') for x in moduleContext['settings']['addon']])
            )

        moduleContext[oid] = {}

        moduleContext[oid]['settings'] = settings

    if moduleContext['iterations']:
        if context['stopFlag']: # switching to final iteration
            log.msg('numeric: %s iterations remaining' % moduleContext['settings']['iterations'])
            moduleContext['iterations'] -= 1
            moduleContext['started'] = time.time()
            wait = max(0, float(moduleContext['settings']['period']) - (time.time() - moduleContext['started']))
            raise error.MoreDataNotification(period=wait)
        else:  # storing values on first iteration
            moduleContext[oid]['time'] = time.time()
            moduleContext[oid]['value'] = context['origValue']
            if 'hexvalue' in moduleContext[oid]:
                moduleContext[oid]['hexvalue'] = context['hexvalue']
            if 'hextag' in moduleContext[oid]:
                moduleContext[oid]['hextag'] = context['hextag']
            raise error.NoDataNotification()
    else:
        if context['stopFlag']:
            raise error.NoDataNotification()

        if 'value' in moduleContext[oid]:
            if context['origValue'].tagSet not in (
                        rfc1902.Counter32.tagSet,
                        rfc1902.Counter64.tagSet,
                        rfc1902.TimeTicks.tagSet,
                        rfc1902.Gauge32.tagSet,
                        rfc1902.Integer.tagSet):
                if 'hextag' in moduleContext[oid]:
                    tag = moduleContext[oid]['hextag']
                if 'hexvalue' in moduleContext[oid]:
                    value = moduleContext[oid]['hexvalue']
                return oid, tag, value

            if tag not in moduleContext['settings']['taglist']:
                return oid, tag, moduleContext[oid]['value']
 
            moduleContext[oid]['settings']['rate'] = (int(context['origValue']) - int(moduleContext[oid]['value'])) / (time.time() - moduleContext[oid]['time'])

            tag += ':numeric'
            value = ','.join(
                [ '%s=%s' % (k,v) for k,v in moduleContext[oid]['settings'].items() ]
            )
            return oid, tag, value
        else:
            raise error.NoDataNotification()

def shutdown(**context): pass