zephir.monitor.agents.netstat

Package zephir :: Package monitor :: Package agents :: Module netstat |
[frames] | no frames]

# Source Code for Module zephir.monitor.agents.netstat

      1  # -*- coding: UTF-8 -*-
      2  ###########################################################################
      3  # Eole NG - 2007
      4  # Copyright Pole de Competence Eole  (Ministere Education - Academie Dijon)
      5  # Licence CeCill  cf /root/LicenceEole.txt
      6  # eole@ac-dijon.fr
      7  ###########################################################################
      8
      9  """
     10  Agents zephir affichant les Informations Système
     11  """
     12
     13  from zephir.monitor.agentmanager.agent import MultiRRDAgent
     14  from zephir.monitor.agentmanager import status
     15  from zephir.monitor.agentmanager.data import TableData, HTMLData
     16  from zephir.monitor.agentmanager.util import percent
     17
     18  from twisted.internet import defer
     19  from twisted.internet.utils import getProcessOutput
     20  import re
     21
     22  SECONDS_PER_DAY = 3600*24
     23
     24  # column titles in /proc/net/dev
     25  (IBYTES, IPACKETS, IERRS,
     26   IDROP, IFIFO, IFRAME, ICOMPRESSED, IMULTICAST,
     27   OBYTES, OPACKETS, OERRS,
     28   ODROP, OFIFO, OCOLLS, OCARRIER, OCOMPRESSED,
     29   ) = range(0,16)
     30
     31  IPADDRESS_RE = re.compile('(?<=addr:)\d\d?\d?.\d\d?\d?.\d\d?\d?.\d\d?\d?')
     32  ERROR_RATE_ALERT_THRESHOLD = 10 # in percent
     33
     34 -def _mega(val):
     35      """ transfo de la valeur passée (string en octets) en Mo
     36      """
     37      return (int(val)/1024/1024)
     38
     39 -def _stat_format(x):
     40      return "%.1f" % x
     41
     42 -class NetStat(MultiRRDAgent):
     43      """
     44      Bilan de l'etat des cartes réseau
     45      présentation en tableau
     46      + graphe pour chaque carte
     47      """
     48
     49 -    def __init__(self, name, **params):
     50          MultiRRDAgent.__init__(self, name, **params)
     51          self.last_measure = None
     52          self.table = TableData([
     53              ('name', 'Nom', {'align':'right'}, None),
     54              ('address', 'Adresse', {'align':'left'}, None),
     55              ('input KB', 'Entrée (Ko)', {'align':'right'}, _stat_format),
     56              ('input err%', '(% err)', {'align':'right'}, _stat_format),
     57              ('output KB', 'Sortie (Ko)', {'align':'right'}, _stat_format),
     58              ('output err%', '(% err)', {'align':'right'}, _stat_format) ])
     59          title1 = HTMLData("<h3>Interfaces réseau<h3>")
     60          title2 = HTMLData("<h3>Statistiques réseau (Entrées/Sorties)<h3>")
     61          self.data.extend([title1, self.table, title2])
     62
     63 -    def init_data(self, archive_dir):
     64          """on initialise les archives rrd, et on définit
     65          la liste des données"""
     66          MultiRRDAgent.init_data(self,archive_dir)
     67
     68 -    def measure(self):
     69          ifconfig = getProcessOutput('/sbin/ifconfig',
     70                                      env = {'LC_ALL': 'C'})
     71          catproc = getProcessOutput('/bin/cat',
     72                                     args = ['/proc/net/dev'],
     73                                     env = {'LC_ALL': 'C'})
     74          cmds = defer.DeferredList([ifconfig, catproc])
     75          cmds.addCallback(self.measure_process)
     76          return cmds
     77
     78 -    def measure_process(self, cmds_results):
     79          [(ifconfig_success, ifconfig),
     80           (catproc_success, catproc)] = cmds_results
     81          assert ifconfig_success and catproc_success #FIXME
     82          # get address of each interface
     83          addresses = {}
     84          blocks = ifconfig.strip().split('\n\n')
     85          for b in blocks:
     86              name_line, addr_line = b.splitlines()[0:2]
     87              name = name_line.split()[0].replace('.','_')
     88              # en mode conteneur, on ne fait pas de statistiques sur les cartes virtuelles
     89              if (not name.strip().startswith('ve')) and name.strip() != 'br0':
     90                  addr_match = IPADDRESS_RE.search(addr_line)
     91                  #FIXME set agent status
     92                  if addr_match is not None:
     93                      addr = addr_match.group()
     94                      addresses[name] = addr
     95
     96          # get interfaces statistics from /proc
     97          statistics = []
     98          dico={}
     99          lines = catproc.splitlines()[2:] # drop header lines
    100          for l in lines:
    101              if_name, stats = l.split(':')
    102              # en mode conteneur, on ne fait pas de statistiques sur les cartes virtuelles
    103              if (not if_name.strip().startswith('ve')) and name.strip() != 'br0':
    104                  if_name = if_name.strip().replace('.','_')
    105                  if addresses.has_key(if_name):
    106                      if_addr = addresses[if_name]
    107                  else:
    108                      # pas d'infos sur une des interfaces
    109                      if_addr = "non configurée"
    110                  stats = stats.split()
    111                  inkb = int(float(stats[IBYTES])/1024.0)
    112                  outkb = int(float(stats[OBYTES])/1024.0)
    113                  iner = percent(stats[IERRS], stats[IPACKETS])
    114                  outer = percent(stats[OERRS], stats[OPACKETS])
    115                  if_stats = {'name': if_name,
    116                              'address': if_addr,
    117                              'input KB': inkb,
    118                              'output KB': outkb,
    119                              'input err%': iner,
    120                              'output err%': outer }
    121                  statistics.append(if_stats)
    122                  dico['in_%s' % if_name] = inkb
    123                  dico['iner_%s' % if_name] = iner
    124                  dico['out_%s' % if_name] = outkb
    125                  dico['outer_%s' % if_name] = outer
    126                  self.measure_data.update(dico)
    127          # données du tableau
    128          dico['statistics'] = statistics
    129          return dico
    130
    131 -    def save_measure(self, measure):
    132          MultiRRDAgent.save_measure(self, measure)
    133          measure.value = {'statistics':measure.value['statistics']}
    134          self.last_measure = measure
    135
    136 -    def write_data(self):
    137          MultiRRDAgent.write_data(self)
    138          if self.last_measure is not None:
    139              self.table.table_data = self.last_measure.value['statistics']
    140
    141 -    def check_status(self):
    142          return status.OK()
    143