Package Products :: Package ZenUtils :: Module NetworkTree |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenUtils.NetworkTree

      1  ###########################################################################
      2  #
      3  # This program is part of Zenoss Core, an open source monitoring platform.
      4  # Copyright (C) 2007, Zenoss Inc.
      5  #
      6  # This program is free software; you can redistribute it and/or modify it
      7  # under the terms of the GNU General Public License version 2 as published by
      8  # the Free Software Foundation.
      9  #
     10  # For complete information please visit: http://www.zenoss.com/oss/
     11  #
     12  ###########################################################################
     13
     14  from Products.ZenModel.Link import ILink
     15
     16 -def _fromDeviceToNetworks(dev):
     17      for iface in dev.os.interfaces():
     18          for ip in iface.ipaddresses():
     19              net = ip.network()
     20              if net is None or net.netmask == 32:
     21                  continue
     22              else:
     23                  yield net
     24
     25 -def _fromNetworkToDevices(net, devclass):
     26      for ip in net.ipaddresses():
     27          dev = ip.device()
     28          if dev is None:
     29              continue
     30          dcp = dev.getDeviceClassPath()
     31          if not ( dcp.startswith(devclass) or
     32              dcp.startswith('/Network/Router')):
     33              continue
     34          else:
     35              yield dev
     36
     37 -def _get_related(node, filter='/'):
     38      if node.meta_type=='IpNetwork':
     39          children = _fromNetworkToDevices(node, filter)
     40      elif node.meta_type=='Device':
     41          children = _fromDeviceToNetworks(node)
     42      else:
     43          raise NotImplementedError
     44      return children
     45
     46 -def _sortedpair(x,y):
     47      l = [x,y]
     48      cmpf = lambda x,y:int(x.meta_type=='Device')-int(y.meta_type=='Device')
     49      l.sort(cmpf)
     50      return tuple(l)
     51
     52 -def _get_connections(rootnode, depth=1, pairs=None, filter='/'):
     53      """ Depth-first search of the network tree emanating from
     54          rootnode, returning (network, device) edges.
     55      """
     56      if not pairs:
     57          pairs = []
     58      if depth:
     59          for node in _get_related(rootnode, filter):
     60              sorted = _sortedpair(rootnode, node)
     61              pair = [x.id for x in sorted]
     62              if pair not in pairs:
     63                  pairs.append(pair)
     64                  yield sorted
     65                  for childnode in _get_related(node, filter):
     66                      for n in _get_connections(
     67                          childnode, depth-1, pairs, filter):
     68                          yield n
     69
     70 -def get_edges(rootnode, depth=1, withIcons=False, filter='/'):
     71      """ Returns some edges """
     72      depth = int(depth)
     73      g = _get_connections(rootnode, depth, [], filter)
     74      def getColor(node):
     75          if node.meta_type=='IpNetwork':
     76              return '0xffffff'
     77          summary = node.getEventSummary()
     78          colors = '0xff0000 0xff8c00 0xffd700 0x00ff00 0x00ff00'.split()
     79          color = '0x00ff00'
     80          for i in range(5):
     81              if summary[i][2]>0:
     82                  color = colors[i]
     83                  break
     84          return color
     85      for nodea, nodeb in g:
     86          if withIcons:
     87              yield ((nodea.titleOrId(), nodea.getIconPath(), getColor(nodea)),
     88                     (nodeb.titleOrId(), nodeb.getIconPath(), getColor(nodeb)))
     89          else:
     90              yield (nodea.titleOrId(), nodeb.titleOrId())
     91
     92 -def getDeviceNetworkLinks(rootdevice):
     93      """ Returns network links to other devices """
     94      visited = []
     95      ifaces = rootdevice.os.interfaces()
     96      ifaceids = [x.getPrimaryId() for x in ifaces]
     97      for iface in ifaces:
     98          for ip in iface.ipaddresses.objectValuesGen():
     99              for ipsib in ip.network().ipaddresses.objectValuesGen():
    100                  ifacesib = ipsib.interface()
    101                  if ifacesib is None: continue
    102                  if (ifacesib.getPrimaryId() in visited or
    103                      ifacesib.getPrimaryId() in ifaceids):
    104                      continue
    105                  visited.append(ifacesib.getPrimaryId())
    106                  link = NetworkLink()
    107                  link.setEndpoints(iface, ifacesib)
    108                  yield link
    109
    110
    111
    112 -class NetworkLink(ILink):
    113      """ Represents a link between two IpInterfaces
    114          related by network connectivity.
    115          Not a persistent object, so not managed
    116          by a LinkManager.
    117          Implements Products.ZenModel.Link.ILink.
    118      """
    119
    120      OSI_layer = '3'
    121      pointa = None
    122      pointb = None
    123
    124 -    def __hash__(self):
    125          eps = [x.id for x in self.getEndpoints()]
    126          eps.sort()
    127          return hash(':'.join(eps))
    128
    129 -    def setEndpoints(self, pointa, pointb):
    130          self.pointa = pointa
    131          self.pointb = pointb
    132          self.endpoints = (pointa, pointb)
    133
    134 -    def getEndpoints(self):
    135          return self.endpoints
    136
    137 -    def getStatus(self):
    138          eps = self.endpoints
    139          if max([ep.getPingStatus() for ep in eps]) > 0:
    140              return 5
    141          zem = eps[0].dmd.ZenEventManager
    142          return max(map(zem.getMaxSeverity,eps))
    143
    144 -    def getEndpointNames(self):
    145          return (self.pointa.id, self.pointb.id)
    146
    147 -    def getOtherEndpoint(self, endpoint):
    148          if endpoint==self.pointa: return self.pointb
    149          elif endpoint==self.pointb: return self.pointa
    150          else: return None
    151
    152 -    def getDataForJSON(self):
    153          # Eventually will return data for serialization
    154          import json
    155          return json.dumps([
    156              self.id,
    157              self.getEndpointNames()[0],
    158              self.getEndpointNames()[1],
    159              self.OSI_layer,
    160              self.link_type,
    161              self.entry_type,
    162              self.id
    163          ])
    164
    165 -    def getGeomapData(self, context, full=False):
    166          """ Return the addresses of the endpoints
    167              aggregated for the generation of the context
    168          """
    169          dmd = context.dmd
    170          generation = len(context.getPrimaryPath())+1
    171          def getancestoraddress(endpoint):
    172              loc = endpoint.device().location()
    173              if loc is None: return
    174              path = loc.getPrimaryPath()
    175              path = '/'.join(path[:generation])
    176              ancestor = dmd.getObjByPath(path)
    177              if full:
    178                  return ancestor.getGeomapData()
    179              else:
    180                  return ancestor.address
    181          result = map(getancestoraddress, self.endpoints)
    182          result = filter(lambda x:x, result)
    183          if len(result) < 2: return None
    184          if result[0]==result[1]: return None
    185          result.sort()
    186          return tuple(result)
    187