zephir.monitor.agents.services

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

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

      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  Agent zephir pour la surveillance de services via tcpcheck
     11  """
     12
     13  from twisted.internet import defer
     14  from twisted.internet.utils import getProcessOutput, getProcessValue
     15  from os import system
     16
     17  from zephir.monitor.agentmanager.agent import Agent
     18  from zephir.monitor.agentmanager.data import HTMLData, TableData
     19  from zephir.monitor.agentmanager.util import status_to_img, boolean_to_onoff, log
     20  from zephir.monitor.agentmanager import status
     21
     22  TCPCHECK = '/usr/bin/tcpcheck'
     23
     24 -def compare_hostports(hp1, hp2):
     25      h1, p1 = hp1.split(':')
     26      h2, p2 = hp2.split(':')
     27      result = cmp(h1, h2) # alpha comparison on hosts
     28      if result != 0:
     29          return result
     30      else: # numeric comparison on ports
     31          return cmp(int(p1), int(p2))
     32
     33 -class SSHService(Agent):
     34      """agent spécifique à ssh. Utilise netstats pour éviter les logs
     35      d'avertissement générés par l'utilisation de tcpcheck.
     36      """
     37
     38 -    def __init__(self, name,
     39                   tcp_services, # dict {"host:port": "comment"}
     40                   **params):
     41          Agent.__init__(self, name, **params)
     42          self.tcp_services = tcp_services
     43          self.table = TableData([
     44              ('status', "état", {'align':'center'}, status_to_img),
     45              ('description', "Description", {'align':'left'}, None),
     46              ('host', "Hôte", {'align':'left'}, None),
     47              ('port', "Port", {'align':'left'}, None) ])
     48          self.data = [self.table]
     49
     50
     51 -    def measure(self):
     52          tcpcheck = getProcessOutput('/bin/netstat',
     53                                      args = ['-ntlp'],
     54                                      env = {'LC_ALL': 'C'})
     55          tcpcheck.addCallback(self.measure_process)
     56          return tcpcheck
     57
     58 -    def measure_process(self, tcpcheck_result):
     59          status = boolean_to_onoff(False)
     60          lines = tcpcheck_result.splitlines()
     61          try:
     62              hostport = self.tcp_services.keys()[0]
     63              host = hostport[:hostport.rindex(':')]
     64              port = hostport[hostport.rindex(':')+1:]
     65          except:
     66              log.msg('SSH Agent, erreur de détermination du port (utilisation de 22 par défaut)')
     67              host = 'localhost'
     68              port = '22'
     69          for line in lines:
     70              if 'sshd' in line:
     71                  status = boolean_to_onoff(':%s' % port in line and 'LISTEN' in line)
     72          mesures=[{ 'description': self.tcp_services[hostport],
     73                     'host': host,
     74                     'port': port,
     75                     'status': status }]
     76          self.measure_data['status'] = status
     77          return {'services': mesures}
     78
     79 -    def write_data(self):
     80          Agent.write_data(self)
     81          if self.last_measure is not None:
     82              self.table.table_data = self.last_measure.value['services']
     83
     84 -    def check_status(self):
     85          """remonte une erreur si un des services est tombé"""
     86          if self.last_measure is not None:
     87              for service in self.last_measure.value['services']:
     88                  if service['status'] != 'On':
     89                      return status.Error()
     90          else:
     91              # pas de mesure connue
     92              return status.Unknown()
     93          return status.OK()
     94
     95 -class TCPServices(Agent):
     96
     97 -    def __init__(self, name,
     98                   tcp_services, # dict {"host:port": "comment"}
     99                   **params):
    100          Agent.__init__(self, name, **params)
    101          self.tcp_services = tcp_services
    102          self.table = TableData([
    103              ('status', "état", {'align':'center'}, status_to_img),
    104              ('description', "Description", {'align':'left'}, None),
    105              ('host', "Hôte", {'align':'left'}, None),
    106              ('port', "Port", {'align':'left'}, None) ])
    107          self.data = [self.table]
    108
    109
    110 -    def measure(self):
    111          tcpcheck = getProcessOutput(TCPCHECK,
    112                                      args = ['3'] + self.tcp_services.keys(),
    113                                      env = {'LC_ALL': 'C'})
    114          tcpcheck.addCallback(self.measure_process)
    115          return tcpcheck
    116
    117 -    def measure_process(self, tcpcheck_result):
    118          lines = tcpcheck_result.splitlines()
    119          hostports_status = [l.split(' ', 1) for l in lines]
    120          hostports_status.sort(lambda (hp1, s1), (hp2, s2):
    121                                compare_hostports(hp1, hp2))
    122          for hostport, status in hostports_status:
    123              status = boolean_to_onoff(status.endswith('alive'))
    124              mesures=[{ 'description': self.tcp_services[hostport],
    125                         'host': hostport.split(':')[0],
    126                         'port': hostport.split(':')[1],
    127                         'status': status }]
    128              self.measure_data['status'] = status
    129          return {'services': mesures}
    130
    131 -    def write_data(self):
    132          Agent.write_data(self)
    133          if self.last_measure is not None:
    134              self.table.table_data = self.last_measure.value['services']
    135
    136 -    def check_status(self):
    137          """remonte une erreur si un des services est tombé"""
    138          if self.last_measure is not None:
    139              for service in self.last_measure.value['services']:
    140                  if service['status'] != 'On':
    141                      return status.Error()
    142          else:
    143              # pas de mesure connue
    144              return status.Unknown()
    145          return status.OK()
    146
    147
    148 -class PIDService(Agent):
    149
    150 -    def __init__(self, name,
    151                   tcp_services, # dict {"daemon": "comment"}
    152                   **params):
    153          Agent.__init__(self, name, **params)
    154          self.tcp_services = tcp_services
    155          self.table = TableData([
    156              ('status', "état", {'align':'center'}, status_to_img),
    157              ('description', "Description", {'align':'left'}, None),
    158              ('host', "Hôte", {'align':'left'}, None),
    159              ('port', "Port", {'align':'left'}, None) ])
    160          self.data = [self.table]
    161
    162 -    def measure(self):
    163
    164          res = system('/bin/pidof %s >/dev/null'%self.tcp_services.keys()[0])
    165          status = boolean_to_onoff(res==0)
    166          mesures=[{ 'description': self.tcp_services.values()[0],
    167                     'host': 'localhost',
    168                     'port': '',
    169                     'status': status }]
    170          self.measure_data['status'] = status
    171          return {'services': mesures}
    172
    173 -    def write_data(self):
    174          Agent.write_data(self)
    175          if self.last_measure is not None:
    176              self.table.table_data = self.last_measure.value['services']
    177
    178 -    def check_status(self):
    179          """remonte une erreur si un des services est tombé"""
    180          if self.last_measure is not None:
    181              for service in self.last_measure.value['services']:
    182                  if service['status'] != 'On':
    183                      return status.Error()
    184          else:
    185              # pas de mesure connue
    186              return status.Unknown()
    187          return status.OK()
    188
    189
    190 -class VPNService(Agent):
    191
    192 -    def __init__(self, name,
    193                   tcp_services, # dict {"host:port": "comment"}
    194                   **params):
    195          Agent.__init__(self, name, **params)
    196          self.tcp_services = tcp_services
    197          self.table = TableData([
    198              ('status', "Etat", {'align':'center'}, status_to_img),
    199              ('description', "Description", {'align':'left'}, None),
    200              ('host', "Hôte", {'align':'left'}, None),
    201              ('port', "Port", {'align':'left'}, None) ])
    202          self.data = [self.table]
    203
    204
    205 -    def measure(self):
    206          cmd = "/usr/sbin/ipsec"
    207          vpncheck = getProcessOutput(cmd,
    208                                      args=['status'],
    209                                      env = {'LC_ALL': 'C'})
    210          vpncheck.addCallbacks(self.measure_vpn,self.service_error)
    211          return vpncheck
    212
    213 -    def service_error(self,data):
    214          """status a remonté une erreur
    215          """
    216          log.msg("erreur status : %s" % str(data))
    217          status = 'Off'
    218          mesures=[{ 'description': "Service Réseau Virtuel Privé (IpSec)",
    219                     'host': 'localhost',
    220                     'port': '',
    221                     'status': status }]
    222          return {'services': mesures}
    223
    224 -    def measure_vpn(self, data):
    225          status = 'Off'
    226          # si not running apparait dans les premières lignes de la sortie, ipsec est arreté
    227          data = data.split('\n')
    228          end = 5
    229          if len(data) < 5:
    230              end = len(data)
    231          first_lines = "".join(data[0:end])
    232          if first_lines.count('not running') == 0:
    233              status = 'On'
    234
    235          mesures=[{ 'description': "Service Réseau Virtuel Privé (IpSec)",
    236                     'host': 'localhost',
    237                     'port': '',
    238                     'status': status }]
    239          return {'services': mesures}
    240
    241 -    def write_data(self):
    242          Agent.write_data(self)
    243          if self.last_measure is not None:
    244              self.table.table_data = self.last_measure.value['services']
    245
    246 -    def check_status(self):
    247          """remonte une erreur si un des services est tombé"""
    248          if self.last_measure is not None:
    249              for service in self.last_measure.value['services']:
    250                  if service['status'] != 'On':
    251                      return status.Error()
    252          else:
    253              # pas de mesure connue
    254              return status.Unknown()
    255          return status.OK()
    256