Пример #1
0
        # then detect potential problems that should be warned
        if not isinstance(registries, (tuple, list)):
            cls.warning("%s has __registries__ which is not a list or tuple", obj)
            return False
        if not callable(selector):
            cls.warning("%s has not callable __select__", obj)
            return False
        return True

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg, *a, **kw: None


# init logging
set_log_methods(RegistryStore, getLogger("registry.store"))
set_log_methods(Registry, getLogger("registry"))


# helpers for debugging selectors
TRACED_OIDS = None


def _trace_selector(cls, selector, args, ret):
    vobj = args[0]
    if TRACED_OIDS == "all" or vobj.__regid__ in TRACED_OIDS:
        print("%s -> %s for %s(%s)" % (cls, ret, vobj, vobj.__regid__))


def _lltrace(selector):
    """use this decorator on your predicates so they become traceable with
Пример #2
0
    @classproperty
    def __registries__(cls):
        if cls.events is None:
            return []
        return ['%s_hooks' % ev for ev in cls.events]

    known_args = set(('entity', 'rtype', 'eidfrom', 'eidto', 'repo', 'timestamp'))
    def __init__(self, req, event, **kwargs):
        for arg in self.known_args:
            if arg in kwargs:
                setattr(self, arg, kwargs.pop(arg))
        super(Hook, self).__init__(req, **kwargs)
        self.event = event

set_log_methods(Hook, getLogger('cubicweb.hook'))


# abtract hooks for relation propagation #######################################
# See example usage in hooks of the nosylist cube

class PropagateRelationHook(Hook):
    """propagate some `main_rtype` relation on entities linked as object of
    `subject_relations` or as subject of `object_relations` (the watched
    relations).

    This hook ensure that when one of the watched relation is added, the
    `main_rtype` relation is added to the target entity of the relation.
    Notice there are no default behaviour defined when a watched relation is
    deleted, you'll have to handle this by yourself.
Пример #3
0
        # then detect potential problems that should be warned
        if not isinstance(registries, (tuple, list)):
            cls.warning('%s has __registries__ which is not a list or tuple', obj)
            return False
        if not callable(selector):
            cls.warning('%s has not callable __select__', obj)
            return False
        return True

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg, *a, **kw: None


# init logging
set_log_methods(RegistryStore, getLogger('registry.store'))
set_log_methods(Registry, getLogger('registry'))


# helpers for debugging selectors
TRACED_OIDS = None

def _trace_selector(cls, selector, args, ret):
    vobj = args[0]
    if TRACED_OIDS == 'all' or vobj.__regid__ in TRACED_OIDS:
        print('%s -> %s for %s(%s)' % (cls, ret, vobj, vobj.__regid__))

def _lltrace(selector):
    """use this decorator on your predicates so they become traceable with
    :class:`traced_selection`
    """
Пример #4
0
                    raise
                return False
            for msg, recipients in msgs:
                try:
                    smtp.sendmail(fromaddr, recipients, msg.as_bytes())
                except Exception as ex:
                    self.exception("error sending mail to %s (%s)",
                                   recipients, ex)
                    if self.mode == 'test':
                        raise
            smtp.close()
        finally:
            SMTP_LOCK.release()
        return True

set_log_methods(CubicWebNoAppConfiguration,
                logging.getLogger('cubicweb.configuration'))

# alias to get a configuration instance from an instance id
instance_configuration = CubicWebConfiguration.config_for


_EXT_REGISTERED = False
def register_stored_procedures():
    from logilab.database import FunctionDescr
    from rql.utils import register_function, iter_funcnode_variables
    from rql.nodes import SortTerm, Constant, VariableRef

    global _EXT_REGISTERED
    if _EXT_REGISTERED:
        return
    _EXT_REGISTERED = True
                sys.exit(0)
            else:
                self.config.debug('exit on SIGTERM (on next turn)')
                self._alive = 0
        elif sig_num == signal.SIGHUP:
            self.config.info('reloading configuration on SIGHUP')
            reload(self.config)

    def _run(self):
        """should be overridden in the mixed class"""
        raise NotImplementedError()


import logging
from logilab.common.logging_ext import set_log_methods
set_log_methods(DaemonMixIn, logging.getLogger('lgc.daemon'))

## command line utilities ######################################################

L_OPTIONS = ["help", "log=", "delay=", 'no-detach']
S_OPTIONS = 'hl:d:n'


def print_help(modconfig):
    print """  --help or -h
    displays this message
  --log <log_level>
    log treshold (7 record everything, 0 record only emergency.)
    Defaults to %s
  --delay <delay>
    the number of seconds between two runs.
Пример #6
0
            else:
                self.config.debug("exit on SIGTERM (on next turn)")
                self._alive = 0
        elif sig_num == signal.SIGHUP:
            self.config.info("reloading configuration on SIGHUP")
            reload(self.config)

    def _run(self):
        """should be overridden in the mixed class"""
        raise NotImplementedError()


import logging
from logilab.common.logging_ext import set_log_methods

set_log_methods(DaemonMixIn, logging.getLogger("lgc.daemon"))

## command line utilities ######################################################

L_OPTIONS = ["help", "log=", "delay=", "no-detach"]
S_OPTIONS = "hl:d:n"


def print_help(modconfig):
    print """  --help or -h
    displays this message
  --log <log_level>
    log treshold (7 record everything, 0 record only emergency.)
    Defaults to %s
  --delay <delay>
    the number of seconds between two runs.
Пример #7
0
# make all exceptions accessible from the package
from logilab.common.registry import ObjectNotFound, NoSelectableObject, RegistryNotFound  # noqa
from yams import ValidationError
from cubicweb._exceptions import *  # noqa

from io import BytesIO

# ignore the pygments UserWarnings
warnings.filterwarnings('ignore', category=UserWarning,
                        message='.*was already imported',
                        module='.*pygments')

# pre python 2.7.2 safety
logging.basicConfig()
set_log_methods(sys.modules[__name__], logging.getLogger('cubicweb'))

# this is necessary for i18n devtools test where chdir is done while __path__ is relative, which
# breaks later imports
__path__[0] = os.path.abspath(__path__[0])  # noqa
CW_SOFTWARE_ROOT = __path__[0]  # noqa


# '_' is available to mark internationalized string but should not be used to
# do the actual translation
_ = str


class Binary(BytesIO):
    """class to hold binary data. Use BytesIO to prevent use of unicode data"""
    _allowed_types = (bytes, bytearray, memoryview)
Пример #8
0
                        value = value.getvalue()
                    else:
                        value = crypt_password(value)
                    value = self._binary(value)
                elif isinstance(value, Binary):
                    value = self._binary(value.getvalue())
            attrs[SQL_PREFIX + str(attr)] = value
        attrs[SQL_PREFIX + 'eid'] = entity.eid
        return attrs

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg, *a, **kw: None


set_log_methods(SQLAdapterMixIn, getLogger('cubicweb.sqladapter'))

# connection initialization functions ##########################################


def _install_sqlite_querier_patch():
    """This monkey-patch hotfixes a bug sqlite causing some dates to be returned as strings rather than
    date objects (http://www.sqlite.org/cvstrac/tktview?tn=1327,33)
    """
    from cubicweb.server.querier import QuerierHelper

    if hasattr(QuerierHelper, '_sqlite_patched'):
        return  # already monkey patched

    def wrap_execute(base_execute):
        def new_execute(*args, **kwargs):
Пример #9
0
    #        <registry name>.<obj id>.<property id>
    # * value: tuple (property type, vocabfunc, default value, property description)
    #         possible types are those used by `logilab.common.configuration`
    #
    # notice that when it exists multiple objects with the same id (adaptation,
    # overriding) only the first encountered definition is considered, so those
    # objects can't try to have different default values for instance.
    #
    # you can then access to a property value using self.cw_propval, where self
    # is an instance of class

    @classmethod
    def _cwpropkey(cls, propid):
        """return cw property key for the property of the given id for this
        class
        """
        return '%s.%s.%s' % (cls.__registry__, cls.__regid__, propid)

    def cw_propval(self, propid):
        """return cw property value associated to key

        <cls.__registry__>.<cls.id>.<propid>
        """
        return self._cw.property_value(self._cwpropkey(propid))

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg,*a,**kw: None

set_log_methods(AppObject, getLogger('cubicweb.appobject'))
Пример #10
0
                        obj)
            return False

        if not callable(selector):
            cls.warning("%s has not callable __select__", obj)
            return False

        return True

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg, *a, **kw: None


# init logging
set_log_methods(RegistryStore, getLogger("registry.store"))
set_log_methods(Registry, getLogger("registry"))

# helpers for debugging selectors
TRACED_OIDS = None


def _trace_selector(cls, selector, args, ret):
    vobj = args[0]
    if TRACED_OIDS == "all" or vobj.__regid__ in TRACED_OIDS:
        print("%s -> %s for %s(%s)" % (cls, ret, vobj, vobj.__regid__))


def _lltrace(selector):
    """use this decorator on your predicates so they become traceable with
    :class:`traced_selection`
Пример #11
0
            self.warning(
                'using explict target type in %s.tag_subject_of() '
                'has no effect, use (%s, %s, "*") instead of (%s, %s, %s)',
                self.name, subj, rtype, subj, rtype, obj)
        super(NoTargetRelationTagsDict, self).tag_subject_of(
            (subj, rtype, '*'), tag)

    def tag_object_of(self, key, tag):
        subj, rtype, obj = key
        if subj != '*':
            self.warning(
                'using explict subject type in %s.tag_object_of() '
                'has no effect, use ("*", %s, %s) instead of (%s, %s, %s)',
                self.name, rtype, obj, subj, rtype, obj)
        super(NoTargetRelationTagsDict, self).tag_object_of(('*', rtype, obj),
                                                            tag)

    def tag_relation(self, key, tag):
        if key[-1] == 'subject' and key[-2] != '*':
            if isinstance(key, tuple):
                key = list(key)
            key[-2] = '*'
        elif key[-1] == 'object' and key[0] != '*':
            if isinstance(key, tuple):
                key = list(key)
            key[0] = '*'
        super(NoTargetRelationTagsDict, self).tag_relation(key, tag)


set_log_methods(RelationTags, logging.getLogger('cubicweb.rtags'))
Пример #12
0
                stream.write(content)
            try:
                mode = os.stat(sourcefile).st_mode
                os.chmod(tmpfile, mode)
            except IOError:
                self.warning(
                    'Cannot set access mode for %s; you may encouter '
                    'file permissions issues', cachefile)
            try:
                os.rename(tmpfile, cachefile)
            except OSError as err:
                if err.errno != errno.EEXIST:
                    raise
                # Under windows, os.rename won't overwrite an existing file
                os.unlink(cachefile)
                os.rename(tmpfile, cachefile)
            adirectory = self._cache_directory
        return adirectory

    def compile(self, content):
        return self._percent_rgx.sub('%%', content) % self

    # these are overridden by set_log_methods below
    # only defining here to prevent pylint from complaining
    info = warning = error = critical = exception = debug = lambda msg, *a, **kw: None


from cubicweb.web import LOGGER
from logilab.common.logging_ext import set_log_methods
set_log_methods(PropertySheet, LOGGER)
Пример #13
0
        :rtype: bool
        :return:
          a boolean indicating whether this type is defined in this schema
        """
        return rtype in self._relations

    def rschema(self, rtype):
        """return the relation schema for the given type

        :rtype: `RelationSchema`
        """
        try:
            return self._relations[rtype]
        except KeyError:
            raise KeyError('No relation named %s in schema' % rtype)

    def finalize(self):
        """Finalize schema

        Can be used to, e.g., infer relations from inheritance, computed
        relations, etc.
        """
        self.infer_specialization_rules()


import logging
from logilab.common.logging_ext import set_log_methods
LOGGER = logging.getLogger('yams')
set_log_methods(Schema, LOGGER)