Search is not available for this dataset
text
stringlengths
75
104k
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, ...], ...
def install_packages(self): """ Installs all required packages listed for this satchel. Normally called indirectly by running packager.configure(). """ os_version = self.os_version package_list = self.get_package_list() if package_list: package_list_st...
def run_on_all_sites(self, cmd, *args, **kwargs): """ Like run(), but re-runs the command for each site in the current role. """ r = self.local_renderer for _site, _data in iter_sites(): r.env.SITE = _site with self.settings(warn_only=True): ...
def file_contains(self, *args, **kwargs): """ filename text http://docs.fabfile.org/en/1.13/api/contrib/files.html#fabric.contrib.files.contains """ from fabric.contrib.files import contains return contains(*args, **kwargs)
def record_manifest(self): """ Returns a dictionary representing a serialized state of the service. """ manifest = get_component_settings(prefixes=[self.name]) # Record a signature of each template so we know to redeploy when they change. for template in self.get_templat...
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): ...
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...
def user_exists(name): """ Check if a PostgreSQL user exists. """ with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True): res = _run_as_pg('''psql -t -A -c "SELECT COUNT(*) FROM pg_user WHERE usename = '%(name)s';"''' % locals()) return (res == "1")
def create_user(name, password, superuser=False, createdb=False, createrole=False, inherit=True, login=True, connection_limit=None, encrypted_password=False): """ Create a PostgreSQL user. Example:: import burlap # Create DB user if it does not exist ...
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}') ...
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. ...
def exists(self, name='default', site=None, use_root=False): """ Returns true if a database with the given name exists. False otherwise. """ r = self.database_renderer(name=name, site=site) if int(use_root): kwargs = dict( db_user=r.env.get('db_root_...
def load(self, dump_fn='', prep_only=0, force_upload=0, from_local=0, name=None, site=None, dest_dir=None, force_host=None): """ Restores a database snapshot onto the target database server. If prep_only=1, commands for preparing the load will be generated, but not the command to finall...
def shell(self, name='default', site=None, **kwargs): """ Opens a SQL shell to the given database, assuming the configured database and user supports this feature. """ r = self.database_renderer(name=name, site=site) self.write_pgpass(name=name, site=site, root=True) ...
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_onl...
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...
def set_cwd(new_path): """ Usage: with set_cwd('/some/dir'): walk_around_the_filesystem() """ try: curdir = os.getcwd() except OSError: curdir = new_path try: os.chdir(new_path) yield finally: os.chdir(curdir)
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 [li...
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', 'std...
def record_manifest(self): """ Returns a dictionary representing a serialized state of the service. """ data = {} data['required_packages'] = self.install_required(type=SYSTEM, verbose=False, list_only=True) data['required_packages'].sort() data['custom_packages']...
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: ...
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_...
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 [] ...
def install_custom(self, *args, **kwargs): """ Installs all system packages listed in the appropriate <packager>-requirements.txt. """ if not self.env.manage_custom: return packager = self.packager if packager == APT: return self.install_ap...
def refresh(self, *args, **kwargs): """ Updates/upgrades all system packages. """ r = self.local_renderer packager = self.packager if packager == APT: r.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq update --fix-missing') elif packager == YUM: ...
def upgrade(self, full=0): """ Updates/upgrades all system packages. """ full = int(full) r = self.local_renderer packager = self.packager if packager == APT: r.sudo('DEBIAN_FRONTEND=noninteractive apt-get -yq upgrade') if full: ...
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_pytho...
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().s...
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 ...
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 sel...
def load(self, dump_fn='', prep_only=0, force_upload=0, from_local=0, name=None, site=None, dest_dir=None): """ Restores a database snapshot onto the target database server. If prep_only=1, commands for preparing the load will be generated, but not the command to finally load the snapsh...
def shell(self, name='default', user=None, password=None, root=0, verbose=1, write_password=1, no_db=0, no_pw=0): """ Opens a SQL shell to the given database, assuming the configured database and user supports this feature. """ raise NotImplementedError
def update_settings(self, d, role, path='roles/{role}/settings.yaml'): """ Writes a key/value pair to a settings file. """ try: import ruamel.yaml load_func = ruamel.yaml.round_trip_load dump_func = ruamel.yaml.round_trip_dump except ImportErro...
def configure_bleeding(self): """ Enables the repository for a most current version on Debian systems. https://www.rabbitmq.com/install-debian.html """ lm = self.last_manifest r = self.local_renderer if self.env.bleeding and not lm.bleeding: # Ins...
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. ...
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, s...
def record_manifest(self): """ Returns a dictionary representing a serialized state of the service. """ data = super(RabbitMQSatchel, self).record_manifest() params = sorted(list(self.get_user_vhosts())) # [(user, password, vhost)] data['rabbitmq_all_site_vhosts'] = param...
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_va...
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 = se...
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: #TOD...
def manifest_filename(self): """ Returns the path to the manifest file. """ r = self.local_renderer tp_fn = r.format(r.env.data_dir + '/manifest.yaml') return tp_fn
def get_current_thumbprint(self, components=None): """ Returns a dictionary representing the current configuration state. Thumbprint is of the form: { component_name1: {key: value}, component_name2: {key: value}, ... } ...
def get_previous_thumbprint(self, components=None): """ Returns a dictionary representing the previous configuration state. Thumbprint is of the form: { component_name1: {key: value}, component_name2: {key: value}, ... } ...
def lock(self): """ Marks the remote server as currently being deployed to. """ self.init() r = self.local_renderer if self.file_exists(r.env.lockfile_path): raise exceptions.AbortDeployment('Lock file %s exists. Perhaps another deployment is currently underwa...
def unlock(self): """ Unmarks the remote server as currently being deployed to. """ self.init() r = self.local_renderer if self.file_exists(r.env.lockfile_path): self.vprint('Unlocking %s.' % r.env.lockfile_path) r.run_or_local('rm -f {lockfile_pat...
def fake(self, components=None):#, set_satchels=None): """ Update the thumbprint on the remote server but execute no satchel configurators. components = A comma-delimited list of satchel names to limit the fake deployment to. set_satchels = A semi-colon delimited list of key-value pairs...
def get_component_funcs(self, components=None): """ Calculates the components functions that need to be executed for a deployment. """ current_tp = self.get_current_thumbprint(components=components) or {} previous_tp = self.get_previous_thumbprint(components=components) or {} ...
def preview(self, components=None, ask=0): """ Inspects differences between the last deployment and the current code state. """ ask = int(ask) self.init() component_order, plan_funcs = self.get_component_funcs(components=components) print('\n%i changes found f...
def push(self, components=None, yes=0): """ Executes all satchel configurators to apply pending changes to the server. """ from burlap import notifier service = self.get_satchel('service') self.lock() try: yes = int(yes) if not yes: ...
def get_thumbprint(self): """ Calculates the current thumbprint of the item being tracked. """ d = {} settings = dj.get_settings() for name in self.names: d[name] = getattr(settings, name) return d
def get_settings(self, site=None, role=None): """ Retrieves the Django settings dictionary. """ r = self.local_renderer _stdout = sys.stdout _stderr = sys.stderr if not self.verbose: sys.stdout = StringIO() sys.stderr = StringIO() t...
def install_sql(self, site=None, database='default', apps=None, stop_on_error=0, fn=None): """ Installs all custom SQL. """ #from burlap.db import load_db_set stop_on_error = int(stop_on_error) site = site or ALL name = database r = self.local_renderer...
def createsuperuser(self, username='admin', email=None, password=None, site=None): """ Runs the Django createsuperuser management command. """ r = self.local_renderer site = site or self.genv.SITE self.set_site_specifics(site) options = ['--username=%s' % username...
def loaddata(self, path, site=None): """ Runs the Dango loaddata management command. By default, runs on only the current site. Pass site=all to run on all sites. """ site = site or self.genv.SITE r = self.local_renderer r.env._loaddata_path = path ...
def manage(self, cmd, *args, **kwargs): """ A generic wrapper around Django's manage command. """ r = self.local_renderer environs = kwargs.pop('environs', '').strip() if environs: environs = ' '.join('export %s=%s;' % tuple(_.split('=')) for _ in environs.spl...
def manage_all(self, *args, **kwargs): """ Runs manage() across all unique site default databases. """ for site, site_data in self.iter_unique_databases(site='all'): if self.verbose: print('-'*80, file=sys.stderr) print('site:', site, file=sys....
def load_django_settings(self): """ Loads Django settings for the current site and sets them so Django internals can be run. """ r = self.local_renderer # Save environment variables so we can restore them later. _env = {} save_vars = ['ALLOW_CELERY', 'DJANGO_SETT...
def shell(self): """ Opens a Django focussed Python shell. Essentially the equivalent of running `manage.py shell`. """ r = self.local_renderer if '@' in self.genv.host_string: r.env.shell_host_string = self.genv.host_string else: r.env.she...
def syncdb(self, site=None, all=0, database=None, ignore_errors=1): # pylint: disable=redefined-builtin """ Runs the standard Django syncdb command for one or more sites. """ r = self.local_renderer ignore_errors = int(ignore_errors) post_south = self.version_tuple >= (...
def migrate(self, app='', migration='', site=None, fake=0, ignore_errors=None, skip_databases=None, database=None, migrate_apps='', delete_ghosts=1): """ Runs the standard South migrate command for one or more sites. """ # Note, to pass a comma-delimted list in a fab command, escape the ...
def manage_async(self, command='', name='process', site=ALL, exclude_sites='', end_message='', recipients=''): """ Starts a Django management command in a screen. Parameters: command :- all arguments passed to `./manage` as a single string site :- the site to run the c...
def get_media_timestamp(self, last_timestamp=None): """ Retrieves the most recent timestamp of the media in the static root. If last_timestamp is given, retrieves the first timestamp more recent than this value. """ r = self.local_renderer _latest_timestamp = -1e99999999...
def set_root_login(self, r): """ Looks up the root login for the given database on the given host and sets it to environment variables. Populates these standard variables: db_root_password db_root_username """ # Check the legacy password locati...
def database_renderer(self, name=None, site=None, role=None): """ Renders local settings for a specific database. """ name = name or self.env.default_db_name site = site or self.genv.SITE role = role or self.genv.ROLE key = (name, site, role) self.vpri...
def get_free_space(self): """ Return free space in bytes. """ cmd = "df -k | grep -vE '^Filesystem|tmpfs|cdrom|none|udev|cgroup' | awk '{ print($1 \" \" $4 }'" lines = [_ for _ in self.run(cmd).strip().split('\n') if _.startswith('/')] assert len(lines) == 1, 'Ambiguous d...
def load_db_set(self, name, r=None): """ Loads database parameters from a specific named set. """ r = r or self db_set = r.genv.db_sets.get(name, {}) r.genv.update(db_set)
def loadable(self, src, dst): """ Determines if there's enough space to load the target database. """ from fabric import state from fabric.task_utils import crawl src_task = crawl(src, state.commands) assert src_task, 'Unknown source role: %s' % src dst_...
def dump(self, dest_dir=None, to_local=1, from_local=0, archive=0, dump_fn=None, name=None, site=None, use_sudo=0, cleanup=1): """ Exports the target database to a single transportable file on the localhost, appropriate for loading using load(). """ r = self.local_renderer ...
def show(keyword=''): """ Displays a list of all environment key/value pairs for the current role. """ keyword = keyword.strip().lower() max_len = max(len(k) for k in env.iterkeys()) keyword_found = False for k in sorted(env.keys()): if keyword and keyword not in k.lower(): ...
def record_manifest(): """ Called after a deployment to record any data necessary to detect changes for a future deployment. """ data = {} # Record settings. data['settings'] = dict( (k, v) for k, v in env.items() if not isinstance(v, types.GeneratorType) and k.strip(...
def fix_eth0_rename(self, hardware_addr): """ A bug as of 2016.10.10 causes eth0 to be renamed to enx*. This renames it to eth0. http://raspberrypi.stackexchange.com/q/43560/29103 """ r = self.local_renderer r.env.hardware_addr = hardware_addr r.sudo('ln ...
def assume_localhost(self): """ Sets connection parameters to localhost, if not set already. """ if not self.genv.host_string: self.genv.host_string = 'localhost' self.genv.hosts = ['localhost'] self.genv.user = getpass.getuser()
def init_raspbian_disk(self, yes=0): """ Downloads the latest Raspbian image and writes it to a microSD card. Based on the instructions from: https://www.raspberrypi.org/documentation/installation/installing-images/linux.md """ self.assume_localhost() yes = int...
def init_ubuntu_disk(self, yes=0): """ Downloads the latest Ubuntu image and writes it to a microSD card. Based on the instructions from: https://wiki.ubuntu.com/ARM/RaspberryPi For recommended SD card brands, see: http://elinux.org/RPi_SD_cards Note,...
def init_raspbian_vm(self): """ Creates an image for running Raspbian in a QEMU virtual machine. Based on the guide at: https://github.com/dhruvvyas90/qemu-rpi-kernel/wiki/Emulating-Jessie-image-with-4.1.x-kernel """ r = self.local_renderer r.comment('Inst...
def create_raspbian_vagrant_box(self): """ Creates a box for easily spinning up a virtual machine with Vagrant. http://unix.stackexchange.com/a/222907/16477 https://github.com/pradels/vagrant-libvirt """ r = self.local_renderer r.sudo('adduser --disabled-passwo...
def configure_hdmi(self): """ Configures HDMI to support hot-plugging, so it'll work even if it wasn't plugged in when the Pi was originally powered up. Note, this does cause slightly higher power consumption, so if you don't need HDMI, don't bother with this. http://ra...
def configure_camera(self): """ Enables access to the camera. http://raspberrypi.stackexchange.com/questions/14229/how-can-i-enable-the-camera-without-using-raspi-config https://mike632t.wordpress.com/2014/06/26/raspberry-pi-camera-setup/ Afterwards, test with: ...
def fix_lsmod_for_pi3(self): """ Some images purporting to support both the Pi2 and Pi3 use the wrong kernel modules. """ r = self.local_renderer r.env.rpi2_conf = '/etc/modules-load.d/rpi2.conf' r.sudo("sed '/bcm2808_rng/d' {rpi2_conf}") r.sudo("echo bcm2835_rng ...
def pre_deploy(self): """ Runs methods services have requested be run before each deployment. """ for service in self.genv.services: service = service.strip().upper() funcs = common.service_pre_deployers.get(service) if funcs: print('Ru...
def deploy(self): """ Applies routine, typically application-level changes to the service. """ for service in self.genv.services: service = service.strip().upper() funcs = common.service_deployers.get(service) if funcs: print('Deploying...
def post_deploy(self): """ Runs methods services have requested be run before after deployment. """ for service in self.genv.services: service = service.strip().upper() self.vprint('post_deploy:', service) funcs = common.service_post_deployers.get(serv...
def pre_db_dump(self): """ Runs methods services that have requested to be run before each database dump. """ for service in self.genv.services: service = service.strip().upper() funcs = common.service_pre_db_dumpers.get(service) if funcs: ...
def post_db_dump(self): """ Runs methods services that have requested to be run before each database dump. """ for service in self.genv.services: service = service.strip().upper() funcs = common.service_post_db_dumpers.get(service) if funcs: ...
def configure(self): """ Applies one-time settings changes to the host, usually to initialize the service. """ print('env.services:', self.genv.services) for service in list(self.genv.services): service = service.strip().upper() funcs = common.service_conf...
def get_locale_dict(self, text=None): """ Reads /etc/default/locale and returns a dictionary representing its key pairs. """ text = text or self.cat_locale() # Format NAME="value". return dict(re.findall(r'^([a-zA-Z_]+)\s*=\s*[\'\"]*([0-8a-zA-Z_\.\:\-]+)[\'\"]*', text, re...
def enable_mods(self): """ Enables all modules in the current module list. Does not disable any currently enabled modules not in the list. """ r = self.local_renderer for mod_name in r.env.mods_enabled: with self.settings(warn_only=True): self....
def optimize_wsgi_processes(self): """ Based on the number of sites per server and the number of resources on the server, calculates the optimal number of processes that should be allocated for each WSGI site. """ r = self.local_renderer #r.env.wsgi_processes = 5 ...
def create_local_renderer(self): """ Instantiates a new local renderer. Override this to do any additional initialization. """ r = super(ApacheSatchel, self).create_local_renderer() # Dynamically set values based on target operating system. os_version = self.os_v...
def install_auth_basic_user_file(self, site=None): """ Installs users for basic httpd auth. """ r = self.local_renderer hostname = self.current_hostname target_sites = self.genv.available_sites_by_host.get(hostname, None) for _site, site_data in self.iter_sites...
def sync_media(self, sync_set=None, clean=0, iter_local_paths=0): """ Uploads select media to an Apache accessible directory. """ # Ensure a site is selected. self.genv.SITE = self.genv.SITE or self.genv.default_site r = self.local_renderer clean = int(clean) ...
def get_media_timestamp(self): """ Called after a deployment to record any data necessary to detect changes for a future deployment. """ from burlap.common import get_last_modified_timestamp data = 0 for path in self.sync_media(iter_local_paths=1): dat...
def record_manifest(self): """ Called after a deployment to record any data necessary to detect changes for a future deployment. """ manifest = super(ApacheSatchel, self).record_manifest() manifest['available_sites'] = self.genv.available_sites manifest['available...
def configure_modevasive(self): """ Installs the mod-evasive Apache module for combating DDOS attacks. https://www.linode.com/docs/websites/apache-tips-and-tricks/modevasive-on-apache """ r = self.local_renderer if r.env.modevasive_enabled: self.install_packa...
def configure_modsecurity(self): """ Installs the mod-security Apache module. https://www.modsecurity.org """ r = self.local_renderer if r.env.modsecurity_enabled and not self.last_manifest.modsecurity_enabled: self.install_packages() # Write mo...
def configure_modrpaf(self): """ Installs the mod-rpaf Apache module. https://github.com/gnif/mod_rpaf """ r = self.local_renderer if r.env.modrpaf_enabled: self.install_packages() self.enable_mod('rpaf') else: if self.last_man...
def configure_site(self, full=1, site=None, delete_old=0): """ Configures Apache to host one or more websites. """ from burlap import service r = self.local_renderer print('Configuring Apache...', file=sys.stderr) site = site or self.genv.SITE if int(d...
def maint_up(self): """ Forwards all traffic to a page saying the server is down for maintenance. """ r = self.local_renderer fn = self.render_to_file(r.env.maintenance_template, extra={'current_hostname': self.current_hostname}) r.put(local_path=fn, remote_path=r.env.mai...
def restart(self): """ Supervisor can take a very long time to start and stop, so wait for it. """ n = 60 sleep_n = int(self.env.max_restart_wait_minutes/10.*60) for _ in xrange(n): self.stop() if self.dryrun or not self.is_running(): ...
def record_manifest(self): """ Called after a deployment to record any data necessary to detect changes for a future deployment. """ data = super(SupervisorSatchel, self).record_manifest() # Celery deploys itself through supervisor, so monitor its changes too in Apache s...