Beispiel #1
0
    def _parse_tags(tags, name=None, default='all'):
        r = set()

        if not isinstance(tags, (list, set, tuple)):
            if tags is not None:
                if name:
                    LOG.warning("invalid tags configuration in %s", name)
                else:
                    LOG.warning("invalid tags")
            r.add(default)
            return r

        for tag in tags:
            if not helpers.has_len(tag):
                LOG.warning("invalid tag type: %r", tag)
                continue

            m = PARSE_TAGS(tag.strip())
            if not m:
                LOG.warning("invalid tag: %r", tag)
                continue

            r.add(m.group(0))

        if not r:
            r.add(default)

        return r
Beispiel #2
0
    def _pathify(self):
        """
        rfc2616 says in 5.1.2: "all HTTP/1.1 servers MUST accept the
        absoluteURI form in requests" so if we get one, transform it
        to abs_path.
        Raises HttpReqError if the request is malformed, else returns
        (path, query, fragment)
        """
        try:
            path = self.path
            if helpers.has_len(path):
                path = re.sub(r'^/+', '/', path)

            (path,
             query,
             self._fragment) = urisup.uri_help_split(path)[2:]

            if not path:
                path = '/'

            if path[0] != '/':
                raise urisup.InvalidURIError('path %r does not start with "/"' % path)

            self._path = re.sub(r'/+', '/', path)

            if query:
                self._query_params = self.querylist_to_dict(query)

            return self._path
        except urisup.InvalidURIError as e:
            LOG.error("invalid URI: %s", e)
            raise self.req_error(400, str(e))
Beispiel #3
0
    def getCountry(value):
        """
        returns the country name from country code

        @return string
        """
        if not helpers.has_len(value):
            return False

        return COUNTRIES.get(ensure_str(value).lower(), False)
Beispiel #4
0
    def validate(value):
        """
        checks if given value is a valid country codes

        @param string value
        @return bool
        """
        if not helpers.has_len(value):
            return False

        return ensure_str(value).lower() in COUNTRIES
Beispiel #5
0
    def register(self, notifier):
        if not isinstance(notifier, DWhoNotifierBase):
            raise TypeError("Invalid Notifier class. (class: %r)" % notifier)

        if helpers.has_len(notifier.SCHEME):
            schemes = [notifier.SCHEME]
        else:
            schemes = notifier.SCHEME

        if not isinstance(schemes, (list, tuple)):
            raise TypeError(
                "Invalid Notifier SCHEME. (class: %r, scheme: %r)" %
                (notifier, schemes))

        for scheme in schemes:
            scheme = scheme.lower()
            if not dict.__contains__(self, scheme):
                dict.__setitem__(self, scheme, [])
            dict.__getitem__(self, scheme).append(notifier)
Beispiel #6
0
    def _run(self, xvars=None, names=None, tags=None):
        if not xvars:
            xvars = {}

        if helpers.has_len(names):
            names = set([names])

        if not names or not isinstance(names, (list, tuple, set)):
            names = self.notif_names

        tags = self._parse_tags(tags)

        nvars = copy.deepcopy(xvars)
        nvars['_ENV_'] = copy.deepcopy(os.environ)
        nvars['_GMTIME_'] = datetime.utcnow()
        nvars['_HOSTNAME_'] = getfqdn()
        nvars['_SERVER_ID_'] = self.server_id
        nvars['_SOFTNAME_'] = get_softname()
        nvars['_SOFTVER_'] = get_softver()
        nvars['_TAGS_'] = tags
        nvars['_TIME_'] = datetime.now()
        nvars['_TIMESTAMP_'] = time.time()
        nvars['_UUID_'] = "%s" % uuid.uuid4()
        nvars['_VARS_'] = copy.deepcopy(xvars)

        if not self.workerpool:
            self.workerpool = WorkerPool(max_workers=1, name='notifiers')

        for name in names:
            if name not in self.notifications:
                LOG.warning("unable to find notifier: %r", name)
                continue

            notification = self.notifications[name]

            if not notification['cfg']['general'].get('enabled', True):
                continue

            if 'always' in notification['tags']:
                LOG.debug("'always' tag found. (notifier: %r)", name)
            elif 'all' in tags and 'never' in notification['tags']:
                LOG.debug("'never' tag found. (notifier: %r)", name)
            else:
                common_tags = tags.intersection(notification['tags'])
                if common_tags:
                    LOG.debug("common tags found %r. (notifier: %r)",
                              list(common_tags), name)
                else:
                    LOG.debug("no common tag found. (notifier: %r)", name)
                    continue

            nvars['_NAME_'] = name

            tpl = None
            if notification['tpl']:
                tpl = json.loads(
                    Template(notification['tpl'],
                             imports=[
                                 'import json',
                                 'from escapejson import escapejson',
                                 'from os import environ as ENV'
                             ]).render(**nvars))

            cfg = notification['cfg'].copy()
            cfg['general']['uri'] = Template(
                cfg['general']['uri']).render(**nvars)
            uri = urisup.uri_help_split(cfg['general']['uri'])

            for notifier in notification['notifiers']:
                if not cfg['general'].get('async'):
                    notifier(name, cfg, uri, nvars, tpl)
                    continue

                self.workerpool.run_args(notifier,
                                         _name_="notifier:%s" % name,
                                         name=name,
                                         cfg=cfg,
                                         uri=uri,
                                         nvars=nvars,
                                         tpl=tpl)

        while self.workerpool:
            if self.workerpool.killable():
                self.workerpool.killall(0)
                self.workerpool = None
            time.sleep(0.5)
Beispiel #7
0
def set_softver(version):
    global _SOFTVER

    if not _SOFTVER and helpers.has_len(version):
        _SOFTVER = version
Beispiel #8
0
def set_softname(name):
    global _SOFTNAME

    if not _SOFTNAME and helpers.has_len(name):
        _SOFTNAME = name