def init(config): if not agent or not config: return if os.path.exists(config): agent.initialize(config) else: logging.getLogger(__name__).error('%s doesn\'t exist, newrelic disabled', config)
def get_rpc_application(): """Creates a Gunicorn Thrift compatible TProcessor and initializes NewRelic """ global __new_relic _init_django() if agent and not __new_relic: # pragma: no cover try: agent.initialize() logging.info('Initialized New Relic application') __new_relic = True except Exception as exc: # pylint: disable=all logging.warning( 'Could not wrap RPC server in New Relic config. Exc: %s', exc) for i_app in settings.INSTALLED_APPS: if i_app.startswith('django') or 'manifold' in i_app: continue try: importlib.import_module("%s.views" % i_app) except ImportError: # pragma: no cover logging.info( 'No module "%s.views" found, skipping RPC calls from it...', i_app) _print_rpc_config() return TProcessor(load_service(), handler)
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 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 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()
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 init_newrelic_agent(): try: _ = os.environ["NEW_RELIC_LICENSE_KEY"] except KeyError: logger.info("Agent will not report data to New Relic APM") else: config_file = os.environ.get("NEW_RELIC_CONFIG_FILE") env = os.environ.get("NEW_RELIC_ENVIRONMENT") log_file = "stdout" log_level = logging.DEBUG agent.initialize(config_file, env, log_file, log_level) logger.info("Agent start reporting data to New Relic APM")
def monitoring(method): """Decorator for monitioring specific methods""" from newrelic import agent load_config() config_location = config['newrelic']['config'] environment = config['newrelic']['environment'] agent.initialize(config_location, environment) if method is None: return functools.partial(monitoring) return agent.BackgroundTaskWrapper(method)
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 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)
config = Config.factory(enviroment) app.config.from_object(config) from acme_orders.models import init_engine init_engine(app.config['DB_URI'], echo=app.config['SQL_ALCHEMY_ECHO']) from acme_orders.views import ImporterAPI, OrderAPI api.add_resource(OrderAPI, '/acme_orders/api/v1/orders', endpoint='orders') api.add_resource(OrderAPI, '/acme_orders/api/v1/orders/<int:order_id>', endpoint='order') api.add_resource(ImporterAPI, '/acme_orders/api/v1/orders/import', endpoint='importer') api.add_resource(ImporterAPI, '/acme_orders/api/v1/orders/import/status/<task_id>', endpoint='importer_status') # CONFIG CROSS ORIGIN REQUEST SHARING CORS(app, resources=r'/*', allow_headers='Content-Type', supports_credentials=True) # Starts New relic Agent if enviroment != 'Testing': agent.initialize(app.config['NEW_RELIC_INI_PATH'], 'production') @babel.localeselector def get_locale(): return request.accept_languages.best_match(app.config['LANGUAGES'].keys())
def config(self, config): self.active = config.newrelic_active if self.active: agent.initialize(config.newrelic_ini_path, config.newrelic_application_env) self.newrelic_application = agent.application()
from newrelic.agent import initialize initialize('./newrelic.ini', 'integration') from bottle import Bottle, run import urllib2 app = Bottle() @app.route('/hello') def hello(): r = urllib2.urlopen('https://www.google.com/') return "Hello World!" run(app, host='localhost', port=8080)
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 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 init(config_file): if agent and config_file and os.path.exists(config_file): agent.initialize(config_file) else: logger = logging.getLogger(__name__) logger.warn('newrelic hasn\'t been initialized')
import sys ROOT_DIR = os.path.realpath(__file__).replace("/wsgi.py", "") VENV_DIR = os.path.dirname(ROOT_DIR) site.addsitedir(os.path.join(VENV_DIR, "lib/python2.7/site-packages/")) sys.path.append(ROOT_DIR) from newrelic import agent from eisitirio import app from eisitirio import system # pylint: disable=unused-import APP = app.APP agent.initialize(os.path.join(VENV_DIR, "newrelic.ini")) # boto and requests are a bit noisy, so we set their level to tone them down logging.getLogger("boto").setLevel(logging.WARNING) logging.getLogger("requests").setLevel(logging.WARNING) # newrelic sets up its own handler to push things to stderr, we want to prevent # the messages reaching the root logger and being duplicated logging.getLogger("newrelic").propagate = False @agent.wsgi_application() def application(req_environ, start_response): """Wrapper around actual application to load config based on environment.""" if "EISITIRIO_CONFIG" not in req_environ or not APP.config.from_pyfile( req_environ["EISITIRIO_CONFIG"]
""" WSGI config for app project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.conf import settings from django.core.wsgi import get_wsgi_application from newrelic import agent agent.initialize(settings.BASE_DIR + '/newrelic.ini') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") application = get_wsgi_application() application = agent.wsgi_application()(application)
import sys ROOT_DIR = os.path.realpath(__file__).replace('/wsgi.py', '') VENV_DIR = os.path.dirname(ROOT_DIR) site.addsitedir(os.path.join(VENV_DIR, 'lib/python2.7/site-packages/')) sys.path.append(ROOT_DIR) from newrelic import agent from eisitirio import app from eisitirio import system # pylint: disable=unused-import APP = app.APP agent.initialize(os.path.join(VENV_DIR, 'newrelic.ini')) @agent.wsgi_application() def application(req_environ, start_response): """Wrapper around actual application to load config based on environment.""" if 'EISITIRIO_ENV' in req_environ: if req_environ['EISITIRIO_ENV'] == 'DEVELOPMENT': APP.config.from_pyfile('config/development.py') return APP(req_environ, start_response) elif req_environ['EISITIRIO_ENV'] == 'STAGING': APP.config.from_pyfile('config/staging.py') return APP(req_environ, start_response) elif req_environ['EISITIRIO_ENV'] == 'PRODUCTION': APP.config.from_pyfile('config/production.py') return APP(req_environ, start_response)
if group == "Python/napfs": set_transaction_name(txn_name) with FunctionTrace(name=txn_name, group=group): try: return f(*args, **kwargs) except Exception as e: if not isinstance(e, falcon.HTTPNotFound): notice_error(sys.exc_info()) raise return inner # noinspection PyBroadException try: if os.getenv('NEW_RELIC_LICENSE_KEY'): initialize() except Exception: pass def wrap_app(app): return WSGIApplicationWrapper(app) else: # noinspection PyUnusedLocal def trace(f, group=None): return f def wrap_app(app): return app
APPS_DIR = os.path.join(PROJECT_DIR, 'apps') sys.path.insert(0, PROJECT_DIR) sys.path.insert(0, ROOT_DIR) sys.path.insert(0, APPS_DIR) # Get sensitive configuration config = ConfigParser() config.read(ROOT_DIR + '/conf/sensitive/configuration.ini') if int(config.get('django', 'development_mode')) == 1: # Development mode os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.dev') else: # Production mode os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.prod') reload(sys) sys.setdefaultencoding('utf-8') application = get_wsgi_application() # Load celery djcelery.setup_loader() if int(config.get('django', 'development_mode')) == 0: # Production mode from newrelic import agent agent.initialize(ROOT_DIR + '/conf/sensitive/configuration.ini') application = agent.wsgi_application()(application)
): try: return f(*args, **kwargs) except Exception as e: if not isinstance(e, falcon.HTTPNotFound): record_exception(*sys.exc_info()) raise return inner # noinspection PyBroadException try: newrelic_config = os.getenv('NEW_RELIC_CONFIG_FILE', None) if newrelic_config and os.path.getsize(newrelic_config) > 0: environment = os.getenv('NEW_RELIC_CONFIG_ENV', 'development') initialize(newrelic_config, environment=environment) except Exception: pass def wrap_app(app): return WSGIApplicationWrapper(app) else: # noinspection PyUnusedLocal def trace(f, group=None): return f def wrap_app(app): return app
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.base') #Let's wrap with newrelic if it's installed try: from newrelic import agent confpath = os.environ.get('NEWRELIC_CONFIG_PATH') if confpath and os.path.exists(confpath): agent.initialize(confpath) application = agent.WSGIApplicationWrapper(get_wsgi_application()) else: application = get_wsgi_application() except ImportError: application = get_wsgi_application()
""" WSGI config for app project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.conf import settings from django.core.wsgi import get_wsgi_application from newrelic import agent agent.initialize(settings.BASE_DIR + '/newrelic.ini') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") application = get_wsgi_application() application = agent.wsgi_application()(application)
from newrelic.agent import initialize initialize('config/newrelic.ini', environment='celery') from application import create_celery app = create_celery()
# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. import os import os.path from newrelic import agent agent.initialize() from paste.deploy import loadapp from pyramid.paster import setup_logging from raven.middleware import Sentry from waitress import serve basedir = os.path.dirname(os.path.realpath(__file__)) conf_file = os.path.join(basedir, 'yithlibraryserver', 'config-templates', 'production.ini') application = loadapp('config:%s' % conf_file) application = agent.WSGIApplicationWrapper(Sentry(application)) setup_logging(conf_file)
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 wsgi(ctx, port, timeout, cdn, proxy_mode, admin_password, db_filter, ws, cron, cron_interval, server_wide_modules, dev): debug, config, params, logger = ( ctx.obj['debug'], ctx.obj['config'], ctx.obj['params'], ctx.obj['logger'] ) # Patch odoo config, since we run with gevent # we do not need multiple workers, but Odoo needs # to be fooled. config['workers'] = 2 config['dev_mode'] = ['all'] config['admin_passwd'] = admin_password config['dbfilter'] = db_filter config['server_wide_modules'] = ','.join(server_wide_modules) # Odoo still uses a deprecated conf module for server_wide_modules import odoo.conf odoo.conf.server_wide_modules = server_wide_modules if ws: from odooku.services.websocket import WebSocketServer as Server else: from odooku.services.wsgi import WSGIServer as Server from odooku.services.wsgi import WSGIApplicationRulesWrapper from odooku.services.cron import CronRunner # Initialize newrelic_agent global newrelic_agent if newrelic_agent and any(key in os.environ for key in [ 'NEW_RELIC_LICENSE_KEY', 'NEW_RELIC_CONFIG_FILE' ]): newrelic_agent.initialize() else: newrelic_agent = None # Keep track of custom config params params.TIMEOUT = timeout params.CDN_ENABLED = cdn params.WS_ENABLED = ws # Load wsgi rules rules = WSGIApplicationRulesWrapper.load() def serve(): max_accept = config['db_maxconn'] if cron: cron_runner = CronRunner() max_accept -= 1 gevent.spawn(cron_runner.run_forever, interval=cron_interval) server = Server( port, max_accept=max_accept, proxy_mode=proxy_mode, rules=rules, newrelic_agent=newrelic_agent, timeout=timeout ) server.serve_forever() if dev: logger.warning("Running in development mode") run_with_reloader(serve) else: serve()
def run(): from newrelic.agent import initialize initialize('config/newrelic.ini') app.run("0.0.0.0", debug=True, use_reloader=True, port=5000)
import sys ROOT_DIR = os.path.realpath(__file__).replace('/wsgi.py', '') VENV_DIR = os.path.dirname(ROOT_DIR) site.addsitedir(os.path.join(VENV_DIR, 'lib/python2.7/site-packages/')) sys.path.append(ROOT_DIR) from newrelic import agent from eisitirio import app from eisitirio import system # pylint: disable=unused-import APP = app.APP agent.initialize(os.path.join(VENV_DIR, 'newrelic.ini')) # boto and requests are a bit noisy, so we set their level to tone them down logging.getLogger('boto').setLevel(logging.WARNING) logging.getLogger('requests').setLevel(logging.WARNING) # newrelic sets up its own handler to push things to stderr, we want to prevent # the messages reaching the root logger and being duplicated logging.getLogger('newrelic').propagate = False @agent.wsgi_application() def application(req_environ, start_response): """Wrapper around actual application to load config based on environment.""" if ( 'EISITIRIO_CONFIG' not in req_environ or not APP.config.from_pyfile(req_environ['EISITIRIO_CONFIG'])
# -*- coding: utf-8 -*- import os try: import newrelic.agent as nr except ImportError: pass else: nr.initialize() from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{cookiecutter.project_slug}}.settings") application = get_wsgi_application()
import logging import sys import time from concurrent.futures import ThreadPoolExecutor from django.core.management.base import BaseCommand from django.db import connection from django.utils import timezone from newrelic import agent from hc.api.models import Check executor = ThreadPoolExecutor(max_workers=10) logger = logging.getLogger(__name__) agent.initialize() agent.register_application() def _stdout(message): sys.stdout.write(message) sys.stdout.write('\n') sys.stdout.flush() @agent.background_task() def handle_many(): """ Send alerts for many checks simultaneously. """ query = Check.objects.filter(user__isnull=False) now = timezone.now()
import os if os.environ.get('USE_NEWRELIC', False): print("RUNNING NEWRELIC!!!!!!") import newrelic.agent as nr_agent nr_agent.initialize("newrelic.ini") if os.environ.get('USE_TCELL', False): print("RUNNING TCELL!!!!!!") import tcell_agent tcell_agent.init() import argparse from werkzeug.serving import run_simple from werkzeug.wsgi import DispatcherMiddleware from quokka import create_app, create_api from quokka.utils.paas import activate application = DispatcherMiddleware(create_app(), {'/api': create_api()}) application = app = activate(application) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run Quokka App for WSGI") parser.add_argument('-p', '--port', help='App Port') parser.add_argument('-i', '--host', help='App Host') parser.add_argument('-r', '--reloader', action='store_true', help='Turn reloader on') parser.add_argument('-d',