summaryrefslogtreecommitdiff
path: root/pysnmp/entity/rfc3413/oneliner/mibvar.py
blob: cb7b16328d08061bf4a25498b4e1e4a13c5b8dda (plain)
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
from pysnmp.proto import rfc1902
from pysnmp.smi.builder import ZipMibSource
from pysnmp.smi.compiler import addMibCompiler
from pysnmp.error import PySnmpError
from pyasn1.error import PyAsn1Error

#
# An OID-like object that embeds MIB resolution.
#
# Valid initializers include:
# MibVariable('1.3.6.1.2.1.1.1.0'),
# MibVariable('iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0')
# MibVariable('SNMPv2-MIB', 'system'),
# MibVariable('SNMPv2-MIB', 'sysDescr', 0),
# MibVariable('IP-MIB', 'ipAdEntAddr', '127.0.0.1', 123),
# 

class MibVariable:
    stDirty, stOidOnly, stClean, stUnresolved = 1, 2, 4, 8
        
    def __init__(self, *args):
        self.__args = args
        self.__mibSourcesToAdd = self.__modNamesToLoad = None
        self.__asn1SourcesToAdd = None
        self.__state  = self.stDirty

    #
    # public API
    #
    def getMibSymbol(self):
        if self.__state & self.stClean:
            return self.__modName, self.__symName, self.__indices
        else:
            raise PySnmpError('%s object not fully initialized' % self.__class__.__name__)

    def getOid(self):
        if self.__state & (self.stOidOnly | self.stClean):
            return self.__oid
        else:
            raise PySnmpError('%s object not fully initialized' % self.__class__.__name__)

    def getLabel(self):
        if self.__state & self.stClean:
            return self.__label
        else:
            raise PySnmpError('%s object not fully initialized' % self.__class__.__name__)

    def getMibNode(self):  # XXX
        if self.__state & self.stClean:
            return self.__mibNode
        else:
            raise PySnmpError('%s object not fully initialized' % self.__class__.__name__)
   
    def isFullyResolved(self):
        return not (self.__state & self.stUnresolved)

    #
    # A gateway to MIBs manipulation routines
    #

    def addAsn1Sources(self, *asn1Sources):
        self.__asn1SourcesToAdd = asn1Sources
        return self

    def addMibSource(self, *mibSources):
        self.__mibSourcesToAdd = mibSources
        return self

    # provides deferred MIBs load
    def loadMibs(self, *modNames):
        self.__modNamesToLoad = modNames
        return self

    # this would eventually be called by an entity which posses a
    # reference to MibViewController
    def resolveWithMib(self, mibViewController, oidOnly=False):
        if self.__mibSourcesToAdd is not None:
            mibSources = tuple(
                [ ZipMibSource(x) for x in self.__mibSourcesToAdd ]
            ) + mibViewController.mibBuilder.getMibSources()
            mibViewController.mibBuilder.setMibSources(*mibSources)
            self.__mibSourcesToAdd = None

        if self.__asn1SourcesToAdd is not None:
            addMibCompiler(
                mibViewController.mibBuilder,
                sources=self.__asn1SourcesToAdd
            )
            self.__asn1SourcesToAdd = None

        if self.__modNamesToLoad is not None:
            mibViewController.mibBuilder.loadModules(*self.__modNamesToLoad)
            self.__modNamesToLoad = None

        if self.__state & (self.stOidOnly | self.stClean):
            return self

        MibScalar, MibTableColumn, = mibViewController.mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTableColumn')

        if len(self.__args) == 1:  # OID or label
            try:
                self.__oid = rfc1902.ObjectName(self.__args[0])
            except PyAsn1Error:
                try:
                    label = tuple(self.__args[0].split('.'))
                except ValueError:
                    raise PySnmpError('Bad OID format %s' % (self.__args[0],))
                prefix, label, suffix = mibViewController.getNodeNameByOid(
                    label
                )
             
                if suffix:
                    try:
                        suffix = tuple([ int(x) for x in suffix ])
                    except ValueError:
                        raise PySnmpError('Unknown object name component %s' % (suffix,))

                self.__oid = rfc1902.ObjectName(prefix + suffix)

                self.__state |= self.stOidOnly

                if oidOnly:
                    return self
            else:
                self.__state |= self.stOidOnly

                if oidOnly:
                    return self

                prefix, label, suffix = mibViewController.getNodeNameByOid(
                    self.__oid
                )

            modName, symName, _ = mibViewController.getNodeLocation(prefix)

            self.__modName = modName
            self.__symName = symName

            self.__label = label

            mibNode, = mibViewController.mibBuilder.importSymbols(
                modName, symName
            )

            self.__mibNode = mibNode

            if isinstance(mibNode, MibTableColumn): # table column
                rowModName, rowSymName, _ = mibViewController.getNodeLocation(
                    mibNode.name[:-1]
                )
                rowNode, = mibViewController.mibBuilder.importSymbols(
                    rowModName, rowSymName
                )
                self.__indices = rowNode.getIndicesFromInstId(suffix)
            elif isinstance(mibNode, MibScalar): # scalar
                self.__indices = ( rfc1902.ObjectName(suffix), )
            else:
                self.__indices = ( rfc1902.ObjectName(suffix), )
                self.__state |= self.stUnresolved
            self.__state |= self.stClean
            return self
        elif len(self.__args) > 1:  # MIB, symbol[, index, index ...]
            self.__modName = self.__args[0]
            if self.__args[1]:
                self.__symName = self.__args[1]
            else:
                mibViewController.mibBuilder.loadModules(self.__modName)
                oid, _, _ = mibViewController.getFirstNodeName(self.__modName)
                _, self.__symName, _ = mibViewController.getNodeLocation(oid)

            mibNode, = mibViewController.mibBuilder.importSymbols(
                self.__modName, self.__symName
            )

            self.__mibNode = mibNode

            self.__indices = ()
            self.__oid = rfc1902.ObjectName(mibNode.getName())

            prefix, label, suffix = mibViewController.getNodeNameByOid(
                self.__oid
            )
            self.__label = label

            if isinstance(mibNode, MibTableColumn): # table
                rowModName, rowSymName, _ = mibViewController.getNodeLocation(
                    mibNode.name[:-1]
                )
                rowNode, = mibViewController.mibBuilder.importSymbols(
                    rowModName, rowSymName
                )
                if self.__args[2:]:
                    instIds = rowNode.getInstIdFromIndices(*self.__args[2:])
                    self.__oid += instIds
                    self.__indices = rowNode.getIndicesFromInstId(instIds)
            elif self.__args[2:]: # any other kind of MIB node with indices
                instId = rfc1902.ObjectName(
                    '.'.join([ str(x) for x in self.__args[2:] ])
                )
                self.__oid += instId
                self.__indices = ( instId, )
            self.__state |= (self.stClean | self.stOidOnly)
            return self
        else:
            raise PySnmpError('Non-OID, label or MIB symbol')

    def prettyPrint(self):
        if self.__state & self.stClean:
            return '%s::%s.%s' % (
                self.__modName, self.__symName,
                '.'.join(['"%s"' % x.prettyPrint() for x in self.__indices ])
            )
        else:
            raise PySnmpError('%s object not fully initialized' % self.__class__.__name__)
 
    def __repr__(self):
        return '%s(%s)' % (self.__class__.__name__, ', '.join([ repr(x) for x in self.__args]))

    # Redirect some attrs access to the OID object to behave alike

    def __str__(self):
        if self.__state & self.stOidOnly:
            return str(self.__oid)
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __eq__(self, other):
        if self.__state & self.stOidOnly:
            return self.__oid == other
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __ne__(self, other):
        if self.__state & self.stOidOnly:
            return self.__oid != other
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __lt__(self, other):
        if self.__state & self.stOidOnly:
            return self.__oid < other
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __le__(self, other):
        if self.__state & self.stOidOnly:
            return self.__oid <= other
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __gt__(self, other):
        if self.__state & self.stOidOnly:
            return self.__oid > other
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __ge__(self, other):
        if self.__state & self.stOidOnly:
            return self.__oid > other
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __nonzero__(self):
        if self.__state & self.stOidOnly:
            return self.__oid != 0
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __bool__(self):
        if self.__state & self.stOidOnly:
            return bool(self.__oid)
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __getitem__(self, i):
        if self.__state & self.stOidOnly:
            return self.__oid[i]
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __len__(self):
        if self.__state & self.stOidOnly:
            return len(self.__oid)
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __add__(self, other):
        if self.__state & self.stOidOnly:
            return self.__oid + other
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __radd__(self, other):
        if self.__state & self.stOidOnly:
            return other + self.__oid
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __hash__(self):
        if self.__state & self.stOidOnly:
            return hash(self.__oid)
        else:
            raise PySnmpError('%s object not properly initialized' % self.__class__.__name__)

    def __getattr__(self, attr):
        if self.__state & self.stOidOnly:
            if attr in ( 'asTuple', 'clone', 'subtype', 'isPrefixOf',
                        'isSameTypeWith', 'isSuperTypeOf'):
                return getattr(self.__oid, attr)
            raise AttributeError
        else:
            raise PySnmpError('%s object not properly initialized for %s access' % (self.__class__.__name__, attr))