INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Wraps function fn in a try catch block that re-raises error_class. Args: fn (function): function to wrapped error_class (Exception): Error class to be re-raised Returns: (object): fn wrapped in a try catch.
def error_wrapper(fn, error_class): # type: (Callable or None, Exception) -> ... """Wraps function fn in a try catch block that re-raises error_class. Args: fn (function): function to wrapped error_class (Exception): Error class to be re-raised Returns: (object): fn wrapped in a t...
A helper callback to be executed after the connection is made to ensure that Ceph is installed.
def ceph_is_installed(module): """ A helper callback to be executed after the connection is made to ensure that Ceph is installed. """ ceph_package = Ceph(module.conn) if not ceph_package.installed: host = module.conn.hostname raise RuntimeError( 'ceph needs to be ins...
Ignoring errors, call `ceph --version` and return only the version portion of the output. For example, output like:: ceph version 9.0.1-1234kjd (asdflkj2k3jh234jhg) Would return:: 9.0.1-1234kjd
def _get_version_output(self): """ Ignoring errors, call `ceph --version` and return only the version portion of the output. For example, output like:: ceph version 9.0.1-1234kjd (asdflkj2k3jh234jhg) Would return:: 9.0.1-1234kjd """ if not self....
Returns True if the running system's terminal supports color, and False otherwise.
def supports_color(): """ Returns True if the running system's terminal supports color, and False otherwise. """ unsupported_platform = (sys.platform in ('win32', 'Pocket PC')) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if ...
Main entry point to get a colored formatter, it will use the BASE_FORMAT by default and fall back to no colors if the system does not support it
def color_format(): """ Main entry point to get a colored formatter, it will use the BASE_FORMAT by default and fall back to no colors if the system does not support it """ str_format = BASE_COLOR_FORMAT if supports_color() else BASE_FORMAT color_format = color_message(str_format) return...
A direct check for JSON output on the monitor status. For newer versions of Ceph (dumpling and newer) a new mon_status command was added ( `ceph daemon mon mon_status` ) and should be revisited if the output changes as this check depends on that availability.
def mon_status_check(conn, logger, hostname, args): """ A direct check for JSON output on the monitor status. For newer versions of Ceph (dumpling and newer) a new mon_status command was added ( `ceph daemon mon mon_status` ) and should be revisited if the output changes as this check depends on th...
Make sure we are able to catch up common mishaps with monitors and use that state of a monitor to determine what is missing and warn apropriately about it.
def catch_mon_errors(conn, logger, hostname, cfg, args): """ Make sure we are able to catch up common mishaps with monitors and use that state of a monitor to determine what is missing and warn apropriately about it. """ monmap = mon_status_check(conn, logger, hostname, args).get('monmap', {}) ...
run ``ceph daemon mon.`hostname` mon_status`` on the remote end and provide not only the output, but be able to return a boolean status of what is going on. ``False`` represents a monitor that is not doing OK even if it is up and running, while ``True`` would mean the monitor is up and running correctly...
def mon_status(conn, logger, hostname, args, silent=False): """ run ``ceph daemon mon.`hostname` mon_status`` on the remote end and provide not only the output, but be able to return a boolean status of what is going on. ``False`` represents a monitor that is not doing OK even if it is up and ru...
This is a very, very, dumb parser that will look for `[entity]` sections and return a list of those sections. It is not possible to parse this with ConfigParser even though it is almost the same thing. Since this is only used to spit out warnings, it is OK to just be naive about the parsing.
def keyring_parser(path): """ This is a very, very, dumb parser that will look for `[entity]` sections and return a list of those sections. It is not possible to parse this with ConfigParser even though it is almost the same thing. Since this is only used to spit out warnings, it is OK to just be n...
A helper to collect all keyrings into a single blob that will be used to inject it to mons with ``--mkfs`` on remote nodes We require all keyring files to be concatenated to be in a directory to end with ``.keyring``.
def concatenate_keyrings(args): """ A helper to collect all keyrings into a single blob that will be used to inject it to mons with ``--mkfs`` on remote nodes We require all keyring files to be concatenated to be in a directory to end with ``.keyring``. """ keyring_path = os.path.abspath(ar...
Make sure that the host that we are connecting to has the same value as the `hostname` in the remote host, otherwise mons can fail not reaching quorum.
def hostname_is_compatible(conn, logger, provided_hostname): """ Make sure that the host that we are connecting to has the same value as the `hostname` in the remote host, otherwise mons can fail not reaching quorum. """ logger.debug('determining if provided host has same hostname in remote') re...
Read the Ceph config file and return the value of mon_initial_members Optionally, a NeedHostError can be raised if the value is None.
def get_mon_initial_members(args, error_on_empty=False, _cfg=None): """ Read the Ceph config file and return the value of mon_initial_members Optionally, a NeedHostError can be raised if the value is None. """ if _cfg: cfg = _cfg else: cfg = conf.ceph.load(args) mon_initial_m...
Run a command to check the status of a mon, return a boolean. We heavily depend on the format of the output, if that ever changes we need to modify this. Check daemon status for 3 times output of the status should be similar to:: mon.mira094: running {"version":"0.61.5"} or when it fails:...
def is_running(conn, args): """ Run a command to check the status of a mon, return a boolean. We heavily depend on the format of the output, if that ever changes we need to modify this. Check daemon status for 3 times output of the status should be similar to:: mon.mira094: running {"v...
Remote validator that accepts a connection object to ensure that a certain executable is available returning its full path if so. Otherwise an exception with thorough details will be raised, informing the user that the executable was not found.
def executable_path(conn, executable): """ Remote validator that accepts a connection object to ensure that a certain executable is available returning its full path if so. Otherwise an exception with thorough details will be raised, informing the user that the executable was not found. """ ...
This helper should only used as a fallback (last resort) as it is not guaranteed that it will be absolutely correct.
def is_upstart(conn): """ This helper should only used as a fallback (last resort) as it is not guaranteed that it will be absolutely correct. """ # it may be possible that we may be systemd and the caller never checked # before so lets do that if is_systemd(conn): return False ...
Enable a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection.
def enable_service(conn, service='ceph'): """ Enable a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection. """ if is_systemd(conn): remoto.process.run( ...
Disable a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection.
def disable_service(conn, service='ceph'): """ Disable a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection. """ if is_systemd(conn): # Without the check, an error ...
Stop a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection.
def stop_service(conn, service='ceph'): """ Stop a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection. """ if is_systemd(conn): # Without the check, an error is rai...
Stop a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection.
def start_service(conn, service='ceph'): """ Stop a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection. """ if is_systemd(conn): remoto.process.run( con...
Detects if a systemd service is enabled or not.
def is_systemd_service_enabled(conn, service='ceph'): """ Detects if a systemd service is enabled or not. """ _, _, returncode = remoto.process.check( conn, [ 'systemctl', 'is-enabled', '--quiet', '{service}'.format(service=service), ...
Repo definition management
def make(parser): """ Repo definition management """ parser.add_argument( 'repo_name', metavar='REPO-NAME', help='Name of repo to manage. Can match an entry in cephdeploy.conf' ) parser.add_argument( '--repo-url', help='a repo URL that mirrors/contains ...
Read the configuration file and look for ceph-deploy sections to set flags/defaults from the values found. This will alter the ``args`` object that is created by argparse.
def set_overrides(args, _conf=None): """ Read the configuration file and look for ceph-deploy sections to set flags/defaults from the values found. This will alter the ``args`` object that is created by argparse. """ # Get the subcommand name to avoid overwritting values from other # subcomm...
Given a specific section in the configuration file that maps to a subcommand (except for the global section) read all the keys that are actual argument flags and slap the values for that one subcommand. Return the altered ``args`` object at the end.
def override_subcommand(section_name, section_items, args): """ Given a specific section in the configuration file that maps to a subcommand (except for the global section) read all the keys that are actual argument flags and slap the values for that one subcommand. Return the altered ``args`` obje...
Attempt to get a configuration value from a certain section in a ``cfg`` object but returning None if not found. Avoids the need to be doing try/except {ConfigParser Exceptions} every time.
def get_safe(self, section, key, default=None): """ Attempt to get a configuration value from a certain section in a ``cfg`` object but returning None if not found. Avoids the need to be doing try/except {ConfigParser Exceptions} every time. """ try: return se...
boolean to reflect having (or not) any repository sections
def has_repos(self): """ boolean to reflect having (or not) any repository sections """ for section in self.sections(): if section not in self.reserved_sections: return True return False
Assumes that the value for a given key is going to be a list separated by commas. It gets rid of trailing comments. If just one item is present it returns a list with a single item, if no key is found an empty list is returned.
def get_list(self, section, key): """ Assumes that the value for a given key is going to be a list separated by commas. It gets rid of trailing comments. If just one item is present it returns a list with a single item, if no key is found an empty list is returned. """ ...
Go through all the repositories defined in the config file and search for a truthy value for the ``default`` key. If there isn't any return None.
def get_default_repo(self): """ Go through all the repositories defined in the config file and search for a truthy value for the ``default`` key. If there isn't any return None. """ for repo in self.get_repos(): if self.get_safe(repo, 'default') and self.getbo...
Make sure that a given host all subnets specified will have at least one IP in that range.
def validate_host_ip(ips, subnets): """ Make sure that a given host all subnets specified will have at least one IP in that range. """ # Make sure we prune ``None`` arguments subnets = [s for s in subnets if s is not None] validate_one_subnet = len(subnets) == 1 def ip_in_one_subnet(ips...
Given a public subnet, chose the one IP from the remote host that exists within the subnet range.
def get_public_network_ip(ips, public_subnet): """ Given a public subnet, chose the one IP from the remote host that exists within the subnet range. """ for ip in ips: if net.ip_in_subnet(ip, public_subnet): return ip msg = "IPs (%s) are not valid for any of subnet specified ...
Start deploying a new cluster, and write a CLUSTER.conf and keyring for it.
def make(parser): """ Start deploying a new cluster, and write a CLUSTER.conf and keyring for it. """ parser.add_argument( 'mon', metavar='MON', nargs='+', help='initial monitor hostname, fqdn, or hostname:fqdn pair', type=arg_validators.Hostname(), ) ...
Ceph MDS daemon management
def make(parser): """ Ceph MDS daemon management """ mds_parser = parser.add_subparsers(dest='subcommand') mds_parser.required = True mds_create = mds_parser.add_parser( 'create', help='Deploy Ceph MDS on remote host(s)' ) mds_create.add_argument( 'mds', ...
Select a init system Returns the name of a init system (upstart, sysvinit ...).
def choose_init(module): """ Select a init system Returns the name of a init system (upstart, sysvinit ...). """ if module.normalized_release.int_major < 7: return 'sysvinit' if not module.conn.remote_module.path_exists("/usr/lib/systemd/system/ceph.target"): return 'sysvinit'...
EPEL started packaging Ceph so we need to make sure that the ceph.repo we install has a higher priority than the EPEL repo so that when installing Ceph it will come from the repo file we create. The name of the package changed back and forth (!) since CentOS 4: From the CentOS wiki:: Note: Th...
def install_yum_priorities(distro, _yum=None): """ EPEL started packaging Ceph so we need to make sure that the ceph.repo we install has a higher priority than the EPEL repo so that when installing Ceph it will come from the repo file we create. The name of the package changed back and forth (!) si...
Very simple decorator that tries any of the exception(s) passed in as a single exception class or tuple (containing multiple ones) returning the exception message and optionally handling the problem if it raises with the handler if it is provided. So instead of doing something like this:: def ...
def catches(catch=None, handler=None, exit=True, handle_all=False): """ Very simple decorator that tries any of the exception(s) passed in as a single exception class or tuple (containing multiple ones) returning the exception message and optionally handling the problem if it raises with the handler...
An exception is passed in and this function returns the proper string depending on the result so it is readable enough.
def make_exception_message(exc): """ An exception is passed in and this function returns the proper string depending on the result so it is readable enough. """ if str(exc): return '%s: %s\n' % (exc.__class__.__name__, exc) else: return '%s\n' % (exc.__class__.__name__)
detect platform information from remote host
def platform_information(_linux_distribution=None): """ detect platform information from remote host """ linux_distribution = _linux_distribution or platform.linux_distribution distro, release, codename = linux_distribution() if not distro: distro, release, codename = parse_os_release() if n...
Extract (distro, release, codename) from /etc/os-release if present
def parse_os_release(release_path='/etc/os-release'): """ Extract (distro, release, codename) from /etc/os-release if present """ release_info = {} if os.path.isfile(release_path): for line in open(release_path, 'r').readlines(): line = line.strip() if line.startswith('#'): ...
add deb repo to /etc/apt/sources.list.d/
def write_sources_list(url, codename, filename='ceph.list', mode=0o644): """add deb repo to /etc/apt/sources.list.d/""" repo_path = os.path.join('/etc/apt/sources.list.d', filename) content = 'deb {url} {codename} main\n'.format( url=url, codename=codename, ) write_file(repo_path, co...
add deb repo to /etc/apt/sources.list.d/ from content
def write_sources_list_content(content, filename='ceph.list', mode=0o644): """add deb repo to /etc/apt/sources.list.d/ from content""" repo_path = os.path.join('/etc/apt/sources.list.d', filename) if not isinstance(content, str): content = content.decode('utf-8') write_file(repo_path, content.en...
add yum repo file in /etc/yum.repos.d/
def write_yum_repo(content, filename='ceph.repo'): """add yum repo file in /etc/yum.repos.d/""" repo_path = os.path.join('/etc/yum.repos.d', filename) if not isinstance(content, str): content = content.decode('utf-8') write_file(repo_path, content.encode('utf-8'))
write cluster configuration to /etc/ceph/{cluster}.conf
def write_conf(cluster, conf, overwrite): """ write cluster configuration to /etc/ceph/{cluster}.conf """ path = '/etc/ceph/{cluster}.conf'.format(cluster=cluster) tmp_file = tempfile.NamedTemporaryFile('w', dir='/etc/ceph', delete=False) err_msg = 'config file %s exists with different content; use --ov...
create a keyring file
def write_keyring(path, key, uid=-1, gid=-1): """ create a keyring file """ # Note that we *require* to avoid deletion of the temp file # otherwise we risk not being able to copy the contents from # one file system to the other, hence the `delete=False` tmp_file = tempfile.NamedTemporaryFile('wb', d...
create the mon path if it does not exist
def create_mon_path(path, uid=-1, gid=-1): """create the mon path if it does not exist""" if not os.path.exists(path): os.makedirs(path) os.chown(path, uid, gid);
create a done file to avoid re-doing the mon deployment
def create_done_path(done_path, uid=-1, gid=-1): """create a done file to avoid re-doing the mon deployment""" with open(done_path, 'wb'): pass os.chown(done_path, uid, gid);
create the init path if it does not exist
def create_init_path(init_path, uid=-1, gid=-1): """create the init path if it does not exist""" if not os.path.exists(init_path): with open(init_path, 'wb'): pass os.chown(init_path, uid, gid);
create the monitor keyring file
def write_monitor_keyring(keyring, monitor_keyring, uid=-1, gid=-1): """create the monitor keyring file""" write_file(keyring, monitor_keyring, 0o600, None, uid, gid)
find the location of an executable
def which(executable): """find the location of an executable""" locations = ( '/usr/local/bin', '/bin', '/usr/bin', '/usr/local/sbin', '/usr/sbin', '/sbin', ) for location in locations: executable_path = os.path.join(location, executable) ...
move old monitor data
def make_mon_removed_dir(path, file_name): """ move old monitor data """ try: os.makedirs('/var/lib/ceph/mon-removed') except OSError as e: if e.errno != errno.EEXIST: raise shutil.move(path, os.path.join('/var/lib/ceph/mon-removed/', file_name))
create path if it doesn't exist
def safe_mkdir(path, uid=-1, gid=-1): """ create path if it doesn't exist """ try: os.mkdir(path) except OSError as e: if e.errno == errno.EEXIST: pass else: raise else: os.chown(path, uid, gid)
create path recursively if it doesn't exist
def safe_makedirs(path, uid=-1, gid=-1): """ create path recursively if it doesn't exist """ try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST: pass else: raise else: os.chown(path, uid, gid)
zeroing last few blocks of device
def zeroing(dev): """ zeroing last few blocks of device """ # this kills the crab # # sgdisk will wipe out the main copy of the GPT partition # table (sorry), but it doesn't remove the backup copies, and # subsequent commands will continue to complain and fail when # they see those. zeroing...
Configure Yum priorities to include obsoletes
def enable_yum_priority_obsoletes(path="/etc/yum/pluginconf.d/priorities.conf"): """Configure Yum priorities to include obsoletes""" config = configparser.ConfigParser() config.read(path) config.set('main', 'check_obsoletes', '1') with open(path, 'w') as fout: config.write(fout)
Copy ceph.conf to/from remote host(s)
def make(parser): """ Copy ceph.conf to/from remote host(s) """ config_parser = parser.add_subparsers(dest='subcommand') config_parser.required = True config_push = config_parser.add_parser( 'push', help='push Ceph config file to one or more remote hosts' ) config_pu...
:param args: Will be used to infer the proper configuration name, or if args.ceph_conf is passed in, that will take precedence
def load(args): """ :param args: Will be used to infer the proper configuration name, or if args.ceph_conf is passed in, that will take precedence """ path = args.ceph_conf or '{cluster}.conf'.format(cluster=args.cluster) try: f = open(path) except IOError as e: raise exc.Co...
Read the actual file *as is* without parsing/modifiying it so that it can be written maintaining its same properties. :param args: Will be used to infer the proper configuration name :paran path: alternatively, use a path for any configuration file loading
def load_raw(args): """ Read the actual file *as is* without parsing/modifiying it so that it can be written maintaining its same properties. :param args: Will be used to infer the proper configuration name :paran path: alternatively, use a path for any configuration file loading """ path =...
write cluster configuration to /etc/ceph/{cluster}.conf
def write_conf(cluster, conf, overwrite): """ write cluster configuration to /etc/ceph/{cluster}.conf """ import os path = '/etc/ceph/{cluster}.conf'.format(cluster=cluster) tmp = '{path}.{pid}.tmp'.format(path=path, pid=os.getpid()) if os.path.exists(path): with open(path) as f: ...
Attempt to get a configuration value from a certain section in a ``cfg`` object but returning None if not found. Avoids the need to be doing try/except {ConfigParser Exceptions} every time.
def safe_get(self, section, key): """ Attempt to get a configuration value from a certain section in a ``cfg`` object but returning None if not found. Avoids the need to be doing try/except {ConfigParser Exceptions} every time. """ try: #Use full parent functi...
Repo files need special care in that a whole line should not be present if there is no value for it. Because we were using `format()` we could not conditionally add a line for a repo file. So the end result would contain a key with a missing value (say if we were passing `None`). For example, it could ...
def custom_repo(**kw): """ Repo files need special care in that a whole line should not be present if there is no value for it. Because we were using `format()` we could not conditionally add a line for a repo file. So the end result would contain a key with a missing value (say if we were passing `...
Ensure that vendored code/dirs are removed, possibly when packaging when the environment flag is set to avoid vendoring.
def clean_vendor(name): """ Ensure that vendored code/dirs are removed, possibly when packaging when the environment flag is set to avoid vendoring. """ this_dir = path.dirname(path.abspath(__file__)) vendor_dest = path.join(this_dir, 'ceph_deploy/lib/vendor/%s' % name) run(['rm', '-rf', ven...
This is the main entry point for vendorizing requirements. It expects a list of tuples that should contain the name of the library and the version. For example, a library ``foo`` with version ``0.0.1`` would look like:: vendor_requirements = [ ('foo', '0.0.1'), ]
def vendorize(vendor_requirements): """ This is the main entry point for vendorizing requirements. It expects a list of tuples that should contain the name of the library and the version. For example, a library ``foo`` with version ``0.0.1`` would look like:: vendor_requirements = [ ...
Check two keyrings are identical
def _keyring_equivalent(keyring_one, keyring_two): """ Check two keyrings are identical """ def keyring_extract_key(file_path): """ Cephx keyring files may or may not have white space before some lines. They may have some values in quotes, so a safe way to compare is to e...
Get the local filename for a keyring type
def keytype_path_to(args, keytype): """ Get the local filename for a keyring type """ if keytype == "admin": return '{cluster}.client.admin.keyring'.format( cluster=args.cluster) if keytype == "mon": return '{cluster}.mon.keyring'.format( cluster=args.cluster)...
Get or create the keyring from the mon using the mon keyring by keytype and copy to dest_dir
def gatherkeys_missing(args, distro, rlogger, keypath, keytype, dest_dir): """ Get or create the keyring from the mon using the mon keyring by keytype and copy to dest_dir """ args_prefix = [ '/usr/bin/ceph', '--connect-timeout=25', '--cluster={cluster}'.format( c...
Connect to mon and gather keys if mon is in quorum.
def gatherkeys_with_mon(args, host, dest_dir): """ Connect to mon and gather keys if mon is in quorum. """ distro = hosts.get(host, username=args.username) remote_hostname = distro.conn.remote_module.shortname() dir_keytype_mon = ceph_deploy.util.paths.mon.path(args.cluster, remote_hostname) ...
Gather keys from any mon and store in current working directory. Backs up keys from previous installs and stores new keys.
def gatherkeys(args): """ Gather keys from any mon and store in current working directory. Backs up keys from previous installs and stores new keys. """ oldmask = os.umask(0o77) try: try: tmpd = tempfile.mkdtemp() LOG.info("Storing keys in temp directory %s", tmp...
Gather authentication keys for provisioning new nodes.
def make(parser): """ Gather authentication keys for provisioning new nodes. """ parser.add_argument( 'mon', metavar='HOST', nargs='+', help='monitor host to pull keys from', ) parser.set_defaults( func=gatherkeys, )
Retrieve the module that matches the distribution of a ``hostname``. This function will connect to that host and retrieve the distribution information, then return the appropriate module and slap a few attributes to that module defining the information it found from the hostname. For example, if host `...
def get(hostname, username=None, fallback=None, detect_sudo=True, use_rhceph=False, callbacks=None): """ Retrieve the module that matches the distribution of a ``hostname``. This function will connect to that host and retrieve the distribution information, then re...
A very simple helper, meant to return a connection that will know about the need to use sudo.
def get_connection(hostname, username, logger, threads=5, use_sudo=None, detect_sudo=True): """ A very simple helper, meant to return a connection that will know about the need to use sudo. """ if username: hostname = "%s@%s" % (username, hostname) try: conn = remoto.Connection( ...
Helper for local connections that are sometimes needed to operate on local hosts
def get_local_connection(logger, use_sudo=False): """ Helper for local connections that are sometimes needed to operate on local hosts """ return get_connection( socket.gethostname(), # cannot rely on 'localhost' here None, logger=logger, threads=1, use_sudo=...
Ceph MGR daemon management
def make(parser): """ Ceph MGR daemon management """ mgr_parser = parser.add_subparsers(dest='subcommand') mgr_parser.required = True mgr_create = mgr_parser.add_parser( 'create', help='Deploy Ceph MGR on remote host(s)' ) mgr_create.add_argument( 'mgr', ...
Manage packages on remote hosts.
def make(parser): """ Manage packages on remote hosts. """ action = parser.add_mutually_exclusive_group() action.add_argument( '--install', metavar='PKG(s)', help='Comma-separated package(s) to install', ) action.add_argument( '--remove', metavar='P...
Read the bootstrap-osd key for `cluster`.
def get_bootstrap_osd_key(cluster): """ Read the bootstrap-osd key for `cluster`. """ path = '{cluster}.bootstrap-osd.keyring'.format(cluster=cluster) try: with open(path, 'rb') as f: return f.read() except IOError: raise RuntimeError('bootstrap-osd keyring not found;...
Run on osd node, writes the bootstrap key if not there yet.
def create_osd_keyring(conn, cluster, key): """ Run on osd node, writes the bootstrap key if not there yet. """ logger = conn.logger path = '/var/lib/ceph/bootstrap-osd/{cluster}.keyring'.format( cluster=cluster, ) if not conn.remote_module.path_exists(path): logger.warning('...
Check the status of an OSD. Make sure all are up and in What good output would look like:: { "epoch": 8, "num_osds": 1, "num_up_osds": 1, "num_in_osds": "1", "full": "false", "nearfull": "false" } Note how the booleans ar...
def osd_tree(conn, cluster): """ Check the status of an OSD. Make sure all are up and in What good output would look like:: { "epoch": 8, "num_osds": 1, "num_up_osds": 1, "num_in_osds": "1", "full": "false", "nearfull": "false...
Look for possible issues when checking the status of an OSD and report them back to the user.
def catch_osd_errors(conn, logger, args): """ Look for possible issues when checking the status of an OSD and report them back to the user. """ logger.info('checking OSD status...') status = osd_status_check(conn, args.cluster) osds = int(status.get('num_osds', 0)) up_osds = int(status.g...
Run on osd node, creates an OSD from a data disk.
def create_osd( conn, cluster, data, journal, zap, fs_type, dmcrypt, dmcrypt_dir, storetype, block_wal, block_db, **kw): """ Run on osd node, creates an OSD from a data disk. """ ceph_volume_executable = syst...
Prepare a data disk on remote host.
def make(parser): """ Prepare a data disk on remote host. """ sub_command_help = dedent(""" Create OSDs from a data disk on a remote host: ceph-deploy osd create {node} --data /path/to/device For bluestore, optional devices can be used:: ceph-deploy osd create {node} --data /p...
Manage disks on a remote host.
def make_disk(parser): """ Manage disks on a remote host. """ disk_parser = parser.add_subparsers(dest='subcommand') disk_parser.required = True disk_zap = disk_parser.add_parser( 'zap', help='destroy existing data and filesystem on LV or partition', ) disk_zap.add_a...
Historically everything CentOS, RHEL, and Scientific has been mapped to `el6` urls, but as we are adding repositories for `rhel`, the URLs should map correctly to, say, `rhel6` or `rhel7`. This function looks into the `distro` object and determines the right url part for the given distro, falling back ...
def repository_url_part(distro): """ Historically everything CentOS, RHEL, and Scientific has been mapped to `el6` urls, but as we are adding repositories for `rhel`, the URLs should map correctly to, say, `rhel6` or `rhel7`. This function looks into the `distro` object and determines the right url...
args may need a bunch of logic to set proper defaults that argparse is not well suited for.
def sanitize_args(args): """ args may need a bunch of logic to set proper defaults that argparse is not well suited for. """ if args.release is None: args.release = 'nautilus' args.default_release = True # XXX This whole dance is because --stable is getting deprecated if arg...
Since the package split, now there are various different Ceph components to install like: * ceph * ceph-mon * ceph-mgr * ceph-osd * ceph-mds This helper function should parse the args that may contain specifics about these flags and return the default if none are passed in (which is, i...
def detect_components(args, distro): """ Since the package split, now there are various different Ceph components to install like: * ceph * ceph-mon * ceph-mgr * ceph-osd * ceph-mds This helper function should parse the args that may contain specifics about these flags and retu...
A boolean to determine the logic needed to proceed with a custom repo installation instead of cramming everything nect to the logic operator.
def should_use_custom_repo(args, cd_conf, repo_url): """ A boolean to determine the logic needed to proceed with a custom repo installation instead of cramming everything nect to the logic operator. """ if repo_url: # repo_url signals a CLI override, return False immediately return F...
A custom repo install helper that will go through config checks to retrieve repos (and any extra repos defined) and install those ``cd_conf`` is the object built from argparse that holds the flags and information needed to determine what metadata from the configuration to be used.
def custom_repo(distro, args, cd_conf, rlogger, install_ceph=None): """ A custom repo install helper that will go through config checks to retrieve repos (and any extra repos defined) and install those ``cd_conf`` is the object built from argparse that holds the flags and information needed to dete...
For a user that only wants to install the repository only (and avoid installing Ceph and its dependencies).
def install_repo(args): """ For a user that only wants to install the repository only (and avoid installing Ceph and its dependencies). """ cd_conf = getattr(args, 'cd_conf', None) for hostname in args.host: LOG.debug('Detecting platform for host %s ...', hostname) distro = host...
Install Ceph packages on remote hosts.
def make(parser): """ Install Ceph packages on remote hosts. """ version = parser.add_mutually_exclusive_group() # XXX deprecated in favor of release version.add_argument( '--stable', nargs='?', action=StoreVersion, metavar='CODENAME', help='[DEPRECATED]...
Remove Ceph packages from remote hosts.
def make_uninstall(parser): """ Remove Ceph packages from remote hosts. """ parser.add_argument( 'host', metavar='HOST', nargs='+', help='hosts to uninstall Ceph from', ) parser.set_defaults( func=uninstall, )
Remove Ceph packages from remote hosts and purge all data.
def make_purge(parser): """ Remove Ceph packages from remote hosts and purge all data. """ parser.add_argument( 'host', metavar='HOST', nargs='+', help='hosts to purge Ceph from', ) parser.set_defaults( func=purge, )
Purge (delete, destroy, discard, shred) any Ceph data from /var/lib/ceph
def make_purge_data(parser): """ Purge (delete, destroy, discard, shred) any Ceph data from /var/lib/ceph """ parser.add_argument( 'host', metavar='HOST', nargs='+', help='hosts to purge Ceph data from', ) parser.set_defaults( func=purgedata, )
Iterate through list of MON hosts, return tuples of (name, host).
def mon_hosts(mons): """ Iterate through list of MON hosts, return tuples of (name, host). """ for m in mons: if m.count(':'): (name, host) = m.split(':') else: name = m host = m if name.count('.') > 0: name = name.split('.'...
Ceph RGW daemon management
def make(parser): """ Ceph RGW daemon management """ rgw_parser = parser.add_subparsers(dest='subcommand') rgw_parser.required = True rgw_create = rgw_parser.add_parser( 'create', help='Create an RGW instance' ) rgw_create.add_argument( 'rgw', metavar=...
Ensure that current host can SSH remotely to the remote host using the ``BatchMode`` option to prevent a password prompt. That attempt will error with an exit status of 255 and a ``Permission denied`` message or a``Host key verification failed`` message.
def can_connect_passwordless(hostname): """ Ensure that current host can SSH remotely to the remote host using the ``BatchMode`` option to prevent a password prompt. That attempt will error with an exit status of 255 and a ``Permission denied`` message or a``Host key verification failed`` message. ...
Select a init system Returns the name of a init system (upstart, sysvinit ...).
def choose_init(module): """ Select a init system Returns the name of a init system (upstart, sysvinit ...). """ # Upstart checks first because when installing ceph, the # `/lib/systemd/system/ceph.target` file may be created, fooling this # detection mechanism. if is_upstart(module.con...
Example usage:: >>> from ceph_deploy.util.paths import mon >>> mon.keyring('mycluster', 'myhostname') /var/lib/ceph/tmp/mycluster-myhostname.mon.keyring
def keyring(cluster, hostname): """ Example usage:: >>> from ceph_deploy.util.paths import mon >>> mon.keyring('mycluster', 'myhostname') /var/lib/ceph/tmp/mycluster-myhostname.mon.keyring """ keyring_file = '%s-%s.mon.keyring' % (cluster, hostname) return join(constants.tmp...
Example usage:: >>> from ceph_deploy.util.paths import mon >>> mon.asok('mycluster', 'myhostname') /var/run/ceph/mycluster-mon.myhostname.asok
def asok(cluster, hostname): """ Example usage:: >>> from ceph_deploy.util.paths import mon >>> mon.asok('mycluster', 'myhostname') /var/run/ceph/mycluster-mon.myhostname.asok """ asok_file = '%s-mon.%s.asok' % (cluster, hostname) return join(constants.base_run_path, asok_fi...
Example usage:: >>> from ceph_deploy.util.paths import mon >>> mon.monmap('mycluster', 'myhostname') /var/lib/ceph/tmp/mycluster.myhostname.monmap
def monmap(cluster, hostname): """ Example usage:: >>> from ceph_deploy.util.paths import mon >>> mon.monmap('mycluster', 'myhostname') /var/lib/ceph/tmp/mycluster.myhostname.monmap """ monmap mon_map_file = '%s.%s.monmap' % (cluster, hostname) return join(constants.tmp_...
Search result of getaddrinfo() for a non-localhost-net address
def get_nonlocal_ip(host, subnet=None): """ Search result of getaddrinfo() for a non-localhost-net address """ try: ailist = socket.getaddrinfo(host, None) except socket.gaierror: raise exc.UnableToResolveError(host) for ai in ailist: # an ai is a 5-tuple; the last elemen...
Does IP exists in a given subnet utility. Returns a boolean
def ip_in_subnet(ip, subnet): """Does IP exists in a given subnet utility. Returns a boolean""" ipaddr = int(''.join(['%02x' % int(x) for x in ip.split('.')]), 16) netstr, bits = subnet.split('/') netaddr = int(''.join(['%02x' % int(x) for x in netstr.split('.')]), 16) mask = (0xffffffff << (32 - in...
Returns True if host is within specified subnet, otherwise False
def in_subnet(cidr, addrs=None): """ Returns True if host is within specified subnet, otherwise False """ for address in addrs: if ip_in_subnet(address, cidr): return True return False
Returns a list of IPv4/IPv6 addresses assigned to the host. 127.0.0.1/::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. Example output looks like:: >>> ip_addresses(conn) >>> ['192.168.1.111...
def ip_addresses(conn, interface=None, include_loopback=False): """ Returns a list of IPv4/IPv6 addresses assigned to the host. 127.0.0.1/::1 is ignored, unless 'include_loopback=True' is indicated. If 'interface' is provided, then only IP addresses from that interface will be returned. Example out...
Obtain interface information for *NIX/BSD variants in remote servers. Example output from a remote node with a couple of interfaces:: {'eth0': {'hwaddr': '08:00:27:08:c2:e4', 'inet': [{'address': '10.0.2.15', 'broadcast': '10.0.2.255', ...
def linux_interfaces(conn): """ Obtain interface information for *NIX/BSD variants in remote servers. Example output from a remote node with a couple of interfaces:: {'eth0': {'hwaddr': '08:00:27:08:c2:e4', 'inet': [{'address': '10.0.2.15', 'broadcast'...