コード例 #1
0
ファイル: handlers.py プロジェクト: vigilo/connector
 def _send_failed(self, e, msg):
     """errback: remet le message en base"""
     errmsg = _('Requeuing message (%(reason)s).')
     LOGGER.info(errmsg % {
         "reason": get_error_message(e),
     })
     self.queue.append(msg)
コード例 #2
0
ファイル: rule_dispatcher.py プロジェクト: vigilo/correlator
 def no_database(failure):
     """
     Méthode appelée lorsque la connexion avec la base de données
     ne peut être établie.
     """
     LOGGER.error(_("Unable to contact the database: %s"),
         get_error_message(failure.getErrorMessage()))
     try:
         reactor.stop()
     except error.ReactorNotRunning:
         pass
コード例 #3
0
ファイル: amqp.py プロジェクト: vigilo/connector
def getErrorMessage(error):
    """
    Retourne le message renvoyé par le serveur dans une exception
    C{txamqp.client.Closed}
    """
    if isinstance(error, failure.Failure):
        error = error.value
    if isinstance(error, Exception):
        error = error.args[0]
    try:
        try:
            return unicode(error.fields[1])
        except (UnicodeEncodeError, UnicodeDecodeError):
            return error.fields[1].decode('utf-8')
    except (KeyError, AttributeError, IndexError,
            UnicodeEncodeError, UnicodeDecodeError):
        return get_error_message(error)
コード例 #4
0
ファイル: application.py プロジェクト: vigilo/vigiconf
 def _threaded_action(self, action, servername):
     """
     Exécute l'action sur le serveur. Cette méthode est éxecutée dans un
     thread séparé.
     @param action: Action à effectuer. Correspond à une méthode de la
         classe, suivie de C{Server}.
     @type  action: C{str}
     @param servername: nom du serveur sur lequel lancer l'action.
     @type  servername: C{str}
     """
     try:
         getattr(self, "%sServer" % action)(servername)
     except ApplicationError, e: # if it fails
         LOGGER.error(get_error_message(e))
         thread = current_thread()
         try:
             self.threads[thread]["status"] = False
         except KeyError:
             # si la clé n'est pas présente on ignore silencieusement, il
             # y a eu un timeout de détecté dans le thread principal.
             pass
コード例 #5
0
ファイル: status.py プロジェクト: vigilo/connector
def statuspublisher_factory(settings, client, providers=None):
    """
    Construit une instance de L{StatusPublisher}

    @param settings: fichier de configuration
    @type  settings: C{vigilo.common.conf.settings}
    @param client: client du bus
    @type  client: L{vigilo.connector.client.VigiloClient}
    @param providers: liste de fournisseurs de statistiques
    @type  providers: C{list}
    """
    hostname = settings.get("connector", {}).get("hostname", None)
    if hostname is None:
        hostname = socket.gethostname()
        if "." in hostname: # on ne veut pas le FQDN
            hostname = hostname[:hostname.index(".")]

    idinstance = settings.get("instance", "")
    servicename = os.path.basename(sys.argv[0])
    if idinstance:
        servicename = servicename + "-" + str(idinstance)
    servicename = settings.get("connector", {}).get("status_service",
            servicename)
    smne = settings["connector"].get("self_monitoring_nagios_exchange", None)
    smpe = settings["connector"].get("self_monitoring_perf_exchange", None)
    publications = settings.get('publications', {}).copy()
    try:
        # Si besoin (paramètre de surcharge défini dans la configuration)
        # surcharger le paramètre de publication pour les messages qui viennent
        # de l'auto-supervision du connecteur.
        if smne is not None:
            publications["nagios"] = smne
        if smpe is not None:
            publications["perf"] = smpe
        publications = parsePublications(publications)
    except Exception, e:
        LOGGER.error(_('Invalid configuration option for publications: '
                       '(%(error)s).') % {"error": get_error_message(e)})
        sys.exit(1)
コード例 #6
0
ファイル: application.py プロジェクト: vigilo/vigiconf
 def execute(self, action, servers):
     """
     Arrête ou démarre les applications sur les serveurs spécifiés.
     @param action: C{start} ou C{stop}
     @type  action: C{str}
     @param servers: Liste des noms de serveurs sur lesquels exécuter
         l'action.
     @type  servers: C{list} de C{str}
     """
     if not self.applications:
         return
     status = True
     results = []
     if isinstance(self.attempts, int) and \
        self.attempts > 0:
         attempts = self.attempts
     else:
         attempts = 1
     priorities = {}
     # construction d'un dictionnaire de priorité d'application
     # dict = {1: [app1, app2],
     #         2: [app3, app4]}
     for app in self.applications:
         p = app.priority
         if p in priorities:
             priorities[p].append(app)
         else:
             priorities[p] = [app]
     # lancement des action/application pour chaque priorité
     for priority in sorted(priorities, reverse=True):
         apps = priorities[priority]
         for app in apps:
             results.append(app.execute(action, servers, async=True))
         test = 0
         timedout = []
         while test < attempts :
             test += 1
             if timedout:
                 # attente d'un interval de temps avant nouvel essai
                 msg = _("Next attempt for %(action)s action in %(interval)d"
                         " second(s) (attempt #%(attempt)d)") % {
                               "action": action,
                               "interval": self.interval,
                               "attempt": test}
                 LOGGER.info(msg)
                 sleep(self.interval)
                 for e in timedout:
                     app = e.application
                     act = e.action
                     servers = e.servers
                     # relance des exécutions précédemment en time out
                     results.append(app.execute(act, servers, async=True))
             timedout = []
             for result in results:
                 try:
                     status = status and result.get()
                 except ApplicationTimeOutError, e:
                     LOGGER.info(get_error_message(e))
                     status = status and e.status
                     timedout.append(e)
             results = []
         if timedout:
             for e in timedout:
                 LOGGER.error(get_error_message(e))
             sys.exit(2)
コード例 #7
0
 def test_unknown_str_exception(self):
     """Message d'erreur d'une exception avec encodage inconnu."""
     # "éçà" encodé en ISO-8859-15.
     e = ValueError('Some error \xE9\xE7\xE0')
     msg = get_error_message(e)
     self.assertTrue(isinstance(msg, unicode))
コード例 #8
0
 def test_utf8_str_exception(self):
     """Message d'erreur d'une exception UTF-8."""
     # "éçà" encodé en UTF-8.
     e = ValueError('Some error \xC3\xA9\xC3\xA7\xC3\xA0')
     self.assertEquals(u'Some error éçà', get_error_message(e))
コード例 #9
0
 def test_unicode_exception(self):
     """Message d'erreur d'une exception Unicode."""
     e = ValueError(u'Some error éçà')
     self.assertEquals(u'Some error éçà', get_error_message(e))
コード例 #10
0
ファイル: test.py プロジェクト: vigilo/vigiconf
    def load_hclasses_checks(self):
        """
        Get all the available methods to check for a host class validity.

        Each host class can define in a __init__.py file three techniques to
        check if a host corresponds to the host class.
         - the first technique is an attribute named "sysdescr": a regexp which
           will be matched against the SNMPv2-MIB::sysDescr.0
           (.1.3.6.1.2.1.1.1.0) result. Be careful to include leading and
           ending wildcards (.*) as needed.
         - the second technique is an attribute named "oid": if this OID is
           present in a host's SNMP walk, then the host class applies to it.
         - the third technique is a detect_snmp() function, for more complex
           matching.  This function is given the whole SNMP result map, and
           returns True or False if the host class applies to this result.

        This method loads these techniques in the L{hclasschecks} hashmap for
        each available host class.

        This function is mainly used by the
        L{Discoverator<discoverator.Discoverator>}.
        """
        if self.hclasschecks:
            return # already loaded
        for pathdir in self.path:
            if not os.path.exists(pathdir):
                continue
            for hclass in os.listdir(pathdir):
                if hclass.startswith("."):
                    continue
                hclassdir = os.path.join(pathdir, hclass)
                self.hclasschecks[hclass] = {
                    "sysdescr": None,
                    "oid": None,
                    "detect_snmp": None,
                }

                try:
                    mod_info = imp.find_module(hclass, [pathdir])
                except ImportError:
                    # Pas de fichier __init__.py, __init__.pyc
                    # ou __init__.pyo.
                    continue

                try:
                    mod = imp.load_module(
                            "vigilo.vigiconf.tests.%s" % hclass,
                            *mod_info)
                except KeyboardInterrupt:
                    raise
                except Exception, e:
                    LOGGER.warning(
                        _("Unable to load %(file)s: %(error)s") % {
                            'file': hclassdir,
                            'error': get_error_message(e),
                         })
                else:
                    # Mise à jour des prédicats en fonction du contenu
                    # du fichier __init__ du module.
                    for hccheck in self.hclasschecks[hclass].keys():
                        if hasattr(mod, hccheck):
                            self.hclasschecks[hclass][hccheck] = \
                                getattr(mod, hccheck)
                finally:
コード例 #11
0
ファイル: test.py プロジェクト: vigilo/vigiconf
    def load_tests(self):
        """
        Get all the available tests.

        It sets the self.tests class attributes as a dict reflecting the path
        to get a test. Example::

            { "Test1": { "hclass1": <class Test1 from hclass1/Test1.py>,
                         "hclass2": <class Test1 from hclass2/Test1.py>,
                         "hclass3": <class Test1 from hclass3/Test1.py>,
                       },
              "Test2": { "hclass1": <class Test2 from hclass1/Test2.py>,
                         "hclass4": <class Test2 from hclass4/Test2.py>,
                       },
            }
        """
        for pathdir in self.path:
            if not os.path.exists(pathdir):
                continue
            for hclass in os.listdir(pathdir):
                if hclass.startswith("."):
                    continue
                hclassdir = os.path.join(pathdir, hclass)
                if not os.path.isdir(hclassdir):
                    continue

                # On charge d'abord la classe d'équipements.
                try:
                    mod_info = imp.find_module(hclass, [pathdir])
                except ImportError:
                    LOGGER.warning(
                        _('Invalid hostclass "%s". Missing __init__.py?') %
                        hclass
                    )
                    continue
                try:
                    mod = imp.load_module(
                            "vigilo.vigiconf.tests.%s" % hclass,
                            *mod_info)
                except KeyboardInterrupt:
                    raise
                except Exception, e:
                    LOGGER.warning(
                        _("Unable to load %(file)s: %(error)s") % {
                            'file': hclassdir,
                            'error': get_error_message(e),
                         })
                    continue

                # Puis les tests qu'elle contient.
                testfiles = set()
                for testfile in os.listdir(hclassdir):
                    if (not testfile.endswith((".py", ".pyc", ".pyo"))) or \
                            testfile.startswith("__"):
                        continue
                    mod_name = testfile.rpartition('.')[0]
                    # Évite de charger plusieurs fois le même test
                    # (depuis le .py et depuis le .pyc par exemple).
                    if mod_name in testfiles:
                        continue
                    # Load the file and get the class name
                    try:
                        mod_info = imp.find_module(mod_name, [hclassdir])
                    except ImportError:
                        # On ignore silencieusement l'erreur.
                        continue

                    try:
                        mod = imp.load_module(
                            "vigilo.vigiconf.tests.%s.%s" % (hclass, mod_name),
                            *mod_info)
                    except KeyboardInterrupt:
                        raise
                    except Exception, e:
                        raise
                        LOGGER.warning(
                            _("Unable to load %(file)s: %(error)s") % {
                                'file': os.path.join(hclassdir, testfile),
                                'error': get_error_message(e),
                             })
                    else:
                        for current_test_name, current_test_class \
                            in inspect.getmembers(mod, self._filter_tests):
                            if not self.tests.has_key(current_test_name):
                                self.tests[current_test_name] = {}
                            self.tests[current_test_name][hclass] = \
                                current_test_class
                        testfiles.add(mod_name)
                    finally:
                        # find_module() ouvre un descripteur de fichier
                        # en cas de succès et c'est à nous de le refermer.
                        if mod_info[0]:
コード例 #12
0
ファイル: rule_dispatcher.py プロジェクト: vigilo/correlator
 def _processException(self, failure):
     if not failure.check(KeyboardInterrupt):
         LOGGER.error(_('Unexpected error: %s'),
             get_error_message(failure.getErrorMessage()))
     return failure
コード例 #13
0
ファイル: handlers.py プロジェクト: vigilo/connector
 def eb(f):
     LOGGER.error(_("Error trying to save a message to the backup "
                    "database: %s"), get_error_message(f.value))