Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
to = recipients(**kwargs)
msg = message(**kwargs)
tls = self.client.get('tls', True)
# Test cases specify stub: true. This uses a stub that logs emails
if self.stub:
server = SMTPStub(self.client['host'], self.client.get('port', self.ports[tls]),
self.stub)
else:
server = smtplib.SMTP(self.client['host'], self.client.get('port', self.ports[tls]))
if tls:
server.starttls()
if self.email is not None and self.password is not None:
server.login(self.email, self.password)
server.sendmail(sender, to, msg.as_string())
server.quit()
app_log.info('Email sent via %s (%s) to %s', self.client['host'], self.email,
', '.join(to))
app_log_extra['port'] = conf.listen.port
# browser: True opens the application home page on localhost.
# browser: url opens the application to a specific URL
url = 'http://127.0.0.1:%d/' % conf.listen.port
if conf.browser:
if isinstance(conf.browser, str):
url = urlparse.urljoin(url, conf.browser)
try:
browser = webbrowser.get()
app_log.info('Opening %s in %s browser', url, browser.__class__.__name__)
browser.open(url)
except webbrowser.Error:
app_log.info('Unable to open browser')
else:
app_log.info(' opens the browser. starts the debugger.')
# Ensure that we call shutdown() on Ctrl-C.
# On Windows, Tornado does not exit on Ctrl-C. This also fixes that.
# When Ctrl-C is pressed, signal_handler() sets _exit to [True].
# check_exit() periodically watches and calls shutdown().
# But signal handlers can only be set in the main thread.
# So ignore if we're not in the main thread (e.g. for nosetests, Windows service)
#
# Note: The PeriodicCallback takes up a small amount of CPU time.
# Note: getch() doesn't handle keyboard buffer queue.
# Note: This is no guarantee that shutdown() will be called.
if isinstance(threading.current_thread(), threading._MainThread):
exit = [False]
def check_exit():
if exit[0] is True:
response = requests.get(url)
response.raise_for_status()
handle = six.BytesIO(response.content)
# Identify relevant files from the ZIP file
zipfile = ZipFile(handle)
files = zipfile.infolist()
if config.get('contentdir', True):
prefix = os.path.commonprefix(zipfile.namelist())
if prefix.endswith('/'):
files = zip_prefix_filter(files, prefix)
# Extract relevant files from ZIP file
if safe_rmtree(target):
zipfile.extractall(target, files)
app_log.info('Extracted %d files into %s', len(files), target)
def schedule(conf):
'''Set up the Gramex PeriodicCallback scheduler'''
# Create tasks running on ioloop for the given schedule, store it in info.schedule
from . import scheduler
_stop_all_tasks(info.schedule)
for name, sched in conf.items():
_key = cache_key('schedule', sched)
if _key in _cache:
task = info.schedule[name] = _cache[_key]
task.call_later()
continue
try:
app_log.info('Initialising schedule:%s', name)
_cache[_key] = scheduler.Task(name, sched, info.threadpool,
ioloop=info._main_ioloop)
info.schedule[name] = _cache[_key]
except Exception as e:
app_log.exception(e)
def callback():
'''Called after all services are started. Opens browser if required'''
if ioloop_running(ioloop):
return
# If enterprise version is installed, user must accept license
try:
import gramexenterprise # noqa
gramex.license.accept()
except ImportError:
pass
app_log.info('Listening on port %d', conf.listen.port)
app_log_extra['port'] = conf.listen.port
# browser: True opens the application home page on localhost.
# browser: url opens the application to a specific URL
url = 'http://127.0.0.1:%d/' % conf.listen.port
if conf.browser:
if isinstance(conf.browser, str):
url = urlparse.urljoin(url, conf.browser)
try:
browser = webbrowser.get()
app_log.info('Opening %s in %s browser', url, browser.__class__.__name__)
browser.open(url)
except webbrowser.Error:
app_log.info('Unable to open browser')
else:
app_log.info(' opens the browser. starts the debugger.')
def close(self):
'''Stop capture.js if it has been started by this object'''
if hasattr(self, 'proc'):
try:
process = psutil.Process(self.proc.pid)
for proc in process.children(recursive=True):
proc.kill()
process.kill()
except psutil.NoSuchProcess:
app_log.info('%s PID %d already killed', self.engine.script, self.proc.pid)
pass
delattr(self, 'proc')
def summarize(transforms=[], post_transforms=[], run=True,
session_threshold=15, cutoff_buffer=0):
'''summarize'''
app_log.info('logviewer: Summarize started')
levels = DB_CONFIG['levels']
table = DB_CONFIG['table'].format
# dimensions and metrics to summarize
groups = DB_CONFIG['dimensions']
aggfuncs = DB_CONFIG['metrics']
log_file = conf.log.handlers.requests.filename
# Handle for multiple instances requests.csv$LISTENPORT
log_file = '{0}{1}'.format(*log_file.partition('.csv'))
folder = os.path.dirname(log_file)
conn = sqlite3.connect(os.path.join(folder, 'logviewer.db'))
# drop agg tables from database
if run in ['drop', 'reload']:
droptable = 'DROP TABLE IF EXISTS {}'.format
for freq in levels:
app_log.info('logviewer: Dropping {} table'.format(table(freq)))
conn.execute(droptable(table(freq)))
if name in {'sys'}:
continue
if name is None or path is None or not os.path.exists(path):
app_log.warning('Path for module %s is %s: not found', name, path)
continue
# On Python 3, __file__ points to the .py file. In Python 2, it's the .pyc file
# https://www.python.org/dev/peps/pep-3147/#file
if path.lower().endswith('.pyc'):
path = path[:-1]
if not os.path.exists(path):
app_log.warning('Path for module %s is %s: not found', name, path)
continue
# The first time, don't reload it. Thereafter, if it's older or resized, reload it
fstat = stat(path)
if fstat != _MODULE_CACHE.get(name, fstat):
app_log.info('Reloading module %s', name)
six.moves.reload_module(module)
_MODULE_CACHE[name] = fstat
started = False
# If process was never started, start it
if key not in _daemons:
started = _daemons[key] = Subprocess(args, **kwargs)
# Ensure that process is running. Restart if required
proc = _daemons[key]
restart = int(restart)
while proc.proc.returncode is not None and restart > 0:
restart -= 1
proc = started = _daemons[key] = Subprocess(args, **kwargs)
if proc.proc.returncode is not None:
raise RuntimeError('Error %d starting %s' % (proc.proc.returncode, arg_str))
if started:
app_log.info('Started: %s', arg_str)
future = Future()
# If process was started, wait until it has initialized. Else just return the proc
if first_line and started:
if isinstance(first_line, six.string_types):
def check(proc):
actual = queue.get(timeout=timeout).decode('utf-8')
if first_line not in actual:
raise AssertionError('%s: wrong first line: %s (no "%s")' %
(arg_str, actual, first_line))
elif isinstance(first_line, _regex_type):
def check(proc):
actual = queue.get(timeout=timeout).decode('utf-8')
if not first_line.search(actual):
raise AssertionError('%s: wrong first line: %s' % (arg_str, actual))
elif callable(first_line):
def run(self, *args, **kwargs):
'''Run task. Then set up next callback.'''
app_log.info('Running %s', self.name)
try:
self.result = self.function(*args, **kwargs)
finally:
# Run again, if not stopped via self.stop() or end of schedule
if self.callback is not None:
self.call_later()