Package Products :: Package ZenModel :: Module IpAddress |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenModel.IpAddress

      1  ##############################################################################
      2  #
      3  # Copyright (C) Zenoss, Inc. 2007, all rights reserved.
      4  #
      5  # This content is made available according to terms specified in
      6  # License.zenoss under the directory where your Zenoss product is installed.
      7  #
      8  ##############################################################################
      9
     10
     11  __doc__ = """IpAddress
     12
     13  IpAddress represents a device residing on an IP network.
     14  """
     15
     16  import socket
     17  import logging
     18  log = logging.getLogger("zen.IpAddress")
     19
     20  #base classes for IpAddress
     21  from ManagedEntity import ManagedEntity
     22
     23  from ipaddr import IPAddress
     24
     25  from AccessControl import ClassSecurityInfo
     26  from Globals import DTMLFile
     27  from Globals import InitializeClass
     28  import zope.interface
     29  from Products import Zuul
     30  from Products.Zuul.interfaces import IInfo
     31  from Products.ZenUtils.jsonutils import json
     32  from Products.Zuul.utils import allowedRolesAndUsers
     33  from Products.ZenModel.interfaces import IIndexed
     34  from Products.ZenModel.Linkable import Layer3Linkable
     35  from Products.ZenRelations.RelSchema import ToOne, ToMany, ToManyCont
     36  from Products.ZenUtils.IpUtil import maskToBits, checkip, ipToDecimal, netFromIpAndNet, \
     37                                       ipwrap, ipunwrap, ipunwrap_strip
     38  from Products.ZenModel.Exceptions import WrongSubnetError
     39  from Products.ZenUtils.IpUtil import numbip
     40
     41
     42 -def manage_addIpAddress(context, id, netmask=24, REQUEST = None):
     43      """make an IpAddress"""
     44      ip = IpAddress(id, netmask)
     45      context._setObject(ip.id, ip)
     46      if REQUEST is not None:
     47          REQUEST['RESPONSE'].redirect(context.absolute_url()
     48                                       +'/manage_main')
     49
     50
     51  addIpAddress = DTMLFile('dtml/addIpAddress',globals())
     52
     53
     54 -class IpAddress(ManagedEntity, Layer3Linkable):
     55      """IpAddress object"""
     56      zope.interface.implements(IIndexed)
     57
     58      event_key = portal_type = meta_type = 'IpAddress'
     59
     60      default_catalog = 'ipSearch'
     61
     62      version = 4
     63
     64      _properties = (
     65          {'id':'netmask', 'type':'string', 'mode':'w', 'setter':'setNetmask'},
     66          {'id':'ptrName', 'type':'string', 'mode':'w'},
     67          {'id':'version', 'type':'int', 'mode':'w'},
     68          )
     69      _relations = ManagedEntity._relations + (
     70          ("network", ToOne(ToManyCont,"Products.ZenModel.IpNetwork","ipaddresses")),
     71          ("interface", ToOne(ToMany,"Products.ZenModel.IpInterface","ipaddresses")),
     72          ("clientroutes", ToMany(ToOne,"Products.ZenModel.IpRouteEntry","nexthop")),
     73          )
     74
     75      factory_type_information = (
     76          {
     77              'id'             : 'IpAddress',
     78              'meta_type'      : 'IpAddress',
     79              'description'    : """Ip Address Class""",
     80              'icon'           : 'IpAddress_icon.gif',
     81              'product'        : 'ZenModel',
     82              'factory'        : 'manage_addIpAddress',
     83              'immediate_view' : 'viewIpAddressOverview',
     84              'actions'        :
     85              (
     86                  { 'id'            : 'overview'
     87                  , 'name'          : 'Overview'
     88                  , 'action'        : 'viewIpAddressOverview'
     89                  , 'permissions'   : ( "View", )
     90                  },
     91              )
     92            },
     93          )
     94
     95      security = ClassSecurityInfo()
     96
     97 -    def __init__(self, id, netmask=24):
     98          checkip(id)
     99          ManagedEntity.__init__(self, ipwrap(id))
    100          ipobj = IPAddress(ipunwrap_strip(id))
    101          if ipobj.version == 6:
    102              # No user-definable subnet masks for IPv6
    103              netmask = 64
    104          self._netmask = maskToBits(netmask)
    105          self.ptrName = None
    106          self.title = ipunwrap(id)
    107          self.version = ipobj.version
    108
    109 -    def setPtrName(self):
    110          try:
    111              data = socket.gethostbyaddr(ipunwrap(self.id))
    112              if data: self.ptrName = data[0]
    113          except socket.error, e:
    114              self.ptrName = ""
    115              log.warn("%s: %s", self.title, e)
    116
    117      security.declareProtected('View', 'primarySortKey')
    118 -    def primarySortKey(self):
    119          """
    120          Make sure that networks sort correctly
    121          """
    122          return ipToDecimal(self.id)
    123
    124 -    def setNetmask(self, value):
    125          self._netmask = maskToBits(value)
    126
    127 -    def _setPropValue(self, id, value):
    128          """
    129          Override from PerpertyManager to handle checks and IP creation
    130          """
    131          self._wrapperCheck(value)
    132          if id == 'netmask':
    133              self.setNetmask(value)
    134          else:
    135              setattr(self,id,value)
    136
    137 -    def __getattr__(self, name):
    138          if name == 'netmask':
    139              return self._netmask
    140          else:
    141              raise AttributeError( name )
    142
    143      security.declareProtected('Change Device', 'setIpAddress')
    144 -    def setIpAddress(self, ip):
    145          """
    146          Set the IP address. Use the format 1.1.1.1/24 to also set the netmask
    147          """
    148          iparray = ip.split("/")
    149          if len(iparray) > 1:
    150              ip = iparray[0]
    151              self._netmask = maskToBits(iparray[1])
    152          checkip(ip)
    153          aqself = self.primaryAq() #set aq path
    154          network = aqself.aq_parent
    155          netip = netFromIpAndNet(ip, network.netmask)
    156          if netip == network.id:
    157              network._renameObject(aqself.id, ipwrap(ip))
    158          else:
    159              raise WrongSubnetError(
    160                      "IP %s is in a different subnet than %s" % (ipunwrap(ip), ipunwrap(self.id)) )
    161
    162      security.declareProtected('View', 'getIp')
    163 -    def getIp(self):
    164          """
    165          Return only the IP address
    166          """
    167          return ipunwrap(self.id)
    168
    169      security.declareProtected('View', 'getIpAddress')
    170 -    def getIpAddress(self):
    171          """
    172          Return the IP with its netmask in the form 1.1.1.1/24
    173          """
    174          return ipunwrap(self.id) + "/" + str(self._netmask)
    175
    176 -    def __str__(self):
    177          return self.getIpAddress()
    178
    179      security.declareProtected('View', 'getInterfaceName')
    180 -    def getInterfaceName(self):
    181          if self.interface():
    182              return self.interface().name()
    183          return "No Interface"
    184
    185      security.declareProtected('View', 'getDeviceName')
    186 -    def getDeviceName(self):
    187          if self.interface():
    188              return self.device().titleOrId()
    189          return "No Device"
    190
    191      security.declareProtected('View', 'getNetworkName')
    192 -    def getNetworkName(self):
    193          if self.network():
    194              return self.network().getNetworkName()
    195          return "No Network"
    196
    197 -    def getInterfaceDescription(self):
    198          """
    199          Used for indexing
    200          """
    201          if self.interface():
    202              return self.interface().description
    203
    204 -    def getInterfaceMacAddress(self):
    205          """
    206          Used for indexing
    207          """
    208          if self.interface():
    209              return self.interface().macaddress
    210
    211      security.declareProtected('View', 'getNetworkUrl')
    212 -    def getNetworkUrl(self):
    213          if self.network():
    214              return self.network().absolute_url()
    215          return ""
    216
    217      security.declareProtected('View', 'getDeviceUrl')
    218 -    def getDeviceUrl(self):
    219          """
    220          Get the primary URL path of the device to which this IP
    221          is associated.  If no device return the URL to the IP itself.
    222          """
    223          d = self.device()
    224          if d:
    225              return d.getPrimaryUrlPath()
    226          else:
    227              return self.getPrimaryUrlPath()
    228
    229 -    def device(self):
    230          """
    231          Return the device for this IP
    232          """
    233          iface = self.interface()
    234          if iface: return iface.device()
    235          return None
    236
    237 -    def index_object(self, idxs=None):
    238          super(IpAddress, self).index_object(idxs)
    239          self.index_links()
    240
    241 -    def unindex_object(self):
    242          self.unindex_links()
    243          super(IpAddress, self).unindex_object()
    244
    245 -    def deviceId(self):
    246          """
    247          The device id, for indexing purposes.
    248          """
    249          d = self.device()
    250          if d: return d.id
    251          else: return None
    252
    253 -    def interfaceId(self):
    254          """
    255          The interface id, for indexing purposes.
    256          """
    257          i = self.interface()
    258          if i: return i.id
    259          else: return None
    260
    261 -    def ipAddressId(self):
    262          """
    263          The ipAddress id, for indexing purposes.
    264          """
    265          return self.getPrimaryId()
    266
    267 -    def networkId(self):
    268          """
    269          The network id, for indexing purposes.
    270          """
    271          n = self.network()
    272          if n: return n.getPrimaryId()
    273          else: return None
    274
    275 -    def ipAddressAsInt(self):
    276          ip = self.getIpAddress()
    277          if ip:
    278              ip = ip.partition('/')[0]
    279          return str(numbip(ip))
    280
    281  InitializeClass(IpAddress)
    282