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 local_config(args): import os import sys import logging if len(args) == 0: usage('local-config') sys.exit(1) from newrelic.config import initialize from newrelic.core.config import global_settings 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 initialize_usage(usage_name, args): import os import sys import logging if len(args) == 0: usage(usage_name) sys.exit(1) from newrelic.config import initialize from newrelic.core.config import global_settings log_level = logging.DEBUG log_file = get_log_file_path(args) 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) return global_settings()
def server_config(args): import os import sys import logging import time if len(args) == 0: usage('server-config') sys.exit(1) from newrelic.agent import 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) _timeout = 30.0 _start = time.time() _application = register_application(timeout=_timeout) _end = time.time() _duration = _end - _start _logger = logging.getLogger(__name__) if not _application.active: _logger.error( 'Unable to register application for test, ' 'connection could not be established within %s seconds.', _timeout) return _logger.debug('Registration took %s seconds.', _duration) for key, value in sorted(_application.settings): print('%s = %r' % (key, value))
def data_source(args): import sys if len(args) == 0: usage('data-source') sys.exit(1) from newrelic.platform import run run(*args)
def server_config(args): import os import sys import logging import time if len(args) == 0: usage('server-config') sys.exit(1) from newrelic.agent import 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) _timeout = 30.0 _start = time.time() _application = register_application(timeout=_timeout) _end = time.time() _duration = _end - _start _logger = logging.getLogger(__name__) if not _application.active: _logger.error('Unable to register application for test, ' 'connection could not be established within %s seconds.', _timeout) return _logger.debug('Registration took %s seconds.', _duration) for key, value in sorted(_application.settings): print('%s = %r' % (key, value))
def record_deploy_cmd(args): import sys if len(args) < 2: usage("record-deploy") sys.exit(1) def _args(config_file, description, revision="Unknown", 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) host = settings.host if host == "collector.newrelic.com": host = "api.newrelic.com" elif host.startswith("collector.eu"): host = "api.eu.newrelic.com" elif host == "staging-collector.newrelic.com": host = "staging-api.newrelic.com" port = settings.port or 443 record_deploy( host=host, api_key=settings.api_key, app_name=settings.app_name, description=description, revision=revision, changelog=changelog, user=user, port=port, proxy_scheme=settings.proxy_scheme, proxy_host=settings.proxy_host, proxy_user=settings.proxy_user, proxy_pass=settings.proxy_pass, timeout=settings.agent_limits.data_collector_timeout, ca_bundle_path=settings.ca_bundle_path, disable_certificate_validation=settings.debug. disable_certificate_validation, )
def license_info(args): import os import sys if len(args) != 0: usage('license-info') sys.exit(1) from newrelic import __file__ as package_root package_root = os.path.dirname(package_root) license_file = os.path.join(package_root, 'LICENSE') license = open(license_file, 'r').read() print(license, end='')
def network_config(args): import os import sys import logging if len(args) == 0: usage('network-config') sys.exit(1) from newrelic.config import initialize from newrelic.core.config import global_settings 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 debug_console(args): import sys if len(args) == 0: usage('debug-console') sys.exit(1) from newrelic.console import ClientShell config_file = args[0] log_object = None if len(args) >= 2: log_object = open(args[1], 'w') shell = ClientShell(config_file, log=log_object) shell.cmdloop()
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 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)
def generate_config(args): import os import sys if len(args) == 0: usage('generate-config') sys.exit(1) from newrelic import __file__ as package_root package_root = os.path.dirname(package_root) config_file = os.path.join(package_root, 'newrelic.ini') content = open(config_file, 'r').read() if len(args) >= 1: content = content.replace('*** REPLACE ME ***', args[0]) if len(args) >= 2 and args[1] != '-': output_file = open(args[1], 'w') output_file.write(content) output_file.close() else: print(content)
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.api.application import register_application from newrelic.config import initialize from newrelic.core.config import global_settings 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('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()
def local_config(args): import sys if len(args) < 2: usage("record-deploy") sys.exit(1) def _args(app_id, config_file, revision, description=None, changelog=None, user=None, timestamp=None, *args): return ( app_id, config_file, revision, description, changelog, user, timestamp, ) app_id, config_file, revision, description, changelog, user, timestamp = _args( *args) settings = global_settings() settings.monitor_mode = False initialize(config_file) 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.startswith("collector.eu"): host = "api.eu.newrelic.com" elif host == "staging-collector.newrelic.com": host = "staging-api.newrelic.com" port = settings.port url = "%s://%s/v2/applications/%s/deployments.json" scheme = "https" server = port and "%s:%d" % (host, port) or host url = url % (scheme, server, app_id) proxy_scheme = settings.proxy_scheme proxy_host = settings.proxy_host proxy_port = settings.proxy_port proxy_user = settings.proxy_user proxy_pass = settings.proxy_pass if proxy_scheme is None: proxy_scheme = "https" timeout = settings.agent_limits.data_collector_timeout proxies = proxy_details(proxy_scheme, proxy_host, proxy_port, proxy_user, proxy_pass) if user is None: user = pwd.getpwuid(os.getuid()).pw_gecos data = {} data["deployment"] = {} data["deployment"]["revision"] = revision if description is not None: data["deployment"]["description"] = description if changelog is not None: data["deployment"]["changelog"] = changelog if user is not None: data["deployment"]["user"] = user if timestamp is not None: data["deployment"]["timestamp"] = timestamp headers = {} headers["X-Api-Key"] = api_key headers["Content-Type"] = "application/json" cert_loc = settings.ca_bundle_path if cert_loc is None: cert_loc = certs.where() if settings.debug.disable_certificate_validation: cert_loc = False data = json.dumps(data) 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. The response " "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, r.json()))
def run_program(args): import os import sys import time if len(args) == 0: usage('run-program') sys.exit(1) startup_debug = os.environ.get('NEW_RELIC_STARTUP_DEBUG', 'off').lower() in ('on', 'true', '1') def log_message(text, *args): if startup_debug: text = text % args timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) print('NEWRELIC: %s (%d) - %s' % (timestamp, os.getpid(), text)) log_message('New Relic Admin Script (%s)', __file__) log_message('working_directory = %r', os.getcwd()) log_message('current_command = %r', sys.argv) log_message('sys.prefix = %r', os.path.normpath(sys.prefix)) try: log_message('sys.real_prefix = %r', sys.real_prefix) except AttributeError: pass log_message('sys.version_info = %r', sys.version_info) log_message('sys.executable = %r', sys.executable) log_message('sys.flags = %r', sys.flags) log_message('sys.path = %r', sys.path) for name in sorted(os.environ.keys()): if name.startswith('NEW_RELIC_') or name.startswith('PYTHON'): if name == 'NEW_RELIC_LICENSE_KEY': continue log_message('%s = %r', name, os.environ.get(name)) from newrelic import __file__ as root_directory root_directory = os.path.dirname(root_directory) boot_directory = os.path.join(root_directory, 'bootstrap') log_message('root_directory = %r', root_directory) log_message('boot_directory = %r', boot_directory) python_path = boot_directory if 'PYTHONPATH' in os.environ: path = os.environ['PYTHONPATH'].split(os.path.pathsep) if boot_directory not in path: python_path = "%s%s%s" % (boot_directory, os.path.pathsep, os.environ['PYTHONPATH']) os.environ['PYTHONPATH'] = python_path os.environ['NEW_RELIC_ADMIN_COMMAND'] = repr(sys.argv) os.environ['NEW_RELIC_PYTHON_PREFIX'] = os.path.realpath( os.path.normpath(sys.prefix)) os.environ['NEW_RELIC_PYTHON_VERSION'] = '.'.join( map(str, sys.version_info[:2])) # If not an absolute or relative path, then we need to # see if program can be found in PATH. Note that can # be found in current working directory even though '.' # not in PATH. program_exe_path = args[0] if not os.path.dirname(program_exe_path): program_search_path = os.environ.get('PATH', '').split(os.path.pathsep) for path in program_search_path: path = os.path.join(path, program_exe_path) if os.path.exists(path) and os.access(path, os.X_OK): program_exe_path = path break log_message('program_exe_path = %r', program_exe_path) log_message('execl_arguments = %r', [program_exe_path] + args) os.execl(program_exe_path, *args)
def run_program(args): import os import sys import time if len(args) == 0: usage('run-program') sys.exit(1) startup_debug = os.environ.get('NEW_RELIC_STARTUP_DEBUG', 'off').lower() in ('on', 'true', '1') def log_message(text, *args): if startup_debug: text = text % args timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) print('NEWRELIC: %s (%d) - %s' % (timestamp, os.getpid(), text)) log_message('New Relic Admin Script (%s)', __file__) log_message('working_directory = %r', os.getcwd()) log_message('current_command = %r', sys.argv) log_message('sys.prefix = %r', os.path.normpath(sys.prefix)) try: log_message('sys.real_prefix = %r', sys.real_prefix) except AttributeError: pass log_message('sys.version_info = %r', sys.version_info) log_message('sys.executable = %r', sys.executable) log_message('sys.flags = %r', sys.flags) log_message('sys.path = %r', sys.path) for name in sorted(os.environ.keys()): if name.startswith('NEW_RELIC_') or name.startswith('PYTHON'): log_message('%s = %r', name, os.environ.get(name)) from newrelic import version, __file__ as root_directory root_directory = os.path.dirname(root_directory) boot_directory = os.path.join(root_directory, 'bootstrap') log_message('root_directory = %r', root_directory) log_message('boot_directory = %r', boot_directory) python_path = boot_directory if 'PYTHONPATH' in os.environ: path = os.environ['PYTHONPATH'].split(os.path.pathsep) if not boot_directory in path: python_path = "%s%s%s" % (boot_directory, os.path.pathsep, os.environ['PYTHONPATH']) os.environ['PYTHONPATH'] = python_path os.environ['NEW_RELIC_ADMIN_COMMAND'] = repr(sys.argv) os.environ['NEW_RELIC_PYTHON_PREFIX'] = os.path.realpath( os.path.normpath(sys.prefix)) os.environ['NEW_RELIC_PYTHON_VERSION'] = '.'.join( map(str, sys.version_info[:2])) # If not an absolute or relative path, then we need to # see if program can be found in PATH. Note that can # be found in current working directory even though '.' # not in PATH. program_exe_path = args[0] if not os.path.dirname(program_exe_path): program_search_path = os.environ.get('PATH', '').split(os.path.pathsep) for path in program_search_path: path = os.path.join(path, program_exe_path) if os.path.exists(path) and os.access(path, os.X_OK): program_exe_path = path break log_message('program_exe_path = %r', program_exe_path) log_message('execl_arguments = %r', [program_exe_path]+args) os.execl(program_exe_path, *args)
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()
def record_deploy(args): import sys if len(args) < 2: usage("record-deploy") sys.exit(1) def _args(config_file, description, revision="Unknown", 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) host = settings.host if host == "collector.newrelic.com": host = "api.newrelic.com" elif host.startswith("collector.eu"): host = "api.eu.newrelic.com" elif host == "staging-collector.newrelic.com": host = "staging-api.newrelic.com" port = settings.port server = port and "%s:%d" % (host, port) or host app_id = fetch_app_id(settings.app_name, server=server) if app_id is None: raise RuntimeError( "The application named %r was not found in your account. Please " "try running the newrelic-admin server-config command to force " "the application to register with New Relic." % settings.app_name) url = "https://{}/v2/applications/{}/deployments.json".format( server, app_id) if user is None: user = pwd.getpwuid(os.getuid()).pw_gecos deployment = {} deployment["revision"] = revision if description: deployment["description"] = description if changelog: deployment["changelog"] = changelog if user: deployment["user"] = user data = {"deployment": deployment} r = requests.post(url, json=data, **api_request_kwargs()) if r.status_code != 201: raise RuntimeError( "An unexpected HTTP response of %r was received " "for request made to %r. The payload for the request was %r. " "The response 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, data, r.json()))