Example #1
0
def local_config(args):
    import os
    import sys
    import logging

    if len(args) == 0:
        usage('local-config')
        sys.exit(1)

    from newrelic.agent import global_settings, initialize

    if len(args) >= 2:
        log_file = args[1]
    else:
        log_file = '/tmp/python-agent-test.log'

    log_level = logging.DEBUG

    try:
        os.unlink(log_file)
    except Exception:
        pass

    config_file = args[0]
    environment = os.environ.get('NEW_RELIC_ENVIRONMENT')

    if config_file == '-':
        config_file = os.environ.get('NEW_RELIC_CONFIG_FILE')

    initialize(config_file, environment, ignore_errors=False,
            log_file=log_file, log_level=log_level)

    for key, value in sorted(global_settings()):
        print('%s = %r' % (key, value))
def should_ignore(exc, value, tb):
    from django.http import Http404

    settings = global_settings()

    if (isinstance(value, Http404) and
            (404 in settings.error_collector.ignore_status_codes)):
        return True
def should_ignore(exc, value, tb):
    from django.http import Http404

    settings = global_settings()

    if (isinstance(value, Http404)
            and (404 in settings.error_collector.ignore_status_codes)):
        return True
Example #4
0
def init_new_relic(license_key, application_name):
    from newrelic import agent
    settings = agent.global_settings()

    settings.license_key = license_key
    settings.app_name = application_name
    settings.transaction_tracer.enabled = False
    settings.error_collector.enabled = False
    settings.slow_sql.enabled = False
    settings.browser_monitoring.auto_instrument = False
    agent.initialize()
Example #5
0
    def __call__(self, *args, **kwargs):
        transaction = current_transaction()

        settings = global_settings()

        rollup = []
        rollup.append('Datastore/all')
        rollup.append('Datastore/%s/all' %
                self._nr_dbapi2_module._nr_database_product)

        with FunctionTrace(transaction, callable_name(self.__wrapped__),
                terminal=True, rollup=rollup):
            return self.__connection_wrapper__(self.__wrapped__(
                    *args, **kwargs), self._nr_dbapi2_module, (args, kwargs))
def instrument_django_template_base(module):
    global module_django_template_base
    module_django_template_base = module

    settings = global_settings()

    if 'django.instrumentation.inclusion-tags.r1' in settings.feature_flag:
        wrap_function_wrapper(module, 'generic_tag_compiler',
                _nr_wrapper_django_template_base_generic_tag_compiler_)

        wrap_function_wrapper(module, 'Library.tag',
                _nr_wrapper_django_template_base_Library_tag_)

        wrap_function_wrapper(module, 'Library.inclusion_tag',
                _nr_wrapper_django_template_base_Library_inclusion_tag_)
def instrument_django_template_base(module):
    global module_django_template_base
    module_django_template_base = module

    settings = global_settings()

    if 'django.instrumentation.inclusion-tags.r1' in settings.feature_flag:
        wrap_function_wrapper(
            module, 'generic_tag_compiler',
            _nr_wrapper_django_template_base_generic_tag_compiler_)

        wrap_function_wrapper(module, 'Library.tag',
                              _nr_wrapper_django_template_base_Library_tag_)

        wrap_function_wrapper(
            module, 'Library.inclusion_tag',
            _nr_wrapper_django_template_base_Library_inclusion_tag_)
    def __call__(self, *args, **kwargs):
        transaction = current_transaction()

        settings = global_settings()

        if 'database.instrumentation.r1' in settings.feature_flag:
            rollup = 'Database/all'
        else:
            rollup = []
            rollup.append('Datastore/all')
            rollup.append('Datastore/%s/all' %
                    self._nr_dbapi2_module._nr_database_name)

        with FunctionTrace(transaction, callable_name(self.__wrapped__),
                terminal=True, rollup=rollup):
            return self.__connection_wrapper__(self.__wrapped__(
                    *args, **kwargs), self._nr_dbapi2_module, (args, kwargs))
Example #9
0
def network_config(args):
    import os
    import sys
    import logging

    if len(args) == 0:
        usage('network-config')
        sys.exit(1)

    from newrelic.agent import global_settings, initialize

    if len(args) >= 2:
        log_file = args[1]
    else:
        log_file = '/tmp/python-agent-test.log'

    log_level = logging.DEBUG

    try:
        os.unlink(log_file)
    except Exception:
        pass

    config_file = args[0]
    environment = os.environ.get('NEW_RELIC_ENVIRONMENT')

    if config_file == '-':
        config_file = os.environ.get('NEW_RELIC_CONFIG_FILE')

    initialize(config_file,
               environment,
               ignore_errors=False,
               log_file=log_file,
               log_level=log_level)

    _settings = global_settings()

    print('host = %r' % _settings.host)
    print('port = %r' % _settings.port)
    print('proxy_scheme = %r' % _settings.proxy_scheme)
    print('proxy_host = %r' % _settings.proxy_host)
    print('proxy_port = %r' % _settings.proxy_port)
    print('proxy_user = %r' % _settings.proxy_user)
    print('proxy_pass = %r' % _settings.proxy_pass)
    print('ssl = %r' % _settings.ssl)
def network_config(args):
    import os
    import sys
    import logging

    if len(args) == 0:
        usage('network-config')
        sys.exit(1)

    from newrelic.agent import global_settings, initialize

    if len(args) >= 2:
        log_file = args[1]
    else:
        log_file = '/tmp/python-agent-test.log'

    log_level = logging.DEBUG

    try:
        os.unlink(log_file)
    except Exception:
        pass

    config_file = args[0]
    environment = os.environ.get('NEW_RELIC_ENVIRONMENT')

    if config_file == '-':
        config_file = os.environ.get('NEW_RELIC_CONFIG_FILE')

    initialize(config_file, environment, ignore_errors=False,
            log_file=log_file, log_level=log_level)

    _settings = global_settings()

    print('host = %r' % _settings.host)
    print('port = %r' % _settings.port)
    print('proxy_scheme = %r' % _settings.proxy_scheme)
    print('proxy_host = %r' % _settings.proxy_host)
    print('proxy_port = %r' % _settings.proxy_port)
    print('proxy_user = %r' % _settings.proxy_user)
    print('proxy_pass = %r' % _settings.proxy_pass)
    print('ssl = %r' % _settings.ssl)
def should_ignore(exc, value, tb):
    from cherrypy import HTTPError, HTTPRedirect

    # Ignore certain exceptions based on HTTP status codes. The default list
    # of status codes are defined in the settings.error_collector object.

    settings = global_settings()
    if isinstance(value, (HTTPError, HTTPRedirect)) and value.status in settings.error_collector.ignore_status_codes:
        return True

    # Ignore certain exceptions based on their name.

    module = value.__class__.__module__
    name = value.__class__.__name__
    fullname = "%s:%s" % (module, name)

    ignore_exceptions = ("cherrypy._cperror:InternalRedirect",)

    if fullname in ignore_exceptions:
        return True
Example #12
0
def should_ignore(exc, value, tb):
    from cherrypy import HTTPError, HTTPRedirect

    # Ignore certain exceptions based on HTTP status codes. The default list
    # of status codes are defined in the settings.error_collector object.

    settings = global_settings()
    if (isinstance(value, (HTTPError, HTTPRedirect))
            and value.status in settings.error_collector.ignore_status_codes):
        return True

    # Ignore certain exceptions based on their name.

    module = value.__class__.__module__
    name = value.__class__.__name__
    fullname = '%s:%s' % (module, name)

    ignore_exceptions = ('cherrypy._cperror:InternalRedirect',)

    if fullname in ignore_exceptions:
        return True
def should_ignore(exc, value, tb):
    from pyramid.httpexceptions import HTTPException
    from pyramid.exceptions import PredicateMismatch

    # Ignore certain exceptions based on HTTP status codes. The default
    # list of status codes are defined in the settings.error_collector
    # object.

    settings = global_settings()

    if (isinstance(value, HTTPException) and (value.code in
                    settings.error_collector.ignore_status_codes)):
        return True

    # Always ignore PredicateMismatch as it is raised by views to force
    # subsequent views to be consulted when multi views are being used.
    # It isn't therefore strictly an error as such as a subsequent view
    # could still handle the request. See TODO items though for a corner
    # case where this can mean an error isn't logged when it should.

    if isinstance(value, PredicateMismatch):
        return True
def should_ignore(exc, value, tb):
    from pyramid.httpexceptions import HTTPException
    from pyramid.exceptions import PredicateMismatch

    # Ignore certain exceptions based on HTTP status codes. The default
    # list of status codes are defined in the settings.error_collector
    # object.

    settings = global_settings()

    if (isinstance(value, HTTPException)
            and (value.code in settings.error_collector.ignore_status_codes)):
        return True

    # Always ignore PredicateMismatch as it is raised by views to force
    # subsequent views to be consulted when multi views are being used.
    # It isn't therefore strictly an error as such as a subsequent view
    # could still handle the request. See TODO items though for a corner
    # case where this can mean an error isn't logged when it should.

    if isinstance(value, PredicateMismatch):
        return True
Example #15
0
def license_key(args):
    import os
    import sys
    import logging

    if len(args) == 0:
        usage('license-key')
        sys.exit(1)

    from newrelic.agent import global_settings, initialize

    if len(args) >= 2:
        log_file = args[1]
    else:
        log_file = '/tmp/python-agent-test.log'

    log_level = logging.DEBUG

    try:
        os.unlink(log_file)
    except Exception:
        pass

    config_file = args[0]
    environment = os.environ.get('NEW_RELIC_ENVIRONMENT')

    if config_file == '-':
        config_file = os.environ.get('NEW_RELIC_CONFIG_FILE')

    initialize(config_file,
               environment,
               ignore_errors=False,
               log_file=log_file,
               log_level=log_level)

    _settings = global_settings()

    print('license_key = %r' % _settings.license_key)
Example #16
0
def local_config(args):
    import sys

    if len(args) < 2:
        usage('record-deploy')
        sys.exit(1)

    def _args(config_file, description, revision=None, changelog=None,
            user=None, *args):
        return config_file, description, revision, changelog, user

    config_file, description, revision, changelog, user = _args(*args)

    settings = global_settings()

    settings.monitor_mode = False

    initialize(config_file)

    app_name = settings.app_name

    api_key = settings.api_key or 'NO API KEY WAS SET IN AGENT CONFIGURATION'

    host = settings.host

    if host == 'collector.newrelic.com':
        host = 'api.newrelic.com'
    elif host == 'staging-collector.newrelic.com':
        host = 'staging-api.newrelic.com'

    port = settings.port
    ssl = settings.ssl

    url = '%s://%s/deployments.xml'

    scheme = ssl and 'https' or 'http'
    server = port and '%s:%d' % (host, port) or host

    url = url % (scheme, server)

    proxy_host = settings.proxy_host
    proxy_port = settings.proxy_port
    proxy_user = settings.proxy_user
    proxy_pass = settings.proxy_pass

    timeout = settings.agent_limits.data_collector_timeout

    proxies = proxy_details(None, proxy_host, proxy_port, proxy_user,
            proxy_pass)

    if user is None:
        user = pwd.getpwuid(os.getuid()).pw_gecos

    data = {}

    data['deployment[app_name]'] = app_name

    if description is not None:
        data['deployment[description]'] = description
    if revision is not None:
        data['deployment[revision]'] = revision
    if changelog is not None:
        data['deployment[changelog]'] = changelog
    if user is not None:
        data['deployment[user]'] = user

    headers = {}

    headers['X-API-Key'] = api_key

    cert_loc = certs.where()

    r = requests.post(url, proxies=proxies, headers=headers,
            timeout=timeout, data=data, verify=cert_loc)

    if r.status_code != 201:
        raise RuntimeError('An unexpected HTTP response of %r was received '
                'for request made to %r. The API key for the request was '
                '%r. The payload for the request was %r. If this issue '
                'persists then please report this problem to New Relic '
                'support for further investigation.' % (r.status_code,
                url, api_key, data))
def validate_config(args):
    import os
    import sys
    import logging
    import time

    if len(args) == 0:
        usage('validate-config')
        sys.exit(1)

    from newrelic.agent import (global_settings, initialize,
            register_application)

    if len(args) >= 2:
        log_file = args[1]
    else:
        log_file = '/tmp/python-agent-test.log'

    log_level = logging.DEBUG

    try:
        os.unlink(log_file)
    except Exception:
        pass

    config_file = args[0]
    environment = os.environ.get('NEW_RELIC_ENVIRONMENT')

    if config_file == '-':
        config_file = os.environ.get('NEW_RELIC_CONFIG_FILE')

    initialize(config_file, environment, ignore_errors=False,
            log_file=log_file, log_level=log_level)

    _logger = logging.getLogger(__name__)

    _logger.debug('Starting agent validation.')

    _settings = global_settings()

    app_name = os.environ.get('NEW_RELIC_TEST_APP_NAME', 'Python Agent Test')

    _settings.app_name = app_name
    _settings.transaction_tracer.transaction_threshold = 0
    _settings.shutdown_timeout = 30.0

    _settings.debug.log_malformed_json_data = True
    _settings.debug.log_data_collector_payloads = True
    _settings.debug.log_transaction_trace_payload = True

    print(_user_message % dict(app_name=app_name, log_file=log_file))

    _logger.debug('Register test application.')

    _logger.debug('Collector host is %r.', _settings.host)
    _logger.debug('Collector port is %r.', _settings.port)

    _logger.debug('Proxy scheme is %r.', _settings.proxy_scheme)
    _logger.debug('Proxy host is %r.', _settings.proxy_host)
    _logger.debug('Proxy port is %r.', _settings.proxy_port)
    _logger.debug('Proxy user is %r.', _settings.proxy_user)

    _logger.debug('SSL enabled is %r.', _settings.ssl)

    _logger.debug('License key is %r.', _settings.license_key)

    _timeout = 30.0

    _start = time.time()
    _application = register_application(timeout=_timeout)
    _end = time.time()

    _duration = _end - _start

    if not _application.active:
        _logger.error('Unable to register application for test, '
            'connection could not be established within %s seconds.',
            _timeout)
        return

    if hasattr(_application.settings, 'messages'):
        for message in _application.settings.messages:
            if message['message'].startswith('Reporting to:'):
                parts = message['message'].split('Reporting to:')
                url = parts[1].strip()
                print('Registration successful. Reporting to:')
                print()
                print('  %s' % url)
                print()
                break

    _logger.debug('Registration took %s seconds.', _duration)

    _logger.debug('Run the validation test.')

    _run_validation_test()
Example #18
0
def validate_config(args):
    import os
    import sys
    import logging
    import time

    if len(args) == 0:
        usage('validate-config')
        sys.exit(1)

    from newrelic.agent import (global_settings, initialize,
                                register_application)

    if len(args) >= 2:
        log_file = args[1]
    else:
        log_file = '/tmp/python-agent-test.log'

    log_level = logging.DEBUG

    try:
        os.unlink(log_file)
    except Exception:
        pass

    config_file = args[0]
    environment = os.environ.get('NEW_RELIC_ENVIRONMENT')

    if config_file == '-':
        config_file = os.environ.get('NEW_RELIC_CONFIG_FILE')

    initialize(config_file,
               environment,
               ignore_errors=False,
               log_file=log_file,
               log_level=log_level)

    _logger = logging.getLogger(__name__)

    _logger.debug('Starting agent validation.')

    _settings = global_settings()

    app_name = os.environ.get('NEW_RELIC_TEST_APP_NAME', 'Python Agent Test')

    _settings.app_name = app_name
    _settings.transaction_tracer.transaction_threshold = 0
    _settings.shutdown_timeout = 30.0

    _settings.debug.log_malformed_json_data = True
    _settings.debug.log_data_collector_payloads = True
    _settings.debug.log_transaction_trace_payload = True

    print(_user_message % dict(app_name=app_name, log_file=log_file))

    _logger.debug('Register test application.')

    _logger.debug('Collector host is %r.', _settings.host)
    _logger.debug('Collector port is %r.', _settings.port)

    _logger.debug('Proxy scheme is %r.', _settings.proxy_scheme)
    _logger.debug('Proxy host is %r.', _settings.proxy_host)
    _logger.debug('Proxy port is %r.', _settings.proxy_port)
    _logger.debug('Proxy user is %r.', _settings.proxy_user)

    _logger.debug('SSL enabled is %r.', _settings.ssl)

    _logger.debug('License key is %r.', _settings.license_key)

    _timeout = 30.0

    _start = time.time()
    _application = register_application(timeout=_timeout)
    _end = time.time()

    _duration = _end - _start

    if not _application.active:
        _logger.error(
            'Unable to register application for test, '
            'connection could not be established within %s seconds.', _timeout)
        return

    if hasattr(_application.settings, 'messages'):
        for message in _application.settings.messages:
            if message['message'].startswith('Reporting to:'):
                parts = message['message'].split('Reporting to:')
                url = parts[1].strip()
                print('Registration successful. Reporting to:')
                print()
                print('  %s' % url)
                print()
                break

    _logger.debug('Registration took %s seconds.', _duration)

    _logger.debug('Run the validation test.')

    _run_validation_test()