_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q258500
FileSatchel.copy
validation
def copy(self, source, destination, recursive=False, use_sudo=False): """ Copy a file or directory """ func = use_sudo and run_as_root or self.run
python
{ "resource": "" }
q258501
FileSatchel.move
validation
def move(self, source, destination, use_sudo=False): """ Move a file or directory """ func
python
{ "resource": "" }
q258502
FileSatchel.remove
validation
def remove(self, path, recursive=False, use_sudo=False): """ Remove a file or directory """ func = use_sudo and run_as_root or
python
{ "resource": "" }
q258503
FileSatchel.require
validation
def require(self, path=None, contents=None, source=None, url=None, md5=None, use_sudo=False, owner=None, group='', mode=None, verify_remote=True, temp_dir='/tmp'): """ Require a file to exist and have specific contents and properties. You can provide either: - *contents*: the required contents of the file:: from fabtools import require require.file('/tmp/hello.txt', contents='Hello, world') - *source*: the local path of a file to upload:: from fabtools import require require.file('/tmp/hello.txt', source='files/hello.txt') - *url*: the URL of a file to download (*path* is then optional):: from fabric.api import cd from fabtools import require with cd('tmp'): require.file(url='http://example.com/files/hello.txt') If *verify_remote* is ``True`` (the default), then an MD5 comparison will be used to check whether the remote file is the same as the source. If this is ``False``, the file will be assumed to be the same if it is present. This is useful for very large files, where generating an MD5 sum may take a while. When providing either the *contents* or the *source* parameter, Fabric's ``put`` function will be used to upload the file to the remote host. When ``use_sudo`` is ``True``, the file will first be uploaded to a temporary directory, then moved to its final location. The default temporary directory is ``/tmp``, but can be overridden with the *temp_dir* parameter. If *temp_dir* is an empty string, then the user's home directory will be used. If `use_sudo` is `True`, then the remote file will be owned by root, and its mode will reflect root's default *umask*. The optional *owner*,
python
{ "resource": "" }
q258504
SeleniumSatchel.check_for_change
validation
def check_for_change(self): """ Determines if a new release has been made. """ r = self.local_renderer lm = self.last_manifest last_fingerprint = lm.fingerprint current_fingerprint = self.get_target_geckodriver_version_number() self.vprint('last_fingerprint:', last_fingerprint)
python
{ "resource": "" }
q258505
update
validation
def update(kernel=False): """ Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``. Exclude *kernel* upgrades by default. """ manager = MANAGER
python
{ "resource": "" }
q258506
is_installed
validation
def is_installed(pkg_name): """ Check if an RPM package is installed. """ manager = MANAGER with settings(hide('running', 'stdout',
python
{ "resource": "" }
q258507
install
validation
def install(packages, repos=None, yes=None, options=None): """ Install one or more RPM packages. Extra *repos* may be passed to ``yum`` to enable extra repositories at install time. Extra *yes* may be passed to ``yum`` to validate license if necessary. Extra *options* may be passed to ``yum`` if necessary (e.g. ``['--nogpgcheck', '--exclude=package']``). :: import burlap # Install a single package, in an alternative install root burlap.rpm.install('emacs', options='--installroot=/my/new/location') # Install multiple packages silently burlap.rpm.install([ 'unzip', 'nano' ], '--quiet') """ manager = MANAGER
python
{ "resource": "" }
q258508
groupinstall
validation
def groupinstall(group, options=None): """ Install a group of packages. You can use ``yum grouplist`` to get the list of groups. Extra *options* may be passed to ``yum`` if necessary like (e.g. ``['--nogpgcheck', '--exclude=package']``).
python
{ "resource": "" }
q258509
groupuninstall
validation
def groupuninstall(group, options=None): """ Remove an existing software group. Extra *options* may be passed to ``yum`` if necessary. """ manager = MANAGER if options is None: options = [] elif isinstance(options, str):
python
{ "resource": "" }
q258510
repolist
validation
def repolist(status='', media=None): """ Get the list of ``yum`` repositories. Returns enabled repositories by default. Extra *status* may be passed to list disabled repositories if necessary. Media and debug repositories are kept disabled, except if you pass *media*. :: import burlap # Install a package that may be included in disabled
python
{ "resource": "" }
q258511
S3Satchel.sync
validation
def sync(self, sync_set, force=0, site=None, role=None): """ Uploads media to an Amazon S3 bucket using s3sync. Requires s3cmd. Install with: pip install s3cmd """ from burlap.dj import dj force = int(force) r = self.local_renderer r.env.sync_force_flag = ' --force ' if force else '' _settings = dj.get_settings(site=site, role=role) assert _settings, 'Unable to import settings.' for k in _settings.__dict__.iterkeys(): if k.startswith('AWS_'): r.genv[k] = _settings.__dict__[k] site_data = r.genv.sites[r.genv.SITE] r.env.update(site_data) r.env.virtualenv_bin_dir = os.path.split(sys.executable)[0] rets = [] for paths in r.env.sync_sets[sync_set]: is_local = paths.get('is_local', True) local_path = paths['local_path'] % r.genv remote_path = paths['remote_path'] remote_path = remote_path.replace(':/', '/') if not remote_path.startswith('s3://'): remote_path = 's3://' + remote_path local_path = local_path % r.genv if is_local: #local_or_dryrun('which s3sync')#, capture=True) r.env.local_path = os.path.abspath(local_path)
python
{ "resource": "" }
q258512
S3Satchel.invalidate
validation
def invalidate(self, *paths): """ Issues invalidation requests to a Cloudfront distribution for the current static media bucket, triggering it to reload the specified paths from the origin. Note, only 1000 paths can be issued in a request at any one time. """ dj = self.get_satchel('dj') if not paths: return # http://boto.readthedocs.org/en/latest/cloudfront_tut.html _settings = dj.get_settings() if not _settings.AWS_STATIC_BUCKET_NAME: print('No static media bucket set.') return if isinstance(paths, six.string_types): paths = paths.split(',') all_paths = map(str.strip, paths) i = 0 while 1: paths = all_paths[i:i+1000] if not paths: break c = boto.connect_cloudfront() rs = c.get_all_distributions() target_dist = None for dist in rs:
python
{ "resource": "" }
q258513
S3Satchel.get_or_create_bucket
validation
def get_or_create_bucket(self, name): """ Gets an S3 bucket of the given name, creating one if it doesn't already exist. Should be called with a role, if AWS credentials are stored in role settings. e.g. fab local s3.get_or_create_bucket:mybucket
python
{ "resource": "" }
q258514
IPSatchel.static
validation
def static(self): """ Configures the server to use a static IP. """ fn = self.render_to_file('ip/ip_interfaces_static.template') r
python
{ "resource": "" }
q258515
upgrade
validation
def upgrade(safe=True): """ Upgrade all packages. """ manager = MANAGER if safe: cmd = 'upgrade' else:
python
{ "resource": "" }
q258516
is_installed
validation
def is_installed(pkg_name): """ Check if a package is installed. """ with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True): res = run("dpkg -s %(pkg_name)s" % locals()) for line in res.splitlines(): if line.startswith("Status: "):
python
{ "resource": "" }
q258517
install
validation
def install(packages, update=False, options=None, version=None): """ Install one or more packages. If *update* is ``True``, the package definitions will be updated first, using :py:func:`~burlap.deb.update_index`. Extra *options* may be passed to ``apt-get`` if necessary. Example:: import burlap # Update index, then install a single package burlap.deb.install('build-essential', update=True) # Install multiple packages burlap.deb.install([
python
{ "resource": "" }
q258518
preseed_package
validation
def preseed_package(pkg_name, preseed): """ Enable unattended package installation by preseeding ``debconf`` parameters. Example:: import burlap # Unattended install of Postfix mail server burlap.deb.preseed_package('postfix', { 'postfix/main_mailer_type': ('select', 'Internet Site'), 'postfix/mailname': ('string', 'example.com'), 'postfix/destinations': ('string', 'example.com, localhost.localdomain, localhost'),
python
{ "resource": "" }
q258519
get_selections
validation
def get_selections(): """ Get the state of ``dkpg`` selections. Returns a dict with state => [packages]. """ with settings(hide('stdout')):
python
{ "resource": "" }
q258520
apt_key_exists
validation
def apt_key_exists(keyid): """ Check if the given key id exists in apt keyring. """ # Command extracted from apt-key source gpg_cmd = 'gpg --ignore-time-conflict --no-options --no-default-keyring --keyring /etc/apt/trusted.gpg'
python
{ "resource": "" }
q258521
add_apt_key
validation
def add_apt_key(filename=None, url=None, keyid=None, keyserver='subkeys.pgp.net', update=False): """ Trust packages signed with this public key. Example:: import burlap # Varnish signing key from URL and verify fingerprint) burlap.deb.add_apt_key(keyid='C4DEFFEB', url='http://repo.varnish-cache.org/debian/GPG-key.txt') # Nginx signing key from default key server (subkeys.pgp.net) burlap.deb.add_apt_key(keyid='7BD9BF62') # From custom key server burlap.deb.add_apt_key(keyid='7BD9BF62', keyserver='keyserver.ubuntu.com') # From a file burlap.deb.add_apt_key(keyid='7BD9BF62', filename='nginx.asc' """ if keyid is None: if filename is not None: run_as_root('apt-key add %(filename)s' % locals()) elif url is not None: run_as_root('wget %(url)s -O - | apt-key add -' % locals()) else: raise ValueError('Either filename, url or keyid must be provided as argument') else: if filename is not None: _check_pgp_key(filename, keyid)
python
{ "resource": "" }
q258522
GroupSatchel.exists
validation
def exists(self, name): """ Check if a group exists. """ with self.settings(hide('running', 'stdout', 'warnings'), warn_only=True):
python
{ "resource": "" }
q258523
UserSatchel.enter_password_change
validation
def enter_password_change(self, username=None, old_password=None): """ Responds to a forced password change via `passwd` prompts due to password expiration. """ from fabric.state import connections from fabric.network import disconnect_all r = self.local_renderer # print('self.genv.user:', self.genv.user) # print('self.env.passwords:', self.env.passwords) r.genv.user = r.genv.user or username r.pc('Changing password for user {user} via interactive prompts.') r.env.old_password = r.env.default_passwords[self.genv.user] # print('self.genv.user:', self.genv.user) # print('self.env.passwords:', self.env.passwords) r.env.new_password = self.env.passwords[self.genv.user] if old_password: r.env.old_password = old_password prompts = { '(current) UNIX password: ': r.env.old_password, 'Enter new UNIX password: ': r.env.new_password, 'Retype new UNIX password: ': r.env.new_password, #"Login password for '%s': " % r.genv.user: r.env.new_password, # "Login password for '%s': " % r.genv.user: r.env.old_password, }
python
{ "resource": "" }
q258524
UserSatchel.togroups
validation
def togroups(self, user, groups): """ Adds the user to the given list of groups. """ r = self.local_renderer if isinstance(groups, six.string_types): groups = [_.strip() for _ in groups.split(',') if _.strip()] for group in groups:
python
{ "resource": "" }
q258525
UserSatchel.create
validation
def create(self, username, groups=None, uid=None, create_home=None, system=False, password=None, home_dir=None): """ Creates a user with the given username. """ r = self.local_renderer r.env.username = username args = [] if uid: args.append('-u %s' % uid) if create_home is None: create_home = not system if create_home is True: if home_dir: args.append('--home %s' % home_dir) elif create_home is False:
python
{ "resource": "" }
q258526
UserSatchel.expire_password
validation
def expire_password(self, username): """ Forces the user to change their password the next time they login. """
python
{ "resource": "" }
q258527
run_as_root
validation
def run_as_root(command, *args, **kwargs): """ Run a remote command as the root user. When connecting as root to the remote system, this will use Fabric's ``run`` function. In other cases, it will use ``sudo``. """ from
python
{ "resource": "" }
q258528
get_file_hash
validation
def get_file_hash(fin, block_size=2**20): """ Iteratively builds a file hash without loading the entire file into memory. Designed to process an arbitrary binary file. """ if isinstance(fin, six.string_types): fin = open(fin) h = hashlib.sha512() while True: data = fin.read(block_size) if not data: break try: h.update(data)
python
{ "resource": "" }
q258529
InadynSatchel.check
validation
def check(self): """ Run inadyn from the commandline to test the configuration. To be run like: fab role inadyn.check """ self._validate_settings()
python
{ "resource": "" }
q258530
DebugSatchel.shell
validation
def shell(self, gui=0, command='', dryrun=None, shell_interactive_cmd_str=None): """ Opens an SSH connection. """ from burlap.common import get_hosts_for_site if dryrun is not None: self.dryrun = dryrun r = self.local_renderer if r.genv.SITE != r.genv.default_site: shell_hosts = get_hosts_for_site() if shell_hosts: r.genv.host_string = shell_hosts[0] r.env.SITE = r.genv.SITE or r.genv.default_site if int(gui): r.env.shell_default_options.append('-X') if 'host_string' not in self.genv or not self.genv.host_string: if 'available_sites' in self.genv and r.env.SITE not in r.genv.available_sites: raise Exception('No host_string set. Unknown site %s.' % r.env.SITE) else: raise Exception('No host_string set.') if '@' in r.genv.host_string: r.env.shell_host_string = r.genv.host_string else: r.env.shell_host_string = '{user}@{host_string}' if command: r.env.shell_interactive_cmd_str = command else: r.env.shell_interactive_cmd_str = r.format(shell_interactive_cmd_str or r.env.shell_interactive_cmd) r.env.shell_default_options_str = ' '.join(r.env.shell_default_options) if self.is_local: self.vprint('Using direct local.') cmd = '{shell_interactive_cmd_str}'
python
{ "resource": "" }
q258531
DebugSatchel.disk
validation
def disk(self): """ Display percent of disk usage. """ r
python
{ "resource": "" }
q258532
DebugSatchel.tunnel
validation
def tunnel(self, local_port, remote_port): """ Creates an SSH tunnel. """ r = self.local_renderer r.env.tunnel_local_port = local_port r.env.tunnel_remote_port = remote_port
python
{ "resource": "" }
q258533
install_setuptools
validation
def install_setuptools(python_cmd='python', use_sudo=True): """ Install the latest version of `setuptools`_. :: import burlap burlap.python_setuptools.install_setuptools() """ setuptools_version = package_version('setuptools', python_cmd) distribute_version = package_version('distribute', python_cmd) if setuptools_version is None:
python
{ "resource": "" }
q258534
_install_from_scratch
validation
def _install_from_scratch(python_cmd, use_sudo): """ Install setuptools from scratch using installer """ with cd("/tmp"): download(EZ_SETUP_URL) command = '%(python_cmd)s ez_setup.py'
python
{ "resource": "" }
q258535
install
validation
def install(packages, upgrade=False, use_sudo=False, python_cmd='python'): """ Install Python packages with ``easy_install``. Examples:: import burlap # Install a single package burlap.python_setuptools.install('package', use_sudo=True) # Install a list of packages burlap.python_setuptools.install(['pkg1', 'pkg2'], use_sudo=True) .. note:: most of the time, you'll want to use
python
{ "resource": "" }
q258536
PIPSatchel.bootstrap
validation
def bootstrap(self, force=0): """ Installs all the necessary packages necessary for managing virtual environments with pip. """ force = int(force) if self.has_pip() and not force: return r = self.local_renderer if r.env.bootstrap_method == GET_PIP: r.sudo('curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | python') elif r.env.bootstrap_method == EZ_SETUP: r.run('wget http://peak.telecommunity.com/dist/ez_setup.py -O /tmp/ez_setup.py') with self.settings(warn_only=True): r.sudo('python /tmp/ez_setup.py -U setuptools')
python
{ "resource": "" }
q258537
PIPSatchel.has_virtualenv
validation
def has_virtualenv(self): """ Returns true if the virtualenv tool is installed.
python
{ "resource": "" }
q258538
PIPSatchel.virtualenv_exists
validation
def virtualenv_exists(self, virtualenv_dir=None): """ Returns true if the virtual environment has been created. """ r = self.local_renderer ret = True with self.settings(warn_only=True): ret = r.run_or_local('ls {virtualenv_dir}') or '' ret = 'cannot access' not
python
{ "resource": "" }
q258539
PIPSatchel.what_requires
validation
def what_requires(self, name): """ Lists the packages that require the given package. """
python
{ "resource": "" }
q258540
PIPSatchel.init
validation
def init(self): """ Creates the virtual environment. """ r = self.local_renderer # if self.virtualenv_exists(): # print('virtualenv exists') # return print('Creating new virtual environment...') with self.settings(warn_only=True): cmd
python
{ "resource": "" }
q258541
PIPSatchel.get_combined_requirements
validation
def get_combined_requirements(self, requirements=None): """ Returns all requirements files combined into one string. """ requirements = requirements or self.env.requirements def iter_lines(fn): with open(fn, 'r') as fin: for line in fin.readlines(): line = line.strip()
python
{ "resource": "" }
q258542
list_instances
validation
def list_instances(show=1, name=None, group=None, release=None, except_release=None): """ Retrieves all virtual machines instances in the current environment. """ from burlap.common import shelf, OrderedDict, get_verbose verbose = get_verbose() require('vm_type', 'vm_group') assert env.vm_type, 'No VM type specified.' env.vm_type = (env.vm_type or '').lower() _name = name _group = group _release = release if verbose: print('name=%s, group=%s, release=%s' % (_name, _group, _release)) env.vm_elastic_ip_mappings = shelf.get('vm_elastic_ip_mappings') data = type(env)() if env.vm_type == EC2: if verbose: print('Checking EC2...') for instance in get_all_running_ec2_instances(): name = instance.tags.get(env.vm_name_tag) group = instance.tags.get(env.vm_group_tag) release = instance.tags.get(env.vm_release_tag) if env.vm_group and env.vm_group != group: if verbose: print(('Skipping instance %s because its group "%s" ' 'does not match env.vm_group "%s".') \ % (instance.public_dns_name, group, env.vm_group)) continue if _group and group != _group: if verbose: print(('Skipping instance %s because its group "%s" ' 'does not match local group "%s".') \ % (instance.public_dns_name, group, _group)) continue if _name and name != _name: if verbose: print(('Skipping instance %s because its name "%s" ' 'does not match name "%s".') \ % (instance.public_dns_name, name, _name))
python
{ "resource": "" }
q258543
get_or_create_ec2_key_pair
validation
def get_or_create_ec2_key_pair(name=None, verbose=1): """ Creates and saves an EC2 key pair to a local PEM file. """ verbose = int(verbose) name = name or env.vm_ec2_keypair_name pem_path = 'roles/%s/%s.pem' % (env.ROLE, name) conn = get_ec2_connection() kp = conn.get_key_pair(name)
python
{ "resource": "" }
q258544
exists
validation
def exists(name=None, group=None, release=None, except_release=None, verbose=1): """ Determines if a virtual machine instance exists. """ verbose = int(verbose) instances = list_instances( name=name, group=group, release=release, except_release=except_release,
python
{ "resource": "" }
q258545
get_or_create
validation
def get_or_create(name=None, group=None, config=None, extra=0, verbose=0, backend_opts=None): """ Creates a virtual machine instance. """ require('vm_type', 'vm_group') backend_opts = backend_opts or {} verbose = int(verbose) extra = int(extra) if config: config_fn = common.find_template(config) config = yaml.load(open(config_fn)) env.update(config) env.vm_type = (env.vm_type or '').lower() assert env.vm_type, 'No VM type specified.' group = group or env.vm_group assert group, 'No VM group specified.' ret = exists(name=name, group=group) if not extra and ret: if verbose: print('VM %s:%s exists.' % (name, group)) return ret today =
python
{ "resource": "" }
q258546
delete
validation
def delete(name=None, group=None, release=None, except_release=None, dryrun=1, verbose=1): """ Permanently erase one or more VM instances from existence. """ verbose = int(verbose) if env.vm_type == EC2: conn = get_ec2_connection() instances = list_instances( name=name, group=group, release=release, except_release=except_release, ) for instance_name, instance_data in instances.items(): public_dns_name = instance_data['public_dns_name'] print('\nDeleting %s (%s)...' \ % (instance_name, instance_data['id']))
python
{ "resource": "" }
q258547
get_name
validation
def get_name(): """ Retrieves the instance name associated with the current host string. """ if env.vm_type == EC2: for instance in get_all_running_ec2_instances():
python
{ "resource": "" }
q258548
respawn
validation
def respawn(name=None, group=None): """ Deletes and recreates one or more VM instances. """ if name is None: name = get_name()
python
{ "resource": "" }
q258549
RsyncSatchel.deploy_code
validation
def deploy_code(self): """ Generates a rsync of all deployable code. """ assert self.genv.SITE, 'Site unspecified.' assert self.genv.ROLE, 'Role unspecified.' r = self.local_renderer if self.env.exclusions: r.env.exclusions_str
python
{ "resource": "" }
q258550
init_env
validation
def init_env(): """ Populates the global env variables with custom default settings. """ env.ROLES_DIR = ROLE_DIR env.services = [] env.confirm_deployment = False env.is_local = None env.base_config_dir = '.' env.src_dir = 'src' # The path relative to fab where the code resides. env.sites = {} # {site:site_settings} env[SITE] = None env[ROLE] = None env.hosts_retriever = None env.hosts_retrievers = type(env)() #'default':lambda hostname: hostname, env.hostname_translator = 'default' env.hostname_translators = type(env)() env.hostname_translators.default = lambda hostname: hostname env.default_site = None # A list of all site names that should be available on the current host. env.available_sites = [] # A list of all site names per host. # {hostname:
python
{ "resource": "" }
q258551
create_module
validation
def create_module(name, code=None): """ Dynamically creates a module with the given name. """ if name not in sys.modules: sys.modules[name] = imp.new_module(name) module = sys.modules[name] if code: print('executing code for %s: %s' % (name, code))
python
{ "resource": "" }
q258552
add_class_methods_as_module_level_functions_for_fabric
validation
def add_class_methods_as_module_level_functions_for_fabric(instance, module_name, method_name, module_alias=None): ''' Utility to take the methods of the instance of a class, instance, and add them as functions to a module, module_name, so that Fabric can find and call them. Call this at the bottom of a module after the class definition. ''' import imp from .decorators import task_or_dryrun # get the module as an object module_obj = sys.modules[module_name] module_alias = re.sub('[^a-zA-Z0-9]+', '', module_alias or '') # Iterate over the methods of the class and dynamically create a function # for each method that calls the method and add it to the current module # NOTE: inspect.ismethod actually executes the methods?! #for method in inspect.getmembers(instance, predicate=inspect.ismethod): method_obj = getattr(instance, method_name) if not method_name.startswith('_'): # get the bound method func = getattr(instance, method_name) # if module_name == 'buildbot' or module_alias == 'buildbot': # print('-'*80) # print('module_name:', module_name) # print('method_name:', method_name) # print('module_alias:', module_alias) # print('module_obj:', module_obj) # print('func.module:', func.__module__)
python
{ "resource": "" }
q258553
str_to_list
validation
def str_to_list(s): """ Converts a string of comma delimited values and returns a list. """ if s is None: return [] elif isinstance(s, (tuple, list)): return s elif not
python
{ "resource": "" }
q258554
get_hosts_retriever
validation
def get_hosts_retriever(s=None): """ Given the function name, looks up the method for dynamically retrieving host data. """ s = s or env.hosts_retriever # #assert s, 'No hosts retriever specified.'
python
{ "resource": "" }
q258555
write_temp_file_or_dryrun
validation
def write_temp_file_or_dryrun(content, *args, **kwargs): """ Writes the given content to a local temporary file. """ dryrun = get_dryrun(kwargs.get('dryrun')) if dryrun: fd, tmp_fn = tempfile.mkstemp() os.remove(tmp_fn) cmd_run = 'local' cmd = 'cat <<EOT >> %s\n%s\nEOT' % (tmp_fn, content)
python
{ "resource": "" }
q258556
reboot_or_dryrun
validation
def reboot_or_dryrun(*args, **kwargs): """ An improved version of fabric.operations.reboot with better error handling. """ from fabric.state import connections verbose = get_verbose() dryrun = get_dryrun(kwargs.get('dryrun')) # Use 'wait' as max total wait time kwargs.setdefault('wait', 120) wait = int(kwargs['wait']) command = kwargs.get('command', 'reboot') now = int(kwargs.get('now', 0)) print('now:', now) if now: command += ' now' # Shorter timeout for a more granular cycle than the default. timeout = int(kwargs.get('timeout', 30)) reconnect_hostname = kwargs.pop('new_hostname', env.host_string) if 'dryrun' in kwargs: del kwargs['dryrun'] if dryrun: print('%s sudo: %s' % (render_command_prefix(), command)) else: if is_local(): if raw_input('reboot localhost now? ').strip()[0].lower() != 'y': return attempts = int(round(float(wait) / float(timeout))) # Don't bleed settings, since this is supposed to be self-contained. # User adaptations will probably want to drop the "with settings()" and # just have globally set timeout/attempts values. with settings(warn_only=True): _sudo(command) env.host_string = reconnect_hostname success = False for attempt in xrange(attempts): # Try to make sure we don't slip in before pre-reboot lockdown if verbose:
python
{ "resource": "" }
q258557
get_component_settings
validation
def get_component_settings(prefixes=None): """ Returns a subset of the env dictionary containing only those keys with the name prefix. """ prefixes = prefixes or [] assert isinstance(prefixes, (tuple, list)), 'Prefixes must be a sequence type, not %s.' % type(prefixes) data = {} for name in prefixes: name
python
{ "resource": "" }
q258558
get_last_modified_timestamp
validation
def get_last_modified_timestamp(path, ignore=None): """ Recursively finds the most recent timestamp in the given directory. """ ignore = ignore or [] if not isinstance(path, six.string_types): return ignore_str = '' if ignore: assert isinstance(ignore, (tuple, list)) ignore_str = ' '.join("! -name '%s'" % _ for _ in ignore) cmd = 'find "'+path+'" ' + ignore_str + ' -type f -printf "%T@ %p\n" | sort -n | tail -1 | cut -f 1 -d " "' #'find '+path+' -type f -printf "%T@ %p\n" | sort -n | tail -1 | cut -d " " -f1 ret =
python
{ "resource": "" }
q258559
check_settings_for_differences
validation
def check_settings_for_differences(old, new, as_bool=False, as_tri=False): """ Returns a subset of the env dictionary keys that differ, either being added, deleted or changed between old and new. """ assert not as_bool or not as_tri old = old or {} new = new or {} changes = set(k for k in set(new.iterkeys()).intersection(old.iterkeys()) if new[k] != old[k])
python
{ "resource": "" }
q258560
get_packager
validation
def get_packager(): """ Returns the packager detected on the remote system. """ # TODO: remove once fabric stops using contextlib.nested. # https://github.com/fabric/fabric/issues/1364 import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) common_packager = get_rc('common_packager') if common_packager: return common_packager #TODO:cache result by current env.host_string so we can handle multiple hosts with different OSes with settings(warn_only=True): with hide('running', 'stdout', 'stderr', 'warnings'): ret = _run('cat /etc/fedora-release') if ret.succeeded: common_packager = YUM else: ret = _run('cat /etc/lsb-release') if ret.succeeded: common_packager = APT
python
{ "resource": "" }
q258561
get_os_version
validation
def get_os_version(): """ Returns a named tuple describing the operating system on the remote host. """ # TODO: remove once fabric stops using contextlib.nested. # https://github.com/fabric/fabric/issues/1364 import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) common_os_version = get_rc('common_os_version') if common_os_version: return common_os_version with settings(warn_only=True): with hide('running', 'stdout', 'stderr', 'warnings'): ret = _run_or_local('cat /etc/lsb-release') if ret.succeeded: return OS( type=LINUX, distro=UBUNTU, release=re.findall(r'DISTRIB_RELEASE=([0-9\.]+)', ret)[0]) ret = _run_or_local('cat /etc/debian_version') if ret.succeeded:
python
{ "resource": "" }
q258562
render_to_string
validation
def render_to_string(template, extra=None): """ Renders the given template to a string. """ from jinja2 import Template extra = extra or {} final_fqfn = find_template(template) assert final_fqfn, 'Template not found: %s' % template template_content = open(final_fqfn, 'r').read() t = Template(template_content) if extra: context = env.copy()
python
{ "resource": "" }
q258563
render_to_file
validation
def render_to_file(template, fn=None, extra=None, **kwargs): """ Returns a template to a local file. If no filename given, a temporary filename will be generated and returned. """ import tempfile dryrun = get_dryrun(kwargs.get('dryrun')) append_newline = kwargs.pop('append_newline', True) style = kwargs.pop('style', 'cat') # |echo formatter = kwargs.pop('formatter', None) content = render_to_string(template, extra=extra) if append_newline and not content.endswith('\n'): content += '\n' if formatter and callable(formatter): content = formatter(content) if dryrun: if not fn: fd, fn = tempfile.mkstemp() fout = os.fdopen(fd, 'wt') fout.close() else: if fn: fout = open(fn, 'w') else: fd, fn = tempfile.mkstemp()
python
{ "resource": "" }
q258564
install_config
validation
def install_config(local_path=None, remote_path=None, render=True, extra=None, formatter=None): """ Returns a template to a remote file. If no filename given, a temporary filename will be generated and returned. """ local_path = find_template(local_path) if render: extra = extra or {}
python
{ "resource": "" }
q258565
iter_sites
validation
def iter_sites(sites=None, site=None, renderer=None, setter=None, no_secure=False, verbose=None): """ Iterates over sites, safely setting environment variables for each site. """ if verbose is None: verbose = get_verbose() hostname = get_current_hostname() target_sites = env.available_sites_by_host.get(hostname, None) if sites is None: site = site or env.SITE or ALL if site == ALL: sites = list(six.iteritems(env.sites)) else: sys.stderr.flush() sites = [(site, env.sites.get(site))] renderer = renderer #or render_remote_paths env_default = save_env() for _site, site_data in sorted(sites): if no_secure and _site.endswith('_secure'): continue # Only load site configurations that are allowed for this host. if target_sites is None: pass else: assert isinstance(target_sites, (tuple, list)) if _site not in target_sites: if verbose: print('Skipping site %s because
python
{ "resource": "" }
q258566
topological_sort
validation
def topological_sort(source): """perform topo sort on elements. :arg source: list of ``(name, [list of dependancies])`` pairs :returns: list of names, with dependancies listed first """ if isinstance(source, dict): source = source.items() pending = sorted([(name, set(deps)) for name, deps in source]) # copy deps so we can modify set in-place emitted = [] while pending: next_pending = [] next_emitted = [] for entry in pending:
python
{ "resource": "" }
q258567
get_hosts_for_site
validation
def get_hosts_for_site(site=None): """ Returns a list of hosts that have been configured to support the given site. """ site = site or env.SITE hosts = set() for hostname, _sites in six.iteritems(env.available_sites_by_host): # print('checking hostname:',hostname, _sites) for _site in _sites: if _site == site: # print( '_site:',_site)
python
{ "resource": "" }
q258568
Renderer.collect_genv
validation
def collect_genv(self, include_local=True, include_global=True): """ Returns a copy of the global environment with all the local variables copied back into it. """ e = type(self.genv)() if include_global:
python
{ "resource": "" }
q258569
Satchel.capture_bash
validation
def capture_bash(self): """ Context manager that hides the command prefix and activates dryrun to capture all following task commands to their equivalent Bash outputs. """ class Capture(object): def __init__(self, satchel): self.satchel = satchel self._dryrun = self.satchel.dryrun self.satchel.dryrun = 1
python
{ "resource": "" }
q258570
Satchel.register
validation
def register(self): """ Adds this satchel to the global registeries for fast lookup from other satchels. """ self._set_defaults() all_satchels[self.name.upper()] = self manifest_recorder[self.name] = self.record_manifest
python
{ "resource": "" }
q258571
Satchel.unregister
validation
def unregister(self): """ Removes this satchel from global registeries. """ for k in list(env.keys()): if k.startswith(self.env_prefix): del env[k] try: del all_satchels[self.name.upper()] except KeyError: pass try: del manifest_recorder[self.name] except KeyError: pass try:
python
{ "resource": "" }
q258572
Satchel.get_tasks
validation
def get_tasks(self): """ Returns an ordered list of all task names. """ tasks = set(self.tasks)#DEPRECATED for _name in dir(self): # Skip properties so we don't accidentally execute any methods. if isinstance(getattr(type(self), _name, None), property):
python
{ "resource": "" }
q258573
Satchel.local_renderer
validation
def local_renderer(self): """ Retrieves the cached local renderer. """ if not self._local_renderer:
python
{ "resource": "" }
q258574
Satchel.all_other_enabled_satchels
validation
def all_other_enabled_satchels(self): """ Returns a dictionary of satchels used in the current configuration, excluding ourselves. """ return dict( (name, satchel)
python
{ "resource": "" }
q258575
Satchel.lenv
validation
def lenv(self): """ Returns a version of env filtered to only include the variables in our namespace. """ _env = type(env)() for _k, _v in six.iteritems(env):
python
{ "resource": "" }
q258576
Satchel.param_changed_to
validation
def param_changed_to(self, key, to_value, from_value=None): """ Returns true if the given parameter, with name key, has transitioned to the given value. """
python
{ "resource": "" }
q258577
Satchel.reboot_or_dryrun
validation
def reboot_or_dryrun(self, *args, **kwargs): """ Reboots the server and waits for it to come back. """
python
{ "resource": "" }
q258578
Satchel.set_site_specifics
validation
def set_site_specifics(self, site): """ Loads settings for the target site. """ r = self.local_renderer site_data = self.genv.sites[site].copy() r.env.site = site if self.verbose: print('set_site_specifics.data:') pprint(site_data, indent=4) # Remove local namespace settings from the global namespace # by converting <satchel_name>_<variable_name> to <variable_name>.
python
{ "resource": "" }
q258579
Satchel.get_package_list
validation
def get_package_list(self): """ Returns a list of all required packages. """ os_version = self.os_version # OS(type=LINUX, distro=UBUNTU, release='14.04') self.vprint('os_version:', os_version) # Lookup legacy package list. # OS: [package1, package2, ...], req_packages1 = self.required_system_packages if req_packages1: deprecation('The required_system_packages attribute is deprecated, ' 'use the packager_system_packages property instead.') # Lookup new package list. # OS: [package1, package2, ...], req_packages2 = self.packager_system_packages
python
{ "resource": "" }
q258580
Satchel.has_changes
validation
def has_changes(self): """ Returns true if at least one tracker detects a change. """ lm = self.last_manifest for tracker in self.get_trackers():
python
{ "resource": "" }
q258581
Satchel.configure
validation
def configure(self): """ The standard method called to apply functionality when the manifest changes. """ lm = self.last_manifest for tracker in self.get_trackers(): self.vprint('Checking tracker:', tracker) last_thumbprint = lm['_tracker_%s' % tracker.get_natural_key_hash()] self.vprint('last thumbprint:', last_thumbprint)
python
{ "resource": "" }
q258582
PostgreSQLSatchel.write_pgpass
validation
def write_pgpass(self, name=None, site=None, use_sudo=0, root=0): """ Write the file used to store login credentials for PostgreSQL. """ r = self.database_renderer(name=name, site=site) root = int(root) use_sudo = int(use_sudo) r.run('touch {pgpass_path}') if '~' in r.env.pgpass_path: r.run('chmod {pgpass_chmod} {pgpass_path}')
python
{ "resource": "" }
q258583
PostgreSQLSatchel.dumpload
validation
def dumpload(self, site=None, role=None): """ Dumps and loads a database snapshot simultaneously. Requires that the destination server has direct database access to the source server. This is better than a serial dump+load when: 1. The network connection is reliable. 2. You don't need to save the dump file. The benefits of this over a dump+load are: 1. Usually runs faster, since the load and dump happen in parallel. 2. Usually takes up less disk space since no separate dump file is downloaded.
python
{ "resource": "" }
q258584
PostgreSQLSatchel.drop_database
validation
def drop_database(self, name): """ Delete a PostgreSQL database. Example:: import burlap # Remove DB if it exists
python
{ "resource": "" }
q258585
PostgreSQLSatchel.load_table
validation
def load_table(self, table_name, src, dst='localhost', name=None, site=None): """ Directly transfers a table between two databases. """ #TODO: incomplete r = self.database_renderer(name=name, site=site) r.env.table_name = table_name
python
{ "resource": "" }
q258586
interfaces
validation
def interfaces(): """ Get the list of network interfaces. Will return all datalinks on SmartOS. """ with settings(hide('running', 'stdout')):
python
{ "resource": "" }
q258587
address
validation
def address(interface): """ Get the IPv4 address assigned to an interface. Example:: import burlap # Print all configured IP addresses for interface in burlap.network.interfaces(): print(burlap.network.address(interface)) """ with settings(hide('running', 'stdout')): res =
python
{ "resource": "" }
q258588
PackagerSatchel.update
validation
def update(self): """ Preparse the packaging system for installations. """ packager = self.packager if packager == APT:
python
{ "resource": "" }
q258589
PackagerSatchel.install_apt
validation
def install_apt(self, fn=None, package_name=None, update=0, list_only=0): """ Installs system packages listed in apt-requirements.txt. """ r = self.local_renderer assert self.genv[ROLE] apt_req_fqfn = fn or (self.env.apt_requirments_fn and self.find_template(self.env.apt_requirments_fn)) if not apt_req_fqfn: return [] assert os.path.isfile(apt_req_fqfn) lines = list(self.env.apt_packages or []) for _ in open(apt_req_fqfn).readlines(): if _.strip() and not _.strip().startswith('#') \ and (not package_name or _.strip() == package_name): lines.extend(_pkg.strip() for _pkg in _.split(' ') if _pkg.strip())
python
{ "resource": "" }
q258590
PackagerSatchel.install_yum
validation
def install_yum(self, fn=None, package_name=None, update=0, list_only=0): """ Installs system packages listed in yum-requirements.txt. """ assert self.genv[ROLE] yum_req_fn = fn or self.find_template(self.genv.yum_requirments_fn) if not yum_req_fn: return [] assert os.path.isfile(yum_req_fn) update = int(update) if list_only: return [ _.strip() for _ in open(yum_req_fn).readlines() if _.strip() and not _.strip.startswith('#') and (not package_name or _.strip() == package_name)
python
{ "resource": "" }
q258591
PackagerSatchel.list_required
validation
def list_required(self, type=None, service=None): # pylint: disable=redefined-builtin """ Displays all packages required by the current role based on the documented services provided. """ from burlap.common import ( required_system_packages, required_python_packages, required_ruby_packages, ) service = (service or '').strip().upper() type = (type or '').lower().strip() assert not type or type in PACKAGE_TYPES, 'Unknown package type: %s' % (type,) packages_set = set() packages = [] version = self.os_version for _service, satchel in self.all_other_enabled_satchels.items(): _service = _service.strip().upper() if service and service != _service: continue _new = [] if not type or type == SYSTEM: #TODO:deprecated, remove _new.extend(required_system_packages.get( _service, {}).get((version.distro, version.release), [])) try: _pkgs = satchel.packager_system_packages if self.verbose: print('pkgs:') pprint(_pkgs, indent=4) for _key in [(version.distro, version.release), version.distro]: if self.verbose: print('checking key:', _key) if _key in _pkgs: if self.verbose: print('satchel %s requires:' % satchel, _pkgs[_key]) _new.extend(_pkgs[_key])
python
{ "resource": "" }
q258592
PackagerSatchel.install_required
validation
def install_required(self, type=None, service=None, list_only=0, **kwargs): # pylint: disable=redefined-builtin """ Installs system packages listed as required by services this host uses. """ r = self.local_renderer list_only = int(list_only) type = (type or '').lower().strip() assert not type or type in PACKAGE_TYPES, 'Unknown package type: %s' % (type,) lst = [] if type: types = [type]
python
{ "resource": "" }
q258593
PackagerSatchel.uninstall_blacklisted
validation
def uninstall_blacklisted(self): """ Uninstalls all blacklisted packages. """ from burlap.system import distrib_family blacklisted_packages = self.env.blacklisted_packages if not blacklisted_packages: print('No blacklisted packages.') return else: family = distrib_family() if family == DEBIAN:
python
{ "resource": "" }
q258594
CronSatchel.deploy
validation
def deploy(self, site=None): """ Writes entire crontab to the host. """ r = self.local_renderer self.deploy_logrotate() cron_crontabs = [] # if self.verbose: # print('hostname: "%s"' % (hostname,), file=sys.stderr) for _site, site_data in self.iter_sites(site=site): r.env.cron_stdout_log = r.format(r.env.stdout_log_template) r.env.cron_stderr_log = r.format(r.env.stderr_log_template) r.sudo('touch {cron_stdout_log}') r.sudo('touch {cron_stderr_log}') r.sudo('sudo chown {user}:{user} {cron_stdout_log}') r.sudo('sudo chown {user}:{user} {cron_stderr_log}') if self.verbose: print('site:', site, file=sys.stderr) print('env.crontabs_selected:', self.env.crontabs_selected, file=sys.stderr) for selected_crontab in self.env.crontabs_selected: lines = self.env.crontabs_available.get(selected_crontab, []) if self.verbose: print('lines:', lines, file=sys.stderr)
python
{ "resource": "" }
q258595
RabbitMQSatchel.force_stop_and_purge
validation
def force_stop_and_purge(self): """ Forcibly kills Rabbit and purges all its queues. For emergency use when the server becomes unresponsive, even to service stop calls. If this also fails to correct the performance issues, the server may have to be
python
{ "resource": "" }
q258596
RabbitMQSatchel._configure_users
validation
def _configure_users(self, site=None, full=0, only_data=0): """ Installs and configures RabbitMQ. """ site = site or ALL full = int(full) if full and not only_data: packager = self.get_satchel('packager') packager.install_required(type=SYSTEM, service=self.name) r = self.local_renderer params = self.get_user_vhosts(site=site) # [(user, password, vhost)] with settings(warn_only=True): self.add_admin_user() params = sorted(list(params)) if not only_data: for user, password, vhost in params: r.env.broker_user = user r.env.broker_password = password r.env.broker_vhost = vhost with settings(warn_only=True):
python
{ "resource": "" }
q258597
iter_dict_differences
validation
def iter_dict_differences(a, b): """ Returns a generator yielding all the keys that have values that differ between each dictionary. """ common_keys = set(a).union(b) for k
python
{ "resource": "" }
q258598
get_component_order
validation
def get_component_order(component_names): """ Given a list of components, re-orders them according to inter-component dependencies so the most depended upon are first. """ assert isinstance(component_names, (tuple, list)) component_dependences = {} for _name in component_names: deps = set(manifest_deployers_befores.get(_name, []))
python
{ "resource": "" }
q258599
get_deploy_funcs
validation
def get_deploy_funcs(components, current_thumbprint, previous_thumbprint, preview=False): """ Returns a generator yielding the named functions needed for a deployment. """ for component in components: funcs = manifest_deployers.get(component, []) for func_name in funcs: #TODO:remove this after burlap.* naming prefix bug fixed if func_name.startswith('burlap.'): print('skipping %s' % func_name) continue takes_diff = manifest_deployers_takes_diff.get(func_name, False)
python
{ "resource": "" }