_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q258600 | DeploySatchel.manifest_filename | validation | def manifest_filename(self):
"""
Returns the path to the manifest file.
"""
r = self.local_renderer
tp_fn = r.format(r.env.data_dir + '/manifest.yaml')
return tp_fn | python | {
"resource": ""
} |
q258601 | DeploySatchel.get_current_thumbprint | validation | def get_current_thumbprint(self, components=None):
"""
Returns a dictionary representing the current configuration state.
Thumbprint is of the form:
{
component_name1: {key: value},
component_name2: {key: value},
...
}
"""
components = str_to_component_list(components)
if self.verbose:
print('deploy.get_current_thumbprint.components:', components)
manifest_data = {} # {component:data}
for component_name, func in sorted(manifest_recorder.items()):
self.vprint('Checking thumbprint for component %s...' % component_name)
manifest_key = assert_valid_satchel(component_name)
service_name = clean_service_name(component_name)
if service_name not in self.genv.services:
self.vprint('Skipping unused component:', component_name)
continue
elif components and service_name not in components:
self.vprint('Skipping non-matching component:', component_name)
continue
try:
self.vprint('Retrieving manifest for %s...' % component_name)
manifest_data[manifest_key] = func()
if self.verbose:
pprint(manifest_data[manifest_key], indent=4)
except exceptions.AbortDeployment as e:
raise
return manifest_data | python | {
"resource": ""
} |
q258602 | DeploySatchel.get_previous_thumbprint | validation | def get_previous_thumbprint(self, components=None):
"""
Returns a dictionary representing the previous configuration state.
Thumbprint is of the form:
{
component_name1: {key: value},
component_name2: {key: value},
...
}
"""
components = str_to_component_list(components)
tp_fn = self.manifest_filename
tp_text = None
if self.file_exists(tp_fn):
fd = six.BytesIO()
get(tp_fn, fd)
tp_text = fd.getvalue()
manifest_data = {}
raw_data = yaml.load(tp_text)
for k, v in raw_data.items():
manifest_key = assert_valid_satchel(k)
service_name = clean_service_name(k)
if components and service_name not in components:
continue
manifest_data[manifest_key] = v
return manifest_data | python | {
"resource": ""
} |
q258603 | DeploySatchel.lock | validation | def lock(self):
"""
Marks the remote server as currently being deployed to.
"""
self.init()
r = self.local_renderer
if self.file_exists(r.env.lockfile_path):
raise exceptions.AbortDeployment('Lock file %s exists. Perhaps another deployment is currently underway?' % r.env.lockfile_path)
else:
self.vprint('Locking %s.' % r.env.lockfile_path)
r.env.hostname = socket.gethostname()
r.run_or_local('echo "{hostname}" > {lockfile_path}') | python | {
"resource": ""
} |
q258604 | DeploySatchel.unlock | validation | def unlock(self):
"""
Unmarks the remote server as currently being deployed to.
"""
self.init()
r = self.local_renderer
if self.file_exists(r.env.lockfile_path):
self.vprint('Unlocking %s.' % r.env.lockfile_path)
r.run_or_local('rm -f {lockfile_path}') | python | {
"resource": ""
} |
q258605 | DeploySatchel.fake | validation | def fake(self, components=None):#, set_satchels=None):
"""
Update the thumbprint on the remote server but execute no satchel configurators.
components = A comma-delimited list of satchel names to limit the fake deployment to.
set_satchels = A semi-colon delimited list of key-value pairs to set in satchels before recording a fake deployment.
"""
self.init()
# In cases where we only want to fake deployment of a specific satchel, then simply copy the last thumbprint and overwrite with a subset
# of the current thumbprint filtered by our target components.
if components:
current_tp = self.get_previous_thumbprint() or {}
current_tp.update(self.get_current_thumbprint(components=components) or {})
else:
current_tp = self.get_current_thumbprint(components=components) or {}
tp_text = yaml.dump(current_tp)
r = self.local_renderer
r.upload_content(content=tp_text, fn=self.manifest_filename)
# Ensure all cached manifests are cleared, so they reflect the newly deployed changes.
self.reset_all_satchels() | python | {
"resource": ""
} |
q258606 | DeploySatchel.get_component_funcs | validation | def get_component_funcs(self, components=None):
"""
Calculates the components functions that need to be executed for a deployment.
"""
current_tp = self.get_current_thumbprint(components=components) or {}
previous_tp = self.get_previous_thumbprint(components=components) or {}
if self.verbose:
print('Current thumbprint:')
pprint(current_tp, indent=4)
print('Previous thumbprint:')
pprint(previous_tp, indent=4)
differences = list(iter_dict_differences(current_tp, previous_tp))
if self.verbose:
print('Differences:')
pprint(differences, indent=4)
component_order = get_component_order([k for k, (_, _) in differences])
if self.verbose:
print('component_order:')
pprint(component_order, indent=4)
plan_funcs = list(get_deploy_funcs(component_order, current_tp, previous_tp))
return component_order, plan_funcs | python | {
"resource": ""
} |
q258607 | DeploySatchel.preview | validation | def preview(self, components=None, ask=0):
"""
Inspects differences between the last deployment and the current code state.
"""
ask = int(ask)
self.init()
component_order, plan_funcs = self.get_component_funcs(components=components)
print('\n%i changes found for host %s.\n' % (len(component_order), self.genv.host_string))
if component_order and plan_funcs:
if self.verbose:
print('These components have changed:\n')
for component in sorted(component_order):
print((' '*4)+component)
print('Deployment plan for host %s:\n' % self.genv.host_string)
for func_name, _ in plan_funcs:
print(success_str((' '*4)+func_name))
if component_order:
print()
if ask and self.genv.host_string == self.genv.hosts[-1]:
if component_order:
if not raw_input('Begin deployment? [yn] ').strip().lower().startswith('y'):
sys.exit(0)
else:
sys.exit(0) | python | {
"resource": ""
} |
q258608 | DeploySatchel.push | validation | def push(self, components=None, yes=0):
"""
Executes all satchel configurators to apply pending changes to the server.
"""
from burlap import notifier
service = self.get_satchel('service')
self.lock()
try:
yes = int(yes)
if not yes:
# If we want to confirm the deployment with the user, and we're at the first server,
# then run the preview.
if self.genv.host_string == self.genv.hosts[0]:
execute(partial(self.preview, components=components, ask=1))
notifier.notify_pre_deployment()
component_order, plan_funcs = self.get_component_funcs(components=components)
service.pre_deploy()
for func_name, plan_func in plan_funcs:
print('Executing %s...' % func_name)
plan_func()
self.fake(components=components)
service.post_deploy()
notifier.notify_post_deployment()
finally:
self.unlock() | python | {
"resource": ""
} |
q258609 | DjangoSatchel.get_settings | validation | def get_settings(self, site=None, role=None):
"""
Retrieves the Django settings dictionary.
"""
r = self.local_renderer
_stdout = sys.stdout
_stderr = sys.stderr
if not self.verbose:
sys.stdout = StringIO()
sys.stderr = StringIO()
try:
sys.path.insert(0, r.env.src_dir)
# Temporarily override SITE.
tmp_site = self.genv.SITE
if site and site.endswith('_secure'):
site = site[:-7]
site = site or self.genv.SITE or self.genv.default_site
self.set_site(site)
# Temporarily override ROLE.
tmp_role = self.genv.ROLE
if role:
self.set_role(role)
try:
# We need to explicitly delete sub-modules from sys.modules. Otherwise, reload() skips
# them and they'll continue to contain obsolete settings.
if r.env.delete_module_with_prefixes:
for name in sorted(sys.modules):
for prefix in r.env.delete_module_with_prefixes:
if name.startswith(prefix):
if self.verbose:
print('Deleting module %s prior to re-import.' % name)
del sys.modules[name]
break
for name in list(sys.modules):
for s in r.env.delete_module_containing:
if s in name:
del sys.modules[name]
break
if r.env.settings_module in sys.modules:
del sys.modules[r.env.settings_module]
#TODO:fix r.env.settings_module not loading from settings?
# print('r.genv.django_settings_module:', r.genv.django_settings_module, file=_stdout)
# print('r.genv.dj_settings_module:', r.genv.dj_settings_module, file=_stdout)
# print('r.env.settings_module:', r.env.settings_module, file=_stdout)
if 'django_settings_module' in r.genv:
r.env.settings_module = r.genv.django_settings_module
else:
r.env.settings_module = r.env.settings_module or r.genv.dj_settings_module
if self.verbose:
print('r.env.settings_module:', r.env.settings_module, r.format(r.env.settings_module))
module = import_module(r.format(r.env.settings_module))
if site:
assert site == module.SITE, 'Unable to set SITE to "%s" Instead it is set to "%s".' % (site, module.SITE)
# Works as long as settings.py doesn't also reload anything.
import imp
imp.reload(module)
except ImportError as e:
print('Warning: Could not import settings for site "%s": %s' % (site, e), file=_stdout)
traceback.print_exc(file=_stdout)
#raise # breaks *_secure pseudo sites
return
finally:
if tmp_site:
self.set_site(tmp_site)
if tmp_role:
self.set_role(tmp_role)
finally:
sys.stdout = _stdout
sys.stderr = _stderr
sys.path.remove(r.env.src_dir)
return module | python | {
"resource": ""
} |
q258610 | DjangoSatchel.createsuperuser | validation | def createsuperuser(self, username='admin', email=None, password=None, site=None):
"""
Runs the Django createsuperuser management command.
"""
r = self.local_renderer
site = site or self.genv.SITE
self.set_site_specifics(site)
options = ['--username=%s' % username]
if email:
options.append('--email=%s' % email)
if password:
options.append('--password=%s' % password)
r.env.options_str = ' '.join(options)
if self.is_local:
r.env.project_dir = r.env.local_project_dir
r.genv.SITE = r.genv.SITE or site
r.run_or_local('export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; {manage_cmd} {createsuperuser_cmd} {options_str}') | python | {
"resource": ""
} |
q258611 | DjangoSatchel.loaddata | validation | def loaddata(self, path, site=None):
"""
Runs the Dango loaddata management command.
By default, runs on only the current site.
Pass site=all to run on all sites.
"""
site = site or self.genv.SITE
r = self.local_renderer
r.env._loaddata_path = path
for _site, site_data in self.iter_sites(site=site, no_secure=True):
try:
self.set_db(site=_site)
r.env.SITE = _site
r.sudo('export SITE={SITE}; export ROLE={ROLE}; '
'cd {project_dir}; '
'{manage_cmd} loaddata {_loaddata_path}')
except KeyError:
pass | python | {
"resource": ""
} |
q258612 | DjangoSatchel.manage | validation | def manage(self, cmd, *args, **kwargs):
"""
A generic wrapper around Django's manage command.
"""
r = self.local_renderer
environs = kwargs.pop('environs', '').strip()
if environs:
environs = ' '.join('export %s=%s;' % tuple(_.split('=')) for _ in environs.split(','))
environs = ' ' + environs + ' '
r.env.cmd = cmd
r.env.SITE = r.genv.SITE or r.genv.default_site
r.env.args = ' '.join(map(str, args))
r.env.kwargs = ' '.join(
('--%s' % _k if _v in (True, 'True') else '--%s=%s' % (_k, _v))
for _k, _v in kwargs.items())
r.env.environs = environs
if self.is_local:
r.env.project_dir = r.env.local_project_dir
r.run_or_local('export SITE={SITE}; export ROLE={ROLE};{environs} cd {project_dir}; {manage_cmd} {cmd} {args} {kwargs}') | python | {
"resource": ""
} |
q258613 | DjangoSatchel.load_django_settings | validation | def load_django_settings(self):
"""
Loads Django settings for the current site and sets them so Django internals can be run.
"""
r = self.local_renderer
# Save environment variables so we can restore them later.
_env = {}
save_vars = ['ALLOW_CELERY', 'DJANGO_SETTINGS_MODULE']
for var_name in save_vars:
_env[var_name] = os.environ.get(var_name)
try:
# Allow us to import local app modules.
if r.env.local_project_dir:
sys.path.insert(0, r.env.local_project_dir)
#TODO:remove this once bug in django-celery has been fixed
os.environ['ALLOW_CELERY'] = '0'
# print('settings_module:', r.format(r.env.settings_module))
os.environ['DJANGO_SETTINGS_MODULE'] = r.format(r.env.settings_module)
# os.environ['CELERY_LOADER'] = 'django'
# os.environ['SITE'] = r.genv.SITE or r.genv.default_site
# os.environ['ROLE'] = r.genv.ROLE or r.genv.default_role
# In Django >= 1.7, fixes the error AppRegistryNotReady: Apps aren't loaded yet
# Disabling, in Django >= 1.10, throws exception:
# RuntimeError: Model class django.contrib.contenttypes.models.ContentType
# doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
# try:
# from django.core.wsgi import get_wsgi_application
# application = get_wsgi_application()
# except (ImportError, RuntimeError):
# raise
# print('Unable to get wsgi application.')
# traceback.print_exc()
# In Django >= 1.7, fixes the error AppRegistryNotReady: Apps aren't loaded yet
try:
import django
django.setup()
except AttributeError:
# This doesn't exist in Django < 1.7, so ignore it.
pass
# Load Django settings.
settings = self.get_settings()
try:
from django.contrib import staticfiles
from django.conf import settings as _settings
# get_settings() doesn't raise ImportError but returns None instead
if settings is not None:
for k, v in settings.__dict__.items():
setattr(_settings, k, v)
else:
raise ImportError
except (ImportError, RuntimeError):
print('Unable to load settings.')
traceback.print_exc()
finally:
# Restore environment variables.
for var_name, var_value in _env.items():
if var_value is None:
del os.environ[var_name]
else:
os.environ[var_name] = var_value
return settings | python | {
"resource": ""
} |
q258614 | DjangoSatchel.shell | validation | def shell(self):
"""
Opens a Django focussed Python shell.
Essentially the equivalent of running `manage.py shell`.
"""
r = self.local_renderer
if '@' in self.genv.host_string:
r.env.shell_host_string = self.genv.host_string
else:
r.env.shell_host_string = '{user}@{host_string}'
r.env.shell_default_dir = self.genv.shell_default_dir_template
r.env.shell_interactive_djshell_str = self.genv.interactive_shell_template
r.run_or_local('ssh -t -i {key_filename} {shell_host_string} "{shell_interactive_djshell_str}"') | python | {
"resource": ""
} |
q258615 | DjangoSatchel.syncdb | validation | def syncdb(self, site=None, all=0, database=None, ignore_errors=1): # pylint: disable=redefined-builtin
"""
Runs the standard Django syncdb command for one or more sites.
"""
r = self.local_renderer
ignore_errors = int(ignore_errors)
post_south = self.version_tuple >= (1, 7, 0)
use_run_syncdb = self.version_tuple >= (1, 9, 0)
# DEPRECATED: removed in Django>=1.7
r.env.db_syncdb_all_flag = '--all' if int(all) else ''
r.env.db_syncdb_database = ''
if database:
r.env.db_syncdb_database = ' --database=%s' % database
if self.is_local:
r.env.project_dir = r.env.local_project_dir
site = site or self.genv.SITE
for _site, site_data in r.iter_unique_databases(site=site):
r.env.SITE = _site
with self.settings(warn_only=ignore_errors):
if post_south:
if use_run_syncdb:
r.run_or_local(
'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '
'{manage_cmd} migrate --run-syncdb --noinput {db_syncdb_database}')
else:
# Between Django>=1.7,<1.9 we can only do a regular migrate, no true syncdb.
r.run_or_local(
'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '
'{manage_cmd} migrate --noinput {db_syncdb_database}')
else:
r.run_or_local(
'export SITE={SITE}; export ROLE={ROLE}; cd {project_dir}; '
'{manage_cmd} syncdb --noinput {db_syncdb_all_flag} {db_syncdb_database}') | python | {
"resource": ""
} |
q258616 | DjangoSatchel.manage_async | validation | def manage_async(self, command='', name='process', site=ALL, exclude_sites='', end_message='', recipients=''):
"""
Starts a Django management command in a screen.
Parameters:
command :- all arguments passed to `./manage` as a single string
site :- the site to run the command for (default is all)
Designed to be ran like:
fab <role> dj.manage_async:"some_management_command --force"
"""
exclude_sites = exclude_sites.split(':')
r = self.local_renderer
for _site, site_data in self.iter_sites(site=site, no_secure=True):
if _site in exclude_sites:
continue
r.env.SITE = _site
r.env.command = command
r.env.end_email_command = ''
r.env.recipients = recipients or ''
r.env.end_email_command = ''
if end_message:
end_message = end_message + ' for ' + _site
end_message = end_message.replace(' ', '_')
r.env.end_message = end_message
r.env.end_email_command = r.format('{manage_cmd} send_mail --subject={end_message} --recipients={recipients}')
r.env.name = name.format(**r.genv)
r.run(
'screen -dmS {name} bash -c "export SITE={SITE}; '\
'export ROLE={ROLE}; cd {project_dir}; '\
'{manage_cmd} {command} --traceback; {end_email_command}"; sleep 3;') | python | {
"resource": ""
} |
q258617 | DjangoSatchel.get_media_timestamp | validation | def get_media_timestamp(self, last_timestamp=None):
"""
Retrieves the most recent timestamp of the media in the static root.
If last_timestamp is given, retrieves the first timestamp more recent than this value.
"""
r = self.local_renderer
_latest_timestamp = -1e9999999999999999
for path in self.iter_static_paths():
path = r.env.static_root + '/' + path
self.vprint('checking timestamp of path:', path)
if not os.path.isfile(path):
continue
#print('path:', path)
_latest_timestamp = max(_latest_timestamp, get_last_modified_timestamp(path) or _latest_timestamp)
if last_timestamp is not None and _latest_timestamp > last_timestamp:
break
self.vprint('latest_timestamp:', _latest_timestamp)
return _latest_timestamp | python | {
"resource": ""
} |
q258618 | DatabaseSatchel.set_root_login | validation | def set_root_login(self, r):
"""
Looks up the root login for the given database on the given host and sets
it to environment variables.
Populates these standard variables:
db_root_password
db_root_username
"""
# Check the legacy password location.
try:
r.env.db_root_username = r.env.root_username
except AttributeError:
pass
try:
r.env.db_root_password = r.env.root_password
except AttributeError:
pass
# Check the new password location.
key = r.env.get('db_host')
if self.verbose:
print('db.set_root_login.key:', key)
print('db.set_root_logins:', r.env.root_logins)
if key in r.env.root_logins:
data = r.env.root_logins[key]
# print('data:', data)
if 'username' in data:
r.env.db_root_username = data['username']
r.genv.db_root_username = data['username']
if 'password' in data:
r.env.db_root_password = data['password']
r.genv.db_root_password = data['password']
else:
msg = 'Warning: No root login entry found for host %s in role %s.' % (r.env.get('db_host'), self.genv.get('ROLE'))
print(msg, file=sys.stderr) | python | {
"resource": ""
} |
q258619 | DatabaseSatchel.database_renderer | validation | def database_renderer(self, name=None, site=None, role=None):
"""
Renders local settings for a specific database.
"""
name = name or self.env.default_db_name
site = site or self.genv.SITE
role = role or self.genv.ROLE
key = (name, site, role)
self.vprint('checking key:', key)
if key not in self._database_renderers:
self.vprint('No cached db renderer, generating...')
if self.verbose:
print('db.name:', name)
print('db.databases:', self.env.databases)
print('db.databases[%s]:' % name, self.env.databases.get(name))
d = type(self.genv)(self.lenv)
d.update(self.get_database_defaults())
d.update(self.env.databases.get(name, {}))
d['db_name'] = name
if self.verbose:
print('db.d:')
pprint(d, indent=4)
print('db.connection_handler:', d.connection_handler)
if d.connection_handler == CONNECTION_HANDLER_DJANGO:
self.vprint('Using django handler...')
dj = self.get_satchel('dj')
if self.verbose:
print('Loading Django DB settings for site {} and role {}.'.format(site, role), file=sys.stderr)
dj.set_db(name=name, site=site, role=role)
_d = dj.local_renderer.collect_genv(include_local=True, include_global=False)
# Copy "dj_db_*" into "db_*".
for k, v in _d.items():
if k.startswith('dj_db_'):
_d[k[3:]] = v
del _d[k]
if self.verbose:
print('Loaded:')
pprint(_d)
d.update(_d)
elif d.connection_handler and d.connection_handler.startswith(CONNECTION_HANDLER_CUSTOM+':'):
_callable_str = d.connection_handler[len(CONNECTION_HANDLER_CUSTOM+':'):]
self.vprint('Using custom handler %s...' % _callable_str)
_d = str_to_callable(_callable_str)(role=self.genv.ROLE)
if self.verbose:
print('Loaded:')
pprint(_d)
d.update(_d)
r = LocalRenderer(self, lenv=d)
# Optionally set any root logins needed for administrative commands.
self.set_root_login(r)
self._database_renderers[key] = r
else:
self.vprint('Cached db renderer found.')
return self._database_renderers[key] | python | {
"resource": ""
} |
q258620 | DatabaseSatchel.get_free_space | validation | def get_free_space(self):
"""
Return free space in bytes.
"""
cmd = "df -k | grep -vE '^Filesystem|tmpfs|cdrom|none|udev|cgroup' | awk '{ print($1 \" \" $4 }'"
lines = [_ for _ in self.run(cmd).strip().split('\n') if _.startswith('/')]
assert len(lines) == 1, 'Ambiguous devices: %s' % str(lines)
device, kb = lines[0].split(' ')
free_space = int(kb) * 1024
self.vprint('free_space (bytes):', free_space)
return free_space | python | {
"resource": ""
} |
q258621 | DatabaseSatchel.load_db_set | validation | def load_db_set(self, name, r=None):
"""
Loads database parameters from a specific named set.
"""
r = r or self
db_set = r.genv.db_sets.get(name, {})
r.genv.update(db_set) | python | {
"resource": ""
} |
q258622 | DatabaseSatchel.loadable | validation | def loadable(self, src, dst):
"""
Determines if there's enough space to load the target database.
"""
from fabric import state
from fabric.task_utils import crawl
src_task = crawl(src, state.commands)
assert src_task, 'Unknown source role: %s' % src
dst_task = crawl(dst, state.commands)
assert dst_task, 'Unknown destination role: %s' % src
# Get source database size.
src_task()
env.host_string = env.hosts[0]
src_size_bytes = self.get_size()
# Get target database size, if any.
dst_task()
env.host_string = env.hosts[0]
try:
dst_size_bytes = self.get_size()
except (ValueError, TypeError):
dst_size_bytes = 0
# Get target host disk size.
free_space_bytes = self.get_free_space()
# Deduct existing database size, because we'll be deleting it.
balance_bytes = free_space_bytes + dst_size_bytes - src_size_bytes
balance_bytes_scaled, units = pretty_bytes(balance_bytes)
viable = balance_bytes >= 0
if self.verbose:
print('src_db_size:', pretty_bytes(src_size_bytes))
print('dst_db_size:', pretty_bytes(dst_size_bytes))
print('dst_free_space:', pretty_bytes(free_space_bytes))
print
if viable:
print('Viable! There will be %.02f %s of disk space left.' % (balance_bytes_scaled, units))
else:
print('Not viable! We would be %.02f %s short.' % (balance_bytes_scaled, units))
return viable | python | {
"resource": ""
} |
q258623 | RaspberryPiSatchel.assume_localhost | validation | def assume_localhost(self):
"""
Sets connection parameters to localhost, if not set already.
"""
if not self.genv.host_string:
self.genv.host_string = 'localhost'
self.genv.hosts = ['localhost']
self.genv.user = getpass.getuser() | python | {
"resource": ""
} |
q258624 | RaspberryPiSatchel.init_raspbian_disk | validation | def init_raspbian_disk(self, yes=0):
"""
Downloads the latest Raspbian image and writes it to a microSD card.
Based on the instructions from:
https://www.raspberrypi.org/documentation/installation/installing-images/linux.md
"""
self.assume_localhost()
yes = int(yes)
device_question = 'SD card present at %s? ' % self.env.sd_device
if not yes and not raw_input(device_question).lower().startswith('y'):
return
r = self.local_renderer
r.local_if_missing(
fn='{raspbian_image_zip}',
cmd='wget {raspbian_download_url} -O raspbian_lite_latest.zip')
r.lenv.img_fn = \
r.local("unzip -l {raspbian_image_zip} | sed -n 4p | awk '{{print $4}}'", capture=True) or '$IMG_FN'
r.local('echo {img_fn}')
r.local('[ ! -f {img_fn} ] && unzip {raspbian_image_zip} {img_fn} || true')
r.lenv.img_fn = r.local('readlink -f {img_fn}', capture=True)
r.local('echo {img_fn}')
with self.settings(warn_only=True):
r.sudo('[ -d "{sd_media_mount_dir}" ] && umount {sd_media_mount_dir} || true')
with self.settings(warn_only=True):
r.sudo('[ -d "{sd_media_mount_dir2}" ] && umount {sd_media_mount_dir2} || true')
r.pc('Writing the image onto the card.')
r.sudo('time dd bs=4M if={img_fn} of={sd_device}')
# Flush all writes to disk.
r.run('sync') | python | {
"resource": ""
} |
q258625 | RaspberryPiSatchel.init_ubuntu_disk | validation | def init_ubuntu_disk(self, yes=0):
"""
Downloads the latest Ubuntu image and writes it to a microSD card.
Based on the instructions from:
https://wiki.ubuntu.com/ARM/RaspberryPi
For recommended SD card brands, see:
http://elinux.org/RPi_SD_cards
Note, if you get an error like:
Kernel panic-not syncing: VFS: unable to mount root fs
that means the SD card is corrupted. Try re-imaging the card or use a different card.
"""
self.assume_localhost()
yes = int(yes)
if not self.dryrun:
device_question = 'SD card present at %s? ' % self.env.sd_device
inp = raw_input(device_question).strip()
print('inp:', inp)
if not yes and inp and not inp.lower().startswith('y'):
return
r = self.local_renderer
# Confirm SD card is present.
r.local('ls {sd_device}')
# Download image.
r.env.ubuntu_image_fn = os.path.abspath(os.path.split(self.env.ubuntu_download_url)[-1])
r.local('[ ! -f {ubuntu_image_fn} ] && wget {ubuntu_download_url} || true')
# Ensure SD card is unmounted.
with self.settings(warn_only=True):
r.sudo('[ -d "{sd_media_mount_dir}" ] && umount {sd_media_mount_dir}')
with self.settings(warn_only=True):
r.sudo('[ -d "{sd_media_mount_dir2}" ] && umount {sd_media_mount_dir2}')
r.pc('Writing the image onto the card.')
r.sudo('xzcat {ubuntu_image_fn} | dd bs=4M of={sd_device}')
# Flush all writes to disk.
r.run('sync') | python | {
"resource": ""
} |
q258626 | RaspberryPiSatchel.init_raspbian_vm | validation | def init_raspbian_vm(self):
"""
Creates an image for running Raspbian in a QEMU virtual machine.
Based on the guide at:
https://github.com/dhruvvyas90/qemu-rpi-kernel/wiki/Emulating-Jessie-image-with-4.1.x-kernel
"""
r = self.local_renderer
r.comment('Installing system packages.')
r.sudo('add-apt-repository ppa:linaro-maintainers/tools')
r.sudo('apt-get update')
r.sudo('apt-get install libsdl-dev qemu-system')
r.comment('Download image.')
r.local('wget https://downloads.raspberrypi.org/raspbian_lite_latest')
r.local('unzip raspbian_lite_latest.zip')
#TODO:fix name?
#TODO:resize image?
r.comment('Find start of the Linux ext4 partition.')
r.local(
"parted -s 2016-03-18-raspbian-jessie-lite.img unit B print | "
"awk '/^Number/{{p=1;next}}; p{{gsub(/[^[:digit:]]/, "", $2); print $2}}' | sed -n 2p", assign_to='START')
r.local('mkdir -p {raspbian_mount_point}')
r.sudo('mount -v -o offset=$START -t ext4 {raspbian_image} $MNT')
r.comment('Comment out everything in ld.so.preload')
r.local("sed -i 's/^/#/g' {raspbian_mount_point}/etc/ld.so.preload")
r.comment('Comment out entries containing /dev/mmcblk in fstab.')
r.local("sed -i '/mmcblk/ s?^?#?' /etc/fstab")
r.sudo('umount {raspbian_mount_point}')
r.comment('Download kernel.')
r.local('wget https://github.com/dhruvvyas90/qemu-rpi-kernel/blob/master/{raspbian_kernel}?raw=true')
r.local('mv {raspbian_kernel} {libvirt_images_dir}')
r.comment('Creating libvirt machine.')
r.local('virsh define libvirt-raspbian.xml')
r.comment('You should now be able to boot the VM by running:')
r.comment('')
r.comment(' qemu-system-arm -kernel {libvirt_boot_dir}/{raspbian_kernel} '
'-cpu arm1176 -m 256 -M versatilepb -serial stdio -append "root=/dev/sda2 rootfstype=ext4 rw" '
'-hda {libvirt_images_dir}/{raspbian_image}')
r.comment('')
r.comment('Or by running virt-manager.') | python | {
"resource": ""
} |
q258627 | RaspberryPiSatchel.create_raspbian_vagrant_box | validation | def create_raspbian_vagrant_box(self):
"""
Creates a box for easily spinning up a virtual machine with Vagrant.
http://unix.stackexchange.com/a/222907/16477
https://github.com/pradels/vagrant-libvirt
"""
r = self.local_renderer
r.sudo('adduser --disabled-password --gecos "" vagrant')
#vagrant user should be able to run sudo commands without a password prompt
r.sudo('echo "vagrant ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/vagrant')
r.sudo('chmod 0440 /etc/sudoers.d/vagrant')
r.sudo('apt-get update')
r.sudo('apt-get install -y openssh-server')
#put ssh key from vagrant user
r.sudo('mkdir -p /home/vagrant/.ssh')
r.sudo('chmod 0700 /home/vagrant/.ssh')
r.sudo('wget --no-check-certificate https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub -O /home/vagrant/.ssh/authorized_keys')
r.sudo('chmod 0600 /home/vagrant/.ssh/authorized_keys')
r.sudo('chown -R vagrant /home/vagrant/.ssh')
#open sudo vi /etc/ssh/sshd_config and change
#PubKeyAuthentication yes
#PermitEmptyPasswords no
r.sudo("sed -i '/AuthorizedKeysFile/s/^#//g' /etc/ssh/sshd_config")
#PasswordAuthentication no
r.sudo("sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/sshd_config")
r.sudo("sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config")
#restart ssh service using
#sudo service ssh restart
#install additional development packages for the tools to properly compile and install
r.sudo('apt-get upgrade')
r.sudo('apt-get install -y gcc build-essential')
#TODO:fix? throws dpkg: error: fgets gave an empty string from `/var/lib/dpkg/triggers/File'
#r.sudo('apt-get install -y linux-headers-rpi')
#do any change that you want and shutdown the VM . now , come to host machine on which guest VM is running and goto
#the /var/lib/libvirt/images/ and choose raw image in which you did the change and copy somewhere for example /test
r.sudo('mkdir /tmp/test')
r.sudo('cp {libvirt_images_dir}/{raspbian_image} /tmp/test')
r.sudo('cp {libvirt_boot_dir}/{raspbian_kernel} /tmp/test')
#create two file metadata.json and Vagrantfile in /test do entry in metadata.json
r.render_to_file('rpi/metadata.json', '/tmp/test/metadata.json')
r.render_to_file('rpi/Vagrantfile', '/tmp/test/Vagrantfile')
#convert test.img to qcow2 format using
r.sudo('qemu-img convert -f raw -O qcow2 {libvirt_images_dir}/{raspbian_image} {libvirt_images_dir}/{raspbian_image}.qcow2')
#rename ubuntu.qcow2 to box.img
r.sudo('mv {libvirt_images_dir}/{raspbian_image}.qcow2 {libvirt_images_dir}/box.img')
#Note: currently,libvirt-vagrant support only qcow2 format. so , don't change the format just rename to box.img.
#because it takes input with name box.img by default.
#create box
r.sudo('cd /tmp/test; tar cvzf custom_box.box ./metadata.json ./Vagrantfile ./{raspbian_kernel} ./box.img') | python | {
"resource": ""
} |
q258628 | RaspberryPiSatchel.configure_hdmi | validation | def configure_hdmi(self):
"""
Configures HDMI to support hot-plugging, so it'll work even if it wasn't
plugged in when the Pi was originally powered up.
Note, this does cause slightly higher power consumption, so if you don't need HDMI,
don't bother with this.
http://raspberrypi.stackexchange.com/a/2171/29103
"""
r = self.local_renderer
# use HDMI mode even if no HDMI monitor is detected
r.enable_attr(
filename='/boot/config.txt',
key='hdmi_force_hotplug',
value=1,
use_sudo=True,
)
# to normal HDMI mode (Sound will be sent if supported and enabled). Without this line,
# the Raspbmc would switch to DVI (with no audio) mode by default.
r.enable_attr(
filename='/boot/config.txt',
key='hdmi_drive',
value=2,
use_sudo=True,
) | python | {
"resource": ""
} |
q258629 | RaspberryPiSatchel.configure_camera | validation | def configure_camera(self):
"""
Enables access to the camera.
http://raspberrypi.stackexchange.com/questions/14229/how-can-i-enable-the-camera-without-using-raspi-config
https://mike632t.wordpress.com/2014/06/26/raspberry-pi-camera-setup/
Afterwards, test with:
/opt/vc/bin/raspistill --nopreview --output image.jpg
Check for compatibility with:
vcgencmd get_camera
which should show:
supported=1 detected=1
"""
#TODO:check per OS? Works on Raspbian Jessie
r = self.local_renderer
if self.env.camera_enabled:
r.pc('Enabling camera.')
#TODO:fix, doesn't work on Ubuntu, which uses commented-out values
# Set start_x=1
#r.sudo('if grep "start_x=0" /boot/config.txt; then sed -i "s/start_x=0/start_x=1/g" /boot/config.txt; fi')
#r.sudo('if grep "start_x" /boot/config.txt; then true; else echo "start_x=1" >> /boot/config.txt; fi')
r.enable_attr(
filename='/boot/config.txt',
key='start_x',
value=1,
use_sudo=True,
)
# Set gpu_mem=128
# r.sudo('if grep "gpu_mem" /boot/config.txt; then true; else echo "gpu_mem=128" >> /boot/config.txt; fi')
r.enable_attr(
filename='/boot/config.txt',
key='gpu_mem',
value=r.env.gpu_mem,
use_sudo=True,
)
# Compile the Raspberry Pi binaries.
#https://github.com/raspberrypi/userland
r.run('cd ~; git clone https://github.com/raspberrypi/userland.git; cd userland; ./buildme')
r.run('touch ~/.bash_aliases')
#r.run("echo 'PATH=$PATH:/opt/vc/bin\nexport PATH' >> ~/.bash_aliases")
r.append(r'PATH=$PATH:/opt/vc/bin\nexport PATH', '~/.bash_aliases')
#r.run("echo 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/vc/lib\nexport LD_LIBRARY_PATH' >> ~/.bash_aliases")
r.append(r'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/vc/lib\nexport LD_LIBRARY_PATH', '~/.bash_aliases')
r.run('source ~/.bashrc')
r.sudo('ldconfig')
# Allow our user to access the video device.
r.sudo("echo 'SUBSYSTEM==\"vchiq\",GROUP=\"video\",MODE=\"0660\"' > /etc/udev/rules.d/10-vchiq-permissions.rules")
r.sudo("usermod -a -G video {user}")
r.reboot(wait=300, timeout=60)
self.test_camera()
else:
r.disable_attr(
filename='/boot/config.txt',
key='start_x',
use_sudo=True,
)
r.disable_attr(
filename='/boot/config.txt',
key='gpu_mem',
use_sudo=True,
)
r.reboot(wait=300, timeout=60) | python | {
"resource": ""
} |
q258630 | RaspberryPiSatchel.fix_lsmod_for_pi3 | validation | def fix_lsmod_for_pi3(self):
"""
Some images purporting to support both the Pi2 and Pi3 use the wrong kernel modules.
"""
r = self.local_renderer
r.env.rpi2_conf = '/etc/modules-load.d/rpi2.conf'
r.sudo("sed '/bcm2808_rng/d' {rpi2_conf}")
r.sudo("echo bcm2835_rng >> {rpi2_conf}") | python | {
"resource": ""
} |
q258631 | ServiceManagementSatchel.pre_deploy | validation | def pre_deploy(self):
"""
Runs methods services have requested be run before each deployment.
"""
for service in self.genv.services:
service = service.strip().upper()
funcs = common.service_pre_deployers.get(service)
if funcs:
print('Running pre-deployments for service %s...' % (service,))
for func in funcs:
func() | python | {
"resource": ""
} |
q258632 | ServiceManagementSatchel.deploy | validation | def deploy(self):
"""
Applies routine, typically application-level changes to the service.
"""
for service in self.genv.services:
service = service.strip().upper()
funcs = common.service_deployers.get(service)
if funcs:
print('Deploying service %s...' % (service,))
for func in funcs:
if not self.dryrun:
func() | python | {
"resource": ""
} |
q258633 | ServiceManagementSatchel.post_deploy | validation | def post_deploy(self):
"""
Runs methods services have requested be run before after deployment.
"""
for service in self.genv.services:
service = service.strip().upper()
self.vprint('post_deploy:', service)
funcs = common.service_post_deployers.get(service)
if funcs:
self.vprint('Running post-deployments for service %s...' % (service,))
for func in funcs:
try:
func()
except Exception as e:
print('Post deployment error: %s' % e, file=sys.stderr)
print(traceback.format_exc(), file=sys.stderr) | python | {
"resource": ""
} |
q258634 | ServiceManagementSatchel.configure | validation | def configure(self):
"""
Applies one-time settings changes to the host, usually to initialize the service.
"""
print('env.services:', self.genv.services)
for service in list(self.genv.services):
service = service.strip().upper()
funcs = common.service_configurators.get(service, [])
if funcs:
print('!'*80)
print('Configuring service %s...' % (service,))
for func in funcs:
print('Function:', func)
if not self.dryrun:
func() | python | {
"resource": ""
} |
q258635 | ApacheSatchel.enable_mods | validation | def enable_mods(self):
"""
Enables all modules in the current module list.
Does not disable any currently enabled modules not in the list.
"""
r = self.local_renderer
for mod_name in r.env.mods_enabled:
with self.settings(warn_only=True):
self.enable_mod(mod_name) | python | {
"resource": ""
} |
q258636 | ApacheSatchel.optimize_wsgi_processes | validation | def optimize_wsgi_processes(self):
"""
Based on the number of sites per server and the number of resources on the server,
calculates the optimal number of processes that should be allocated for each WSGI site.
"""
r = self.local_renderer
#r.env.wsgi_processes = 5
r.env.wsgi_server_memory_gb = 8
verbose = self.verbose
all_sites = list(self.iter_sites(site=ALL, setter=self.set_site_specifics)) | python | {
"resource": ""
} |
q258637 | ApacheSatchel.create_local_renderer | validation | def create_local_renderer(self):
"""
Instantiates a new local renderer.
Override this to do any additional initialization.
"""
r = super(ApacheSatchel, self).create_local_renderer()
# Dynamically set values based on target operating system.
os_version = self.os_version
apache_specifics = r.env.specifics[os_version.type][os_version.distro]
r.env.update(apache_specifics)
return r | python | {
"resource": ""
} |
q258638 | ApacheSatchel.install_auth_basic_user_file | validation | def install_auth_basic_user_file(self, site=None):
"""
Installs users for basic httpd auth.
"""
r = self.local_renderer
hostname = self.current_hostname
target_sites = self.genv.available_sites_by_host.get(hostname, None)
for _site, site_data in self.iter_sites(site=site, setter=self.set_site_specifics):
if self.verbose:
print('~'*80, file=sys.stderr)
print('Site:', _site, file=sys.stderr)
print('env.apache_auth_basic:', r.env.auth_basic, file=sys.stderr)
# Only load site configurations that are allowed for this host.
if target_sites is not None:
assert isinstance(target_sites, (tuple, list))
if _site not in target_sites:
continue
if not r.env.auth_basic:
continue
assert r.env.auth_basic_users, 'No apache auth users specified.'
for username, password in r.env.auth_basic_users:
r.env.auth_basic_username = username
r.env.auth_basic_password = password
r.env.apache_site = _site
r.env.fn = r.format(r.env.auth_basic_authuserfile)
if self.files.exists(r.env.fn):
r.sudo('htpasswd -b {fn} {auth_basic_username} {auth_basic_password}')
else:
r.sudo('htpasswd -b -c {fn} {auth_basic_username} {auth_basic_password}') | python | {
"resource": ""
} |
q258639 | ApacheSatchel.sync_media | validation | def sync_media(self, sync_set=None, clean=0, iter_local_paths=0):
"""
Uploads select media to an Apache accessible directory.
"""
# Ensure a site is selected.
self.genv.SITE = self.genv.SITE or self.genv.default_site
r = self.local_renderer
clean = int(clean)
self.vprint('Getting site data for %s...' % self.genv.SITE)
self.set_site_specifics(self.genv.SITE)
sync_sets = r.env.sync_sets
if sync_set:
sync_sets = [sync_set]
ret_paths = []
for _sync_set in sync_sets:
for paths in r.env.sync_sets[_sync_set]:
r.env.sync_local_path = os.path.abspath(paths['local_path'] % self.genv)
if paths['local_path'].endswith('/') and not r.env.sync_local_path.endswith('/'):
r.env.sync_local_path += '/'
if iter_local_paths:
ret_paths.append(r.env.sync_local_path)
continue
r.env.sync_remote_path = paths['remote_path'] % self.genv
if clean:
r.sudo('rm -Rf {apache_sync_remote_path}')
print('Syncing %s to %s...' % (r.env.sync_local_path, r.env.sync_remote_path))
r.env.tmp_chmod = paths.get('chmod', r.env.chmod)
r.sudo('mkdir -p {apache_sync_remote_path}')
r.sudo('chmod -R {apache_tmp_chmod} {apache_sync_remote_path}')
r.local('rsync -rvz --progress --recursive --no-p --no-g '
'--rsh "ssh -o StrictHostKeyChecking=no -i {key_filename}" {apache_sync_local_path} {user}@{host_string}:{apache_sync_remote_path}')
r.sudo('chown -R {apache_web_user}:{apache_web_group} {apache_sync_remote_path}')
if iter_local_paths:
return ret_paths | python | {
"resource": ""
} |
q258640 | ApacheSatchel.configure_modevasive | validation | def configure_modevasive(self):
"""
Installs the mod-evasive Apache module for combating DDOS attacks.
https://www.linode.com/docs/websites/apache-tips-and-tricks/modevasive-on-apache
"""
r = self.local_renderer
if r.env.modevasive_enabled:
self.install_packages()
# Write conf for each Ubuntu version since they don't conflict.
fn = r.render_to_file('apache/apache_modevasive.template.conf')
# Ubuntu 12.04
r.put(
local_path=fn,
remote_path='/etc/apache2/mods-available/mod-evasive.conf',
use_sudo=True)
# Ubuntu 14.04
r.put(
local_path=fn,
remote_path='/etc/apache2/mods-available/evasive.conf',
use_sudo=True)
self.enable_mod('evasive')
else:
# print('self.last_manifest:', self.last_manifest)
# print('a:', self.last_manifest.apache_modevasive_enabled)
# print('b:', self.last_manifest.modevasive_enabled)
if self.last_manifest.modevasive_enabled:
self.disable_mod('evasive') | python | {
"resource": ""
} |
q258641 | ApacheSatchel.configure_modsecurity | validation | def configure_modsecurity(self):
"""
Installs the mod-security Apache module.
https://www.modsecurity.org
"""
r = self.local_renderer
if r.env.modsecurity_enabled and not self.last_manifest.modsecurity_enabled:
self.install_packages()
# Write modsecurity.conf.
fn = self.render_to_file('apache/apache_modsecurity.template.conf')
r.put(local_path=fn, remote_path='/etc/modsecurity/modsecurity.conf', use_sudo=True)
# Write OWASP rules.
r.env.modsecurity_download_filename = '/tmp/owasp-modsecurity-crs.tar.gz'
r.sudo('cd /tmp; wget --output-document={apache_modsecurity_download_filename} {apache_modsecurity_download_url}')
r.env.modsecurity_download_top = r.sudo(
"cd /tmp; "
"tar tzf %(apache_modsecurity_download_filename)s | sed -e 's@/.*@@' | uniq" % self.genv)
r.sudo('cd /tmp; tar -zxvf %(apache_modsecurity_download_filename)s' % self.genv)
r.sudo('cd /tmp; cp -R %(apache_modsecurity_download_top)s/* /etc/modsecurity/' % self.genv)
r.sudo('mv /etc/modsecurity/modsecurity_crs_10_setup.conf.example /etc/modsecurity/modsecurity_crs_10_setup.conf')
r.sudo('rm -f /etc/modsecurity/activated_rules/*')
r.sudo('cd /etc/modsecurity/base_rules; '
'for f in * ; do ln -s /etc/modsecurity/base_rules/$f /etc/modsecurity/activated_rules/$f ; done')
r.sudo('cd /etc/modsecurity/optional_rules; '
'for f in * ; do ln -s /etc/modsecurity/optional_rules/$f /etc/modsecurity/activated_rules/$f ; done')
r.env.httpd_conf_append.append('Include "/etc/modsecurity/activated_rules/*.conf"')
self.enable_mod('evasive')
self.enable_mod('headers')
elif not self.env.modsecurity_enabled and self.last_manifest.modsecurity_enabled:
self.disable_mod('modsecurity') | python | {
"resource": ""
} |
q258642 | ApacheSatchel.configure_modrpaf | validation | def configure_modrpaf(self):
"""
Installs the mod-rpaf Apache module.
https://github.com/gnif/mod_rpaf
"""
r = self.local_renderer
if r.env.modrpaf_enabled:
self.install_packages()
self.enable_mod('rpaf')
else:
if self.last_manifest.modrpaf_enabled:
self.disable_mod('mod_rpaf') | python | {
"resource": ""
} |
q258643 | ApacheSatchel.maint_up | validation | def maint_up(self):
"""
Forwards all traffic to a page saying the server is down for maintenance.
"""
r = self.local_renderer
fn = self.render_to_file(r.env.maintenance_template, extra={'current_hostname': self.current_hostname})
r.put(local_path=fn, remote_path=r.env.maintenance_path, use_sudo=True)
r.sudo('chown -R {apache_web_user}:{apache_web_group} {maintenance_path}') | python | {
"resource": ""
} |
q258644 | SupervisorSatchel.restart | validation | def restart(self):
"""
Supervisor can take a very long time to start and stop,
so wait for it.
"""
n = 60
sleep_n = int(self.env.max_restart_wait_minutes/10.*60)
for _ in xrange(n):
self.stop()
if self.dryrun or not self.is_running():
break
print('Waiting for supervisor to stop (%i of %i)...' % (_, n))
time.sleep(sleep_n)
self.start()
for _ in xrange(n):
if self.dryrun or self.is_running():
return
print('Waiting for supervisor to start (%i of %i)...' % (_, n))
time.sleep(sleep_n)
raise Exception('Failed to restart service %s!' % self.name) | python | {
"resource": ""
} |
q258645 | SupervisorSatchel.deploy_services | validation | def deploy_services(self, site=None):
"""
Collects the configurations for all registered services and writes
the appropriate supervisord.conf file.
"""
verbose = self.verbose
r = self.local_renderer
if not r.env.manage_configs:
return
#
# target_sites = self.genv.available_sites_by_host.get(hostname, None)
self.render_paths()
supervisor_services = []
if r.env.purge_all_confs:
r.sudo('rm -Rf /etc/supervisor/conf.d/*')
#TODO:check available_sites_by_host and remove dead?
self.write_configs(site=site)
for _site, site_data in self.iter_sites(site=site, renderer=self.render_paths):
if verbose:
print('deploy_services.site:', _site)
# Only load site configurations that are allowed for this host.
# if target_sites is not None:
# assert isinstance(target_sites, (tuple, list))
# if site not in target_sites:
# continue
for cb in self.genv._supervisor_create_service_callbacks:
if self.verbose:
print('cb:', cb)
ret = cb(site=_site)
if self.verbose:
print('ret:', ret)
if isinstance(ret, six.string_types):
supervisor_services.append(ret)
elif isinstance(ret, tuple):
assert len(ret) == 2
conf_name, conf_content = ret
if self.dryrun:
print('supervisor conf filename:', conf_name)
print(conf_content)
self.write_to_file(conf_content)
self.env.services_rendered = '\n'.join(supervisor_services)
fn = self.render_to_file(self.env.config_template)
r.put(local_path=fn, remote_path=self.env.config_path, use_sudo=True)
# We use supervisorctl to configure supervisor, but this will throw a uselessly vague
# error message is supervisor isn't running.
if not self.is_running():
self.start()
# Reload config and then add and remove as necessary (restarts programs)
r.sudo('supervisorctl update') | python | {
"resource": ""
} |
q258646 | GitSatchel.clone | validation | def clone(self, remote_url, path=None, use_sudo=False, user=None):
"""
Clone a remote Git repository into a new directory.
:param remote_url: URL of the remote repository to clone.
:type remote_url: str
:param path: Path of the working copy directory. Must not exist yet.
:type path: str
:param use_sudo: If ``True`` execute ``git`` with
:func:`fabric.operations.sudo`, else with
:func:`fabric.operations.run`.
:type use_sudo: bool
:param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`
with the given user. If ``use_sudo is False`` this parameter
has no effect.
:type user: str
"""
cmd = 'git clone --quiet %s' % remote_url
if path is not None:
cmd = cmd + ' %s' % path
if use_sudo and user is None:
run_as_root(cmd)
elif use_sudo:
sudo(cmd, user=user)
else:
run(cmd) | python | {
"resource": ""
} |
q258647 | GitSatchel.add_remote | validation | def add_remote(self, path, name, remote_url, use_sudo=False, user=None, fetch=True):
"""
Add a remote Git repository into a directory.
:param path: Path of the working copy directory. This directory must exist
and be a Git working copy with a default remote to fetch from.
:type path: str
:param use_sudo: If ``True`` execute ``git`` with
:func:`fabric.operations.sudo`, else with
:func:`fabric.operations.run`.
:type use_sudo: bool
:param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`
with the given user. If ``use_sudo is False`` this parameter
has no effect.
:type user: str
:param name: name for the remote repository
:type name: str
:param remote_url: URL of the remote repository
:type remote_url: str
:param fetch: If ``True`` execute ``git remote add -f``
:type fetch: bool
"""
if path is None:
raise ValueError("Path to the working copy is needed to add a remote")
if fetch:
cmd = 'git remote add -f %s %s' % (name, remote_url)
else:
cmd = 'git remote add %s %s' % (name, remote_url)
with cd(path):
if use_sudo and user is None:
run_as_root(cmd)
elif use_sudo:
sudo(cmd, user=user)
else:
run(cmd) | python | {
"resource": ""
} |
q258648 | GitSatchel.fetch | validation | def fetch(self, path, use_sudo=False, user=None, remote=None):
"""
Fetch changes from the default remote repository.
This will fetch new changesets, but will not update the contents of
the working tree unless yo do a merge or rebase.
:param path: Path of the working copy directory. This directory must exist
and be a Git working copy with a default remote to fetch from.
:type path: str
:param use_sudo: If ``True`` execute ``git`` with
:func:`fabric.operations.sudo`, else with
:func:`fabric.operations.run`.
:type use_sudo: bool
:param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`
with the given user. If ``use_sudo is False`` this parameter
has no effect.
:type user: str
:type remote: Fetch this remote or default remote if is None
:type remote: str
"""
if path is None:
raise ValueError("Path to the working copy is needed to fetch from a remote repository.")
if remote is not None:
cmd = 'git fetch %s' % remote
else:
cmd = 'git fetch'
with cd(path):
if use_sudo and user is None:
run_as_root(cmd)
elif use_sudo:
sudo(cmd, user=user)
else:
run(cmd) | python | {
"resource": ""
} |
q258649 | GitSatchel.pull | validation | def pull(self, path, use_sudo=False, user=None, force=False):
"""
Fetch changes from the default remote repository and merge them.
:param path: Path of the working copy directory. This directory must exist
and be a Git working copy with a default remote to pull from.
:type path: str
:param use_sudo: If ``True`` execute ``git`` with
:func:`fabric.operations.sudo`, else with
:func:`fabric.operations.run`.
:type use_sudo: bool
:param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`
with the given user. If ``use_sudo is False`` this parameter
has no effect.
:type user: str
:param force: If ``True``, append the ``--force`` option to the command.
:type force: bool
"""
if path is None:
raise ValueError("Path to the working copy is needed to pull from a remote repository.")
options = []
if force:
options.append('--force')
options = ' '.join(options)
cmd = 'git pull %s' % options
with cd(path):
if use_sudo and user is None:
run_as_root(cmd)
elif use_sudo:
sudo(cmd, user=user)
else:
run(cmd) | python | {
"resource": ""
} |
q258650 | GitTrackerSatchel.get_logs_between_commits | validation | def get_logs_between_commits(self, a, b):
"""
Retrieves all commit messages for all commits between the given commit numbers
on the current branch.
"""
print('REAL')
ret = self.local('git --no-pager log --pretty=oneline %s...%s' % (a, b), capture=True)
if self.verbose:
print(ret)
return str(ret) | python | {
"resource": ""
} |
q258651 | GitTrackerSatchel.get_current_commit | validation | def get_current_commit(self):
"""
Retrieves the git commit number of the current head branch.
"""
with hide('running', 'stdout', 'stderr', 'warnings'):
s = str(self.local('git rev-parse HEAD', capture=True))
self.vprint('current commit:', s)
return s | python | {
"resource": ""
} |
q258652 | VagrantSatchel.ssh_config | validation | def ssh_config(self, name=''):
"""
Get the SSH parameters for connecting to a vagrant VM.
"""
r = self.local_renderer
with self.settings(hide('running')):
output = r.local('vagrant ssh-config %s' % name, capture=True)
config = {}
for line in output.splitlines()[1:]:
key, value = line.strip().split(' ', 2)
config[key] = value
return config | python | {
"resource": ""
} |
q258653 | VagrantSatchel.version | validation | def version(self):
"""
Get the Vagrant version.
"""
r = self.local_renderer
with self.settings(hide('running', 'warnings'), warn_only=True):
res = r.local('vagrant --version', capture=True)
if res.failed:
return None
line = res.splitlines()[-1]
version = re.match(r'Vagrant (?:v(?:ersion )?)?(.*)', line).group(1)
return tuple(_to_int(part) for part in version.split('.')) | python | {
"resource": ""
} |
q258654 | VagrantSatchel.vagrant | validation | def vagrant(self, name=''):
"""
Run the following tasks on a vagrant box.
First, you need to import this task in your ``fabfile.py``::
from fabric.api import *
from burlap.vagrant import vagrant
@task
def some_task():
run('echo hello')
Then you can easily run tasks on your current Vagrant box::
$ fab vagrant some_task
"""
r = self.local_renderer
config = self.ssh_config(name)
extra_args = self._settings_dict(config)
r.genv.update(extra_args) | python | {
"resource": ""
} |
q258655 | VagrantSatchel.vagrant_settings | validation | def vagrant_settings(self, name='', *args, **kwargs):
"""
Context manager that sets a vagrant VM
as the remote host.
Use this context manager inside a task to run commands
on your current Vagrant box::
from burlap.vagrant import vagrant_settings
with vagrant_settings():
run('hostname')
"""
config = self.ssh_config(name)
extra_args = self._settings_dict(config)
kwargs.update(extra_args)
return self.settings(*args, **kwargs) | python | {
"resource": ""
} |
q258656 | VagrantSatchel.base_boxes | validation | def base_boxes(self):
"""
Get the list of vagrant base boxes
"""
return sorted(list(set([name for name, provider in self._box_list()]))) | python | {
"resource": ""
} |
q258657 | VagrantSatchel.install_from_upstream | validation | def install_from_upstream(self):
"""
Installs Vagrant from the most recent package available from their homepage.
"""
from burlap.system import get_arch, distrib_family
r = self.local_renderer
content = urlopen(r.env.download_url).read()
print(len(content))
matches = DOWNLOAD_LINK_PATTERN.findall(content)
print(matches)
arch = get_arch() # e.g. 'x86_64'
family = distrib_family()
if family == DEBIAN:
ext = '.deb'
matches = [match for match in matches if match.endswith(ext) and arch in match]
print('matches:', matches)
assert matches, "No matches found."
assert len(matches) == 1, "Too many matches found: %s" % (', '.join(matches))
r.env.final_download_url = matches[0]
r.env.local_filename = '/tmp/vagrant%s' % ext
r.run('wget -O {local_filename} {final_download_url}')
r.sudo('dpkg -i {local_filename}')
else:
raise NotImplementedError('Unsupported family: %s' % family) | python | {
"resource": ""
} |
q258658 | distrib_id | validation | def distrib_id():
"""
Get the OS distribution ID.
Example::
from burlap.system import distrib_id
if distrib_id() != 'Debian':
abort(u"Distribution is not supported")
"""
with settings(hide('running', 'stdout')):
kernel = (run('uname -s') or '').strip().lower()
if kernel == LINUX:
# lsb_release works on Ubuntu and Debian >= 6.0
# but is not always included in other distros
if is_file('/usr/bin/lsb_release'):
id_ = run('lsb_release --id --short').strip().lower()
if id in ['arch', 'archlinux']: # old IDs used before lsb-release 1.4-14
id_ = ARCH
return id_
else:
if is_file('/etc/debian_version'):
return DEBIAN
elif is_file('/etc/fedora-release'):
return FEDORA
elif is_file('/etc/arch-release'):
return ARCH
elif is_file('/etc/redhat-release'):
release = run('cat /etc/redhat-release')
if release.startswith('Red Hat Enterprise Linux'):
return REDHAT
elif release.startswith('CentOS'):
return CENTOS
elif release.startswith('Scientific Linux'):
return SLES
elif is_file('/etc/gentoo-release'):
return GENTOO
elif kernel == SUNOS:
return SUNOS | python | {
"resource": ""
} |
q258659 | distrib_release | validation | def distrib_release():
"""
Get the release number of the distribution.
Example::
from burlap.system import distrib_id, distrib_release
if distrib_id() == 'CentOS' and distrib_release() == '6.1':
print(u"CentOS 6.2 has been released. Please upgrade.")
"""
with settings(hide('running', 'stdout')):
kernel = (run('uname -s') or '').strip().lower()
if kernel == LINUX:
return run('lsb_release -r --short')
elif kernel == SUNOS:
return run('uname -v') | python | {
"resource": ""
} |
q258660 | distrib_family | validation | def distrib_family():
"""
Get the distribution family.
Returns one of ``debian``, ``redhat``, ``arch``, ``gentoo``,
``sun``, ``other``.
"""
distrib = (distrib_id() or '').lower()
if distrib in ['debian', 'ubuntu', 'linuxmint', 'elementary os']:
return DEBIAN
elif distrib in ['redhat', 'rhel', 'centos', 'sles', 'fedora']:
return REDHAT
elif distrib in ['sunos']:
return SUN
elif distrib in ['gentoo']:
return GENTOO
elif distrib in ['arch', 'manjarolinux']:
return ARCH
return 'other' | python | {
"resource": ""
} |
q258661 | supported_locales | validation | def supported_locales():
"""
Gets the list of supported locales.
Each locale is returned as a ``(locale, charset)`` tuple.
"""
family = distrib_family()
if family == 'debian':
return _parse_locales('/usr/share/i18n/SUPPORTED')
elif family == 'arch':
return _parse_locales('/etc/locale.gen')
elif family == 'redhat':
return _supported_locales_redhat()
else:
raise UnsupportedFamily(supported=['debian', 'arch', 'redhat']) | python | {
"resource": ""
} |
q258662 | CelerySatchel.force_stop | validation | def force_stop(self):
"""
Forcibly terminates all Celery processes.
"""
r = self.local_renderer
with self.settings(warn_only=True):
r.sudo('pkill -9 -f celery')
r.sudo('rm -f /tmp/celery*.pid') | python | {
"resource": ""
} |
q258663 | CelerySatchel.set_permissions | validation | def set_permissions(self):
"""
Sets ownership and permissions for Celery-related files.
"""
r = self.local_renderer
for path in r.env.paths_owned:
r.env.path_owned = path
r.sudo('chown {celery_daemon_user}:{celery_daemon_user} {celery_path_owned}') | python | {
"resource": ""
} |
q258664 | CelerySatchel.create_supervisor_services | validation | def create_supervisor_services(self, site):
"""
This is called for each site to render a Celery config file.
"""
self.vprint('create_supervisor_services:', site)
self.set_site_specifics(site=site)
r = self.local_renderer
if self.verbose:
print('r.env:')
pprint(r.env, indent=4)
self.vprint('r.env.has_worker:', r.env.has_worker)
if not r.env.has_worker:
self.vprint('skipping: no celery worker')
return
if self.name.lower() not in self.genv.services:
self.vprint('skipping: celery not enabled')
return
hostname = self.current_hostname
target_sites = self.genv.available_sites_by_host.get(hostname, None)
if target_sites and site not in target_sites:
self.vprint('skipping: site not supported on this server')
return
self.render_paths()
conf_name = 'celery_%s.conf' % site
ret = r.render_to_string('celery/celery_supervisor.template.conf')
return conf_name, ret | python | {
"resource": ""
} |
q258665 | BuildBotSatchel.check_ok | validation | def check_ok(self):
"""
Ensures all tests have passed for this branch.
This should be called before deployment, to prevent accidental deployment of code
that hasn't passed automated testing.
"""
import requests
if not self.env.check_ok:
return
# Find current git branch.
branch_name = self._local('git rev-parse --abbrev-ref HEAD', capture=True).strip()
check_ok_paths = self.env.check_ok_paths or {}
if branch_name in check_ok_paths:
check = check_ok_paths[branch_name]
if 'username' in check:
auth = (check['username'], check['password'])
else:
auth = None
ret = requests.get(check['url'], auth=auth)
passed = check['text'] in ret.content
assert passed, 'Check failed: %s' % check['url'] | python | {
"resource": ""
} |
q258666 | HostSatchel.is_present | validation | def is_present(self, host=None):
"""
Returns true if the given host exists on the network.
Returns false otherwise.
"""
r = self.local_renderer
r.env.host = host or self.genv.host_string
ret = r._local("getent hosts {host} | awk '{{ print $1 }}'", capture=True) or ''
if self.verbose:
print('ret:', ret)
ret = ret.strip()
if self.verbose:
print('Host %s %s present.' % (r.env.host, 'IS' if bool(ret) else 'IS NOT'))
ip = ret
ret = bool(ret)
if not ret:
return False
r.env.ip = ip
with settings(warn_only=True):
ret = r._local('ping -c 1 {ip}', capture=True) or ''
packet_loss = re.findall(r'([0-9]+)% packet loss', ret)
# print('packet_loss:',packet_loss)
ip_accessible = packet_loss and int(packet_loss[0]) < 100
if self.verbose:
print('IP %s accessible: %s' % (ip, ip_accessible))
return bool(ip_accessible) | python | {
"resource": ""
} |
q258667 | HostSatchel.purge_keys | validation | def purge_keys(self):
"""
Deletes all SSH keys on the localhost associated with the current remote host.
"""
r = self.local_renderer
r.env.default_ip = self.hostname_to_ip(self.env.default_hostname)
r.env.home_dir = '/home/%s' % getpass.getuser()
r.local('ssh-keygen -f "{home_dir}/.ssh/known_hosts" -R {host_string}')
if self.env.default_hostname:
r.local('ssh-keygen -f "{home_dir}/.ssh/known_hosts" -R {default_hostname}')
if r.env.default_ip:
r.local('ssh-keygen -f "{home_dir}/.ssh/known_hosts" -R {default_ip}') | python | {
"resource": ""
} |
q258668 | HostSatchel.find_working_password | validation | def find_working_password(self, usernames=None, host_strings=None):
"""
Returns the first working combination of username and password for the current host.
"""
r = self.local_renderer
if host_strings is None:
host_strings = []
if not host_strings:
host_strings.append(self.genv.host_string)
if usernames is None:
usernames = []
if not usernames:
usernames.append(self.genv.user)
for host_string in host_strings:
for username in usernames:
passwords = []
passwords.append(self.genv.user_default_passwords[username])
passwords.append(self.genv.user_passwords[username])
passwords.append(self.env.default_password)
for password in passwords:
with settings(warn_only=True):
r.env.host_string = host_string
r.env.password = password
r.env.user = username
ret = r._local("sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello", capture=True)
#print('ret.return_code:', ret.return_code)
# print('ret000:[%s]' % ret)
#code 1 = good password, but prompts needed
#code 5 = bad password
#code 6 = good password, but host public key is unknown
if ret.return_code in (1, 6) or 'hello' in ret:
# Login succeeded, so we haven't yet changed the password, so use the default password.
return host_string, username, password
raise Exception('No working login found.') | python | {
"resource": ""
} |
q258669 | HostSatchel.needs_initrole | validation | def needs_initrole(self, stop_on_error=False):
"""
Returns true if the host does not exist at the expected location and may need
to have its initial configuration set.
Returns false if the host exists at the expected location.
"""
ret = False
target_host_present = self.is_present()
if not target_host_present:
default_host_present = self.is_present(self.env.default_hostname)
if default_host_present:
if self.verbose:
print('Target host missing and default host present so host init required.')
ret = True
else:
if self.verbose:
print('Target host missing but default host also missing, '
'so no host init required.')
# if stop_on_error:
# raise Exception(
# 'Both target and default hosts missing! '
# 'Is the machine turned on and plugged into the network?')
else:
if self.verbose:
print('Target host is present so no host init required.')
return ret | python | {
"resource": ""
} |
q258670 | HostSatchel.initrole | validation | def initrole(self, check=True):
"""
Called to set default password login for systems that do not yet have passwordless
login setup.
"""
if self.env.original_user is None:
self.env.original_user = self.genv.user
if self.env.original_key_filename is None:
self.env.original_key_filename = self.genv.key_filename
host_string = None
user = None
password = None
if self.env.login_check:
host_string, user, password = self.find_working_password(
usernames=[self.genv.user, self.env.default_user],
host_strings=[self.genv.host_string, self.env.default_hostname],
)
if self.verbose:
print('host.initrole.host_string:', host_string)
print('host.initrole.user:', user)
print('host.initrole.password:', password)
# needs = True
# if check:
# needs = self.needs_initrole(stop_on_error=True)
needs = False
if host_string is not None:
self.genv.host_string = host_string
if user is not None:
self.genv.user = user
if password is not None:
self.genv.password = password
if not needs:
return
assert self.env.default_hostname, 'No default hostname set.'
assert self.env.default_user, 'No default user set.'
self.genv.host_string = self.env.default_hostname
if self.env.default_hosts:
self.genv.hosts = self.env.default_hosts
else:
self.genv.hosts = [self.env.default_hostname]
self.genv.user = self.env.default_user
self.genv.password = self.env.default_password
self.genv.key_filename = self.env.default_key_filename
# If the host has been reformatted, the SSH keys will mismatch, throwing an error, so clear them.
self.purge_keys()
# Do a test login with the default password to determine which password we should use.
# r.env.password = self.env.default_password
# with settings(warn_only=True):
# ret = r._local("sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello", capture=True)
# print('ret.return_code:', ret.return_code)
# # print('ret000:[%s]' % ret)
# #code 1 = good password, but prompts needed
# #code 5 = bad password
# #code 6 = good password, but host public key is unknown
# if ret.return_code in (1, 6) or 'hello' in ret:
# # Login succeeded, so we haven't yet changed the password, so use the default password.
# self.genv.password = self.env.default_password
# elif self.genv.user in self.genv.user_passwords:
# # Otherwise, use the password or key set in the config.
# self.genv.password = self.genv.user_passwords[self.genv.user]
# else:
# # Default password fails and there's no current password, so clear.
# self.genv.password = None
# self.genv.password = self.find_working_password()
# print('host.initrole,using password:', self.genv.password)
# Execute post-init callbacks.
for task_name in self.env.post_initrole_tasks:
if self.verbose:
print('Calling post initrole task %s' % task_name)
satchel_name, method_name = task_name.split('.')
satchel = self.get_satchel(name=satchel_name)
getattr(satchel, method_name)()
print('^'*80)
print('host.initrole.host_string:', self.genv.host_string)
print('host.initrole.user:', self.genv.user)
print('host.initrole.password:', self.genv.password) | python | {
"resource": ""
} |
q258671 | HostnameSatchel.get_public_ip | validation | def get_public_ip(self):
"""
Gets the public IP for a host.
"""
r = self.local_renderer
ret = r.run(r.env.get_public_ip_command) or ''
ret = ret.strip()
print('ip:', ret)
return ret | python | {
"resource": ""
} |
q258672 | HostnameSatchel.configure | validation | def configure(self, reboot=1):
"""
Assigns a name to the server accessible from user space.
Note, we add the name to /etc/hosts since not all programs use
/etc/hostname to reliably identify the server hostname.
"""
r = self.local_renderer
for ip, hostname in self.iter_hostnames():
self.vprint('ip/hostname:', ip, hostname)
r.genv.host_string = ip
r.env.hostname = hostname
with settings(warn_only=True):
r.sudo('echo "{hostname}" > /etc/hostname')
r.sudo('echo "127.0.0.1 {hostname}" | cat - /etc/hosts > /tmp/out && mv /tmp/out /etc/hosts')
r.sudo(r.env.set_hostname_command)
if r.env.auto_reboot and int(reboot):
r.reboot() | python | {
"resource": ""
} |
q258673 | partitions | validation | def partitions(device=""):
"""
Get a partition list for all disk or for selected device only
Example::
from burlap.disk import partitions
spart = {'Linux': 0x83, 'Swap': 0x82}
parts = partitions()
# parts = {'/dev/sda1': 131, '/dev/sda2': 130, '/dev/sda3': 131}
r = parts['/dev/sda1'] == spart['Linux']
r = r and parts['/dev/sda2'] == spart['Swap']
if r:
print("You can format these partitions")
"""
partitions_list = {}
with settings(hide('running', 'stdout')):
res = run_as_root('sfdisk -d %(device)s' % locals())
spart = re.compile(r'(?P<pname>^/.*) : .* Id=(?P<ptypeid>[0-9a-z]+)')
for line in res.splitlines():
m = spart.search(line)
if m:
partitions_list[m.group('pname')] = int(m.group('ptypeid'), 16)
return partitions_list | python | {
"resource": ""
} |
q258674 | getdevice_by_uuid | validation | def getdevice_by_uuid(uuid):
"""
Get a HDD device by uuid
Example::
from burlap.disk import getdevice_by_uuid
device = getdevice_by_uuid("356fafdc-21d5-408e-a3e9-2b3f32cb2a8c")
if device:
mount(device,'/mountpoint')
"""
with settings(hide('running', 'warnings', 'stdout'), warn_only=True):
res = run_as_root('blkid -U %s' % uuid)
if not res.succeeded:
return None
return res | python | {
"resource": ""
} |
q258675 | ismounted | validation | def ismounted(device):
"""
Check if partition is mounted
Example::
from burlap.disk import ismounted
if ismounted('/dev/sda1'):
print ("disk sda1 is mounted")
"""
# Check filesystem
with settings(hide('running', 'stdout')):
res = run_as_root('mount')
for line in res.splitlines():
fields = line.split()
if fields[0] == device:
return True
# Check swap
with settings(hide('running', 'stdout')):
res = run_as_root('swapon -s')
for line in res.splitlines():
fields = line.split()
if fields[0] == device:
return True
return False | python | {
"resource": ""
} |
q258676 | query | validation | def query(query, use_sudo=True, **kwargs):
"""
Run a MySQL query.
"""
func = use_sudo and run_as_root or run
user = kwargs.get('mysql_user') or env.get('mysql_user')
password = kwargs.get('mysql_password') or env.get('mysql_password')
options = [
'--batch',
'--raw',
'--skip-column-names',
]
if user:
options.append('--user=%s' % quote(user))
if password:
options.append('--password=%s' % quote(password))
options = ' '.join(options)
return func('mysql %(options)s --execute=%(query)s' % {
'options': options,
'query': quote(query),
}) | python | {
"resource": ""
} |
q258677 | create_user | validation | def create_user(name, password, host='localhost', **kwargs):
"""
Create a MySQL user.
Example::
import burlap
# Create DB user if it does not exist
if not burlap.mysql.user_exists('dbuser'):
burlap.mysql.create_user('dbuser', password='somerandomstring')
"""
with settings(hide('running')):
query("CREATE USER '%(name)s'@'%(host)s' IDENTIFIED BY '%(password)s';" % {
'name': name,
'password': password,
'host': host
}, **kwargs)
puts("Created MySQL user '%s'." % name) | python | {
"resource": ""
} |
q258678 | database_exists | validation | def database_exists(name, **kwargs):
"""
Check if a MySQL database exists.
"""
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
res = query("SHOW DATABASES LIKE '%(name)s';" % {
'name': name
}, **kwargs)
return res.succeeded and (res == name) | python | {
"resource": ""
} |
q258679 | create_database | validation | def create_database(name, owner=None, owner_host='localhost', charset='utf8',
collate='utf8_general_ci', **kwargs):
"""
Create a MySQL database.
Example::
import burlap
# Create DB if it does not exist
if not burlap.mysql.database_exists('myapp'):
burlap.mysql.create_database('myapp', owner='dbuser')
"""
with settings(hide('running')):
query("CREATE DATABASE %(name)s CHARACTER SET %(charset)s COLLATE %(collate)s;" % {
'name': name,
'charset': charset,
'collate': collate
}, **kwargs)
if owner:
query("GRANT ALL PRIVILEGES ON %(name)s.* TO '%(owner)s'@'%(owner_host)s' WITH GRANT OPTION;" % {
'name': name,
'owner': owner,
'owner_host': owner_host
}, **kwargs)
puts("Created MySQL database '%s'." % name) | python | {
"resource": ""
} |
q258680 | MySQLSatchel.conf_path | validation | def conf_path(self):
"""
Retrieves the path to the MySQL configuration file.
"""
from burlap.system import distrib_id, distrib_release
hostname = self.current_hostname
if hostname not in self._conf_cache:
self.env.conf_specifics[hostname] = self.env.conf_default
d_id = distrib_id()
d_release = distrib_release()
for key in ((d_id, d_release), (d_id,)):
if key in self.env.conf_specifics:
self._conf_cache[hostname] = self.env.conf_specifics[key]
return self._conf_cache[hostname] | python | {
"resource": ""
} |
q258681 | MySQLSatchel.prep_root_password | validation | def prep_root_password(self, password=None, **kwargs):
"""
Enters the root password prompt entries into the debconf cache
so we can set them without user interaction.
We keep this process separate from set_root_password() because we also need to do
this before installing the base MySQL package, because that will also prompt the user
for a root login.
"""
r = self.database_renderer(**kwargs)
r.env.root_password = password or r.genv.get('db_root_password')
r.sudo("DEBIAN_FRONTEND=noninteractive dpkg --configure -a")
r.sudo("debconf-set-selections <<< 'mysql-server mysql-server/root_password password {root_password}'")
r.sudo("debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password {root_password}'") | python | {
"resource": ""
} |
q258682 | MySQLSatchel.drop_views | validation | def drop_views(self, name=None, site=None):
"""
Drops all views.
"""
r = self.database_renderer
result = r.sudo("mysql --batch -v -h {db_host} "
#"-u {db_root_username} -p'{db_root_password}' "
"-u {db_user} -p'{db_password}' "
"--execute=\"SELECT GROUP_CONCAT(CONCAT(TABLE_SCHEMA,'.',table_name) SEPARATOR ', ') AS views "
"FROM INFORMATION_SCHEMA.views WHERE TABLE_SCHEMA = '{db_name}' ORDER BY table_name DESC;\"")
result = re.findall(
r'^views[\s\t\r\n]+(.*)',
result,
flags=re.IGNORECASE|re.DOTALL|re.MULTILINE)
if not result:
return
r.env.db_view_list = result[0]
#cmd = ("mysql -v -h {db_host} -u {db_root_username} -p'{db_root_password}' " \
r.sudo("mysql -v -h {db_host} -u {db_user} -p'{db_password}' " \
"--execute=\"DROP VIEW {db_view_list} CASCADE;\"") | python | {
"resource": ""
} |
q258683 | tic_single_object_crossmatch | validation | def tic_single_object_crossmatch(ra, dec, radius):
'''This does a cross-match against the TIC catalog on MAST.
Speed tests: about 10 crossmatches per second. (-> 3 hours for 10^5 objects
to crossmatch).
Parameters
----------
ra,dec : np.array
The coordinates to cross match against, all in decimal degrees.
radius : float
The cross-match radius to use, in decimal degrees.
Returns
-------
dict
Returns the match results JSON from MAST loaded into a dict.
'''
for val in ra,dec,radius:
if not isinstance(val, float):
raise AssertionError('plz input ra,dec,radius in decimal degrees')
# This is a json object
crossmatchInput = {"fields":[{"name":"ra","type":"float"},
{"name":"dec","type":"float"}],
"data":[{"ra":ra,"dec":dec}]}
request = {"service":"Mast.Tic.Crossmatch",
"data":crossmatchInput,
"params":{
"raColumn":"ra",
"decColumn":"dec",
"radius":radius
},
"format":"json",
'removecache':True}
headers,out_string = _mast_query(request)
out_data = json.loads(out_string)
return out_data | python | {
"resource": ""
} |
q258684 | normalized_flux_to_mag | validation | def normalized_flux_to_mag(lcdict,
columns=('sap.sap_flux',
'sap.sap_flux_err',
'sap.sap_bkg',
'sap.sap_bkg_err',
'pdc.pdcsap_flux',
'pdc.pdcsap_flux_err')):
'''This converts the normalized fluxes in the TESS lcdicts to TESS mags.
Uses the object's TESS mag stored in lcdict['objectinfo']['tessmag']::
mag - object_tess_mag = -2.5 log (flux/median_flux)
Parameters
----------
lcdict : lcdict
An `lcdict` produced by `read_tess_fitslc` or
`consolidate_tess_fitslc`. This must have normalized fluxes in its
measurement columns (use the `normalize` kwarg for these functions).
columns : sequence of str
The column keys of the normalized flux and background measurements in
the `lcdict` to operate on and convert to magnitudes in TESS band (T).
Returns
-------
lcdict
The returned `lcdict` will contain extra columns corresponding to
magnitudes for each input normalized flux/background column.
'''
tess_mag = lcdict['objectinfo']['tessmag']
for key in columns:
k1, k2 = key.split('.')
if 'err' not in k2:
lcdict[k1][k2.replace('flux','mag')] = (
tess_mag - 2.5*np.log10(lcdict[k1][k2])
)
else:
lcdict[k1][k2.replace('flux','mag')] = (
- 2.5*np.log10(1.0 - lcdict[k1][k2])
)
return lcdict | python | {
"resource": ""
} |
q258685 | get_time_flux_errs_from_Ames_lightcurve | validation | def get_time_flux_errs_from_Ames_lightcurve(infile,
lctype,
cadence_min=2):
'''Reads TESS Ames-format FITS light curve files.
MIT TOI alerts include Ames lightcurve files. This function gets the finite,
nonzero times, fluxes, and errors with QUALITY == 0.
NOTE: the PDCSAP lightcurve typically still need "pre-whitening" after this
step.
.. deprecated:: 0.3.20
This function will be removed in astrobase v0.4.2. Use the
`read_tess_fitslc` and `consolidate_tess_fitslc` functions instead.
Parameters
----------
infile : str
The path to `*.fits.gz` TOI alert file, from Ames pipeline.
lctype : {'PDCSAP','SAP'}
The type of light curve to extract from the FITS LC file.
cadence_min : int
The expected frame cadence in units of minutes. Raises ValueError if you
use the wrong cadence.
Returns
-------
tuple
The tuple returned is of the form:
(times, normalized (to median) fluxes, flux errors)
'''
warnings.warn(
"Use the astrotess.read_tess_fitslc and "
"astrotess.consolidate_tess_fitslc functions instead of this function. "
"This function will be removed in astrobase v0.4.2.",
FutureWarning
)
if lctype not in ('PDCSAP','SAP'):
raise ValueError('unknown light curve type requested: %s' % lctype)
hdulist = pyfits.open(infile)
main_hdr = hdulist[0].header
lc_hdr = hdulist[1].header
lc = hdulist[1].data
if (('Ames' not in main_hdr['ORIGIN']) or
('LIGHTCURVE' not in lc_hdr['EXTNAME'])):
raise ValueError(
'could not understand input LC format. '
'Is it a TESS TOI LC file?'
)
time = lc['TIME']
flux = lc['{:s}_FLUX'.format(lctype)]
err_flux = lc['{:s}_FLUX_ERR'.format(lctype)]
# REMOVE POINTS FLAGGED WITH:
# attitude tweaks, safe mode, coarse/earth pointing, argabrithening events,
# reaction wheel desaturation events, cosmic rays in optimal aperture
# pixels, manual excludes, discontinuities, stray light from Earth or Moon
# in camera FoV.
# (Note: it's not clear to me what a lot of these mean. Also most of these
# columns are probably not correctly propagated right now.)
sel = (lc['QUALITY'] == 0)
sel &= np.isfinite(time)
sel &= np.isfinite(flux)
sel &= np.isfinite(err_flux)
sel &= ~np.isnan(time)
sel &= ~np.isnan(flux)
sel &= ~np.isnan(err_flux)
sel &= (time != 0)
sel &= (flux != 0)
sel &= (err_flux != 0)
time = time[sel]
flux = flux[sel]
err_flux = err_flux[sel]
# ensure desired cadence
lc_cadence_diff = np.abs(np.nanmedian(np.diff(time))*24*60 - cadence_min)
if lc_cadence_diff > 1.0e-2:
raise ValueError(
'the light curve is not at the required cadence specified: %.2f' %
cadence_min
)
fluxmedian = np.nanmedian(flux)
flux /= fluxmedian
err_flux /= fluxmedian
return time, flux, err_flux | python | {
"resource": ""
} |
q258686 | _pkl_periodogram | validation | def _pkl_periodogram(lspinfo,
plotdpi=100,
override_pfmethod=None):
'''This returns the periodogram plot PNG as base64, plus info as a dict.
Parameters
----------
lspinfo : dict
This is an lspinfo dict containing results from a period-finding
function. If it's from an astrobase period-finding function in
periodbase, this will already be in the correct format. To use external
period-finder results with this function, the `lspinfo` dict must be of
the following form, with at least the keys listed below::
{'periods': np.array of all periods searched by the period-finder,
'lspvals': np.array of periodogram power value for each period,
'bestperiod': a float value that is the period with the highest
peak in the periodogram, i.e. the most-likely actual
period,
'method': a three-letter code naming the period-finder used; must
be one of the keys in the
`astrobase.periodbase.METHODLABELS` dict,
'nbestperiods': a list of the periods corresponding to periodogram
peaks (`nbestlspvals` below) to annotate on the
periodogram plot so they can be called out
visually,
'nbestlspvals': a list of the power values associated with
periodogram peaks to annotate on the periodogram
plot so they can be called out visually; should be
the same length as `nbestperiods` above}
`nbestperiods` and `nbestlspvals` must have at least 5 elements each,
e.g. describing the five 'best' (highest power) peaks in the
periodogram.
plotdpi : int
The resolution in DPI of the output periodogram plot to make.
override_pfmethod : str or None
This is used to set a custom label for this periodogram
method. Normally, this is taken from the 'method' key in the input
`lspinfo` dict, but if you want to override the output method name,
provide this as a string here. This can be useful if you have multiple
results you want to incorporate into a checkplotdict from a single
period-finder (e.g. if you ran BLS over several period ranges
separately).
Returns
-------
dict
Returns a dict that contains the following items::
{methodname: {'periods':the period array from lspinfo,
'lspval': the periodogram power array from lspinfo,
'bestperiod': the best period from lspinfo,
'nbestperiods': the 'nbestperiods' list from lspinfo,
'nbestlspvals': the 'nbestlspvals' list from lspinfo,
'periodogram': base64 encoded string representation of
the periodogram plot}}
The dict is returned in this format so it can be directly incorporated
under the period-finder's label `methodname` in a checkplotdict, using
Python's dict `update()` method.
'''
# get the appropriate plot ylabel
pgramylabel = PLOTYLABELS[lspinfo['method']]
# get the periods and lspvals from lspinfo
periods = lspinfo['periods']
lspvals = lspinfo['lspvals']
bestperiod = lspinfo['bestperiod']
nbestperiods = lspinfo['nbestperiods']
nbestlspvals = lspinfo['nbestlspvals']
# open the figure instance
pgramfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi)
# make the plot
plt.plot(periods,lspvals)
plt.xscale('log',basex=10)
plt.xlabel('Period [days]')
plt.ylabel(pgramylabel)
plottitle = '%s - %.6f d' % (METHODLABELS[lspinfo['method']],
bestperiod)
plt.title(plottitle)
# show the best five peaks on the plot
for xbestperiod, xbestpeak in zip(nbestperiods,
nbestlspvals):
plt.annotate('%.6f' % xbestperiod,
xy=(xbestperiod, xbestpeak), xycoords='data',
xytext=(0.0,25.0), textcoords='offset points',
arrowprops=dict(arrowstyle="->"),fontsize='14.0')
# make a grid
plt.grid(color='#a9a9a9',
alpha=0.9,
zorder=0,
linewidth=1.0,
linestyle=':')
# this is the output instance
pgrampng = StrIO()
pgramfig.savefig(pgrampng,
# bbox_inches='tight',
pad_inches=0.0, format='png')
plt.close()
# encode the finderpng instance to base64
pgrampng.seek(0)
pgramb64 = base64.b64encode(pgrampng.read())
# close the stringio buffer
pgrampng.close()
if not override_pfmethod:
# this is the dict to return
checkplotdict = {
lspinfo['method']:{
'periods':periods,
'lspvals':lspvals,
'bestperiod':bestperiod,
'nbestperiods':nbestperiods,
'nbestlspvals':nbestlspvals,
'periodogram':pgramb64,
}
}
else:
# this is the dict to return
checkplotdict = {
override_pfmethod:{
'periods':periods,
'lspvals':lspvals,
'bestperiod':bestperiod,
'nbestperiods':nbestperiods,
'nbestlspvals':nbestlspvals,
'periodogram':pgramb64,
}
}
return checkplotdict | python | {
"resource": ""
} |
q258687 | _pkl_magseries_plot | validation | def _pkl_magseries_plot(stimes, smags, serrs,
plotdpi=100,
magsarefluxes=False):
'''This returns the magseries plot PNG as base64, plus arrays as dict.
Parameters
----------
stimes,smags,serrs : np.array
The mag/flux time-series arrays along with associated errors. These
should all have been run through nan-stripping and sigma-clipping
beforehand.
plotdpi : int
The resolution of the plot to make in DPI.
magsarefluxes : bool
If True, indicates the input time-series is fluxes and not mags so the
plot y-axis direction and range can be set appropriately.
Returns
-------
dict
A dict of the following form is returned::
{'magseries': {'plot': base64 encoded str representation of the
magnitude/flux time-series plot,
'times': the `stimes` array,
'mags': the `smags` array,
'errs': the 'serrs' array}}
The dict is returned in this format so it can be directly incorporated
in a checkplotdict, using Python's dict `update()` method.
'''
scaledplottime = stimes - npmin(stimes)
# open the figure instance
magseriesfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi)
plt.plot(scaledplottime,
smags,
marker='o',
ms=2.0, ls='None',mew=0,
color='green',
rasterized=True)
# flip y axis for mags
if not magsarefluxes:
plot_ylim = plt.ylim()
plt.ylim((plot_ylim[1], plot_ylim[0]))
# set the x axis limit
plt.xlim((npmin(scaledplottime)-2.0,
npmax(scaledplottime)+2.0))
# make a grid
plt.grid(color='#a9a9a9',
alpha=0.9,
zorder=0,
linewidth=1.0,
linestyle=':')
# make the x and y axis labels
plot_xlabel = 'JD - %.3f' % npmin(stimes)
if magsarefluxes:
plot_ylabel = 'flux'
else:
plot_ylabel = 'magnitude'
plt.xlabel(plot_xlabel)
plt.ylabel(plot_ylabel)
# fix the yaxis ticks (turns off offset and uses the full
# value of the yaxis tick)
plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)
plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)
# this is the output instance
magseriespng = StrIO()
magseriesfig.savefig(magseriespng,
# bbox_inches='tight',
pad_inches=0.05, format='png')
plt.close()
# encode the finderpng instance to base64
magseriespng.seek(0)
magseriesb64 = base64.b64encode(magseriespng.read())
# close the stringio buffer
magseriespng.close()
checkplotdict = {
'magseries':{
'plot':magseriesb64,
'times':stimes,
'mags':smags,
'errs':serrs
}
}
return checkplotdict | python | {
"resource": ""
} |
q258688 | find_lc_timegroups | validation | def find_lc_timegroups(lctimes, mingap=4.0):
'''Finds gaps in the provided time-series and indexes them into groups.
This finds the gaps in the provided `lctimes` array, so we can figure out
which times are for consecutive observations and which represent gaps
between seasons or observing eras.
Parameters
----------
lctimes : array-like
This contains the times to analyze for gaps; assumed to be some form of
Julian date.
mingap : float
This defines how much the difference between consecutive measurements is
allowed to be to consider them as parts of different timegroups. By
default it is set to 4.0 days.
Returns
-------
tuple
A tuple of the form: `(ngroups, [slice(start_ind_1, end_ind_1), ...])`
is returned. This contains the number of groups as the first element,
and a list of Python `slice` objects for each time-group found. These
can be used directly to index into the array of times to quickly get
measurements associated with each group.
'''
lc_time_diffs = np.diff(lctimes)
group_start_indices = np.where(lc_time_diffs > mingap)[0]
if len(group_start_indices) > 0:
group_indices = []
for i, gindex in enumerate(group_start_indices):
if i == 0:
group_indices.append(slice(0,gindex+1))
else:
group_indices.append(slice(group_start_indices[i-1]+1,gindex+1))
# at the end, add the slice for the last group to the end of the times
# array
group_indices.append(slice(group_start_indices[-1]+1,len(lctimes)))
# if there's no large gap in the LC, then there's only one group to worry
# about
else:
group_indices = [slice(0,len(lctimes))]
return len(group_indices), group_indices | python | {
"resource": ""
} |
q258689 | normalize_magseries | validation | def normalize_magseries(times,
mags,
mingap=4.0,
normto='globalmedian',
magsarefluxes=False,
debugmode=False):
'''This normalizes the magnitude time-series to a specified value.
This is used to normalize time series measurements that may have large time
gaps and vertical offsets in mag/flux measurement between these
'timegroups', either due to instrument changes or different filters.
NOTE: this works in-place! The mags array will be replaced with normalized
mags when this function finishes.
Parameters
----------
times,mags : array-like
The times (assumed to be some form of JD) and mags (or flux)
measurements to be normalized.
mingap : float
This defines how much the difference between consecutive measurements is
allowed to be to consider them as parts of different timegroups. By
default it is set to 4.0 days.
normto : {'globalmedian', 'zero'} or a float
Specifies the normalization type::
'globalmedian' -> norms each mag to the global median of the LC column
'zero' -> norms each mag to zero
a float -> norms each mag to this specified float value.
magsarefluxes : bool
Indicates if the input `mags` array is actually an array of flux
measurements instead of magnitude measurements. If this is set to True,
then:
- if `normto` is 'zero', then the median flux is divided from each
observation's flux value to yield normalized fluxes with 1.0 as the
global median.
- if `normto` is 'globalmedian', then the global median flux value
across the entire time series is multiplied with each measurement.
- if `norm` is set to a `float`, then this number is multiplied with the
flux value for each measurement.
debugmode : bool
If this is True, will print out verbose info on each timegroup found.
Returns
-------
times,normalized_mags : np.arrays
Normalized magnitude values after normalization. If normalization fails
for some reason, `times` and `normalized_mags` will both be None.
'''
ngroups, timegroups = find_lc_timegroups(times,
mingap=mingap)
# find all the non-nan indices
finite_ind = np.isfinite(mags)
if any(finite_ind):
# find the global median
global_mag_median = np.median(mags[finite_ind])
# go through the groups and normalize them to the median for
# each group
for tgind, tg in enumerate(timegroups):
finite_ind = np.isfinite(mags[tg])
# find this timegroup's median mag and normalize the mags in
# it to this median
group_median = np.median((mags[tg])[finite_ind])
if magsarefluxes:
mags[tg] = mags[tg]/group_median
else:
mags[tg] = mags[tg] - group_median
if debugmode:
LOGDEBUG('group %s: elems %s, '
'finite elems %s, median mag %s' %
(tgind,
len(mags[tg]),
len(finite_ind),
group_median))
# now that everything is normalized to 0.0, add the global median
# offset back to all the mags and write the result back to the dict
if isinstance(normto, str) and normto == 'globalmedian':
if magsarefluxes:
mags = mags * global_mag_median
else:
mags = mags + global_mag_median
# if the normto is a float, add everything to that float and return
elif isinstance(normto, float):
if magsarefluxes:
mags = mags * normto
else:
mags = mags + normto
# anything else just returns the normalized mags as usual
return times, mags
else:
LOGERROR('measurements are all nan!')
return None, None | python | {
"resource": ""
} |
q258690 | get_snr_of_dip | validation | def get_snr_of_dip(times,
mags,
modeltimes,
modelmags,
atol_normalization=1e-8,
indsforrms=None,
magsarefluxes=False,
verbose=True,
transitdepth=None,
npoints_in_transit=None):
'''Calculate the total SNR of a transit assuming gaussian uncertainties.
`modelmags` gets interpolated onto the cadence of `mags`. The noise is
calculated as the 1-sigma std deviation of the residual (see below).
Following Carter et al. 2009::
Q = sqrt( Γ T ) * δ / σ
for Q the total SNR of the transit in the r->0 limit, where::
r = Rp/Rstar,
T = transit duration,
δ = transit depth,
σ = RMS of the lightcurve in transit.
Γ = sampling rate
Thus Γ * T is roughly the number of points obtained during transit.
(This doesn't correctly account for the SNR during ingress/egress, but this
is a second-order correction).
Note this is the same total SNR as described by e.g., Kovacs et al. 2002,
their Equation 11.
NOTE: this only works with fluxes at the moment.
Parameters
----------
times,mags : np.array
The input flux time-series to process.
modeltimes,modelmags : np.array
A transiting planet model, either from BLS, a trapezoid model, or a
Mandel-Agol model.
atol_normalization : float
The absolute tolerance to which the median of the passed model fluxes
must be equal to 1.
indsforrms : np.array
A array of bools of `len(mags)` used to select points for the RMS
measurement. If not passed, the RMS of the entire passed timeseries is
used as an approximation. Genearlly, it's best to use out of transit
points, so the RMS measurement is not model-dependent.
magsarefluxes : bool
Currently forced to be True because this function only works with
fluxes.
verbose : bool
If True, indicates progress and warns about problems.
transitdepth : float or None
If the transit depth is known, pass it in here. Otherwise, it is
calculated assuming OOT flux is 1.
npoints_in_transits : int or None
If the number of points in transit is known, pass it in here. Otherwise,
the function will guess at this value.
Returns
-------
(snr, transit_depth, noise) : tuple
The returned tuple contains the calculated SNR, transit depth, and noise
of the residual lightcurve calculated using the relation described
above.
'''
if magsarefluxes:
if not np.isclose(np.nanmedian(modelmags), 1, atol=atol_normalization):
raise AssertionError('snr calculation assumes modelmags are '
'median-normalized')
else:
raise NotImplementedError(
'need to implement a method for identifying in-transit points when'
'mags are mags, and not fluxes'
)
if not transitdepth:
# calculate transit depth from whatever model magnitudes are passed.
transitdepth = np.abs(np.max(modelmags) - np.min(modelmags))
# generally, mags (data) and modelmags are at different cadence.
# interpolate modelmags onto the cadence of mags.
if not len(mags) == len(modelmags):
from scipy.interpolate import interp1d
fn = interp1d(modeltimes, modelmags, kind='cubic', bounds_error=True,
fill_value=np.nan)
modelmags = fn(times)
if verbose:
LOGINFO('interpolated model timeseries onto the data timeseries')
subtractedmags = mags - modelmags
if isinstance(indsforrms, np.ndarray):
subtractedrms = np.std(subtractedmags[indsforrms])
if verbose:
LOGINFO('using selected points to measure RMS')
else:
subtractedrms = np.std(subtractedmags)
if verbose:
LOGINFO('using all points to measure RMS')
def _get_npoints_in_transit(modelmags):
# assumes median-normalized fluxes are input
if np.nanmedian(modelmags) == 1:
return len(modelmags[(modelmags != 1)])
else:
raise NotImplementedError
if not npoints_in_transit:
npoints_in_transit = _get_npoints_in_transit(modelmags)
snr = np.sqrt(npoints_in_transit) * transitdepth/subtractedrms
if verbose:
LOGINFO('\npoints in transit: {:d}'.format(npoints_in_transit) +
'\ndepth: {:.2e}'.format(transitdepth) +
'\nrms in residual: {:.2e}'.format(subtractedrms) +
'\n\t SNR: {:.2e}'.format(snr))
return snr, transitdepth, subtractedrms | python | {
"resource": ""
} |
q258691 | estimate_achievable_tmid_precision | validation | def estimate_achievable_tmid_precision(snr, t_ingress_min=10,
t_duration_hr=2.14):
'''Using Carter et al. 2009's estimate, calculate the theoretical optimal
precision on mid-transit time measurement possible given a transit of a
particular SNR.
The relation used is::
sigma_tc = Q^{-1} * T * sqrt(θ/2)
Q = SNR of the transit.
T = transit duration, which is 2.14 hours from discovery paper.
θ = τ/T = ratio of ingress to total duration
~= (few minutes [guess]) / 2.14 hours
Parameters
----------
snr : float
The measured signal-to-noise of the transit, e,g. from
:py:func:`astrobase.periodbase.kbls.bls_stats_singleperiod` or from
running the `.compute_stats()` method on an Astropy BoxLeastSquares
object.
t_ingress_min : float
The ingress duration in minutes. This is t_I to t_II in Winn (2010)
nomenclature.
t_duration_hr : float
The transit duration in hours. This is t_I to t_IV in Winn (2010)
nomenclature.
Returns
-------
float
Returns the precision achievable for transit-center time as calculated
from the relation above. This is in days.
'''
t_ingress = t_ingress_min*u.minute
t_duration = t_duration_hr*u.hour
theta = t_ingress/t_duration
sigma_tc = (1/snr * t_duration * np.sqrt(theta/2))
LOGINFO('assuming t_ingress = {:.1f}'.format(t_ingress))
LOGINFO('assuming t_duration = {:.1f}'.format(t_duration))
LOGINFO('measured SNR={:.2f}\n\t'.format(snr) +
'-->theoretical sigma_tc = {:.2e} = {:.2e} = {:.2e}'.format(
sigma_tc.to(u.minute), sigma_tc.to(u.hour), sigma_tc.to(u.day)))
return sigma_tc.to(u.day).value | python | {
"resource": ""
} |
q258692 | given_lc_get_transit_tmids_tstarts_tends | validation | def given_lc_get_transit_tmids_tstarts_tends(
time,
flux,
err_flux,
blsfit_savpath=None,
trapfit_savpath=None,
magsarefluxes=True,
nworkers=1,
sigclip=None,
extra_maskfrac=0.03
):
'''Gets the transit start, middle, and end times for transits in a given
time-series of observations.
Parameters
----------
time,flux,err_flux : np.array
The input flux time-series measurements and their associated measurement
errors
blsfit_savpath : str or None
If provided as a str, indicates the path of the fit plot to make for a
simple BLS model fit to the transit using the obtained period and epoch.
trapfit_savpath : str or None
If provided as a str, indicates the path of the fit plot to make for a
trapezoidal transit model fit to the transit using the obtained period
and epoch.
sigclip : float or int or sequence of two floats/ints or None
If a single float or int, a symmetric sigma-clip will be performed using
the number provided as the sigma-multiplier to cut out from the input
time-series.
If a list of two ints/floats is provided, the function will perform an
'asymmetric' sigma-clip. The first element in this list is the sigma
value to use for fainter flux/mag values; the second element in this
list is the sigma value to use for brighter flux/mag values. For
example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma
dimmings and greater than 3-sigma brightenings. Here the meaning of
"dimming" and "brightening" is set by *physics* (not the magnitude
system), which is why the `magsarefluxes` kwarg must be correctly set.
If `sigclip` is None, no sigma-clipping will be performed, and the
time-series (with non-finite elems removed) will be passed through to
the output.
magsarefluxes : bool
This is by default True for this function, since it works on fluxes only
at the moment.
nworkers : int
The number of parallel BLS period-finder workers to use.
extra_maskfrac : float
This is the separation (N) from in-transit points you desire, in units
of the transit duration. `extra_maskfrac = 0` if you just want points
inside transit, otherwise::
t_starts = t_Is - N*tdur, t_ends = t_IVs + N*tdur
Thus setting N=0.03 masks slightly more than the guessed transit
duration.
Returns
-------
(tmids_obsd, t_starts, t_ends) : tuple
The returned items are::
tmids_obsd (np.ndarray): best guess of transit midtimes in
lightcurve. Has length number of transits in lightcurve.
t_starts (np.ndarray): t_Is - extra_maskfrac*tdur, for t_Is transit
first contact point.
t_ends (np.ndarray): t_Is + extra_maskfrac*tdur, for t_Is transit
first contact point.
'''
# first, run BLS to get an initial epoch and period.
endp = 1.05*(np.nanmax(time) - np.nanmin(time))/2
blsdict = kbls.bls_parallel_pfind(time, flux, err_flux,
magsarefluxes=magsarefluxes, startp=0.1,
endp=endp, maxtransitduration=0.3,
nworkers=nworkers, sigclip=sigclip)
blsd = kbls.bls_stats_singleperiod(time, flux, err_flux,
blsdict['bestperiod'],
magsarefluxes=True, sigclip=sigclip,
perioddeltapercent=5)
# plot the BLS model.
if blsfit_savpath:
make_fit_plot(blsd['phases'], blsd['phasedmags'], None,
blsd['blsmodel'], blsd['period'], blsd['epoch'],
blsd['epoch'], blsfit_savpath,
magsarefluxes=magsarefluxes)
ingduration_guess = blsd['transitduration'] * 0.2 # a guesstimate.
transitparams = [
blsd['period'], blsd['epoch'], blsd['transitdepth'],
blsd['transitduration'], ingduration_guess
]
# fit a trapezoidal transit model; plot the resulting phased LC.
if trapfit_savpath:
trapd = traptransit_fit_magseries(time, flux, err_flux,
transitparams,
magsarefluxes=magsarefluxes,
sigclip=sigclip,
plotfit=trapfit_savpath)
# use the trapezoidal model's epoch as the guess to identify (roughly) in
# and out of transit points
tmids, t_starts, t_ends = get_transit_times(blsd,
time,
extra_maskfrac,
trapd=trapd)
return tmids, t_starts, t_ends | python | {
"resource": ""
} |
q258693 | given_lc_get_out_of_transit_points | validation | def given_lc_get_out_of_transit_points(
time, flux, err_flux,
blsfit_savpath=None,
trapfit_savpath=None,
in_out_transit_savpath=None,
sigclip=None,
magsarefluxes=True,
nworkers=1,
extra_maskfrac=0.03
):
'''This gets the out-of-transit light curve points.
Relevant during iterative masking of transits for multiple planet system
search.
Parameters
----------
time,flux,err_flux : np.array
The input flux time-series measurements and their associated measurement
errors
blsfit_savpath : str or None
If provided as a str, indicates the path of the fit plot to make for a
simple BLS model fit to the transit using the obtained period and epoch.
trapfit_savpath : str or None
If provided as a str, indicates the path of the fit plot to make for a
trapezoidal transit model fit to the transit using the obtained period
and epoch.
in_out_transit_savpath : str or None
If provided as a str, indicates the path of the plot file that will be
made for a plot showing the in-transit points and out-of-transit points
tagged separately.
sigclip : float or int or sequence of two floats/ints or None
If a single float or int, a symmetric sigma-clip will be performed using
the number provided as the sigma-multiplier to cut out from the input
time-series.
If a list of two ints/floats is provided, the function will perform an
'asymmetric' sigma-clip. The first element in this list is the sigma
value to use for fainter flux/mag values; the second element in this
list is the sigma value to use for brighter flux/mag values. For
example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma
dimmings and greater than 3-sigma brightenings. Here the meaning of
"dimming" and "brightening" is set by *physics* (not the magnitude
system), which is why the `magsarefluxes` kwarg must be correctly set.
If `sigclip` is None, no sigma-clipping will be performed, and the
time-series (with non-finite elems removed) will be passed through to
the output.
magsarefluxes : bool
This is by default True for this function, since it works on fluxes only
at the moment.
nworkers : int
The number of parallel BLS period-finder workers to use.
extra_maskfrac : float
This is the separation (N) from in-transit points you desire, in units
of the transit duration. `extra_maskfrac = 0` if you just want points
inside transit, otherwise::
t_starts = t_Is - N*tdur, t_ends = t_IVs + N*tdur
Thus setting N=0.03 masks slightly more than the guessed transit
duration.
Returns
-------
(times_oot, fluxes_oot, errs_oot) : tuple of np.array
The `times`, `flux`, `err_flux` values from the input at the time values
out-of-transit are returned.
'''
tmids_obsd, t_starts, t_ends = (
given_lc_get_transit_tmids_tstarts_tends(
time, flux, err_flux, blsfit_savpath=blsfit_savpath,
trapfit_savpath=trapfit_savpath, magsarefluxes=magsarefluxes,
nworkers=nworkers, sigclip=sigclip, extra_maskfrac=extra_maskfrac
)
)
in_transit = np.zeros_like(time).astype(bool)
for t_start, t_end in zip(t_starts, t_ends):
this_transit = ( (time > t_start) & (time < t_end) )
in_transit |= this_transit
out_of_transit = ~in_transit
if in_out_transit_savpath:
_in_out_transit_plot(time, flux, in_transit, out_of_transit,
in_out_transit_savpath)
return time[out_of_transit], flux[out_of_transit], err_flux[out_of_transit] | python | {
"resource": ""
} |
q258694 | _pycompress_sqlitecurve | validation | def _pycompress_sqlitecurve(sqlitecurve, force=False):
'''This just compresses the sqlitecurve. Should be independent of OS.
'''
outfile = '%s.gz' % sqlitecurve
try:
if os.path.exists(outfile) and not force:
os.remove(sqlitecurve)
return outfile
else:
with open(sqlitecurve,'rb') as infd:
with gzip.open(outfile,'wb') as outfd:
shutil.copyfileobj(infd, outfd)
if os.path.exists(outfile):
os.remove(sqlitecurve)
return outfile
except Exception as e:
return None | python | {
"resource": ""
} |
q258695 | _pyuncompress_sqlitecurve | validation | def _pyuncompress_sqlitecurve(sqlitecurve, force=False):
'''This just uncompresses the sqlitecurve. Should be independent of OS.
'''
outfile = sqlitecurve.replace('.gz','')
try:
if os.path.exists(outfile) and not force:
return outfile
else:
with gzip.open(sqlitecurve,'rb') as infd:
with open(outfile,'wb') as outfd:
shutil.copyfileobj(infd, outfd)
# do not remove the intput file yet
if os.path.exists(outfile):
return outfile
except Exception as e:
return None | python | {
"resource": ""
} |
q258696 | _gzip_sqlitecurve | validation | def _gzip_sqlitecurve(sqlitecurve, force=False):
'''This just compresses the sqlitecurve in gzip format.
FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).
'''
# -k to keep the input file just in case something explodes
if force:
cmd = 'gzip -k -f %s' % sqlitecurve
else:
cmd = 'gzip -k %s' % sqlitecurve
try:
outfile = '%s.gz' % sqlitecurve
if os.path.exists(outfile) and not force:
# get rid of the .sqlite file only
os.remove(sqlitecurve)
return outfile
else:
subprocess.check_output(cmd, shell=True)
# check if the output file was successfully created
if os.path.exists(outfile):
return outfile
else:
return None
except subprocess.CalledProcessError:
return None | python | {
"resource": ""
} |
q258697 | _gunzip_sqlitecurve | validation | def _gunzip_sqlitecurve(sqlitecurve):
'''This just uncompresses the sqlitecurve in gzip format.
FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably).
'''
# -k to keep the input .gz just in case something explodes
cmd = 'gunzip -k %s' % sqlitecurve
try:
subprocess.check_output(cmd, shell=True)
return sqlitecurve.replace('.gz','')
except subprocess.CalledProcessError:
return None | python | {
"resource": ""
} |
q258698 | _validate_sqlitecurve_filters | validation | def _validate_sqlitecurve_filters(filterstring, lccolumns):
'''This validates the sqlitecurve filter string.
This MUST be valid SQL but not contain any commands.
'''
# first, lowercase, then _squeeze to single spaces
stringelems = _squeeze(filterstring).lower()
# replace shady characters
stringelems = filterstring.replace('(','')
stringelems = stringelems.replace(')','')
stringelems = stringelems.replace(',','')
stringelems = stringelems.replace("'",'"')
stringelems = stringelems.replace('\n',' ')
stringelems = stringelems.replace('\t',' ')
stringelems = _squeeze(stringelems)
# split into words
stringelems = stringelems.split(' ')
stringelems = [x.strip() for x in stringelems]
# get rid of all numbers
stringwords = []
for x in stringelems:
try:
float(x)
except ValueError as e:
stringwords.append(x)
# get rid of everything within quotes
stringwords2 = []
for x in stringwords:
if not(x.startswith('"') and x.endswith('"')):
stringwords2.append(x)
stringwords2 = [x for x in stringwords2 if len(x) > 0]
# check the filterstring words against the allowed words
wordset = set(stringwords2)
# generate the allowed word set for these LC columns
allowedwords = SQLITE_ALLOWED_WORDS + lccolumns
checkset = set(allowedwords)
validatecheck = list(wordset - checkset)
# if there are words left over, then this filter string is suspicious
if len(validatecheck) > 0:
# check if validatecheck contains an elem with % in it
LOGWARNING("provided SQL filter string '%s' "
"contains non-allowed keywords" % filterstring)
return None
else:
return filterstring | python | {
"resource": ""
} |
q258699 | _smartcast | validation | def _smartcast(castee, caster, subval=None):
'''
This just tries to apply the caster function to castee.
Returns None on failure.
'''
try:
return caster(castee)
except Exception as e:
if caster is float or caster is int:
return nan
elif caster is str:
return ''
else:
return subval | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.