~launchpad-pqm/launchpad/devel

10303.1.1 by Gary Poster
use newest version of zc.buildout
1
# Copyright 2009 Canonical Ltd.  This software is licensed under the
2
# GNU Affero General Public License version 3 (see the file LICENSE).
3
4
# This file is imported by parts/scripts/sitecustomize.py, as set up in our
5
# buildout.cfg (see the "initialization" key in the "[scripts]" section).
6
12536.2.4 by Robert Collins
Fix branch a bit.
7
from collections import defaultdict
11594.2.1 by Aaron Bentley
Fix use of itertools.groupby through security proxies.
8
import itertools
10303.1.1 by Gary Poster
use newest version of zc.buildout
9
import os
10981.1.1 by Maris Fogels
Silence DeprecationWarnings from pycrypto 2.0.1 using a new warnings hook in lp_sitecustomize.
10
import warnings
11136.3.1 by Diogo Matsubara
silence the root logger across the entire Launchpad project
11
import logging
10981.1.1 by Maris Fogels
Silence DeprecationWarnings from pycrypto 2.0.1 using a new warnings hook in lp_sitecustomize.
12
11892.6.4 by Julian Edwards
Fix sourcepackagerecipebuild's handleStatus
13
from twisted.internet.defer import (
14
    Deferred,
15
    DeferredList,
16
    )
11593.3.120 by Julian Edwards
re-add revno 11801 which was backed out in devel due to test failures resulting from a twisted bug
17
10981.1.1 by Maris Fogels
Silence DeprecationWarnings from pycrypto 2.0.1 using a new warnings hook in lp_sitecustomize.
18
from bzrlib.branch import Branch
13225.9.1 by Benji York
add the ability to mark an exception as not OOPS report worthy and use
19
from canonical.launchpad.webapp.interfaces import IUnloggedException
11300.2.49 by Stuart Bishop
Tidy and improve logging system infrastructure for great justice.
20
from lp.services.log import loglevels
8758.2.57 by Stuart Bishop
Move LaunchpadLogger to a better location
21
from lp.services.log.logger import LaunchpadLogger
11300.2.44 by Stuart Bishop
Tidy custom loglevels into their own module, and initialize filtering and custom levels in lp_sitecustomize.py for great justice.
22
from lp.services.log.mappingfilter import MappingFilter
11136.3.3 by Diogo Matsubara
move NullHandler to a more central location where it can be imported from lp_sitecustomize.py and test_layers.py test.
23
from lp.services.log.nullhandler import NullHandler
10303.1.1 by Gary Poster
use newest version of zc.buildout
24
from lp.services.mime import customizeMimetypes
13225.9.1 by Benji York
add the ability to mark an exception as not OOPS report worthy and use
25
from zope.interface import alsoProvides
9590.1.94 by Michael Hudson
test passes, some zope security horror though
26
from zope.security import checker
13225.9.1 by Benji York
add the ability to mark an exception as not OOPS report worthy and use
27
import zope.publisher.browser
10981.1.1 by Maris Fogels
Silence DeprecationWarnings from pycrypto 2.0.1 using a new warnings hook in lp_sitecustomize.
28
9590.1.95 by Michael Hudson
more comprehensive zope horror
29
11300.2.44 by Stuart Bishop
Tidy custom loglevels into their own module, and initialize filtering and custom levels in lp_sitecustomize.py for great justice.
30
def add_custom_loglevels():
31
    """Add out custom log levels to the Python logging package."""
11300.2.49 by Stuart Bishop
Tidy and improve logging system infrastructure for great justice.
32
33
    # This import installs custom ZODB loglevels, which we can then
34
    # override. BLATHER is between INFO and DEBUG, so we can leave it.
35
    # TRACE conflicts with DEBUG6, and since we are not using ZEO, we
36
    # just overwrite the level string by calling addLevelName.
37
    from ZODB.loglevels import BLATHER, TRACE
38
39
    # Confirm our above assumptions, and silence lint at the same time.
40
    assert BLATHER == 15
41
    assert TRACE == loglevels.DEBUG6
42
43
    logging.addLevelName(loglevels.DEBUG2, 'DEBUG2')
44
    logging.addLevelName(loglevels.DEBUG3, 'DEBUG3')
45
    logging.addLevelName(loglevels.DEBUG4, 'DEBUG4')
46
    logging.addLevelName(loglevels.DEBUG5, 'DEBUG5')
47
    logging.addLevelName(loglevels.DEBUG6, 'DEBUG6')
48
    logging.addLevelName(loglevels.DEBUG7, 'DEBUG7')
49
    logging.addLevelName(loglevels.DEBUG8, 'DEBUG8')
50
    logging.addLevelName(loglevels.DEBUG9, 'DEBUG9')
51
52
    # Install our customized Logger that provides easy access to our
53
    # custom loglevels.
8758.2.57 by Stuart Bishop
Move LaunchpadLogger to a better location
54
    logging.setLoggerClass(LaunchpadLogger)
11300.2.49 by Stuart Bishop
Tidy and improve logging system infrastructure for great justice.
55
9893.6.42 by Stuart Bishop
Override the root logger with an instance of LaunchpadLogger. Currently, code paths can fail when passed the root logger instead of a logger with our richer API.
56
    # Fix the root logger, replacing it with an instance of our
57
    # customized Logger. The original one is instantiated on import of
58
    # the logging module, so our override does not take effect without
59
    # this manual effort.
9893.6.45 by Stuart Bishop
Do more work replacing root logger, as bzrlib and zope have already created loggers on module import.
60
    old_root = logging.root
8758.2.57 by Stuart Bishop
Move LaunchpadLogger to a better location
61
    new_root = LaunchpadLogger('root', loglevels.WARNING)
9893.6.45 by Stuart Bishop
Do more work replacing root logger, as bzrlib and zope have already created loggers on module import.
62
63
    # Fix globals.
64
    logging.root = new_root
65
    logging.Logger.root = new_root
66
67
    # Fix manager.
68
    manager = logging.Logger.manager
69
    manager.root = new_root
70
71
    # Fix existing Logger instances.
72
    for logger in manager.loggerDict.values():
73
        if getattr(logger, 'parent', None) is old_root:
74
            logger.parent = new_root
9893.6.42 by Stuart Bishop
Override the root logger with an instance of LaunchpadLogger. Currently, code paths can fail when passed the root logger instead of a logger with our richer API.
75
11300.2.44 by Stuart Bishop
Tidy custom loglevels into their own module, and initialize filtering and custom levels in lp_sitecustomize.py for great justice.
76
11136.3.7 by Diogo Matsubara
change the function name to reflect what it's doing
77
def silence_bzr_logger():
11136.3.6 by Diogo Matsubara
fix docstring
78
    """Install the NullHandler on the bzr logger to silence logs."""
12144.1.6 by Jonathan Lange
Don't let bzr log messages propagate
79
    bzr_logger = logging.getLogger('bzr')
80
    bzr_logger.addHandler(NullHandler())
81
    bzr_logger.propagate = False
11136.3.1 by Diogo Matsubara
silence the root logger across the entire Launchpad project
82
11300.2.49 by Stuart Bishop
Tidy and improve logging system infrastructure for great justice.
83
11300.2.44 by Stuart Bishop
Tidy custom loglevels into their own module, and initialize filtering and custom levels in lp_sitecustomize.py for great justice.
84
def silence_zcml_logger():
85
    """Lower level of ZCML parsing DEBUG messages."""
86
    config_filter = MappingFilter(
87
        {logging.DEBUG: (7, 'DEBUG4')}, 'config')
88
    logging.getLogger('config').addFilter(config_filter)
89
11300.2.49 by Stuart Bishop
Tidy and improve logging system infrastructure for great justice.
90
11300.2.44 by Stuart Bishop
Tidy custom loglevels into their own module, and initialize filtering and custom levels in lp_sitecustomize.py for great justice.
91
def silence_transaction_logger():
92
    """Lower level of DEBUG messages from the transaction module."""
93
    # Transaction logging is too noisy. Lower its DEBUG messages
94
    # to DEBUG3. Transactions log to loggers named txn.<thread_id>,
95
    # so we need to register a null handler with a filter to ensure
96
    # the logging records get mutated before being propagated up
97
    # to higher level loggers.
98
    txn_handler = NullHandler()
99
    txn_filter = MappingFilter(
100
        {logging.DEBUG: (8, 'DEBUG3')}, 'txn')
101
    txn_handler.addFilter(txn_filter)
102
    logging.getLogger('txn').addHandler(txn_handler)
103
11300.2.49 by Stuart Bishop
Tidy and improve logging system infrastructure for great justice.
104
9590.1.95 by Michael Hudson
more comprehensive zope horror
105
def dont_wrap_class_and_subclasses(cls):
106
    checker.BasicTypes.update({cls: checker.NoProxy})
107
    for subcls in cls.__subclasses__():
108
        dont_wrap_class_and_subclasses(subcls)
10303.1.1 by Gary Poster
use newest version of zc.buildout
109
11300.2.49 by Stuart Bishop
Tidy and improve logging system infrastructure for great justice.
110
10981.1.1 by Maris Fogels
Silence DeprecationWarnings from pycrypto 2.0.1 using a new warnings hook in lp_sitecustomize.
111
def silence_warnings():
112
    """Silence warnings across the entire Launchpad project."""
113
    # pycrypto-2.0.1 on Python2.6:
114
    #   DeprecationWarning: the sha module is deprecated; use the hashlib
115
    #   module instead
116
    warnings.filterwarnings(
117
        "ignore",
118
        category=DeprecationWarning,
119
        module="Crypto")
12398.2.16 by Jonathan Lange
Respond to review comments
120
    # Filter all deprecation warnings for Zope 3.6, which emanate from
12398.2.9 by Jonathan Lange
Better docstring.
121
    # the zope package.
122
    filter_pattern = '.*(Zope 3.6|provide.*global site manager).*'
123
    warnings.filterwarnings(
124
        'ignore', filter_pattern, category=DeprecationWarning)
125
    # XXX wgrant 2010-03-30 bug=551510:
126
    # Also filter apt_pkg warnings, since Lucid's python-apt has a new API.
127
    warnings.filterwarnings(
128
        'ignore', '.*apt_pkg.*', category=DeprecationWarning)
10981.1.1 by Maris Fogels
Silence DeprecationWarnings from pycrypto 2.0.1 using a new warnings hook in lp_sitecustomize.
129
11300.2.49 by Stuart Bishop
Tidy and improve logging system infrastructure for great justice.
130
9893.6.28 by Stuart Bishop
Reset logging between tests to Launchpad default state, not Z3 default state
131
def customize_logger():
132
    """Customize the logging system.
133
134
    This function is also invoked by the test infrastructure to reset
135
    logging between tests.
136
    """
137
    silence_bzr_logger()
138
    silence_zcml_logger()
139
    silence_transaction_logger()
140
141
13225.9.1 by Benji York
add the ability to mark an exception as not OOPS report worthy and use
142
def customize_get_converter(zope_publisher_browser=zope.publisher.browser):
143
    """URL parameter conversion errors shouldn't generate an OOPS report.
144
145
    This injects (monkey patches) our wrapper around get_converter so improper
146
    use of parameter type converters (like http://...?foo=bar:int) won't
147
    generate OOPS reports.
148
    """
149
    original_get_converter = zope_publisher_browser.get_converter
150
151
    def get_converter(*args, **kws):
152
        """Get a type converter but turn off OOPS reporting if it fails."""
153
        converter = original_get_converter(*args, **kws)
154
155
        def wrapped_converter(v):
156
            try:
157
                return converter(v)
158
            except ValueError, e:
159
                # Mark the exception as not being OOPS-worthy.
160
                alsoProvides(e, IUnloggedException)
161
                raise
162
13225.9.3 by Benji York
add support for get_converter returning None
163
        # The converter can be None, in which case wrapping it makes no sense,
164
        # otherwise it is a function which we wrap.
165
        if converter is None:
166
            return None
167
        else:
168
            return wrapped_converter
13225.9.1 by Benji York
add the ability to mark an exception as not OOPS report worthy and use
169
170
    zope_publisher_browser.get_converter = get_converter
171
172
11692.4.1 by Gary Poster
Allow .lpconfig to be honored if initial configuration is "development"
173
def main(instance_name):
174
    # This is called by our custom buildout-generated sitecustomize.py
175
    # in parts/scripts/sitecustomize.py. The instance name is sent to
176
    # buildout from the Makefile, and then inserted into
177
    # sitecustomize.py.  See buildout.cfg in the "initialization" value
178
    # of the [scripts] section for the code that goes into this custom
179
    # sitecustomize.py.  We do all actual initialization here, in a more
180
    # visible place.
181
    if instance_name and instance_name != 'development':
182
        # See bug 656213 for why we do this carefully.
183
        os.environ.setdefault('LPCONFIG', instance_name)
10303.1.1 by Gary Poster
use newest version of zc.buildout
184
    os.environ['STORM_CEXTENSIONS'] = '1'
11300.2.44 by Stuart Bishop
Tidy custom loglevels into their own module, and initialize filtering and custom levels in lp_sitecustomize.py for great justice.
185
    add_custom_loglevels()
10303.1.1 by Gary Poster
use newest version of zc.buildout
186
    customizeMimetypes()
9590.1.95 by Michael Hudson
more comprehensive zope horror
187
    dont_wrap_class_and_subclasses(Branch)
12536.2.4 by Robert Collins
Fix branch a bit.
188
    checker.BasicTypes.update({defaultdict: checker.NoProxy})
11593.3.120 by Julian Edwards
re-add revno 11801 which was backed out in devel due to test failures resulting from a twisted bug
189
    checker.BasicTypes.update({Deferred: checker.NoProxy})
11892.6.4 by Julian Edwards
Fix sourcepackagerecipebuild's handleStatus
190
    checker.BasicTypes.update({DeferredList: checker.NoProxy})
11594.2.1 by Aaron Bentley
Fix use of itertools.groupby through security proxies.
191
    checker.BasicTypes[itertools.groupby] = checker._iteratorChecker
11594.2.2 by Aaron Bentley
Handle itertools._grouper as well.
192
    # The itertools._grouper type is not exposed by name, so we must get it
193
    # through actually using itertools.groupby.
194
    grouper = type(list(itertools.groupby([0]))[0][1])
195
    checker.BasicTypes[grouper] = checker._iteratorChecker
10981.1.1 by Maris Fogels
Silence DeprecationWarnings from pycrypto 2.0.1 using a new warnings hook in lp_sitecustomize.
196
    silence_warnings()
9893.6.28 by Stuart Bishop
Reset logging between tests to Launchpad default state, not Z3 default state
197
    customize_logger()
13225.9.1 by Benji York
add the ability to mark an exception as not OOPS report worthy and use
198
    customize_get_converter()