예제 #1
0
    def create_session(cls, license_key, app_name, linked_applications,
            environment, settings):

        """Registers the agent for the specified application with the data
        collector and retrieves the server side configuration. Returns a
        session object if successful through which subsequent calls to the
        data collector are made. If unsucessful then None is returned.

        """

        start = time.time()

        # If no license key provided in the call, fallback to using that
        # from the agent configuration file or environment variables.
        # Flag an error if the result still seems invalid.

        if not license_key:
            license_key = global_settings().license_key

        if not license_key:
            _logger.error('A valid account license key cannot be found. '
                'Has a license key been specified in the agent configuration '
                'file or via the NEW_RELIC_LICENSE_KEY environment variable?')

        try:
            # First need to ask the primary data collector which of the many
            # data collector instances we should use for this agent run.

            _logger.debug('Connecting to data collector to register agent '
                    'with license_key=%r, app_name=%r, '
                    'linked_applications=%r, environment=%r and settings=%r.',
                    license_key, app_name, linked_applications, environment,
                    settings)

            url = collector_url()
            redirect_host = cls.send_request(None, url, 'get_redirect_host',
                    license_key)

            # Then we perform a connect to the actual data collector host
            # we need to use. All communications after this point should go
            # to the secondary data collector.
            #
            # We use the global requests session object for now as harvest
            # for different applications are all done in turn. We will need
            # to change this if use multiple threads as currently force
            # session object to maintain only single connection to ensure
            # that keep alive is effective.

            app_names = [app_name] + linked_applications

            local_config = {}

            local_config['host'] = socket.gethostname()
            local_config['pid'] = os.getpid()
            local_config['language'] = 'python'
            local_config['app_name'] = app_names
            local_config['identifier'] = ','.join(app_names)
            local_config['agent_version'] = version
            local_config['environment'] = environment

            connect_settings = {}
            security_settings = {}

            connect_settings['browser_monitoring.loader'] = (
                    settings['browser_monitoring.loader'])
            connect_settings['browser_monitoring.debug'] = (
                    settings['browser_monitoring.debug'])

            security_settings['capture_params'] = settings['capture_params']
            security_settings['transaction_tracer'] = {}
            security_settings['transaction_tracer']['record_sql'] = (
                    settings['transaction_tracer.record_sql'])

            local_config['settings'] = connect_settings
            local_config['security_settings'] = security_settings

            local_config['high_security'] = settings['high_security']
            local_config['labels'] = settings['labels']

            display_name = settings['process_host.display_name']

            if display_name is None:
                local_config['display_name'] = local_config['host']
            else:
                local_config['display_name'] = display_name

            payload = (local_config,)

            url = collector_url(redirect_host)
            server_config = cls.send_request(None, url, 'connect',
                    license_key, None, payload)

            # Apply High Security Mode to server_config, so the local
            # security settings won't get overwritten when we overlay
            # the server settings on top of them.

            server_config = apply_high_security_mode_fixups(settings,
                    server_config)

            # The agent configuration for the application in constructed
            # by taking a snapshot of the locally constructed
            # configuration and overlaying it with that from the server.

            application_config = create_settings_snapshot(server_config)

        except NetworkInterfaceException:
            # The reason for errors of this type have already been logged.
            # No matter what the error we just pass back None. The upper
            # layer needs to count how many success times this has failed
            # and escalate things with a more sever error.

            pass

        except Exception:
            # Any other errors are going to be unexpected and likely will
            # indicate an issue with the implementation of the agent.

            _logger.exception('Unexpected exception when attempting to '
                    'register the agent with the data collector. Please '
                    'report this problem to New Relic support for further '
                    'investigation.')

            pass

        else:
            # Everything fine so we create the session object through which
            # subsequent communication with data collector will be done.

            session = cls(url, license_key, application_config)

            duration = time.time() - start

            # Log successful agent registration and any server side messages.

            _logger.info('Successfully registered New Relic Python agent '
                    'where app_name=%r, pid=%r, redirect_host=%r and '
                    'agent_run_id=%r, in %.2f seconds.', app_name,
                    os.getpid(), redirect_host, session.agent_run_id,
                    duration)

            if getattr(application_config, 'high_security', False):
                _logger.info('High Security Mode is being applied to all '
                        'communications between the agent and the data '
                        'collector for this session.')

            logger_func_mapping = {
                'ERROR': _logger.error,
                'WARN': _logger.warning,
                'INFO': _logger.info,
                'VERBOSE': _logger.debug,
            }

            if 'messages' in server_config:
                for item in server_config['messages']:
                    message = item['message']
                    level = item['level']
                    logger_func = logger_func_mapping.get(level, None)
                    if logger_func:
                        logger_func('%s', message)

            return session
예제 #2
0
def create_session(license_key, app_name, linked_applications, environment,
                   settings):
    """Registers the agent for the specified application with the data
    collector and retrieves the server side configuration. Returns a
    session object if successful through which subsequent calls to the
    data collector are made. If unsucessful then None is returned.

    """

    start = time.time()

    # If no license key provided in the call, fallback to using that
    # from the agent configuration file or environment variables. Flag
    # an error if the result still seems invalid.

    if not license_key:
        license_key = global_settings().license_key

    if not license_key:
        _logger.error(
            'A valid account license key cannot be found. '
            'Has a license key been specified in the agent configuration '
            'file or via the NEW_RELIC_LICENSE_KEY environment variable?')

    try:
        # First need to ask the primary data collector which of the many
        # data collector instances we should use for this agent run.

        _logger.debug(
            'Connecting to data collector to register agent with '
            'license_key=%r, app_name=%r, linked_applications=%r, '
            'environment=%r and settings=%r.', license_key, app_name,
            linked_applications, environment, settings)

        url = collector_url()
        redirect_host = send_request(None, url, 'get_redirect_host',
                                     license_key)

        # Then we perform a connect to the actual data collector host
        # we need to use. All communications after this point should go
        # to the secondary data collector.
        #
        # We use the global requests session object for now as harvest
        # for different applications are all done in turn. We will need
        # to change this if use multiple threads as currently force
        # session object to maintain only single connection to ensure
        # that keep alive is effective.

        app_names = [app_name] + linked_applications

        local_config = {}

        local_config['pid'] = os.getpid()
        local_config['language'] = 'python'
        local_config['host'] = socket.gethostname()
        local_config['app_name'] = app_names
        local_config['identifier'] = ','.join(app_names)
        local_config['agent_version'] = version
        local_config['environment'] = environment
        local_config['settings'] = settings

        payload = (local_config, )

        url = collector_url(redirect_host)
        server_config = send_request(None, url, 'connect', license_key, None,
                                     payload)

        # The agent configuration for the application in constructed
        # by taking a snapshot of the locally constructed configuration
        # and overlaying it with that from the server.

        application_config = create_settings_snapshot(server_config)

    except NetworkInterfaceException:
        # The reason for errors of this type have already been logged.
        # No matter what the error we just pass back None. The upper
        # layer needs to count how many success times this has failed
        # and escalate things with a more sever error.

        pass

    except Exception:
        # Any other errors are going to be unexpected and likely will
        # indicate an issue with the implementation of the agent.

        _logger.exception(
            'Unexpected exception when attempting to '
            'register the agent with the data collector. Please '
            'report this problem to New Relic support for further '
            'investigation.')

        pass

    else:
        # Everything fine so we create the session object through which
        # subsequent communication with data collector will be done.

        session = ApplicationSession(url, license_key, application_config)

        duration = time.time() - start

        # Log successful agent registration and any server side messages.

        _logger.info(
            'Successfully registered New Relic Python agent '
            'where app_name=%r, pid=%r, redirect_host=%r and '
            'agent_run_id=%r, in %.2f seconds.', app_name, os.getpid(),
            redirect_host, session.agent_run_id, duration)

        if hasattr(application_config, 'high_security'):
            _logger.info('High security mode is being applied to all '
                         'communications between the agent and the data '
                         'collector for this session.')

        logger_func_mapping = {
            'ERROR': _logger.error,
            'WARN': _logger.warning,
            'INFO': _logger.info,
            'VERBOSE': _logger.debug,
        }

        if 'messages' in server_config:
            for item in server_config['messages']:
                message = item['message']
                level = item['level']
                logger_func = logger_func_mapping.get(level, None)
                if logger_func:
                    logger_func('%s', message)

        return session
def create_session(license_key, app_name, linked_applications, environment, settings):

    """Registers the agent for the specified application with the data
    collector and retrieves the server side configuration. Returns a
    session object if successful through which subsequent calls to the
    data collector are made. If unsucessful then None is returned.

    """

    start = time.time()

    # If no license key provided in the call, fallback to using that
    # from the agent configuration file or environment variables. Flag
    # an error if the result still seems invalid.

    if not license_key:
        license_key = global_settings().license_key

    if not license_key:
        _logger.error(
            "A valid account license key cannot be found. "
            "Has a license key been specified in the agent configuration "
            "file or via the NEW_RELIC_LICENSE_KEY environment variable?"
        )

    try:
        # First need to ask the primary data collector which of the many
        # data collector instances we should use for this agent run.

        _logger.debug(
            "Connecting to data collector to register agent with "
            "license_key=%r, app_name=%r, linked_applications=%r, "
            "environment=%r and settings=%r.",
            license_key,
            app_name,
            linked_applications,
            environment,
            settings,
        )

        url = collector_url()
        redirect_host = send_request(None, url, "get_redirect_host", license_key)

        # Then we perform a connect to the actual data collector host
        # we need to use. All communications after this point should go
        # to the secondary data collector.
        #
        # We use the global requests session object for now as harvest
        # for different applications are all done in turn. We will need
        # to change this if use multiple threads as currently force
        # session object to maintain only single connection to ensure
        # that keep alive is effective.

        app_names = [app_name] + linked_applications

        local_config = {}

        local_config["pid"] = os.getpid()
        local_config["language"] = "python"
        local_config["host"] = socket.gethostname()
        local_config["app_name"] = app_names
        local_config["identifier"] = ",".join(app_names)
        local_config["agent_version"] = version
        local_config["environment"] = environment
        local_config["settings"] = settings

        payload = (local_config,)

        url = collector_url(redirect_host)
        server_config = send_request(None, url, "connect", license_key, None, payload)

        # The agent configuration for the application in constructed
        # by taking a snapshot of the locally constructed configuration
        # and overlaying it with that from the server.

        application_config = create_settings_snapshot(server_config)

    except NetworkInterfaceException:
        # The reason for errors of this type have already been logged.
        # No matter what the error we just pass back None. The upper
        # layer needs to count how many success times this has failed
        # and escalate things with a more sever error.

        pass

    except Exception:
        # Any other errors are going to be unexpected and likely will
        # indicate an issue with the implementation of the agent.

        _logger.exception(
            "Unexpected exception when attempting to "
            "register the agent with the data collector. Please "
            "report this problem to New Relic support for further "
            "investigation."
        )

        pass

    else:
        # Everything fine so we create the session object through which
        # subsequent communication with data collector will be done.

        session = ApplicationSession(url, license_key, application_config)

        duration = time.time() - start

        # Log successful agent registration and any server side messages.

        _logger.info(
            "Successfully registered New Relic Python agent "
            "where app_name=%r, pid=%r, redirect_host=%r and "
            "agent_run_id=%r, in %.2f seconds.",
            app_name,
            os.getpid(),
            redirect_host,
            session.agent_run_id,
            duration,
        )

        if hasattr(application_config, "high_security"):
            _logger.info(
                "High security mode is being applied to all "
                "communications between the agent and the data "
                "collector for this session."
            )

        logger_func_mapping = {
            "ERROR": _logger.error,
            "WARN": _logger.warning,
            "INFO": _logger.info,
            "VERBOSE": _logger.debug,
        }

        if "messages" in server_config:
            for item in server_config["messages"]:
                message = item["message"]
                level = item["level"]
                logger_func = logger_func_mapping.get(level, None)
                if logger_func:
                    logger_func("%s", message)

        return session