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

# Source Code for Module Products.ZenUtils.NetworkTree

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