_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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 options = '-r ' if recursive else '' func('/bin/cp {0}{1} {2}'.format(options, quote(source), quote(destination)))
python
{ "resource": "" }
q258501
FileSatchel.move
validation
def move(self, source, destination, use_sudo=False): """ Move a file or directory """ func = use_sudo and run_as_root or self.run func('/bin/mv {0} {1}'.format(quote(source), quote(destination)))
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 self.run options = '-r ' if recursive else '' func('/bin/rm {0}{1}'.format(options, quote(path)))
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*, *group* and *mode* parameters can be used to override these properties. .. note:: This function can be accessed directly from the ``fabtools.require`` module for convenience. """ func = use_sudo and run_as_root or self.run # 1) Only a path is given if path and not (contents or source or url): assert path if not self.is_file(path): func('touch "%(path)s"' % locals()) # 2) A URL is specified (path is optional) elif url: if not path: path = os.path.basename(urlparse(url).path) if not self.is_file(path) or md5 and self.md5sum(path) != md5: func('wget --progress=dot:mega "%(url)s" -O "%(path)s"' % locals()) # 3) A local filename, or a content string, is specified else: if source: assert not contents t = None else: fd, source = mkstemp() t = os.fdopen(fd, 'w') t.write(contents) t.close() if verify_remote: # Avoid reading the whole file into memory at once digest = hashlib.md5() f = open(source, 'rb') try: while True: d = f.read(BLOCKSIZE) if not d: break digest.update(d) finally: f.close() else: digest = None if (not self.is_file(path, use_sudo=use_sudo) or (verify_remote and self.md5sum(path, use_sudo=use_sudo) != digest.hexdigest())): with self.settings(hide('running')): self.put(local_path=source, remote_path=path, use_sudo=use_sudo, temp_dir=temp_dir) if t is not None: os.unlink(source) # Ensure correct owner if use_sudo and owner is None: owner = 'root' if (owner and self.get_owner(path, use_sudo) != owner) or \ (group and self.get_group(path, use_sudo) != group): func('chown %(owner)s:%(group)s "%(path)s"' % locals()) # Ensure correct mode if use_sudo and mode is None: mode = oct(0o666 & ~int(self.umask(use_sudo=True), base=8)) if mode and self.get_mode(path, use_sudo) != mode: func('chmod %(mode)s "%(path)s"' % locals())
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) self.vprint('current_fingerprint:', current_fingerprint) if last_fingerprint != current_fingerprint: print('A new release is available. %s' % self.get_most_recent_version()) return True print('No updates found.') return False
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 cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}} cmd = cmds[manager][kernel] run_as_root("%(manager)s %(cmd)s" % locals())
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', 'stderr', 'warnings'), warn_only=True): res = run("rpm --query %(pkg_name)s" % locals()) if res.succeeded: return True return False
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 if options is None: options = [] elif isinstance(options, six.string_types): options = [options] if not isinstance(packages, six.string_types): packages = " ".join(packages) if repos: for repo in repos: options.append('--enablerepo=%(repo)s' % locals()) options = " ".join(options) if isinstance(yes, str): run_as_root('yes %(yes)s | %(manager)s %(options)s install %(packages)s' % locals()) else: run_as_root('%(manager)s %(options)s install %(packages)s' % locals())
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']``). :: import burlap # Install development packages burlap.rpm.groupinstall('Development tools') """ manager = MANAGER if options is None: options = [] elif isinstance(options, str): options = [options] options = " ".join(options) run_as_root('%(manager)s %(options)s groupinstall "%(group)s"' % locals(), pty=False)
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): options = [options] options = " ".join(options) run_as_root('%(manager)s %(options)s groupremove "%(group)s"' % locals())
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 repositories burlap.rpm.install('vim', burlap.rpm.repolist('disabled')) """ manager = MANAGER with settings(hide('running', 'stdout')): if media: repos = run_as_root("%(manager)s repolist %(status)s | sed '$d' | sed -n '/repo id/,$p'" % locals()) else: repos = run_as_root("%(manager)s repolist %(status)s | sed '/Media\\|Debug/d' | sed '$d' | sed -n '/repo id/,$p'" % locals()) return [line.split(' ')[0] for line in repos.splitlines()[1:]]
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) else: #run('which s3sync') r.env.local_path = local_path if local_path.endswith('/') and not r.env.local_path.endswith('/'): r.env.local_path = r.env.local_path + '/' r.env.remote_path = remote_path % r.genv print('Syncing %s to %s...' % (r.env.local_path, r.env.remote_path)) # Superior Python version. if force: r.env.sync_cmd = 'put' else: r.env.sync_cmd = 'sync' r.local( 'export AWS_ACCESS_KEY_ID={aws_access_key_id}; '\ 'export AWS_SECRET_ACCESS_KEY={aws_secret_access_key}; '\ '{s3cmd_path} {sync_cmd} --progress --acl-public --guess-mime-type --no-mime-magic '\ '--delete-removed --cf-invalidate --recursive {sync_force_flag} '\ '{local_path} {remote_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: print(dist.domain_name, dir(dist), dist.__dict__) bucket_name = dist.origin.dns_name.replace('.s3.amazonaws.com', '') if bucket_name == _settings.AWS_STATIC_BUCKET_NAME: target_dist = dist break if not target_dist: raise Exception(('Target distribution %s could not be found in the AWS account.') % (settings.AWS_STATIC_BUCKET_NAME,)) print('Using distribution %s associated with origin %s.' % (target_dist.id, _settings.AWS_STATIC_BUCKET_NAME)) inval_req = c.create_invalidation_request(target_dist.id, paths) print('Issue invalidation request %s.' % (inval_req,)) i += 1000
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 """ from boto.s3 import connection if self.dryrun: print('boto.connect_s3().create_bucket(%s)' % repr(name)) else: conn = connection.S3Connection( self.genv.aws_access_key_id, self.genv.aws_secret_access_key ) bucket = conn.create_bucket(name) return bucket
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 = self.local_renderer r.put(local_path=fn, remote_path=r.env.interfaces_fn, use_sudo=True)
python
{ "resource": "" }
q258515
upgrade
validation
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)
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: "): status = line[8:] if "installed" in status.split(' '): return True return False
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-dev', 'libxml2-dev', ]) # Install a specific version burlap.deb.install('emacs', version='23.3+1-1ubuntu9') """ manager = MANAGER if update: update_index() if options is None: options = [] if version is None: version = '' if version and not isinstance(packages, list): version = '=' + version if not isinstance(packages, six.string_types): packages = " ".join(packages) options.append("--quiet") options.append("--assume-yes") options = " ".join(options) cmd = '%(manager)s install %(options)s %(packages)s%(version)s' % locals() run_as_root(cmd, pty=False)
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'), }) burlap.deb.install('postfix') """ for q_name, _ in preseed.items(): q_type, q_answer = _ run_as_root('echo "%(pkg_name)s %(q_name)s %(q_type)s %(q_answer)s" | debconf-set-selections' % locals())
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')): res = run_as_root('dpkg --get-selections') selections = dict() for line in res.splitlines(): package, status = line.split() selections.setdefault(status, list()).append(package) return selections
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' with settings(hide('everything'), warn_only=True): res = run('%(gpg_cmd)s --fingerprint %(keyid)s' % locals()) return res.succeeded
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) run_as_root('apt-key add %(filename)s' % locals()) elif url is not None: tmp_key = '/tmp/tmp.burlap.key.%(keyid)s.key' % locals() run_as_root('wget %(url)s -O %(tmp_key)s' % locals()) _check_pgp_key(tmp_key, keyid) run_as_root('apt-key add %(tmp_key)s' % locals()) else: keyserver_opt = '--keyserver %(keyserver)s' % locals() if keyserver is not None else '' run_as_root('apt-key adv %(keyserver_opt)s --recv-keys %(keyid)s' % locals()) if update: update_index()
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): return self.run('getent group %(name)s' % locals()).succeeded
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, } print('prompts:', prompts) r.env.password = r.env.old_password with self.settings(warn_only=True): ret = r._local("sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello", capture=True) #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 = r.env.old_password elif self.genv.user in self.genv.user_passwords: # Otherwise, use the password or key set in the config. self.genv.password = r.env.new_password else: # Default password fails and there's no current password, so clear. self.genv.password = None print('using password:', self.genv.password) # Note, the correct current password should be set in host.initrole(), not here. #r.genv.password = r.env.new_password #r.genv.password = r.env.new_password with self.settings(prompts=prompts): ret = r._run('echo checking for expired password') print('ret:[%s]' % ret) do_disconnect = 'passwd: password updated successfully' in ret print('do_disconnect:', do_disconnect) if do_disconnect: # We need to disconnect to reset the session or else Linux will again prompt # us to change our password. disconnect_all() # Further logins should require the new password. self.genv.password = r.env.new_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: r.env.username = user r.env.group = group r.sudo('groupadd --force {group}') r.sudo('adduser {username} {group}')
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: args.append('--no-create-home') if password is None: pass elif password: crypted_password = _crypt_password(password) args.append('-p %s' % quote(crypted_password)) else: args.append('--disabled-password') args.append('--gecos ""') if system: args.append('--system') r.env.args = ' '.join(args) r.env.groups = (groups or '').strip() r.sudo('adduser {args} {username} || true') if groups: for group in groups.split(' '): group = group.strip() if not group: continue r.sudo('adduser %s %s || true' % (username, group))
python
{ "resource": "" }
q258526
UserSatchel.expire_password
validation
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}')
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 burlap.common import run_or_dryrun, sudo_or_dryrun if env.user == 'root': func = run_or_dryrun else: func = sudo_or_dryrun return func(command, *args, **kwargs)
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) except TypeError: # Fixes Python3 error "TypeError: Unicode-objects must be encoded before hashing". h.update(data.encode('utf-8')) return h.hexdigest()
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() r = self.local_renderer r.env.alias = r.env.aliases[0] r.sudo(r.env.check_command_template)
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}' elif r.genv.key_filename: self.vprint('Using key filename.') # If host_string contains the port, then strip it off and pass separately. port = r.env.shell_host_string.split(':')[-1] if port.isdigit(): r.env.shell_host_string = r.env.shell_host_string.split(':')[0] + (' -p %s' % port) cmd = 'ssh -t {shell_default_options_str} -i {key_filename} {shell_host_string} "{shell_interactive_cmd_str}"' elif r.genv.password: self.vprint('Using password.') cmd = 'ssh -t {shell_default_options_str} {shell_host_string} "{shell_interactive_cmd_str}"' else: # No explicit password or key file needed? self.vprint('Using nothing.') cmd = 'ssh -t {shell_default_options_str} {shell_host_string} "{shell_interactive_cmd_str}"' r.local(cmd)
python
{ "resource": "" }
q258531
DebugSatchel.disk
validation
def disk(self): """ Display percent of disk usage. """ r = self.local_renderer r.run(r.env.disk_usage_command)
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 r.local(' ssh -i {key_filename} -L {tunnel_local_port}:localhost:{tunnel_remote_port} {user}@{host_string} -N')
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: _install_from_scratch(python_cmd, use_sudo) else: if distribute_version is None: _upgrade_from_setuptools(python_cmd, use_sudo) else: _upgrade_from_distribute(python_cmd, use_sudo)
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' % locals() if use_sudo: run_as_root(command) else: run(command) run('rm -f 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 :py:func:`burlap.python.install()` instead, which uses ``pip`` to install packages. """ argv = [] if upgrade: argv.append("-U") if isinstance(packages, six.string_types): argv.append(packages) else: argv.extend(packages) _easy_install(argv, python_cmd, use_sudo)
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') r.sudo('easy_install -U pip') elif r.env.bootstrap_method == PYTHON_PIP: r.sudo('apt-get install -y python-pip') else: raise NotImplementedError('Unknown pip bootstrap method: %s' % r.env.bootstrap_method) r.sudo('pip {quiet_flag} install --upgrade pip') r.sudo('pip {quiet_flag} install --upgrade virtualenv')
python
{ "resource": "" }
q258537
PIPSatchel.has_virtualenv
validation
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)
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 in ret.strip().lower() if self.verbose: if ret: print('Yes') else: print('No') return ret
python
{ "resource": "" }
q258539
PIPSatchel.what_requires
validation
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')
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 = '[ ! -d {virtualenv_dir} ] && virtualenv --no-site-packages {virtualenv_dir} || true' if self.is_local: r.run_or_local(cmd) else: r.sudo(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() if not line or line.startswith('#'): continue yield line content = [] if isinstance(requirements, (tuple, list)): for f in requirements: f = self.find_template(f) content.extend(list(iter_lines(f))) else: assert isinstance(requirements, six.string_types) f = self.find_template(requirements) content.extend(list(iter_lines(f))) return '\n'.join(content)
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)) continue if _release and release != _release: if verbose: print(('Skipping instance %s because its release "%s" ' 'does not match release "%s".') \ % (instance.public_dns_name, release, _release)) continue if except_release and release == except_release: continue if verbose: print('Adding instance %s (%s).' \ % (name, instance.public_dns_name)) data.setdefault(name, type(env)()) data[name]['id'] = instance.id data[name]['public_dns_name'] = instance.public_dns_name if verbose: print('Public DNS: %s' % instance.public_dns_name) if env.vm_elastic_ip_mappings and name in env.vm_elastic_ip_mappings: data[name]['ip'] = env.vm_elastic_ip_mappings[name] else: data[name]['ip'] = socket.gethostbyname(instance.public_dns_name) if int(show): pprint(data, indent=4) return data elif env.vm_type == KVM: #virsh list pass else: raise NotImplementedError
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) if kp: print('Key pair %s already exists.' % name) else: # Note, we only get the private key during creation. # If we don't save it here, it's lost forever. kp = conn.create_key_pair(name) open(pem_path, 'wb').write(kp.material) os.system('chmod 600 %s' % pem_path) print('Key pair %s created.' % name) #return kp return pem_path
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, verbose=verbose, show=verbose) ret = bool(instances) if verbose: print('\ninstance %s exist' % ('DOES' if ret else 'does NOT')) #return ret return instances
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 = datetime.date.today() release = int('%i%02i%02i' % (today.year, today.month, today.day)) if not name: existing_instances = list_instances( group=group, release=release, verbose=verbose) name = env.vm_name_template.format(index=len(existing_instances)+1) if env.vm_type == EC2: return get_or_create_ec2_instance( name=name, group=group, release=release, verbose=verbose, backend_opts=backend_opts) else: raise NotImplementedError
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'])) if not get_dryrun(): conn.terminate_instances(instance_ids=[instance_data['id']]) # Clear host key on localhost. known_hosts = os.path.expanduser('~/.ssh/known_hosts') cmd = 'ssh-keygen -f "%s" -R %s' % (known_hosts, public_dns_name) local_or_dryrun(cmd) else: raise NotImplementedError
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(): if env.host_string == instance.public_dns_name: name = instance.tags.get(env.vm_name_tag) return name else: raise NotImplementedError
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() delete(name=name, group=group) instance = get_or_create(name=name, group=group) env.host_string = instance.public_dns_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 = ' '.join( "--exclude='%s'" % _ for _ in self.env.exclusions) r.local(r.env.rsync_command) r.sudo('chown -R {rsync_chown_user}:{rsync_chown_group} {rsync_dst_dir}')
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: [sites]} # If no entry found, will use available_sites. env.available_sites_by_host = {} # The command run to determine the percent of disk usage. env.disk_usage_command = "df -H | grep -vE '^Filesystem|tmpfs|cdrom|none' | awk '{print $5 " " $1}'" env.burlap_data_dir = '.burlap' env.setdefault('roledefs', {}) env.setdefault('roles', []) env.setdefault('hosts', []) env.setdefault('exclude_hosts', [])
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)) exec(code in module.__dict__) # pylint: disable=exec-used exec("from %s import %s" % (name, '*')) # pylint: disable=exec-used return module
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__) # Convert executable to a Fabric task, if not done so already. if not hasattr(func, 'is_task_or_dryrun'): func = task_or_dryrun(func) if module_name == module_alias \ or (module_name.startswith('satchels.') and module_name.endswith(module_alias)): # add the function to the current module setattr(module_obj, method_name, func) else: # Dynamically create a module for the virtual satchel. _module_obj = module_obj module_obj = create_module(module_alias) setattr(module_obj, method_name, func) post_import_modules.add(module_alias) fabric_name = '%s.%s' % (module_alias or module_name, method_name) func.wrapped.__func__.fabric_name = fabric_name return func
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 isinstance(s, six.string_types): raise NotImplementedError('Unknown type: %s' % type(s)) return [_.strip().lower() for _ in (s or '').split(',') if _.strip()]
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.' if not s: return env_hosts_retriever # module_name = '.'.join(s.split('.')[:-1]) # func_name = s.split('.')[-1] # retriever = getattr(importlib.import_module(module_name), func_name) # return retriever return str_to_callable(s) or env_hosts_retriever
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) if BURLAP_COMMAND_PREFIX: print('%s %s: %s' % (render_command_prefix(), cmd_run, cmd)) else: print(cmd) else: fd, tmp_fn = tempfile.mkstemp() fout = open(tmp_fn, 'w') fout.write(content) fout.close() return tmp_fn
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: print('Waiting for %s seconds, wait %i of %i' % (timeout, attempt+1, attempts)) time.sleep(timeout) # This is actually an internal-ish API call, but users can simply drop # it in real fabfile use -- the next run/sudo/put/get/etc call will # automatically trigger a reconnect. # We use it here to force the reconnect while this function is still in # control and has the above timeout settings enabled. try: if verbose: print('Reconnecting to:', env.host_string) # This will fail until the network interface comes back up. connections.connect(env.host_string) # This will also fail until SSH is running again. with settings(timeout=timeout): _run('echo hello') success = True break except Exception as e: print('Exception:', e) if not success: raise Exception('Reboot failed or took longer than %s seconds.' % wait)
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 = name.lower().strip() for k in sorted(env): if k.startswith('%s_' % name): new_k = k[len(name)+1:] data[new_k] = env[k] return data
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 = subprocess.check_output(cmd, shell=True) # Note, we round now to avoid rounding errors later on where some formatters # use different decimal contexts. try: ret = round(float(ret), 2) except ValueError: return return 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]) if changes and as_bool: return True added_keys = set(new.iterkeys()).difference(old.iterkeys()) if added_keys and as_bool: return True if not as_tri: changes.update(added_keys) deled_keys = set(old.iterkeys()).difference(new.iterkeys()) if deled_keys and as_bool: return True if as_bool: return False if not as_tri: changes.update(deled_keys) if as_tri: return added_keys, changes, deled_keys return changes
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 else: for pn in PACKAGERS: ret = _run('which %s' % pn) if ret.succeeded: common_packager = pn break if not common_packager: raise Exception('Unable to determine packager.') set_rc('common_packager', common_packager) return common_packager
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: return OS( type=LINUX, distro=DEBIAN, release=re.findall(r'([0-9\.]+)', ret)[0]) ret = _run_or_local('cat /etc/fedora-release') if ret.succeeded: return OS( type=LINUX, distro=FEDORA, release=re.findall(r'release ([0-9]+)', ret)[0]) raise Exception('Unable to determine OS version.')
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() context.update(extra) else: context = env rendered_content = t.render(**context) rendered_content = rendered_content.replace('&quot;', '"') return rendered_content
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() fout = os.fdopen(fd, 'wt') fout.write(content) fout.close() assert fn if style == 'cat': cmd = 'cat <<EOF > %s\n%s\nEOF' % (fn, content) elif style == 'echo': cmd = 'echo -e %s > %s' % (shellquote(content), fn) else: raise NotImplementedError if BURLAP_COMMAND_PREFIX: print('%s run: %s' % (render_command_prefix(), cmd)) else: print(cmd) return fn
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 {} local_path = render_to_file(template=local_path, extra=extra, formatter=formatter) put_or_dryrun(local_path=local_path, remote_path=remote_path, use_sudo=True)
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 not in among target sites.' % _site) continue env.update(env_default) env.update(env.sites.get(_site, {})) env.SITE = _site if callable(renderer): renderer() if setter: setter(_site) yield _site, site_data # Revert modified keys. env.update(env_default) # Remove keys that were added, not simply updated. added_keys = set(env).difference(env_default) for key in added_keys: # Don't remove internally maintained variables, because these are used to cache hostnames # used by iter_sites(). if key.startswith('_'): continue del env[key]
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: name, deps = entry deps.difference_update(emitted) # remove deps we emitted last pass if deps: # still has deps? recheck during next pass next_pending.append(entry) else: # no more deps? time to emit yield name emitted.append(name) # <-- not required, but helps preserve original ordering next_emitted.append(name) # remember what we emitted for difference_update() in next pass if not next_emitted: # all entries have unmet deps, one of two things is wrong... raise ValueError("cyclic or missing dependancy detected: %r" % (next_pending,)) pending = next_pending emitted = next_emitted
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) host_ip = get_host_ip(hostname) # print( 'host_ip:',host_ip) if host_ip: hosts.add(host_ip) break return list(hosts)
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: e.update(self.genv) if include_local: for k, v in self.lenv.items(): e['%s_%s' % (self.obj.name.lower(), k)] = v return e
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 begincap() self._stdout = sys.stdout self._stderr = sys.stderr self.stdout = sys.stdout = StringIO() self.stderr = sys.stderr = StringIO() def __enter__(self): return self def __exit__(self, type, value, traceback): # pylint: disable=redefined-builtin endcap() self.satchel.dryrun = self._dryrun sys.stdout = self._stdout sys.stderr = self._stderr return Capture(self)
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 # Register service commands. if self.required_system_packages: required_system_packages[self.name.upper()] = self.required_system_packages
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: del manifest_deployers[self.name.upper()] except KeyError: pass try: del manifest_deployers_befores[self.name.upper()] except KeyError: pass try: del required_system_packages[self.name.upper()] except KeyError: pass
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): continue attr = getattr(self, _name) if hasattr(attr, '__call__') and getattr(attr, 'is_task', False): tasks.add(_name) return sorted(tasks)
python
{ "resource": "" }
q258573
Satchel.local_renderer
validation
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
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) for name, satchel in self.all_satchels.items() if name != self.name.upper() and name.lower() in map(str.lower, self.genv.services) )
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): if _k.startswith(self.name+'_'): _env[_k[len(self.name)+1:]] = _v return _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. """ last_value = getattr(self.last_manifest, key) current_value = self.current_manifest.get(key) if from_value is not None: return last_value == from_value and current_value == to_value return last_value != to_value and current_value == to_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. """ warnings.warn('Use self.run() instead.', DeprecationWarning, stacklevel=2) self.reboot(*args, **kwargs)
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>. local_ns = {} for k, v in list(site_data.items()): if k.startswith(self.name + '_'): _k = k[len(self.name + '_'):] local_ns[_k] = v del site_data[k] r.env.update(local_ns) r.env.update(site_data)
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 patterns = [ (os_version.type, os_version.distro, os_version.release), (os_version.distro, os_version.release), (os_version.type, os_version.distro), (os_version.distro,), os_version.distro, ] self.vprint('req_packages1:', req_packages1) self.vprint('req_packages2:', req_packages2) package_list = None found = False for pattern in patterns: self.vprint('pattern:', pattern) for req_packages in (req_packages1, req_packages2): if pattern in req_packages: package_list = req_packages[pattern] found = True break if not found: print('Warning: No operating system pattern found for %s' % (os_version,)) self.vprint('package_list:', package_list) return package_list
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(): last_thumbprint = lm['_tracker_%s' % tracker.get_natural_key_hash()] if tracker.is_changed(last_thumbprint): return True return False
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) has_changed = tracker.is_changed(last_thumbprint) self.vprint('Tracker changed:', has_changed) if has_changed: self.vprint('Change detected!') tracker.act()
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}') else: r.sudo('chmod {pgpass_chmod} {pgpass_path}') if root: r.env.shell_username = r.env.get('db_root_username', 'postgres') r.env.shell_password = r.env.get('db_root_password', 'password') else: r.env.shell_username = r.env.db_user r.env.shell_password = r.env.db_password r.append( '{db_host}:{port}:*:{shell_username}:{shell_password}', r.env.pgpass_path, use_sudo=use_sudo)
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. """ r = self.database_renderer(site=site, role=role) r.run('pg_dump -c --host={host_string} --username={db_user} ' '--blobs --format=c {db_name} -n public | ' 'pg_restore -U {db_postgresql_postgres_user} --create ' '--dbname={db_name}')
python
{ "resource": "" }
q258584
PostgreSQLSatchel.drop_database
validation
def drop_database(self, name): """ Delete a PostgreSQL database. Example:: import burlap # Remove DB if it exists if burlap.postgres.database_exists('myapp'): burlap.postgres.drop_database('myapp') """ with settings(warn_only=True): self.sudo('dropdb %s' % (name,), user='postgres')
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 r.run('psql --user={dst_db_user} --host={dst_db_host} --command="DROP TABLE IF EXISTS {table_name} CASCADE;"') r.run('pg_dump -t {table_name} --user={dst_db_user} --host={dst_db_host} | psql --user={src_db_user} --host={src_db_host}')
python
{ "resource": "" }
q258586
interfaces
validation
def interfaces(): """ Get the list of network interfaces. Will return all datalinks on SmartOS. """ with settings(hide('running', 'stdout')): if is_file('/usr/sbin/dladm'): res = run('/usr/sbin/dladm show-link') else: res = sudo('/sbin/ifconfig -s') return [line.split(' ')[0] for line in res.splitlines()[1:]]
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 = (sudo("/sbin/ifconfig %(interface)s | grep 'inet '" % locals()) or '').split('\n')[-1].strip() if 'addr' in res: return res.split()[1].split(':')[1] return res.split()[1]
python
{ "resource": "" }
q258588
PackagerSatchel.update
validation
def update(self): """ Preparse the packaging system for installations. """ packager = self.packager if packager == APT: self.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq update') elif packager == YUM: self.sudo('yum update') else: raise Exception('Unknown packager: %s' % (packager,))
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()) if list_only: return lines tmp_fn = r.write_temp_file('\n'.join(lines)) apt_req_fqfn = tmp_fn if not self.genv.is_local: r.put(local_path=tmp_fn, remote_path=tmp_fn) apt_req_fqfn = self.genv.put_remote_path r.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq update --fix-missing') r.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq install `cat "%s" | tr "\\n" " "`' % apt_req_fqfn)
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) ] if update: self.sudo_or_dryrun('yum update --assumeyes') if package_name: self.sudo_or_dryrun('yum install --assumeyes %s' % package_name) else: if self.genv.is_local: self.put_or_dryrun(local_path=yum_req_fn) yum_req_fn = self.genv.put_remote_fn self.sudo_or_dryrun('yum install --assumeyes $(cat %(yum_req_fn)s)' % yum_req_fn)
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]) break except AttributeError: pass if not type or type == PYTHON: #TODO:deprecated, remove _new.extend(required_python_packages.get( _service, {}).get((version.distro, version.release), [])) try: _pkgs = satchel.packager_python_packages for _key in [(version.distro, version.release), version.distro]: if _key in _pkgs: _new.extend(_pkgs[_key]) except AttributeError: pass print('_new:', _new) if not type or type == RUBY: #TODO:deprecated, remove _new.extend(required_ruby_packages.get( _service, {}).get((version.distro, version.release), [])) for _ in _new: if _ in packages_set: continue packages_set.add(_) packages.append(_) if self.verbose: for package in sorted(packages): print('package:', package) return packages
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] else: types = PACKAGE_TYPES for _type in types: if _type == SYSTEM: content = '\n'.join(self.list_required(type=_type, service=service)) if list_only: lst.extend(_ for _ in content.split('\n') if _.strip()) if self.verbose: print('content:', content) break fd, fn = tempfile.mkstemp() fout = open(fn, 'w') fout.write(content) fout.close() self.install_custom(fn=fn) else: raise NotImplementedError return lst
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: self.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq purge %s' % ' '.join(blacklisted_packages)) else: raise NotImplementedError('Unknown family: %s' % family)
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) for line in lines: cron_crontabs.append(r.format(line)) if not cron_crontabs: return cron_crontabs = self.env.crontab_headers + cron_crontabs cron_crontabs.append('\n') r.env.crontabs_rendered = '\n'.join(cron_crontabs) fn = self.write_to_file(content=r.env.crontabs_rendered) print('fn:', fn) r.env.put_remote_path = r.put(local_path=fn) if isinstance(r.env.put_remote_path, (tuple, list)): r.env.put_remote_path = r.env.put_remote_path[0] r.sudo('crontab -u {cron_user} {put_remote_path}')
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 completely reinstalled. """ r = self.local_renderer self.stop() with settings(warn_only=True): r.sudo('killall rabbitmq-server') with settings(warn_only=True): r.sudo('killall beam.smp') #TODO:explicitly delete all subfolders, star-delete doesn't work r.sudo('rm -Rf /var/lib/rabbitmq/mnesia/*')
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): r.sudo('rabbitmqctl add_user {broker_user} {broker_password}') r.sudo('rabbitmqctl add_vhost {broker_vhost}') r.sudo('rabbitmqctl set_permissions -p {broker_vhost} {broker_user} ".*" ".*" ".*"') r.sudo('rabbitmqctl set_permissions -p {broker_vhost} {admin_username} ".*" ".*" ".*"') return params
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 in common_keys: a_value = a.get(k) b_value = b.get(k) if a_value != b_value: yield k, (a_value, b_value)
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, [])) deps = deps.intersection(component_names) component_dependences[_name] = deps component_order = list(topological_sort(component_dependences.items())) return component_order
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) func = resolve_deployer(func_name) current = current_thumbprint.get(component) last = previous_thumbprint.get(component) if takes_diff: yield func_name, partial(func, last=last, current=current) else: yield func_name, partial(func)
python
{ "resource": "" }