Search is not available for this dataset
text
stringlengths
75
104k
def record_manifest(self): """ Called after a deployment to record any data necessary to detect changes for a future deployment. """ manifest = super(SeleniumSatchel, self).record_manifest() manifest['fingerprint'] = str(self.get_target_geckodriver_version_number()) ...
def update(kernel=False): """ Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``. Exclude *kernel* upgrades by default. """ manager = MANAGER cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}} cmd = cmds[manager][kernel] run_as_root...
def is_installed(pkg_name): """ Check if an RPM package is installed. """ manager = MANAGER with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True): res = run("rpm --query %(pkg_name)s" % locals()) if res.succeeded: return True return False
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 ...
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']``). :: import burlap # Install developmen...
def uninstall(packages, options=None): """ Remove one or more packages. Extra *options* may be passed to ``yum`` if necessary. """ manager = MANAGER if options is None: options = [] elif isinstance(options, six.string_types): options = [options] if not isinstance(packag...
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): options = [options] options = " ".join(options) ...
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 burla...
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.s...
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 ...
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 """ from boto.s3 im...
def static(self): """ Configures the server to use a static IP. """ fn = self.render_to_file('ip/ip_interfaces_static.template') r = self.local_renderer r.put(local_path=fn, remote_path=r.env.interfaces_fn, use_sudo=True)
def record_manifest(self): """ Called after a deployment to record any data necessary to detect changes for a future deployment. """ manifest = super(TarballSatchel, self).record_manifest() manifest['timestamp'] = self.timestamp return manifest
def get_thumbprint(self): """ Calculates the current thumbprint of the item being tracked. """ extensions = self.extensions.split(' ') name_str = ' -or '.join('-name "%s"' % ext for ext in extensions) cmd = 'find ' + self.base_dir + r' -type f \( ' + name_str + r' \) -exe...
def get_thumbprint(self): """ Calculates the current thumbprint of the item being tracked. """ d = {} if self.names: names = self.names else: names = list(self.satchel.lenv) for name in self.names: d[name] = deepcopy(self.satche...
def get_thumbprint(self): """ Calculates the current thumbprint of the item being tracked. """ d = {} for tracker in self.trackers: d[type(tracker).__name__] = tracker.get_thumbprint() return d
def upgrade(safe=True): """ Upgrade all packages. """ manager = MANAGER if safe: cmd = 'upgrade' else: cmd = 'dist-upgrade' run_as_root("%(manager)s --assume-yes %(cmd)s" % locals(), pty=False)
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: "): stat...
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:: i...
def uninstall(packages, purge=False, options=None): """ Remove one or more packages. If *purge* is ``True``, the package configuration files will be removed from the system. Extra *options* may be passed to ``apt-get`` if necessary. """ manager = MANAGER command = "purge" if purge else...
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...
def get_selections(): """ Get the state of ``dkpg`` selections. Returns a dict with state => [packages]. """ with settings(hide('stdout')): res = run_as_root('dpkg --get-selections') selections = dict() for line in res.splitlines(): package, status = line.split() sel...
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' with settings(hide('everything'), warn_only=True): res = r...
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...
def configure(self): """ Enables the repository for a most current version on Debian systems. https://www.rabbitmq.com/install-debian.html """ os_version = self.os_version if not self.dryrun and os_version.distro != UBUNTU: raise NotImplementedError("OS ...
def exists(self, name): """ Check if a group exists. """ with self.settings(hide('running', 'stdout', 'warnings'), warn_only=True): return self.run('getent group %(name)s' % locals()).succeeded
def create(self, name, gid=None): """ Create a new group. Example:: import burlap if not burlap.group.exists('admin'): burlap.group.create('admin') """ args = [] if gid: args.append('-g %s' % gid) args.append...
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 # ...
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: r.env.username...
def passwordless(self, username, pubkey): """ Configures the user to use an SSL key without a password. Assumes you've run generate_keys() first. """ r = self.local_renderer r.env.username = username r.env.pubkey = pubkey if not self.dryrun: ...
def generate_keys(self, username, hostname): """ Generates *.pem and *.pub key files suitable for setting up passwordless SSH. """ r = self.local_renderer #r.env.key_filename = r.env.key_filename or env.key_filename #assert r.env.key_filename, 'r.env.key_filename or env...
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' %...
def expire_password(self, username): """ Forces the user to change their password the next time they login. """ r = self.local_renderer r.env.username = username r.sudo('chage -d 0 {username}')
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 burlap.common import run_or_dryrun, sudo_or_dryrun if env.user == 'root...
def oct(v, **kwargs): # pylint: disable=redefined-builtin """ A backwards compatible version of oct() that works with Python2.7 and Python3. """ v = str(v) if six.PY2: if v.startswith('0o'): v = '0' + v[2:] else: if not v.starswith('0o'): assert v[0] == '0...
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(b...
def check(self): """ Run inadyn from the commandline to test the configuration. To be run like: fab role inadyn.check """ self._validate_settings() r = self.local_renderer r.env.alias = r.env.aliases[0] r.sudo(r.env.check_command_template)
def list_env(self, key=None): """ Displays a list of environment key/value pairs. """ for k, v in sorted(self.genv.items(), key=lambda o: o[0]): if key and k != key: continue print('%s ' % (k,)) pprint(v, indent=4)
def list_server_specs(self, cpu=1, memory=1, hdd=1): """ Displays a list of common servers characteristics, like number of CPU cores, amount of memory and hard drive capacity. """ r = self.local_renderer cpu = int(cpu) memory = int(memory) hdd = int(hdd) ...
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.ge...
def disk(self): """ Display percent of disk usage. """ r = self.local_renderer r.run(r.env.disk_usage_command)
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 r.local(' ssh -i {key_filename} -L {tunnel_local_port}:localhost:{tunnel_remote_port} {use...
def set_satchel_value(self, satchel, key, value): """ Sets a key/value pair in a satchel's local renderer. """ satchel = self.get_satchel(satchel) r = satchel.local_renderer setattr(r.env, key, value) print('Set %s=%s in satchel %s.' % (key, value, satchel.name))
def package_version(name, python_cmd='python'): """ Get the installed version of a package Returns ``None`` if it can't be found. """ cmd = '''%(python_cmd)s -c \ "import pkg_resources;\ dist = pkg_resources.get_distribution('%(name)s');\ print dist.version" ''' % lo...
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...
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' % locals() if use_sudo: run_as_root(command) else: run(command...
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 ...
def _easy_install(argv, python_cmd, use_sudo): """ Install packages using easy_install We don't know if the easy_install command in the path will be the right one, so we use the setuptools entry point to call the script's main function ourselves. """ command = """python -c "\ from p...
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 == GE...
def has_virtualenv(self): """ Returns true if the virtualenv tool is installed. """ with self.settings(warn_only=True): ret = self.run_or_local('which virtualenv').strip() return bool(ret)
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 = 'cann...
def what_requires(self, name): """ Lists the packages that require the given package. """ r = self.local_renderer r.env.name = name r.local('pipdeptree -p {name} --reverse')
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): ...
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(): ...
def record_manifest(self): """ Called after a deployment to record any data necessary to detect changes for a future deployment. """ manifest = super(PIPSatchel, self).record_manifest() manifest['all-requirements'] = self.get_combined_requirements() if self.verbos...
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_t...
def get_or_create_ec2_security_groups(names=None, verbose=1): """ Creates a security group opening 22, 80 and 443 """ verbose = int(verbose) if verbose: print('Creating EC2 security groups...') conn = get_ec2_connection() if isinstance(names, six.string_types): names = nam...
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) ...
def get_or_create_ec2_instance(name=None, group=None, release=None, verbose=0, backend_opts=None): """ Creates a new EC2 instance. You should normally run get_or_create() instead of directly calling this. """ from burlap.common import shelf, OrderedDict from boto.exception import EC2ResponseErr...
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, ...
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.fi...
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=...
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(): if env.host_string == instance.public_dns_name: name = instance.tags.get(env.vm_name_tag) ...
def respawn(name=None, group=None): """ Deletes and recreates one or more VM instances. """ if name is None: name = get_name() delete(name=name, group=group) instance = get_or_create(name=name, group=group) env.host_string = instance.public_dns_name
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 = ' '.join( ...
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. ...
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)) exec(code in module....
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...
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 isinstance(s, six.string_types): raise NotImplementedError('Unknown type: %s' % type(s)) return [_....
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.' if not s: return env_hosts_retriever # module_name = '.'.join(s.split('.')[:-1]) # ...
def append_or_dryrun(*args, **kwargs): """ Wrapper around Fabric's contrib.files.append() to give it a dryrun option. text filename http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.append """ from fabric.contrib.files import append dryrun = get_dryrun(kwargs.ge...
def disable_attribute_or_dryrun(*args, **kwargs): """ Comments-out a line containing an attribute. The inverse of enable_attribute_or_dryrun(). """ dryrun = get_dryrun(kwargs.get('dryrun')) if 'dryrun' in kwargs: del kwargs['dryrun'] use_sudo = kwargs.pop('use_sudo', False) run...
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\nEO...
def sed_or_dryrun(*args, **kwargs): """ Wrapper around Fabric's contrib.files.sed() to give it a dryrun option. http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.sed """ dryrun = get_dryrun(kwargs.get('dryrun')) if 'dryrun' in kwargs: del kwargs['dryrun'] ...
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...
def pretty_bytes(bytes): # pylint: disable=redefined-builtin """ Scales a byte count to the largest scale with a small whole number that's easier to read. Returns a tuple of the format (scaled_float, unit_string). """ if not bytes: return bytes, 'bytes' sign = bytes/float(bytes) ...
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...
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)) ...
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 ...
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_...
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) ...
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 = ...
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) ...
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 {} ...
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_...
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, de...
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 _si...
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: e.update(self.genv) if include_local: for k...
def _set_defaults(self): """ Wrapper around the overrideable set_defaults(). """ # Register an "enabled" flag on all satchels. # How this flag is interpreted depends on the individual satchel. _prefix = '%s_enabled' % self.name if _prefix not in env: ...
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 ...
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 # Register service commands. if...
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 ...
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): ...
def local_renderer(self): """ Retrieves the cached local renderer. """ if not self._local_renderer: r = self.create_local_renderer() self._local_renderer = r return self._local_renderer
def all_other_enabled_satchels(self): """ Returns a dictionary of satchels used in the current configuration, excluding ourselves. """ return dict( (name, satchel) for name, satchel in self.all_satchels.items() if name != self.name.upper() and name.low...
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): if _k.startswith(self.name+'_'): _env[_k[len(self.name)+1:]] = _v return _env
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. """ last_value = getattr(self.last_manifest, key) current_value = self.current_manifest.get(key) if from_value is not N...
def reboot_or_dryrun(self, *args, **kwargs): """ Reboots the server and waits for it to come back. """ warnings.warn('Use self.run() instead.', DeprecationWarning, stacklevel=2) self.reboot(*args, **kwargs)
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...
def vprint(self, *args, **kwargs): """ When verbose is set, acts like the normal print() function. Otherwise, does nothing. """ if self.verbose: curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) caller_name = calf...