File: instrum.py

package info (click to toggle)
python-pysnmp4 4.1.6a-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,016 kB
  • ctags: 1,826
  • sloc: python: 9,809; sh: 60; makefile: 11
file content (195 lines) | stat: -rw-r--r-- 6,943 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
# MIB modules management
from types import InstanceType
from pysnmp.smi import error

__all__ = [ 'MibInstrumController' ]

class MibInstrumController:
    fsmReadVar = {
        # ( state, status ) -> newState
        ('start', 'ok'): 'readTest',
        ('readTest', 'ok'): 'readGet',
        ('readGet', 'ok'): 'stop',
        ('*', 'err'): 'stop'
    }
    fsmReadNextVar = {
        # ( state, status ) -> newState
        ('start', 'ok'): 'readTestNext',
        ('readTestNext', 'ok'): 'readGetNext',
        ('readGetNext', 'ok'): 'stop',
        ('*', 'err'): 'stop'
    }
    fsmWriteVar = {
        # ( state, status ) -> newState
        ('start', 'ok'): 'writeTest',
        ('writeTest', 'ok'): 'writeCommit',
        ('writeCommit', 'ok'): 'writeCleanup',
        ('writeCleanup', 'ok'): 'readTest',
        # Do read after successful write
        ('readTest', 'ok'): 'readGet',
        ('readGet', 'ok'): 'stop',
        # Error handling
        ('writeTest', 'err'): 'writeCleanup',
        ('writeCommit', 'err'): 'writeUndo',
        ('writeUndo', 'ok'): 'readTest',
        # Ignore read errors (removed columns)
        ('readTest', 'err'): 'stop',
        ('readGet', 'err'): 'stop',
        ('*', 'err'): 'stop'
    }

    def __init__(self, mibBuilder):
        self.mibBuilder = mibBuilder
        self.lastBuildId = -1
            
    # MIB indexing

    def __indexMib(self):
        # Build a tree from MIB objects found at currently loaded modules
        if self.lastBuildId == self.mibBuilder.lastBuildId:
            return

        ( MibScalarInstance,
          MibScalar,
          MibTableColumn,
          MibTableRow,
          MibTable,
          MibTree ) = self.mibBuilder.importSymbols(
            'SNMPv2-SMI',
            'MibScalarInstance',
            'MibScalar',
            'MibTableColumn',
            'MibTableRow',
            'MibTable',
            'MibTree'
            )
            
        mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso')

        #
        # Management Instrumentation gets organized as follows:
        #
        # MibTree
        #   |
        #   +----MibScalar
        #   |        |
        #   |        +-----MibScalarInstance
        #   |
        #   +----MibTable
        #   |
        #   +----MibTableRow
        #          |
        #          +-------MibTableColumn
        #                        |
        #                        +------MibScalarInstance(s)
        #
        # Mind you, only Managed Objects get indexed here, various MIB defs and
        # constants can't be SNMP managed so we drop them.
        #
        scalars = {}; instances = {}; tables = {}; rows = {}; cols = {}

        # Sort by module name to give user a chance to slip-in
        # custom MIB modules (that would sorted out first)
        mibSymbols = self.mibBuilder.mibSymbols.items()
        mibSymbols.sort(lambda x,y: cmp(y[0], x[0]))
        
        for modName, mibMod in mibSymbols:
            for symObj in mibMod.values():
                if type(symObj) != InstanceType:
                    continue
                if isinstance(symObj, MibTable):
                    tables[symObj.name] = symObj
                elif isinstance(symObj, MibTableRow):
                    rows[symObj.name] = symObj
                elif isinstance(symObj, MibTableColumn):
                    cols[symObj.name] = symObj
                elif isinstance(symObj, MibScalarInstance):
                    instances[symObj.name] = symObj
                elif isinstance(symObj, MibScalar):
                    scalars[symObj.name] = symObj

        # Attach Managed Objects Instances to Managed Objects
        for inst in instances.values():
            if scalars.has_key(inst.typeName):
                scalars[inst.typeName].registerSubtrees(inst)
            elif cols.has_key(inst.typeName):
                cols[inst.typeName].registerSubtrees(inst)
            else:
                raise error.SmiError(
                    'Orphan MIB scalar instance %s at %s' % (inst, self)
                    )

        # Attach Table Columns to Table Rows
        for col in cols.values():
            rowName = col.name[:-1] # XXX
            if rows.has_key(rowName):
                rows[rowName].registerSubtrees(col)
            else:
                raise error.SmiError(
                    'Orphan MIB table column %s at %s' % (col, self)
                    )

        # Attach Table Rows to MIB tree
        for row in rows.values():
            mibTree.registerSubtrees(row)

        # Attach Tables to MIB tree
        for table in tables.values():
            mibTree.registerSubtrees(table)

        # Attach Scalars to MIB tree
        for scalar in scalars.values():
            mibTree.registerSubtrees(scalar)
            
        self.lastBuildId = self.mibBuilder.lastBuildId
        
    # MIB instrumentation
    
    def flipFlopFsm(self, fsmTable, inputNameVals, (acFun, acCtx)):
        self.__indexMib()
        mibTree, = self.mibBuilder.importSymbols('SNMPv2-SMI', 'iso')
        outputNameVals = []
        state, status = 'start', 'ok'
        myErr = None
        while 1:
            fsmState = fsmTable.get((state, status))
            if fsmState is None:
                fsmState = fsmTable.get(('*', status))
                if fsmState is None:
                    raise error.SmiError(
                        'Unresolved FSM state %s, %s' % (state, status)
                        )
            state = fsmState
            status = 'ok'
            if state == 'stop':
                break
            idx = 0
            for name, val in inputNameVals:
                f = getattr(mibTree, state, None)
                if f is None:
                    raise error.SmiError(
                        'Unsupported state handler %s at %s' % (state, self)
                        )
                try:
                    # Convert to tuple to avoid ObjectName instantiation
                    # on subscription
                    rval = f(tuple(name), val, idx, (acFun, acCtx))
                except error.SmiError, why:
                    if myErr is None:  # Take the first exception
                        myErr = why
                    status = 'err'
                    break
                else:
                    if rval is not None:
                        outputNameVals.append((rval[0], rval[1]))
                idx = idx + 1
        if myErr:
            raise myErr
        return outputNameVals
    
    def readVars(self, vars, (acFun, acCtx)=(None, None)):
        return self.flipFlopFsm(self.fsmReadVar, vars, (acFun, acCtx))
    def readNextVars(self, vars, (acFun, acCtx)=(None, None)):
        return self.flipFlopFsm(self.fsmReadNextVar, vars, (acFun, acCtx))
    def writeVars(self, vars, (acFun, acCtx)=(None, None)):
        return self.flipFlopFsm(self.fsmWriteVar, vars, (acFun, acCtx))