id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
233,400
ceph/ceph-deploy
ceph_deploy/util/system.py
executable_path
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. """ executable_path = conn.remote_module.which(executable) if not executable_path: raise ExecutableNotFound(executable, conn.hostname) return executable_path
python
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. """ executable_path = conn.remote_module.which(executable) if not executable_path: raise ExecutableNotFound(executable, conn.hostname) return executable_path
[ "def", "executable_path", "(", "conn", ",", "executable", ")", ":", "executable_path", "=", "conn", ".", "remote_module", ".", "which", "(", "executable", ")", "if", "not", "executable_path", ":", "raise", "ExecutableNotFound", "(", "executable", ",", "conn", ".", "hostname", ")", "return", "executable_path" ]
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.
[ "Remote", "validator", "that", "accepts", "a", "connection", "object", "to", "ensure", "that", "a", "certain", "executable", "is", "available", "returning", "its", "full", "path", "if", "so", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/system.py#L5-L16
233,401
ceph/ceph-deploy
ceph_deploy/util/system.py
is_systemd_service_enabled
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), ] ) return returncode == 0
python
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), ] ) return returncode == 0
[ "def", "is_systemd_service_enabled", "(", "conn", ",", "service", "=", "'ceph'", ")", ":", "_", ",", "_", ",", "returncode", "=", "remoto", ".", "process", ".", "check", "(", "conn", ",", "[", "'systemctl'", ",", "'is-enabled'", ",", "'--quiet'", ",", "'{service}'", ".", "format", "(", "service", "=", "service", ")", ",", "]", ")", "return", "returncode", "==", "0" ]
Detects if a systemd service is enabled or not.
[ "Detects", "if", "a", "systemd", "service", "is", "enabled", "or", "not", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/system.py#L167-L180
233,402
ceph/ceph-deploy
ceph_deploy/repo.py
make
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 Ceph packages' ) parser.add_argument( '--gpg-url', help='a GPG key URL to be used with custom repos' ) parser.add_argument( '--remove', '--delete', action='store_true', help='remove repo definition on remote host' ) parser.add_argument( 'host', metavar='HOST', nargs='+', help='host(s) to install on' ) parser.set_defaults( func=repo )
python
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 Ceph packages' ) parser.add_argument( '--gpg-url', help='a GPG key URL to be used with custom repos' ) parser.add_argument( '--remove', '--delete', action='store_true', help='remove repo definition on remote host' ) parser.add_argument( 'host', metavar='HOST', nargs='+', help='host(s) to install on' ) parser.set_defaults( func=repo )
[ "def", "make", "(", "parser", ")", ":", "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 Ceph packages'", ")", "parser", ".", "add_argument", "(", "'--gpg-url'", ",", "help", "=", "'a GPG key URL to be used with custom repos'", ")", "parser", ".", "add_argument", "(", "'--remove'", ",", "'--delete'", ",", "action", "=", "'store_true'", ",", "help", "=", "'remove repo definition on remote host'", ")", "parser", ".", "add_argument", "(", "'host'", ",", "metavar", "=", "'HOST'", ",", "nargs", "=", "'+'", ",", "help", "=", "'host(s) to install on'", ")", "parser", ".", "set_defaults", "(", "func", "=", "repo", ")" ]
Repo definition management
[ "Repo", "definition", "management" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/repo.py#L77-L113
233,403
ceph/ceph-deploy
ceph_deploy/conf/cephdeploy.py
Conf.get_list
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. """ value = self.get_safe(section, key, []) if value == []: return value # strip comments value = re.split(r'\s+#', value)[0] # split on commas value = value.split(',') # strip spaces return [x.strip() for x in value]
python
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. """ value = self.get_safe(section, key, []) if value == []: return value # strip comments value = re.split(r'\s+#', value)[0] # split on commas value = value.split(',') # strip spaces return [x.strip() for x in value]
[ "def", "get_list", "(", "self", ",", "section", ",", "key", ")", ":", "value", "=", "self", ".", "get_safe", "(", "section", ",", "key", ",", "[", "]", ")", "if", "value", "==", "[", "]", ":", "return", "value", "# strip comments", "value", "=", "re", ".", "split", "(", "r'\\s+#'", ",", "value", ")", "[", "0", "]", "# split on commas", "value", "=", "value", ".", "split", "(", "','", ")", "# strip spaces", "return", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "value", "]" ]
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.
[ "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", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/conf/cephdeploy.py#L189-L207
233,404
ceph/ceph-deploy
ceph_deploy/conf/cephdeploy.py
Conf.get_default_repo
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.getboolean(repo, 'default'): return repo return False
python
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.getboolean(repo, 'default'): return repo return False
[ "def", "get_default_repo", "(", "self", ")", ":", "for", "repo", "in", "self", ".", "get_repos", "(", ")", ":", "if", "self", ".", "get_safe", "(", "repo", ",", "'default'", ")", "and", "self", ".", "getboolean", "(", "repo", ",", "'default'", ")", ":", "return", "repo", "return", "False" ]
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.
[ "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", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/conf/cephdeploy.py#L209-L218
233,405
ceph/ceph-deploy
ceph_deploy/new.py
validate_host_ip
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, subnet): """ ensure an ip exists in at least one subnet """ for ip in ips: if net.ip_in_subnet(ip, subnet): return True return False for subnet in subnets: if ip_in_one_subnet(ips, subnet): if validate_one_subnet: return else: # keep going to make sure the other subnets are ok continue else: msg = "subnet (%s) is not valid for any of the ips found %s" % (subnet, str(ips)) raise RuntimeError(msg)
python
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, subnet): """ ensure an ip exists in at least one subnet """ for ip in ips: if net.ip_in_subnet(ip, subnet): return True return False for subnet in subnets: if ip_in_one_subnet(ips, subnet): if validate_one_subnet: return else: # keep going to make sure the other subnets are ok continue else: msg = "subnet (%s) is not valid for any of the ips found %s" % (subnet, str(ips)) raise RuntimeError(msg)
[ "def", "validate_host_ip", "(", "ips", ",", "subnets", ")", ":", "# 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", ",", "subnet", ")", ":", "\"\"\" ensure an ip exists in at least one subnet \"\"\"", "for", "ip", "in", "ips", ":", "if", "net", ".", "ip_in_subnet", "(", "ip", ",", "subnet", ")", ":", "return", "True", "return", "False", "for", "subnet", "in", "subnets", ":", "if", "ip_in_one_subnet", "(", "ips", ",", "subnet", ")", ":", "if", "validate_one_subnet", ":", "return", "else", ":", "# keep going to make sure the other subnets are ok", "continue", "else", ":", "msg", "=", "\"subnet (%s) is not valid for any of the ips found %s\"", "%", "(", "subnet", ",", "str", "(", "ips", ")", ")", "raise", "RuntimeError", "(", "msg", ")" ]
Make sure that a given host all subnets specified will have at least one IP in that range.
[ "Make", "sure", "that", "a", "given", "host", "all", "subnets", "specified", "will", "have", "at", "least", "one", "IP", "in", "that", "range", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/new.py#L78-L102
233,406
ceph/ceph-deploy
ceph_deploy/new.py
get_public_network_ip
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 %s" % (str(ips), str(public_subnet)) raise RuntimeError(msg)
python
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 %s" % (str(ips), str(public_subnet)) raise RuntimeError(msg)
[ "def", "get_public_network_ip", "(", "ips", ",", "public_subnet", ")", ":", "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 %s\"", "%", "(", "str", "(", "ips", ")", ",", "str", "(", "public_subnet", ")", ")", "raise", "RuntimeError", "(", "msg", ")" ]
Given a public subnet, chose the one IP from the remote host that exists within the subnet range.
[ "Given", "a", "public", "subnet", "chose", "the", "one", "IP", "from", "the", "remote", "host", "that", "exists", "within", "the", "subnet", "range", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/new.py#L105-L114
233,407
ceph/ceph-deploy
ceph_deploy/new.py
make
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(), ) parser.add_argument( '--no-ssh-copykey', dest='ssh_copykey', action='store_false', default=True, help='do not attempt to copy SSH keys', ) parser.add_argument( '--fsid', dest='fsid', help='provide an alternate FSID for ceph.conf generation', ) parser.add_argument( '--cluster-network', help='specify the (internal) cluster network', type=arg_validators.Subnet(), ) parser.add_argument( '--public-network', help='specify the public network for a cluster', type=arg_validators.Subnet(), ) parser.set_defaults( func=new, )
python
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(), ) parser.add_argument( '--no-ssh-copykey', dest='ssh_copykey', action='store_false', default=True, help='do not attempt to copy SSH keys', ) parser.add_argument( '--fsid', dest='fsid', help='provide an alternate FSID for ceph.conf generation', ) parser.add_argument( '--cluster-network', help='specify the (internal) cluster network', type=arg_validators.Subnet(), ) parser.add_argument( '--public-network', help='specify the public network for a cluster', type=arg_validators.Subnet(), ) parser.set_defaults( func=new, )
[ "def", "make", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'mon'", ",", "metavar", "=", "'MON'", ",", "nargs", "=", "'+'", ",", "help", "=", "'initial monitor hostname, fqdn, or hostname:fqdn pair'", ",", "type", "=", "arg_validators", ".", "Hostname", "(", ")", ",", ")", "parser", ".", "add_argument", "(", "'--no-ssh-copykey'", ",", "dest", "=", "'ssh_copykey'", ",", "action", "=", "'store_false'", ",", "default", "=", "True", ",", "help", "=", "'do not attempt to copy SSH keys'", ",", ")", "parser", ".", "add_argument", "(", "'--fsid'", ",", "dest", "=", "'fsid'", ",", "help", "=", "'provide an alternate FSID for ceph.conf generation'", ",", ")", "parser", ".", "add_argument", "(", "'--cluster-network'", ",", "help", "=", "'specify the (internal) cluster network'", ",", "type", "=", "arg_validators", ".", "Subnet", "(", ")", ",", ")", "parser", ".", "add_argument", "(", "'--public-network'", ",", "help", "=", "'specify the public network for a cluster'", ",", "type", "=", "arg_validators", ".", "Subnet", "(", ")", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "new", ",", ")" ]
Start deploying a new cluster, and write a CLUSTER.conf and keyring for it.
[ "Start", "deploying", "a", "new", "cluster", "and", "write", "a", "CLUSTER", ".", "conf", "and", "keyring", "for", "it", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/new.py#L237-L276
233,408
ceph/ceph-deploy
ceph_deploy/mds.py
make
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', metavar='HOST[:NAME]', nargs='+', type=colon_separated, help='host (and optionally the daemon name) to deploy on', ) parser.set_defaults( func=mds, )
python
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', metavar='HOST[:NAME]', nargs='+', type=colon_separated, help='host (and optionally the daemon name) to deploy on', ) parser.set_defaults( func=mds, )
[ "def", "make", "(", "parser", ")", ":", "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'", ",", "metavar", "=", "'HOST[:NAME]'", ",", "nargs", "=", "'+'", ",", "type", "=", "colon_separated", ",", "help", "=", "'host (and optionally the daemon name) to deploy on'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "mds", ",", ")" ]
Ceph MDS daemon management
[ "Ceph", "MDS", "daemon", "management" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/mds.py#L206-L226
233,409
ceph/ceph-deploy
ceph_deploy/hosts/util.py
install_yum_priorities
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 (!) since CentOS 4: From the CentOS wiki:: Note: This plugin has carried at least two differing names over time. It is named yum-priorities on CentOS-5 but was named yum-plugin-priorities on CentOS-4. CentOS-6 has reverted to yum-plugin-priorities. :params _yum: Used for testing, so we can inject a fake yum """ yum = _yum or pkg_managers.yum package_name = 'yum-plugin-priorities' if distro.normalized_name == 'centos': if distro.release[0] != '6': package_name = 'yum-priorities' yum(distro.conn, package_name)
python
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 (!) since CentOS 4: From the CentOS wiki:: Note: This plugin has carried at least two differing names over time. It is named yum-priorities on CentOS-5 but was named yum-plugin-priorities on CentOS-4. CentOS-6 has reverted to yum-plugin-priorities. :params _yum: Used for testing, so we can inject a fake yum """ yum = _yum or pkg_managers.yum package_name = 'yum-plugin-priorities' if distro.normalized_name == 'centos': if distro.release[0] != '6': package_name = 'yum-priorities' yum(distro.conn, package_name)
[ "def", "install_yum_priorities", "(", "distro", ",", "_yum", "=", "None", ")", ":", "yum", "=", "_yum", "or", "pkg_managers", ".", "yum", "package_name", "=", "'yum-plugin-priorities'", "if", "distro", ".", "normalized_name", "==", "'centos'", ":", "if", "distro", ".", "release", "[", "0", "]", "!=", "'6'", ":", "package_name", "=", "'yum-priorities'", "yum", "(", "distro", ".", "conn", ",", "package_name", ")" ]
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: This plugin has carried at least two differing names over time. It is named yum-priorities on CentOS-5 but was named yum-plugin-priorities on CentOS-4. CentOS-6 has reverted to yum-plugin-priorities. :params _yum: Used for testing, so we can inject a fake yum
[ "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", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/util.py#L8-L31
233,410
ceph/ceph-deploy
ceph_deploy/util/decorators.py
make_exception_message
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__)
python
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__)
[ "def", "make_exception_message", "(", "exc", ")", ":", "if", "str", "(", "exc", ")", ":", "return", "'%s: %s\\n'", "%", "(", "exc", ".", "__class__", ".", "__name__", ",", "exc", ")", "else", ":", "return", "'%s\\n'", "%", "(", "exc", ".", "__class__", ".", "__name__", ")" ]
An exception is passed in and this function returns the proper string depending on the result so it is readable enough.
[ "An", "exception", "is", "passed", "in", "and", "this", "function", "returns", "the", "proper", "string", "depending", "on", "the", "result", "so", "it", "is", "readable", "enough", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/decorators.py#L102-L111
233,411
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
platform_information
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 not codename and 'debian' in distro.lower(): # this could be an empty string in Debian debian_codenames = { '10': 'buster', '9': 'stretch', '8': 'jessie', '7': 'wheezy', '6': 'squeeze', } major_version = release.split('.')[0] codename = debian_codenames.get(major_version, '') # In order to support newer jessie/sid or wheezy/sid strings we test this # if sid is buried in the minor, we should use sid anyway. if not codename and '/' in release: major, minor = release.split('/') if minor == 'sid': codename = minor else: codename = major if not codename and 'oracle' in distro.lower(): # this could be an empty string in Oracle linux codename = 'oracle' if not codename and 'virtuozzo linux' in distro.lower(): # this could be an empty string in Virtuozzo linux codename = 'virtuozzo' if not codename and 'arch' in distro.lower(): # this could be an empty string in Arch linux codename = 'arch' return ( str(distro).rstrip(), str(release).rstrip(), str(codename).rstrip() )
python
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 not codename and 'debian' in distro.lower(): # this could be an empty string in Debian debian_codenames = { '10': 'buster', '9': 'stretch', '8': 'jessie', '7': 'wheezy', '6': 'squeeze', } major_version = release.split('.')[0] codename = debian_codenames.get(major_version, '') # In order to support newer jessie/sid or wheezy/sid strings we test this # if sid is buried in the minor, we should use sid anyway. if not codename and '/' in release: major, minor = release.split('/') if minor == 'sid': codename = minor else: codename = major if not codename and 'oracle' in distro.lower(): # this could be an empty string in Oracle linux codename = 'oracle' if not codename and 'virtuozzo linux' in distro.lower(): # this could be an empty string in Virtuozzo linux codename = 'virtuozzo' if not codename and 'arch' in distro.lower(): # this could be an empty string in Arch linux codename = 'arch' return ( str(distro).rstrip(), str(release).rstrip(), str(codename).rstrip() )
[ "def", "platform_information", "(", "_linux_distribution", "=", "None", ")", ":", "linux_distribution", "=", "_linux_distribution", "or", "platform", ".", "linux_distribution", "distro", ",", "release", ",", "codename", "=", "linux_distribution", "(", ")", "if", "not", "distro", ":", "distro", ",", "release", ",", "codename", "=", "parse_os_release", "(", ")", "if", "not", "codename", "and", "'debian'", "in", "distro", ".", "lower", "(", ")", ":", "# this could be an empty string in Debian", "debian_codenames", "=", "{", "'10'", ":", "'buster'", ",", "'9'", ":", "'stretch'", ",", "'8'", ":", "'jessie'", ",", "'7'", ":", "'wheezy'", ",", "'6'", ":", "'squeeze'", ",", "}", "major_version", "=", "release", ".", "split", "(", "'.'", ")", "[", "0", "]", "codename", "=", "debian_codenames", ".", "get", "(", "major_version", ",", "''", ")", "# In order to support newer jessie/sid or wheezy/sid strings we test this", "# if sid is buried in the minor, we should use sid anyway.", "if", "not", "codename", "and", "'/'", "in", "release", ":", "major", ",", "minor", "=", "release", ".", "split", "(", "'/'", ")", "if", "minor", "==", "'sid'", ":", "codename", "=", "minor", "else", ":", "codename", "=", "major", "if", "not", "codename", "and", "'oracle'", "in", "distro", ".", "lower", "(", ")", ":", "# this could be an empty string in Oracle linux", "codename", "=", "'oracle'", "if", "not", "codename", "and", "'virtuozzo linux'", "in", "distro", ".", "lower", "(", ")", ":", "# this could be an empty string in Virtuozzo linux", "codename", "=", "'virtuozzo'", "if", "not", "codename", "and", "'arch'", "in", "distro", ".", "lower", "(", ")", ":", "# this could be an empty string in Arch linux", "codename", "=", "'arch'", "return", "(", "str", "(", "distro", ")", ".", "rstrip", "(", ")", ",", "str", "(", "release", ")", ".", "rstrip", "(", ")", ",", "str", "(", "codename", ")", ".", "rstrip", "(", ")", ")" ]
detect platform information from remote host
[ "detect", "platform", "information", "from", "remote", "host" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L14-L50
233,412
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
write_keyring
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', delete=False) tmp_file.write(key) tmp_file.close() keyring_dir = os.path.dirname(path) if not path_exists(keyring_dir): makedir(keyring_dir, uid, gid) shutil.move(tmp_file.name, path)
python
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', delete=False) tmp_file.write(key) tmp_file.close() keyring_dir = os.path.dirname(path) if not path_exists(keyring_dir): makedir(keyring_dir, uid, gid) shutil.move(tmp_file.name, path)
[ "def", "write_keyring", "(", "path", ",", "key", ",", "uid", "=", "-", "1", ",", "gid", "=", "-", "1", ")", ":", "# 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'", ",", "delete", "=", "False", ")", "tmp_file", ".", "write", "(", "key", ")", "tmp_file", ".", "close", "(", ")", "keyring_dir", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "path_exists", "(", "keyring_dir", ")", ":", "makedir", "(", "keyring_dir", ",", "uid", ",", "gid", ")", "shutil", ".", "move", "(", "tmp_file", ".", "name", ",", "path", ")" ]
create a keyring file
[ "create", "a", "keyring", "file" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L178-L189
233,413
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
create_mon_path
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);
python
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);
[ "def", "create_mon_path", "(", "path", ",", "uid", "=", "-", "1", ",", "gid", "=", "-", "1", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "os", ".", "chown", "(", "path", ",", "uid", ",", "gid", ")" ]
create the mon path if it does not exist
[ "create", "the", "mon", "path", "if", "it", "does", "not", "exist" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L192-L196
233,414
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
create_done_path
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);
python
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);
[ "def", "create_done_path", "(", "done_path", ",", "uid", "=", "-", "1", ",", "gid", "=", "-", "1", ")", ":", "with", "open", "(", "done_path", ",", "'wb'", ")", ":", "pass", "os", ".", "chown", "(", "done_path", ",", "uid", ",", "gid", ")" ]
create a done file to avoid re-doing the mon deployment
[ "create", "a", "done", "file", "to", "avoid", "re", "-", "doing", "the", "mon", "deployment" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L199-L203
233,415
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
create_init_path
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);
python
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);
[ "def", "create_init_path", "(", "init_path", ",", "uid", "=", "-", "1", ",", "gid", "=", "-", "1", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "init_path", ")", ":", "with", "open", "(", "init_path", ",", "'wb'", ")", ":", "pass", "os", ".", "chown", "(", "init_path", ",", "uid", ",", "gid", ")" ]
create the init path if it does not exist
[ "create", "the", "init", "path", "if", "it", "does", "not", "exist" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L206-L211
233,416
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
write_monitor_keyring
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)
python
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)
[ "def", "write_monitor_keyring", "(", "keyring", ",", "monitor_keyring", ",", "uid", "=", "-", "1", ",", "gid", "=", "-", "1", ")", ":", "write_file", "(", "keyring", ",", "monitor_keyring", ",", "0o600", ",", "None", ",", "uid", ",", "gid", ")" ]
create the monitor keyring file
[ "create", "the", "monitor", "keyring", "file" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L260-L262
233,417
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
which
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) if os.path.exists(executable_path) and os.path.isfile(executable_path): return executable_path
python
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) if os.path.exists(executable_path) and os.path.isfile(executable_path): return executable_path
[ "def", "which", "(", "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", ")", "if", "os", ".", "path", ".", "exists", "(", "executable_path", ")", "and", "os", ".", "path", ".", "isfile", "(", "executable_path", ")", ":", "return", "executable_path" ]
find the location of an executable
[ "find", "the", "location", "of", "an", "executable" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L331-L345
233,418
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
make_mon_removed_dir
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))
python
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))
[ "def", "make_mon_removed_dir", "(", "path", ",", "file_name", ")", ":", "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", ")", ")" ]
move old monitor data
[ "move", "old", "monitor", "data" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L348-L355
233,419
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
safe_mkdir
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)
python
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)
[ "def", "safe_mkdir", "(", "path", ",", "uid", "=", "-", "1", ",", "gid", "=", "-", "1", ")", ":", "try", ":", "os", ".", "mkdir", "(", "path", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "EEXIST", ":", "pass", "else", ":", "raise", "else", ":", "os", ".", "chown", "(", "path", ",", "uid", ",", "gid", ")" ]
create path if it doesn't exist
[ "create", "path", "if", "it", "doesn", "t", "exist" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L358-L368
233,420
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
safe_makedirs
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)
python
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)
[ "def", "safe_makedirs", "(", "path", ",", "uid", "=", "-", "1", ",", "gid", "=", "-", "1", ")", ":", "try", ":", "os", ".", "makedirs", "(", "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
[ "create", "path", "recursively", "if", "it", "doesn", "t", "exist" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L371-L381
233,421
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
zeroing
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 the last few blocks of the device # appears to do the trick. lba_size = 4096 size = 33 * lba_size return True with open(dev, 'wb') as f: f.seek(-size, os.SEEK_END) f.write(size*b'\0')
python
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 the last few blocks of the device # appears to do the trick. lba_size = 4096 size = 33 * lba_size return True with open(dev, 'wb') as f: f.seek(-size, os.SEEK_END) f.write(size*b'\0')
[ "def", "zeroing", "(", "dev", ")", ":", "# 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 the last few blocks of the device", "# appears to do the trick.", "lba_size", "=", "4096", "size", "=", "33", "*", "lba_size", "return", "True", "with", "open", "(", "dev", ",", "'wb'", ")", "as", "f", ":", "f", ".", "seek", "(", "-", "size", ",", "os", ".", "SEEK_END", ")", "f", ".", "write", "(", "size", "*", "b'\\0'", ")" ]
zeroing last few blocks of device
[ "zeroing", "last", "few", "blocks", "of", "device" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L384-L398
233,422
ceph/ceph-deploy
ceph_deploy/hosts/remotes.py
enable_yum_priority_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)
python
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)
[ "def", "enable_yum_priority_obsoletes", "(", "path", "=", "\"/etc/yum/pluginconf.d/priorities.conf\"", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "path", ")", "config", ".", "set", "(", "'main'", ",", "'check_obsoletes'", ",", "'1'", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "fout", ":", "config", ".", "write", "(", "fout", ")" ]
Configure Yum priorities to include obsoletes
[ "Configure", "Yum", "priorities", "to", "include", "obsoletes" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/remotes.py#L401-L407
233,423
ceph/ceph-deploy
vendor.py
vendorize
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 = [ ('foo', '0.0.1'), ] """ for library in vendor_requirements: if len(library) == 2: name, version = library cmd = None elif len(library) == 3: # a possible cmd we need to run name, version, cmd = library vendor_library(name, version, cmd)
python
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 = [ ('foo', '0.0.1'), ] """ for library in vendor_requirements: if len(library) == 2: name, version = library cmd = None elif len(library) == 3: # a possible cmd we need to run name, version, cmd = library vendor_library(name, version, cmd)
[ "def", "vendorize", "(", "vendor_requirements", ")", ":", "for", "library", "in", "vendor_requirements", ":", "if", "len", "(", "library", ")", "==", "2", ":", "name", ",", "version", "=", "library", "cmd", "=", "None", "elif", "len", "(", "library", ")", "==", "3", ":", "# a possible cmd we need to run", "name", ",", "version", ",", "cmd", "=", "library", "vendor_library", "(", "name", ",", "version", ",", "cmd", ")" ]
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'), ]
[ "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", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/vendor.py#L93-L112
233,424
ceph/ceph-deploy
ceph_deploy/gatherkeys.py
_keyring_equivalent
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 extract the key. """ with open(file_path) as f: for line in f: content = line.strip() if len(content) == 0: continue split_line = content.split('=') if split_line[0].strip() == 'key': return "=".join(split_line[1:]).strip() raise RuntimeError("File '%s' is not a keyring" % file_path) key_one = keyring_extract_key(keyring_one) key_two = keyring_extract_key(keyring_two) return key_one == key_two
python
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 extract the key. """ with open(file_path) as f: for line in f: content = line.strip() if len(content) == 0: continue split_line = content.split('=') if split_line[0].strip() == 'key': return "=".join(split_line[1:]).strip() raise RuntimeError("File '%s' is not a keyring" % file_path) key_one = keyring_extract_key(keyring_one) key_two = keyring_extract_key(keyring_two) return key_one == key_two
[ "def", "_keyring_equivalent", "(", "keyring_one", ",", "keyring_two", ")", ":", "def", "keyring_extract_key", "(", "file_path", ")", ":", "\"\"\"\n Cephx keyring files may or may not have white space before some lines.\n They may have some values in quotes, so a safe way to compare is to\n extract the key.\n \"\"\"", "with", "open", "(", "file_path", ")", "as", "f", ":", "for", "line", "in", "f", ":", "content", "=", "line", ".", "strip", "(", ")", "if", "len", "(", "content", ")", "==", "0", ":", "continue", "split_line", "=", "content", ".", "split", "(", "'='", ")", "if", "split_line", "[", "0", "]", ".", "strip", "(", ")", "==", "'key'", ":", "return", "\"=\"", ".", "join", "(", "split_line", "[", "1", ":", "]", ")", ".", "strip", "(", ")", "raise", "RuntimeError", "(", "\"File '%s' is not a keyring\"", "%", "file_path", ")", "key_one", "=", "keyring_extract_key", "(", "keyring_one", ")", "key_two", "=", "keyring_extract_key", "(", "keyring_two", ")", "return", "key_one", "==", "key_two" ]
Check two keyrings are identical
[ "Check", "two", "keyrings", "are", "identical" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/gatherkeys.py#L17-L38
233,425
ceph/ceph-deploy
ceph_deploy/gatherkeys.py
keytype_path_to
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) return '{cluster}.bootstrap-{what}.keyring'.format( cluster=args.cluster, what=keytype)
python
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) return '{cluster}.bootstrap-{what}.keyring'.format( cluster=args.cluster, what=keytype)
[ "def", "keytype_path_to", "(", "args", ",", "keytype", ")", ":", "if", "keytype", "==", "\"admin\"", ":", "return", "'{cluster}.client.admin.keyring'", ".", "format", "(", "cluster", "=", "args", ".", "cluster", ")", "if", "keytype", "==", "\"mon\"", ":", "return", "'{cluster}.mon.keyring'", ".", "format", "(", "cluster", "=", "args", ".", "cluster", ")", "return", "'{cluster}.bootstrap-{what}.keyring'", ".", "format", "(", "cluster", "=", "args", ".", "cluster", ",", "what", "=", "keytype", ")" ]
Get the local filename for a keyring type
[ "Get", "the", "local", "filename", "for", "a", "keyring", "type" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/gatherkeys.py#L41-L53
233,426
ceph/ceph-deploy
ceph_deploy/gatherkeys.py
gatherkeys_missing
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( cluster=args.cluster), '--name', 'mon.', '--keyring={keypath}'.format( keypath=keypath), ] identity = keytype_identity(keytype) if identity is None: raise RuntimeError('Could not find identity for keytype:%s' % keytype) capabilites = keytype_capabilities(keytype) if capabilites is None: raise RuntimeError('Could not find capabilites for keytype:%s' % keytype) # First try getting the key if it already exists, to handle the case where # it exists but doesn't match the caps we would pass into get-or-create. # This is the same behvaior as in newer ceph-create-keys out, err, code = remoto.process.check( distro.conn, args_prefix + ['auth', 'get', identity] ) if code == errno.ENOENT: out, err, code = remoto.process.check( distro.conn, args_prefix + ['auth', 'get-or-create', identity] + capabilites ) if code != 0: rlogger.error( '"ceph auth get-or-create for keytype %s returned %s', keytype, code ) for line in err: rlogger.debug(line) return False keyring_name_local = keytype_path_to(args, keytype) keyring_path_local = os.path.join(dest_dir, keyring_name_local) with open(keyring_path_local, 'wb') as f: for line in out: f.write(line + b'\n') return True
python
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( cluster=args.cluster), '--name', 'mon.', '--keyring={keypath}'.format( keypath=keypath), ] identity = keytype_identity(keytype) if identity is None: raise RuntimeError('Could not find identity for keytype:%s' % keytype) capabilites = keytype_capabilities(keytype) if capabilites is None: raise RuntimeError('Could not find capabilites for keytype:%s' % keytype) # First try getting the key if it already exists, to handle the case where # it exists but doesn't match the caps we would pass into get-or-create. # This is the same behvaior as in newer ceph-create-keys out, err, code = remoto.process.check( distro.conn, args_prefix + ['auth', 'get', identity] ) if code == errno.ENOENT: out, err, code = remoto.process.check( distro.conn, args_prefix + ['auth', 'get-or-create', identity] + capabilites ) if code != 0: rlogger.error( '"ceph auth get-or-create for keytype %s returned %s', keytype, code ) for line in err: rlogger.debug(line) return False keyring_name_local = keytype_path_to(args, keytype) keyring_path_local = os.path.join(dest_dir, keyring_name_local) with open(keyring_path_local, 'wb') as f: for line in out: f.write(line + b'\n') return True
[ "def", "gatherkeys_missing", "(", "args", ",", "distro", ",", "rlogger", ",", "keypath", ",", "keytype", ",", "dest_dir", ")", ":", "args_prefix", "=", "[", "'/usr/bin/ceph'", ",", "'--connect-timeout=25'", ",", "'--cluster={cluster}'", ".", "format", "(", "cluster", "=", "args", ".", "cluster", ")", ",", "'--name'", ",", "'mon.'", ",", "'--keyring={keypath}'", ".", "format", "(", "keypath", "=", "keypath", ")", ",", "]", "identity", "=", "keytype_identity", "(", "keytype", ")", "if", "identity", "is", "None", ":", "raise", "RuntimeError", "(", "'Could not find identity for keytype:%s'", "%", "keytype", ")", "capabilites", "=", "keytype_capabilities", "(", "keytype", ")", "if", "capabilites", "is", "None", ":", "raise", "RuntimeError", "(", "'Could not find capabilites for keytype:%s'", "%", "keytype", ")", "# First try getting the key if it already exists, to handle the case where", "# it exists but doesn't match the caps we would pass into get-or-create.", "# This is the same behvaior as in newer ceph-create-keys", "out", ",", "err", ",", "code", "=", "remoto", ".", "process", ".", "check", "(", "distro", ".", "conn", ",", "args_prefix", "+", "[", "'auth'", ",", "'get'", ",", "identity", "]", ")", "if", "code", "==", "errno", ".", "ENOENT", ":", "out", ",", "err", ",", "code", "=", "remoto", ".", "process", ".", "check", "(", "distro", ".", "conn", ",", "args_prefix", "+", "[", "'auth'", ",", "'get-or-create'", ",", "identity", "]", "+", "capabilites", ")", "if", "code", "!=", "0", ":", "rlogger", ".", "error", "(", "'\"ceph auth get-or-create for keytype %s returned %s'", ",", "keytype", ",", "code", ")", "for", "line", "in", "err", ":", "rlogger", ".", "debug", "(", "line", ")", "return", "False", "keyring_name_local", "=", "keytype_path_to", "(", "args", ",", "keytype", ")", "keyring_path_local", "=", "os", ".", "path", ".", "join", "(", "dest_dir", ",", "keyring_name_local", ")", "with", "open", "(", "keyring_path_local", ",", "'wb'", ")", "as", "f", ":", "for", "line", "in", "out", ":", "f", ".", "write", "(", "line", "+", "b'\\n'", ")", "return", "True" ]
Get or create the keyring from the mon using the mon keyring by keytype and copy to dest_dir
[ "Get", "or", "create", "the", "keyring", "from", "the", "mon", "using", "the", "mon", "keyring", "by", "keytype", "and", "copy", "to", "dest_dir" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/gatherkeys.py#L100-L147
233,427
ceph/ceph-deploy
ceph_deploy/gatherkeys.py
gatherkeys_with_mon
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) path_keytype_mon = "%s/keyring" % (dir_keytype_mon) mon_key = distro.conn.remote_module.get_file(path_keytype_mon) if mon_key is None: LOG.warning("No mon key found in host: %s", host) return False mon_name_local = keytype_path_to(args, "mon") mon_path_local = os.path.join(dest_dir, mon_name_local) with open(mon_path_local, 'wb') as f: f.write(mon_key) rlogger = logging.getLogger(host) path_asok = ceph_deploy.util.paths.mon.asok(args.cluster, remote_hostname) out, err, code = remoto.process.check( distro.conn, [ "/usr/bin/ceph", "--connect-timeout=25", "--cluster={cluster}".format( cluster=args.cluster), "--admin-daemon={asok}".format( asok=path_asok), "mon_status" ] ) if code != 0: rlogger.error('"ceph mon_status %s" returned %s', host, code) for line in err: rlogger.debug(line) return False try: mon_status = json.loads(b''.join(out).decode('utf-8')) except ValueError: rlogger.error('"ceph mon_status %s" output was not json', host) for line in out: rlogger.error(line) return False mon_number = None mon_map = mon_status.get('monmap') if mon_map is None: rlogger.error("could not find mon map for mons on '%s'", host) return False mon_quorum = mon_status.get('quorum') if mon_quorum is None: rlogger.error("could not find quorum for mons on '%s'" , host) return False mon_map_mons = mon_map.get('mons') if mon_map_mons is None: rlogger.error("could not find mons in monmap on '%s'", host) return False for mon in mon_map_mons: if mon.get('name') == remote_hostname: mon_number = mon.get('rank') break if mon_number is None: rlogger.error("could not find '%s' in monmap", remote_hostname) return False if not mon_number in mon_quorum: rlogger.error("Not yet quorum for '%s'", host) return False for keytype in ["admin", "mds", "mgr", "osd", "rgw"]: if not gatherkeys_missing(args, distro, rlogger, path_keytype_mon, keytype, dest_dir): # We will return failure if we fail to gather any key rlogger.error("Failed to return '%s' key from host %s", keytype, host) return False return True
python
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) path_keytype_mon = "%s/keyring" % (dir_keytype_mon) mon_key = distro.conn.remote_module.get_file(path_keytype_mon) if mon_key is None: LOG.warning("No mon key found in host: %s", host) return False mon_name_local = keytype_path_to(args, "mon") mon_path_local = os.path.join(dest_dir, mon_name_local) with open(mon_path_local, 'wb') as f: f.write(mon_key) rlogger = logging.getLogger(host) path_asok = ceph_deploy.util.paths.mon.asok(args.cluster, remote_hostname) out, err, code = remoto.process.check( distro.conn, [ "/usr/bin/ceph", "--connect-timeout=25", "--cluster={cluster}".format( cluster=args.cluster), "--admin-daemon={asok}".format( asok=path_asok), "mon_status" ] ) if code != 0: rlogger.error('"ceph mon_status %s" returned %s', host, code) for line in err: rlogger.debug(line) return False try: mon_status = json.loads(b''.join(out).decode('utf-8')) except ValueError: rlogger.error('"ceph mon_status %s" output was not json', host) for line in out: rlogger.error(line) return False mon_number = None mon_map = mon_status.get('monmap') if mon_map is None: rlogger.error("could not find mon map for mons on '%s'", host) return False mon_quorum = mon_status.get('quorum') if mon_quorum is None: rlogger.error("could not find quorum for mons on '%s'" , host) return False mon_map_mons = mon_map.get('mons') if mon_map_mons is None: rlogger.error("could not find mons in monmap on '%s'", host) return False for mon in mon_map_mons: if mon.get('name') == remote_hostname: mon_number = mon.get('rank') break if mon_number is None: rlogger.error("could not find '%s' in monmap", remote_hostname) return False if not mon_number in mon_quorum: rlogger.error("Not yet quorum for '%s'", host) return False for keytype in ["admin", "mds", "mgr", "osd", "rgw"]: if not gatherkeys_missing(args, distro, rlogger, path_keytype_mon, keytype, dest_dir): # We will return failure if we fail to gather any key rlogger.error("Failed to return '%s' key from host %s", keytype, host) return False return True
[ "def", "gatherkeys_with_mon", "(", "args", ",", "host", ",", "dest_dir", ")", ":", "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", ")", "path_keytype_mon", "=", "\"%s/keyring\"", "%", "(", "dir_keytype_mon", ")", "mon_key", "=", "distro", ".", "conn", ".", "remote_module", ".", "get_file", "(", "path_keytype_mon", ")", "if", "mon_key", "is", "None", ":", "LOG", ".", "warning", "(", "\"No mon key found in host: %s\"", ",", "host", ")", "return", "False", "mon_name_local", "=", "keytype_path_to", "(", "args", ",", "\"mon\"", ")", "mon_path_local", "=", "os", ".", "path", ".", "join", "(", "dest_dir", ",", "mon_name_local", ")", "with", "open", "(", "mon_path_local", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "mon_key", ")", "rlogger", "=", "logging", ".", "getLogger", "(", "host", ")", "path_asok", "=", "ceph_deploy", ".", "util", ".", "paths", ".", "mon", ".", "asok", "(", "args", ".", "cluster", ",", "remote_hostname", ")", "out", ",", "err", ",", "code", "=", "remoto", ".", "process", ".", "check", "(", "distro", ".", "conn", ",", "[", "\"/usr/bin/ceph\"", ",", "\"--connect-timeout=25\"", ",", "\"--cluster={cluster}\"", ".", "format", "(", "cluster", "=", "args", ".", "cluster", ")", ",", "\"--admin-daemon={asok}\"", ".", "format", "(", "asok", "=", "path_asok", ")", ",", "\"mon_status\"", "]", ")", "if", "code", "!=", "0", ":", "rlogger", ".", "error", "(", "'\"ceph mon_status %s\" returned %s'", ",", "host", ",", "code", ")", "for", "line", "in", "err", ":", "rlogger", ".", "debug", "(", "line", ")", "return", "False", "try", ":", "mon_status", "=", "json", ".", "loads", "(", "b''", ".", "join", "(", "out", ")", ".", "decode", "(", "'utf-8'", ")", ")", "except", "ValueError", ":", "rlogger", ".", "error", "(", "'\"ceph mon_status %s\" output was not json'", ",", "host", ")", "for", "line", "in", "out", ":", "rlogger", ".", "error", "(", "line", ")", "return", "False", "mon_number", "=", "None", "mon_map", "=", "mon_status", ".", "get", "(", "'monmap'", ")", "if", "mon_map", "is", "None", ":", "rlogger", ".", "error", "(", "\"could not find mon map for mons on '%s'\"", ",", "host", ")", "return", "False", "mon_quorum", "=", "mon_status", ".", "get", "(", "'quorum'", ")", "if", "mon_quorum", "is", "None", ":", "rlogger", ".", "error", "(", "\"could not find quorum for mons on '%s'\"", ",", "host", ")", "return", "False", "mon_map_mons", "=", "mon_map", ".", "get", "(", "'mons'", ")", "if", "mon_map_mons", "is", "None", ":", "rlogger", ".", "error", "(", "\"could not find mons in monmap on '%s'\"", ",", "host", ")", "return", "False", "for", "mon", "in", "mon_map_mons", ":", "if", "mon", ".", "get", "(", "'name'", ")", "==", "remote_hostname", ":", "mon_number", "=", "mon", ".", "get", "(", "'rank'", ")", "break", "if", "mon_number", "is", "None", ":", "rlogger", ".", "error", "(", "\"could not find '%s' in monmap\"", ",", "remote_hostname", ")", "return", "False", "if", "not", "mon_number", "in", "mon_quorum", ":", "rlogger", ".", "error", "(", "\"Not yet quorum for '%s'\"", ",", "host", ")", "return", "False", "for", "keytype", "in", "[", "\"admin\"", ",", "\"mds\"", ",", "\"mgr\"", ",", "\"osd\"", ",", "\"rgw\"", "]", ":", "if", "not", "gatherkeys_missing", "(", "args", ",", "distro", ",", "rlogger", ",", "path_keytype_mon", ",", "keytype", ",", "dest_dir", ")", ":", "# We will return failure if we fail to gather any key", "rlogger", ".", "error", "(", "\"Failed to return '%s' key from host %s\"", ",", "keytype", ",", "host", ")", "return", "False", "return", "True" ]
Connect to mon and gather keys if mon is in quorum.
[ "Connect", "to", "mon", "and", "gather", "keys", "if", "mon", "is", "in", "quorum", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/gatherkeys.py#L150-L220
233,428
ceph/ceph-deploy
ceph_deploy/gatherkeys.py
gatherkeys
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", tmpd) sucess = False for host in args.mon: sucess = gatherkeys_with_mon(args, host, tmpd) if sucess: break if not sucess: LOG.error("Failed to connect to host:%s" ,', '.join(args.mon)) raise RuntimeError('Failed to connect any mon') had_error = False date_string = time.strftime("%Y%m%d%H%M%S") for keytype in ["admin", "mds", "mgr", "mon", "osd", "rgw"]: filename = keytype_path_to(args, keytype) tmp_path = os.path.join(tmpd, filename) if not os.path.exists(tmp_path): LOG.error("No key retrived for '%s'" , keytype) had_error = True continue if not os.path.exists(filename): LOG.info("Storing %s" % (filename)) shutil.move(tmp_path, filename) continue if _keyring_equivalent(tmp_path, filename): LOG.info("keyring '%s' already exists" , filename) continue backup_keyring = "%s-%s" % (filename, date_string) LOG.info("Replacing '%s' and backing up old key as '%s'", filename, backup_keyring) shutil.copy(filename, backup_keyring) shutil.move(tmp_path, filename) if had_error: raise RuntimeError('Failed to get all key types') finally: LOG.info("Destroy temp directory %s" %(tmpd)) shutil.rmtree(tmpd) finally: os.umask(oldmask)
python
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", tmpd) sucess = False for host in args.mon: sucess = gatherkeys_with_mon(args, host, tmpd) if sucess: break if not sucess: LOG.error("Failed to connect to host:%s" ,', '.join(args.mon)) raise RuntimeError('Failed to connect any mon') had_error = False date_string = time.strftime("%Y%m%d%H%M%S") for keytype in ["admin", "mds", "mgr", "mon", "osd", "rgw"]: filename = keytype_path_to(args, keytype) tmp_path = os.path.join(tmpd, filename) if not os.path.exists(tmp_path): LOG.error("No key retrived for '%s'" , keytype) had_error = True continue if not os.path.exists(filename): LOG.info("Storing %s" % (filename)) shutil.move(tmp_path, filename) continue if _keyring_equivalent(tmp_path, filename): LOG.info("keyring '%s' already exists" , filename) continue backup_keyring = "%s-%s" % (filename, date_string) LOG.info("Replacing '%s' and backing up old key as '%s'", filename, backup_keyring) shutil.copy(filename, backup_keyring) shutil.move(tmp_path, filename) if had_error: raise RuntimeError('Failed to get all key types') finally: LOG.info("Destroy temp directory %s" %(tmpd)) shutil.rmtree(tmpd) finally: os.umask(oldmask)
[ "def", "gatherkeys", "(", "args", ")", ":", "oldmask", "=", "os", ".", "umask", "(", "0o77", ")", "try", ":", "try", ":", "tmpd", "=", "tempfile", ".", "mkdtemp", "(", ")", "LOG", ".", "info", "(", "\"Storing keys in temp directory %s\"", ",", "tmpd", ")", "sucess", "=", "False", "for", "host", "in", "args", ".", "mon", ":", "sucess", "=", "gatherkeys_with_mon", "(", "args", ",", "host", ",", "tmpd", ")", "if", "sucess", ":", "break", "if", "not", "sucess", ":", "LOG", ".", "error", "(", "\"Failed to connect to host:%s\"", ",", "', '", ".", "join", "(", "args", ".", "mon", ")", ")", "raise", "RuntimeError", "(", "'Failed to connect any mon'", ")", "had_error", "=", "False", "date_string", "=", "time", ".", "strftime", "(", "\"%Y%m%d%H%M%S\"", ")", "for", "keytype", "in", "[", "\"admin\"", ",", "\"mds\"", ",", "\"mgr\"", ",", "\"mon\"", ",", "\"osd\"", ",", "\"rgw\"", "]", ":", "filename", "=", "keytype_path_to", "(", "args", ",", "keytype", ")", "tmp_path", "=", "os", ".", "path", ".", "join", "(", "tmpd", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "tmp_path", ")", ":", "LOG", ".", "error", "(", "\"No key retrived for '%s'\"", ",", "keytype", ")", "had_error", "=", "True", "continue", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOG", ".", "info", "(", "\"Storing %s\"", "%", "(", "filename", ")", ")", "shutil", ".", "move", "(", "tmp_path", ",", "filename", ")", "continue", "if", "_keyring_equivalent", "(", "tmp_path", ",", "filename", ")", ":", "LOG", ".", "info", "(", "\"keyring '%s' already exists\"", ",", "filename", ")", "continue", "backup_keyring", "=", "\"%s-%s\"", "%", "(", "filename", ",", "date_string", ")", "LOG", ".", "info", "(", "\"Replacing '%s' and backing up old key as '%s'\"", ",", "filename", ",", "backup_keyring", ")", "shutil", ".", "copy", "(", "filename", ",", "backup_keyring", ")", "shutil", ".", "move", "(", "tmp_path", ",", "filename", ")", "if", "had_error", ":", "raise", "RuntimeError", "(", "'Failed to get all key types'", ")", "finally", ":", "LOG", ".", "info", "(", "\"Destroy temp directory %s\"", "%", "(", "tmpd", ")", ")", "shutil", ".", "rmtree", "(", "tmpd", ")", "finally", ":", "os", ".", "umask", "(", "oldmask", ")" ]
Gather keys from any mon and store in current working directory. Backs up keys from previous installs and stores new keys.
[ "Gather", "keys", "from", "any", "mon", "and", "store", "in", "current", "working", "directory", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/gatherkeys.py#L223-L268
233,429
ceph/ceph-deploy
ceph_deploy/gatherkeys.py
make
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, )
python
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, )
[ "def", "make", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'mon'", ",", "metavar", "=", "'HOST'", ",", "nargs", "=", "'+'", ",", "help", "=", "'monitor host to pull keys from'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "gatherkeys", ",", ")" ]
Gather authentication keys for provisioning new nodes.
[ "Gather", "authentication", "keys", "for", "provisioning", "new", "nodes", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/gatherkeys.py#L272-L284
233,430
ceph/ceph-deploy
ceph_deploy/hosts/__init__.py
get
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 return the appropriate module and slap a few attributes to that module defining the information it found from the hostname. For example, if host ``node1.example.com`` is an Ubuntu server, the ``debian`` module would be returned and the following would be set:: module.name = 'ubuntu' module.release = '12.04' module.codename = 'precise' :param hostname: A hostname that is reachable/resolvable over the network :param fallback: Optional fallback to use if no supported distro is found :param use_rhceph: Whether or not to install RH Ceph on a RHEL machine or the community distro. Changes what host module is returned for RHEL. :params callbacks: A list of callables that accept one argument (the actual module that contains the connection) that will be called, in order at the end of the instantiation of the module. """ conn = get_connection( hostname, username=username, logger=logging.getLogger(hostname), detect_sudo=detect_sudo ) try: conn.import_module(remotes) except IOError as error: if 'already closed' in getattr(error, 'message', ''): raise RuntimeError('remote connection got closed, ensure ``requiretty`` is disabled for %s' % hostname) distro_name, release, codename = conn.remote_module.platform_information() if not codename or not _get_distro(distro_name): raise exc.UnsupportedPlatform( distro=distro_name, codename=codename, release=release) machine_type = conn.remote_module.machine_type() module = _get_distro(distro_name, use_rhceph=use_rhceph) module.name = distro_name module.normalized_name = _normalized_distro_name(distro_name) module.normalized_release = _normalized_release(release) module.distro = module.normalized_name module.is_el = module.normalized_name in ['redhat', 'centos', 'fedora', 'scientific', 'oracle', 'virtuozzo'] module.is_rpm = module.normalized_name in ['redhat', 'centos', 'fedora', 'scientific', 'suse', 'oracle', 'virtuozzo', 'alt'] module.is_deb = module.normalized_name in ['debian', 'ubuntu'] module.is_pkgtarxz = module.normalized_name in ['arch'] module.release = release module.codename = codename module.conn = conn module.machine_type = machine_type module.init = module.choose_init(module) module.packager = module.get_packager(module) # execute each callback if any if callbacks: for c in callbacks: c(module) return module
python
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 return the appropriate module and slap a few attributes to that module defining the information it found from the hostname. For example, if host ``node1.example.com`` is an Ubuntu server, the ``debian`` module would be returned and the following would be set:: module.name = 'ubuntu' module.release = '12.04' module.codename = 'precise' :param hostname: A hostname that is reachable/resolvable over the network :param fallback: Optional fallback to use if no supported distro is found :param use_rhceph: Whether or not to install RH Ceph on a RHEL machine or the community distro. Changes what host module is returned for RHEL. :params callbacks: A list of callables that accept one argument (the actual module that contains the connection) that will be called, in order at the end of the instantiation of the module. """ conn = get_connection( hostname, username=username, logger=logging.getLogger(hostname), detect_sudo=detect_sudo ) try: conn.import_module(remotes) except IOError as error: if 'already closed' in getattr(error, 'message', ''): raise RuntimeError('remote connection got closed, ensure ``requiretty`` is disabled for %s' % hostname) distro_name, release, codename = conn.remote_module.platform_information() if not codename or not _get_distro(distro_name): raise exc.UnsupportedPlatform( distro=distro_name, codename=codename, release=release) machine_type = conn.remote_module.machine_type() module = _get_distro(distro_name, use_rhceph=use_rhceph) module.name = distro_name module.normalized_name = _normalized_distro_name(distro_name) module.normalized_release = _normalized_release(release) module.distro = module.normalized_name module.is_el = module.normalized_name in ['redhat', 'centos', 'fedora', 'scientific', 'oracle', 'virtuozzo'] module.is_rpm = module.normalized_name in ['redhat', 'centos', 'fedora', 'scientific', 'suse', 'oracle', 'virtuozzo', 'alt'] module.is_deb = module.normalized_name in ['debian', 'ubuntu'] module.is_pkgtarxz = module.normalized_name in ['arch'] module.release = release module.codename = codename module.conn = conn module.machine_type = machine_type module.init = module.choose_init(module) module.packager = module.get_packager(module) # execute each callback if any if callbacks: for c in callbacks: c(module) return module
[ "def", "get", "(", "hostname", ",", "username", "=", "None", ",", "fallback", "=", "None", ",", "detect_sudo", "=", "True", ",", "use_rhceph", "=", "False", ",", "callbacks", "=", "None", ")", ":", "conn", "=", "get_connection", "(", "hostname", ",", "username", "=", "username", ",", "logger", "=", "logging", ".", "getLogger", "(", "hostname", ")", ",", "detect_sudo", "=", "detect_sudo", ")", "try", ":", "conn", ".", "import_module", "(", "remotes", ")", "except", "IOError", "as", "error", ":", "if", "'already closed'", "in", "getattr", "(", "error", ",", "'message'", ",", "''", ")", ":", "raise", "RuntimeError", "(", "'remote connection got closed, ensure ``requiretty`` is disabled for %s'", "%", "hostname", ")", "distro_name", ",", "release", ",", "codename", "=", "conn", ".", "remote_module", ".", "platform_information", "(", ")", "if", "not", "codename", "or", "not", "_get_distro", "(", "distro_name", ")", ":", "raise", "exc", ".", "UnsupportedPlatform", "(", "distro", "=", "distro_name", ",", "codename", "=", "codename", ",", "release", "=", "release", ")", "machine_type", "=", "conn", ".", "remote_module", ".", "machine_type", "(", ")", "module", "=", "_get_distro", "(", "distro_name", ",", "use_rhceph", "=", "use_rhceph", ")", "module", ".", "name", "=", "distro_name", "module", ".", "normalized_name", "=", "_normalized_distro_name", "(", "distro_name", ")", "module", ".", "normalized_release", "=", "_normalized_release", "(", "release", ")", "module", ".", "distro", "=", "module", ".", "normalized_name", "module", ".", "is_el", "=", "module", ".", "normalized_name", "in", "[", "'redhat'", ",", "'centos'", ",", "'fedora'", ",", "'scientific'", ",", "'oracle'", ",", "'virtuozzo'", "]", "module", ".", "is_rpm", "=", "module", ".", "normalized_name", "in", "[", "'redhat'", ",", "'centos'", ",", "'fedora'", ",", "'scientific'", ",", "'suse'", ",", "'oracle'", ",", "'virtuozzo'", ",", "'alt'", "]", "module", ".", "is_deb", "=", "module", ".", "normalized_name", "in", "[", "'debian'", ",", "'ubuntu'", "]", "module", ".", "is_pkgtarxz", "=", "module", ".", "normalized_name", "in", "[", "'arch'", "]", "module", ".", "release", "=", "release", "module", ".", "codename", "=", "codename", "module", ".", "conn", "=", "conn", "module", ".", "machine_type", "=", "machine_type", "module", ".", "init", "=", "module", ".", "choose_init", "(", "module", ")", "module", ".", "packager", "=", "module", ".", "get_packager", "(", "module", ")", "# execute each callback if any", "if", "callbacks", ":", "for", "c", "in", "callbacks", ":", "c", "(", "module", ")", "return", "module" ]
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 ``node1.example.com`` is an Ubuntu server, the ``debian`` module would be returned and the following would be set:: module.name = 'ubuntu' module.release = '12.04' module.codename = 'precise' :param hostname: A hostname that is reachable/resolvable over the network :param fallback: Optional fallback to use if no supported distro is found :param use_rhceph: Whether or not to install RH Ceph on a RHEL machine or the community distro. Changes what host module is returned for RHEL. :params callbacks: A list of callables that accept one argument (the actual module that contains the connection) that will be called, in order at the end of the instantiation of the module.
[ "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", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/__init__.py#L16-L84
233,431
ceph/ceph-deploy
ceph_deploy/connection.py
get_connection
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( hostname, logger=logger, threads=threads, detect_sudo=detect_sudo, ) # Set a timeout value in seconds to disconnect and move on # if no data is sent back. conn.global_timeout = 300 logger.debug("connected to host: %s " % hostname) return conn except Exception as error: msg = "connecting to host: %s " % hostname errors = "resulted in errors: %s %s" % (error.__class__.__name__, error) raise RuntimeError(msg + errors)
python
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( hostname, logger=logger, threads=threads, detect_sudo=detect_sudo, ) # Set a timeout value in seconds to disconnect and move on # if no data is sent back. conn.global_timeout = 300 logger.debug("connected to host: %s " % hostname) return conn except Exception as error: msg = "connecting to host: %s " % hostname errors = "resulted in errors: %s %s" % (error.__class__.__name__, error) raise RuntimeError(msg + errors)
[ "def", "get_connection", "(", "hostname", ",", "username", ",", "logger", ",", "threads", "=", "5", ",", "use_sudo", "=", "None", ",", "detect_sudo", "=", "True", ")", ":", "if", "username", ":", "hostname", "=", "\"%s@%s\"", "%", "(", "username", ",", "hostname", ")", "try", ":", "conn", "=", "remoto", ".", "Connection", "(", "hostname", ",", "logger", "=", "logger", ",", "threads", "=", "threads", ",", "detect_sudo", "=", "detect_sudo", ",", ")", "# Set a timeout value in seconds to disconnect and move on", "# if no data is sent back.", "conn", ".", "global_timeout", "=", "300", "logger", ".", "debug", "(", "\"connected to host: %s \"", "%", "hostname", ")", "return", "conn", "except", "Exception", "as", "error", ":", "msg", "=", "\"connecting to host: %s \"", "%", "hostname", "errors", "=", "\"resulted in errors: %s %s\"", "%", "(", "error", ".", "__class__", ".", "__name__", ",", "error", ")", "raise", "RuntimeError", "(", "msg", "+", "errors", ")" ]
A very simple helper, meant to return a connection that will know about the need to use sudo.
[ "A", "very", "simple", "helper", "meant", "to", "return", "a", "connection", "that", "will", "know", "about", "the", "need", "to", "use", "sudo", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/connection.py#L5-L29
233,432
ceph/ceph-deploy
ceph_deploy/connection.py
get_local_connection
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=use_sudo, detect_sudo=False )
python
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=use_sudo, detect_sudo=False )
[ "def", "get_local_connection", "(", "logger", ",", "use_sudo", "=", "False", ")", ":", "return", "get_connection", "(", "socket", ".", "gethostname", "(", ")", ",", "# cannot rely on 'localhost' here", "None", ",", "logger", "=", "logger", ",", "threads", "=", "1", ",", "use_sudo", "=", "use_sudo", ",", "detect_sudo", "=", "False", ")" ]
Helper for local connections that are sometimes needed to operate on local hosts
[ "Helper", "for", "local", "connections", "that", "are", "sometimes", "needed", "to", "operate", "on", "local", "hosts" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/connection.py#L32-L44
233,433
ceph/ceph-deploy
ceph_deploy/mgr.py
make
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', metavar='HOST[:NAME]', nargs='+', type=colon_separated, help='host (and optionally the daemon name) to deploy on', ) parser.set_defaults( func=mgr, )
python
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', metavar='HOST[:NAME]', nargs='+', type=colon_separated, help='host (and optionally the daemon name) to deploy on', ) parser.set_defaults( func=mgr, )
[ "def", "make", "(", "parser", ")", ":", "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'", ",", "metavar", "=", "'HOST[:NAME]'", ",", "nargs", "=", "'+'", ",", "type", "=", "colon_separated", ",", "help", "=", "'host (and optionally the daemon name) to deploy on'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "mgr", ",", ")" ]
Ceph MGR daemon management
[ "Ceph", "MGR", "daemon", "management" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/mgr.py#L206-L226
233,434
ceph/ceph-deploy
ceph_deploy/pkg.py
make
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='PKG(s)', help='Comma-separated package(s) to remove', ) parser.add_argument( 'hosts', nargs='+', ) parser.set_defaults( func=pkg, )
python
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='PKG(s)', help='Comma-separated package(s) to remove', ) parser.add_argument( 'hosts', nargs='+', ) parser.set_defaults( func=pkg, )
[ "def", "make", "(", "parser", ")", ":", "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", "=", "'PKG(s)'", ",", "help", "=", "'Comma-separated package(s) to remove'", ",", ")", "parser", ".", "add_argument", "(", "'hosts'", ",", "nargs", "=", "'+'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "pkg", ",", ")" ]
Manage packages on remote hosts.
[ "Manage", "packages", "on", "remote", "hosts", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/pkg.py#L60-L86
233,435
ceph/ceph-deploy
ceph_deploy/osd.py
get_bootstrap_osd_key
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 \'gatherkeys\'')
python
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 \'gatherkeys\'')
[ "def", "get_bootstrap_osd_key", "(", "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 \\'gatherkeys\\''", ")" ]
Read the bootstrap-osd key for `cluster`.
[ "Read", "the", "bootstrap", "-", "osd", "key", "for", "cluster", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/osd.py#L17-L26
233,436
ceph/ceph-deploy
ceph_deploy/osd.py
create_osd_keyring
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('osd keyring does not exist yet, creating one') conn.remote_module.write_keyring(path, key)
python
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('osd keyring does not exist yet, creating one') conn.remote_module.write_keyring(path, key)
[ "def", "create_osd_keyring", "(", "conn", ",", "cluster", ",", "key", ")", ":", "logger", "=", "conn", ".", "logger", "path", "=", "'/var/lib/ceph/bootstrap-osd/{cluster}.keyring'", ".", "format", "(", "cluster", "=", "cluster", ",", ")", "if", "not", "conn", ".", "remote_module", ".", "path_exists", "(", "path", ")", ":", "logger", ".", "warning", "(", "'osd keyring does not exist yet, creating one'", ")", "conn", ".", "remote_module", ".", "write_keyring", "(", "path", ",", "key", ")" ]
Run on osd node, writes the bootstrap key if not there yet.
[ "Run", "on", "osd", "node", "writes", "the", "bootstrap", "key", "if", "not", "there", "yet", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/osd.py#L29-L39
233,437
ceph/ceph-deploy
ceph_deploy/osd.py
osd_tree
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" } Note how the booleans are actually strings, so we need to take that into account and fix it before returning the dictionary. Issue #8108 """ ceph_executable = system.executable_path(conn, 'ceph') command = [ ceph_executable, '--cluster={cluster}'.format(cluster=cluster), 'osd', 'tree', '--format=json', ] out, err, code = remoto.process.check( conn, command, ) try: loaded_json = json.loads(b''.join(out).decode('utf-8')) # convert boolean strings to actual booleans because # --format=json fails to do this properly for k, v in loaded_json.items(): if v == 'true': loaded_json[k] = True elif v == 'false': loaded_json[k] = False return loaded_json except ValueError: return {}
python
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" } Note how the booleans are actually strings, so we need to take that into account and fix it before returning the dictionary. Issue #8108 """ ceph_executable = system.executable_path(conn, 'ceph') command = [ ceph_executable, '--cluster={cluster}'.format(cluster=cluster), 'osd', 'tree', '--format=json', ] out, err, code = remoto.process.check( conn, command, ) try: loaded_json = json.loads(b''.join(out).decode('utf-8')) # convert boolean strings to actual booleans because # --format=json fails to do this properly for k, v in loaded_json.items(): if v == 'true': loaded_json[k] = True elif v == 'false': loaded_json[k] = False return loaded_json except ValueError: return {}
[ "def", "osd_tree", "(", "conn", ",", "cluster", ")", ":", "ceph_executable", "=", "system", ".", "executable_path", "(", "conn", ",", "'ceph'", ")", "command", "=", "[", "ceph_executable", ",", "'--cluster={cluster}'", ".", "format", "(", "cluster", "=", "cluster", ")", ",", "'osd'", ",", "'tree'", ",", "'--format=json'", ",", "]", "out", ",", "err", ",", "code", "=", "remoto", ".", "process", ".", "check", "(", "conn", ",", "command", ",", ")", "try", ":", "loaded_json", "=", "json", ".", "loads", "(", "b''", ".", "join", "(", "out", ")", ".", "decode", "(", "'utf-8'", ")", ")", "# convert boolean strings to actual booleans because", "# --format=json fails to do this properly", "for", "k", ",", "v", "in", "loaded_json", ".", "items", "(", ")", ":", "if", "v", "==", "'true'", ":", "loaded_json", "[", "k", "]", "=", "True", "elif", "v", "==", "'false'", ":", "loaded_json", "[", "k", "]", "=", "False", "return", "loaded_json", "except", "ValueError", ":", "return", "{", "}" ]
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 are actually strings, so we need to take that into account and fix it before returning the dictionary. Issue #8108
[ "Check", "the", "status", "of", "an", "OSD", ".", "Make", "sure", "all", "are", "up", "and", "in" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/osd.py#L42-L85
233,438
ceph/ceph-deploy
ceph_deploy/osd.py
catch_osd_errors
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.get('num_up_osds', 0)) in_osds = int(status.get('num_in_osds', 0)) full = status.get('full', False) nearfull = status.get('nearfull', False) if osds > up_osds: difference = osds - up_osds logger.warning('there %s %d OSD%s down' % ( ['is', 'are'][difference != 1], difference, "s"[difference == 1:]) ) if osds > in_osds: difference = osds - in_osds logger.warning('there %s %d OSD%s out' % ( ['is', 'are'][difference != 1], difference, "s"[difference == 1:]) ) if full: logger.warning('OSDs are full!') if nearfull: logger.warning('OSDs are near full!')
python
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.get('num_up_osds', 0)) in_osds = int(status.get('num_in_osds', 0)) full = status.get('full', False) nearfull = status.get('nearfull', False) if osds > up_osds: difference = osds - up_osds logger.warning('there %s %d OSD%s down' % ( ['is', 'are'][difference != 1], difference, "s"[difference == 1:]) ) if osds > in_osds: difference = osds - in_osds logger.warning('there %s %d OSD%s out' % ( ['is', 'are'][difference != 1], difference, "s"[difference == 1:]) ) if full: logger.warning('OSDs are full!') if nearfull: logger.warning('OSDs are near full!')
[ "def", "catch_osd_errors", "(", "conn", ",", "logger", ",", "args", ")", ":", "logger", ".", "info", "(", "'checking OSD status...'", ")", "status", "=", "osd_status_check", "(", "conn", ",", "args", ".", "cluster", ")", "osds", "=", "int", "(", "status", ".", "get", "(", "'num_osds'", ",", "0", ")", ")", "up_osds", "=", "int", "(", "status", ".", "get", "(", "'num_up_osds'", ",", "0", ")", ")", "in_osds", "=", "int", "(", "status", ".", "get", "(", "'num_in_osds'", ",", "0", ")", ")", "full", "=", "status", ".", "get", "(", "'full'", ",", "False", ")", "nearfull", "=", "status", ".", "get", "(", "'nearfull'", ",", "False", ")", "if", "osds", ">", "up_osds", ":", "difference", "=", "osds", "-", "up_osds", "logger", ".", "warning", "(", "'there %s %d OSD%s down'", "%", "(", "[", "'is'", ",", "'are'", "]", "[", "difference", "!=", "1", "]", ",", "difference", ",", "\"s\"", "[", "difference", "==", "1", ":", "]", ")", ")", "if", "osds", ">", "in_osds", ":", "difference", "=", "osds", "-", "in_osds", "logger", ".", "warning", "(", "'there %s %d OSD%s out'", "%", "(", "[", "'is'", ",", "'are'", "]", "[", "difference", "!=", "1", "]", ",", "difference", ",", "\"s\"", "[", "difference", "==", "1", ":", "]", ")", ")", "if", "full", ":", "logger", ".", "warning", "(", "'OSDs are full!'", ")", "if", "nearfull", ":", "logger", ".", "warning", "(", "'OSDs are near full!'", ")" ]
Look for possible issues when checking the status of an OSD and report them back to the user.
[ "Look", "for", "possible", "issues", "when", "checking", "the", "status", "of", "an", "OSD", "and", "report", "them", "back", "to", "the", "user", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/osd.py#L141-L174
233,439
ceph/ceph-deploy
ceph_deploy/osd.py
create_osd
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 = system.executable_path(conn, 'ceph-volume') args = [ ceph_volume_executable, '--cluster', cluster, 'lvm', 'create', '--%s' % storetype, '--data', data ] if zap: LOG.warning('zapping is no longer supported when preparing') if dmcrypt: args.append('--dmcrypt') # TODO: re-enable dmcrypt support once ceph-volume grows it LOG.warning('dmcrypt is currently not supported') if storetype == 'bluestore': if block_wal: args.append('--block.wal') args.append(block_wal) if block_db: args.append('--block.db') args.append(block_db) elif storetype == 'filestore': if not journal: raise RuntimeError('A journal lv or GPT partition must be specified when using filestore') args.append('--journal') args.append(journal) if kw.get('debug'): remoto.process.run( conn, args, extend_env={'CEPH_VOLUME_DEBUG': '1'} ) else: remoto.process.run( conn, args )
python
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 = system.executable_path(conn, 'ceph-volume') args = [ ceph_volume_executable, '--cluster', cluster, 'lvm', 'create', '--%s' % storetype, '--data', data ] if zap: LOG.warning('zapping is no longer supported when preparing') if dmcrypt: args.append('--dmcrypt') # TODO: re-enable dmcrypt support once ceph-volume grows it LOG.warning('dmcrypt is currently not supported') if storetype == 'bluestore': if block_wal: args.append('--block.wal') args.append(block_wal) if block_db: args.append('--block.db') args.append(block_db) elif storetype == 'filestore': if not journal: raise RuntimeError('A journal lv or GPT partition must be specified when using filestore') args.append('--journal') args.append(journal) if kw.get('debug'): remoto.process.run( conn, args, extend_env={'CEPH_VOLUME_DEBUG': '1'} ) else: remoto.process.run( conn, args )
[ "def", "create_osd", "(", "conn", ",", "cluster", ",", "data", ",", "journal", ",", "zap", ",", "fs_type", ",", "dmcrypt", ",", "dmcrypt_dir", ",", "storetype", ",", "block_wal", ",", "block_db", ",", "*", "*", "kw", ")", ":", "ceph_volume_executable", "=", "system", ".", "executable_path", "(", "conn", ",", "'ceph-volume'", ")", "args", "=", "[", "ceph_volume_executable", ",", "'--cluster'", ",", "cluster", ",", "'lvm'", ",", "'create'", ",", "'--%s'", "%", "storetype", ",", "'--data'", ",", "data", "]", "if", "zap", ":", "LOG", ".", "warning", "(", "'zapping is no longer supported when preparing'", ")", "if", "dmcrypt", ":", "args", ".", "append", "(", "'--dmcrypt'", ")", "# TODO: re-enable dmcrypt support once ceph-volume grows it", "LOG", ".", "warning", "(", "'dmcrypt is currently not supported'", ")", "if", "storetype", "==", "'bluestore'", ":", "if", "block_wal", ":", "args", ".", "append", "(", "'--block.wal'", ")", "args", ".", "append", "(", "block_wal", ")", "if", "block_db", ":", "args", ".", "append", "(", "'--block.db'", ")", "args", ".", "append", "(", "block_db", ")", "elif", "storetype", "==", "'filestore'", ":", "if", "not", "journal", ":", "raise", "RuntimeError", "(", "'A journal lv or GPT partition must be specified when using filestore'", ")", "args", ".", "append", "(", "'--journal'", ")", "args", ".", "append", "(", "journal", ")", "if", "kw", ".", "get", "(", "'debug'", ")", ":", "remoto", ".", "process", ".", "run", "(", "conn", ",", "args", ",", "extend_env", "=", "{", "'CEPH_VOLUME_DEBUG'", ":", "'1'", "}", ")", "else", ":", "remoto", ".", "process", ".", "run", "(", "conn", ",", "args", ")" ]
Run on osd node, creates an OSD from a data disk.
[ "Run", "on", "osd", "node", "creates", "an", "OSD", "from", "a", "data", "disk", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/osd.py#L177-L233
233,440
ceph/ceph-deploy
ceph_deploy/osd.py
make
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 /path/to/data --block-db /path/to/db-device ceph-deploy osd create {node} --data /path/to/data --block-wal /path/to/wal-device ceph-deploy osd create {node} --data /path/to/data --block-db /path/to/db-device --block-wal /path/to/wal-device For filestore, the journal must be specified, as well as the objectstore:: ceph-deploy osd create {node} --filestore --data /path/to/data --journal /path/to/journal For data devices, it can be an existing logical volume in the format of: vg/lv, or a device. For other OSD components like wal, db, and journal, it can be logical volume (in vg/lv format) or it must be a GPT partition. """ ) parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.description = sub_command_help osd_parser = parser.add_subparsers(dest='subcommand') osd_parser.required = True osd_list = osd_parser.add_parser( 'list', help='List OSD info from remote host(s)' ) osd_list.add_argument( 'host', nargs='+', metavar='HOST', help='remote host(s) to list OSDs from' ) osd_list.add_argument( '--debug', action='store_true', help='Enable debug mode on remote ceph-volume calls', ) osd_create = osd_parser.add_parser( 'create', help='Create new Ceph OSD daemon by preparing and activating a device' ) osd_create.add_argument( '--data', metavar='DATA', help='The OSD data logical volume (vg/lv) or absolute path to device' ) osd_create.add_argument( '--journal', help='Logical Volume (vg/lv) or path to GPT partition', ) osd_create.add_argument( '--zap-disk', action='store_true', help='DEPRECATED - cannot zap when creating an OSD' ) osd_create.add_argument( '--fs-type', metavar='FS_TYPE', choices=['xfs', 'btrfs' ], default='xfs', help='filesystem to use to format DEVICE (xfs, btrfs)', ) osd_create.add_argument( '--dmcrypt', action='store_true', help='use dm-crypt on DEVICE', ) osd_create.add_argument( '--dmcrypt-key-dir', metavar='KEYDIR', default='/etc/ceph/dmcrypt-keys', help='directory where dm-crypt keys are stored', ) osd_create.add_argument( '--filestore', action='store_true', default=None, help='filestore objectstore', ) osd_create.add_argument( '--bluestore', action='store_true', default=None, help='bluestore objectstore', ) osd_create.add_argument( '--block-db', default=None, help='bluestore block.db path' ) osd_create.add_argument( '--block-wal', default=None, help='bluestore block.wal path' ) osd_create.add_argument( 'host', nargs='?', metavar='HOST', help='Remote host to connect' ) osd_create.add_argument( '--debug', action='store_true', help='Enable debug mode on remote ceph-volume calls', ) parser.set_defaults( func=osd, )
python
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 /path/to/data --block-db /path/to/db-device ceph-deploy osd create {node} --data /path/to/data --block-wal /path/to/wal-device ceph-deploy osd create {node} --data /path/to/data --block-db /path/to/db-device --block-wal /path/to/wal-device For filestore, the journal must be specified, as well as the objectstore:: ceph-deploy osd create {node} --filestore --data /path/to/data --journal /path/to/journal For data devices, it can be an existing logical volume in the format of: vg/lv, or a device. For other OSD components like wal, db, and journal, it can be logical volume (in vg/lv format) or it must be a GPT partition. """ ) parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.description = sub_command_help osd_parser = parser.add_subparsers(dest='subcommand') osd_parser.required = True osd_list = osd_parser.add_parser( 'list', help='List OSD info from remote host(s)' ) osd_list.add_argument( 'host', nargs='+', metavar='HOST', help='remote host(s) to list OSDs from' ) osd_list.add_argument( '--debug', action='store_true', help='Enable debug mode on remote ceph-volume calls', ) osd_create = osd_parser.add_parser( 'create', help='Create new Ceph OSD daemon by preparing and activating a device' ) osd_create.add_argument( '--data', metavar='DATA', help='The OSD data logical volume (vg/lv) or absolute path to device' ) osd_create.add_argument( '--journal', help='Logical Volume (vg/lv) or path to GPT partition', ) osd_create.add_argument( '--zap-disk', action='store_true', help='DEPRECATED - cannot zap when creating an OSD' ) osd_create.add_argument( '--fs-type', metavar='FS_TYPE', choices=['xfs', 'btrfs' ], default='xfs', help='filesystem to use to format DEVICE (xfs, btrfs)', ) osd_create.add_argument( '--dmcrypt', action='store_true', help='use dm-crypt on DEVICE', ) osd_create.add_argument( '--dmcrypt-key-dir', metavar='KEYDIR', default='/etc/ceph/dmcrypt-keys', help='directory where dm-crypt keys are stored', ) osd_create.add_argument( '--filestore', action='store_true', default=None, help='filestore objectstore', ) osd_create.add_argument( '--bluestore', action='store_true', default=None, help='bluestore objectstore', ) osd_create.add_argument( '--block-db', default=None, help='bluestore block.db path' ) osd_create.add_argument( '--block-wal', default=None, help='bluestore block.wal path' ) osd_create.add_argument( 'host', nargs='?', metavar='HOST', help='Remote host to connect' ) osd_create.add_argument( '--debug', action='store_true', help='Enable debug mode on remote ceph-volume calls', ) parser.set_defaults( func=osd, )
[ "def", "make", "(", "parser", ")", ":", "sub_command_help", "=", "dedent", "(", "\"\"\"\n Create OSDs from a data disk on a remote host:\n\n ceph-deploy osd create {node} --data /path/to/device\n\n For bluestore, optional devices can be used::\n\n ceph-deploy osd create {node} --data /path/to/data --block-db /path/to/db-device\n ceph-deploy osd create {node} --data /path/to/data --block-wal /path/to/wal-device\n ceph-deploy osd create {node} --data /path/to/data --block-db /path/to/db-device --block-wal /path/to/wal-device\n\n For filestore, the journal must be specified, as well as the objectstore::\n\n ceph-deploy osd create {node} --filestore --data /path/to/data --journal /path/to/journal\n\n For data devices, it can be an existing logical volume in the format of:\n vg/lv, or a device. For other OSD components like wal, db, and journal, it\n can be logical volume (in vg/lv format) or it must be a GPT partition.\n \"\"\"", ")", "parser", ".", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", "parser", ".", "description", "=", "sub_command_help", "osd_parser", "=", "parser", ".", "add_subparsers", "(", "dest", "=", "'subcommand'", ")", "osd_parser", ".", "required", "=", "True", "osd_list", "=", "osd_parser", ".", "add_parser", "(", "'list'", ",", "help", "=", "'List OSD info from remote host(s)'", ")", "osd_list", ".", "add_argument", "(", "'host'", ",", "nargs", "=", "'+'", ",", "metavar", "=", "'HOST'", ",", "help", "=", "'remote host(s) to list OSDs from'", ")", "osd_list", ".", "add_argument", "(", "'--debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enable debug mode on remote ceph-volume calls'", ",", ")", "osd_create", "=", "osd_parser", ".", "add_parser", "(", "'create'", ",", "help", "=", "'Create new Ceph OSD daemon by preparing and activating a device'", ")", "osd_create", ".", "add_argument", "(", "'--data'", ",", "metavar", "=", "'DATA'", ",", "help", "=", "'The OSD data logical volume (vg/lv) or absolute path to device'", ")", "osd_create", ".", "add_argument", "(", "'--journal'", ",", "help", "=", "'Logical Volume (vg/lv) or path to GPT partition'", ",", ")", "osd_create", ".", "add_argument", "(", "'--zap-disk'", ",", "action", "=", "'store_true'", ",", "help", "=", "'DEPRECATED - cannot zap when creating an OSD'", ")", "osd_create", ".", "add_argument", "(", "'--fs-type'", ",", "metavar", "=", "'FS_TYPE'", ",", "choices", "=", "[", "'xfs'", ",", "'btrfs'", "]", ",", "default", "=", "'xfs'", ",", "help", "=", "'filesystem to use to format DEVICE (xfs, btrfs)'", ",", ")", "osd_create", ".", "add_argument", "(", "'--dmcrypt'", ",", "action", "=", "'store_true'", ",", "help", "=", "'use dm-crypt on DEVICE'", ",", ")", "osd_create", ".", "add_argument", "(", "'--dmcrypt-key-dir'", ",", "metavar", "=", "'KEYDIR'", ",", "default", "=", "'/etc/ceph/dmcrypt-keys'", ",", "help", "=", "'directory where dm-crypt keys are stored'", ",", ")", "osd_create", ".", "add_argument", "(", "'--filestore'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "'filestore objectstore'", ",", ")", "osd_create", ".", "add_argument", "(", "'--bluestore'", ",", "action", "=", "'store_true'", ",", "default", "=", "None", ",", "help", "=", "'bluestore objectstore'", ",", ")", "osd_create", ".", "add_argument", "(", "'--block-db'", ",", "default", "=", "None", ",", "help", "=", "'bluestore block.db path'", ")", "osd_create", ".", "add_argument", "(", "'--block-wal'", ",", "default", "=", "None", ",", "help", "=", "'bluestore block.wal path'", ")", "osd_create", ".", "add_argument", "(", "'host'", ",", "nargs", "=", "'?'", ",", "metavar", "=", "'HOST'", ",", "help", "=", "'Remote host to connect'", ")", "osd_create", ".", "add_argument", "(", "'--debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enable debug mode on remote ceph-volume calls'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "osd", ",", ")" ]
Prepare a data disk on remote host.
[ "Prepare", "a", "data", "disk", "on", "remote", "host", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/osd.py#L445-L561
233,441
ceph/ceph-deploy
ceph_deploy/osd.py
make_disk
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_argument( 'host', nargs='?', metavar='HOST', help='Remote HOST(s) to connect' ) disk_zap.add_argument( 'disk', nargs='+', metavar='DISK', help='Disk(s) to zap' ) disk_zap.add_argument( '--debug', action='store_true', help='Enable debug mode on remote ceph-volume calls', ) disk_list = disk_parser.add_parser( 'list', help='List disk info from remote host(s)' ) disk_list.add_argument( 'host', nargs='+', metavar='HOST', help='Remote HOST(s) to list OSDs from' ) disk_list.add_argument( '--debug', action='store_true', help='Enable debug mode on remote ceph-volume calls', ) parser.set_defaults( func=disk, )
python
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_argument( 'host', nargs='?', metavar='HOST', help='Remote HOST(s) to connect' ) disk_zap.add_argument( 'disk', nargs='+', metavar='DISK', help='Disk(s) to zap' ) disk_zap.add_argument( '--debug', action='store_true', help='Enable debug mode on remote ceph-volume calls', ) disk_list = disk_parser.add_parser( 'list', help='List disk info from remote host(s)' ) disk_list.add_argument( 'host', nargs='+', metavar='HOST', help='Remote HOST(s) to list OSDs from' ) disk_list.add_argument( '--debug', action='store_true', help='Enable debug mode on remote ceph-volume calls', ) parser.set_defaults( func=disk, )
[ "def", "make_disk", "(", "parser", ")", ":", "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_argument", "(", "'host'", ",", "nargs", "=", "'?'", ",", "metavar", "=", "'HOST'", ",", "help", "=", "'Remote HOST(s) to connect'", ")", "disk_zap", ".", "add_argument", "(", "'disk'", ",", "nargs", "=", "'+'", ",", "metavar", "=", "'DISK'", ",", "help", "=", "'Disk(s) to zap'", ")", "disk_zap", ".", "add_argument", "(", "'--debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enable debug mode on remote ceph-volume calls'", ",", ")", "disk_list", "=", "disk_parser", ".", "add_parser", "(", "'list'", ",", "help", "=", "'List disk info from remote host(s)'", ")", "disk_list", ".", "add_argument", "(", "'host'", ",", "nargs", "=", "'+'", ",", "metavar", "=", "'HOST'", ",", "help", "=", "'Remote HOST(s) to list OSDs from'", ")", "disk_list", ".", "add_argument", "(", "'--debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enable debug mode on remote ceph-volume calls'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "disk", ",", ")" ]
Manage disks on a remote host.
[ "Manage", "disks", "on", "a", "remote", "host", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/osd.py#L565-L610
233,442
ceph/ceph-deploy
ceph_deploy/hosts/centos/install.py
repository_url_part
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 part for the given distro, falling back to `el6` when all else fails. Specifically to work around the issue of CentOS vs RHEL:: >>> import platform >>> platform.linux_distribution() ('Red Hat Enterprise Linux Server', '7.0', 'Maipo') """ if distro.normalized_release.int_major >= 6: if distro.normalized_name == 'redhat': return 'rhel' + distro.normalized_release.major if distro.normalized_name in ['centos', 'scientific', 'oracle', 'virtuozzo']: return 'el' + distro.normalized_release.major return 'el6'
python
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 part for the given distro, falling back to `el6` when all else fails. Specifically to work around the issue of CentOS vs RHEL:: >>> import platform >>> platform.linux_distribution() ('Red Hat Enterprise Linux Server', '7.0', 'Maipo') """ if distro.normalized_release.int_major >= 6: if distro.normalized_name == 'redhat': return 'rhel' + distro.normalized_release.major if distro.normalized_name in ['centos', 'scientific', 'oracle', 'virtuozzo']: return 'el' + distro.normalized_release.major return 'el6'
[ "def", "repository_url_part", "(", "distro", ")", ":", "if", "distro", ".", "normalized_release", ".", "int_major", ">=", "6", ":", "if", "distro", ".", "normalized_name", "==", "'redhat'", ":", "return", "'rhel'", "+", "distro", ".", "normalized_release", ".", "major", "if", "distro", ".", "normalized_name", "in", "[", "'centos'", ",", "'scientific'", ",", "'oracle'", ",", "'virtuozzo'", "]", ":", "return", "'el'", "+", "distro", ".", "normalized_release", ".", "major", "return", "'el6'" ]
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 to `el6` when all else fails. Specifically to work around the issue of CentOS vs RHEL:: >>> import platform >>> platform.linux_distribution() ('Red Hat Enterprise Linux Server', '7.0', 'Maipo')
[ "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", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/centos/install.py#L19-L41
233,443
ceph/ceph-deploy
ceph_deploy/install.py
sanitize_args
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 args.stable is not None: LOG.warning('the --stable flag is deprecated, use --release instead') args.release = args.stable # XXX Tango ends here. return args
python
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 args.stable is not None: LOG.warning('the --stable flag is deprecated, use --release instead') args.release = args.stable # XXX Tango ends here. return args
[ "def", "sanitize_args", "(", "args", ")", ":", "if", "args", ".", "release", "is", "None", ":", "args", ".", "release", "=", "'nautilus'", "args", ".", "default_release", "=", "True", "# XXX This whole dance is because --stable is getting deprecated", "if", "args", ".", "stable", "is", "not", "None", ":", "LOG", ".", "warning", "(", "'the --stable flag is deprecated, use --release instead'", ")", "args", ".", "release", "=", "args", ".", "stable", "# XXX Tango ends here.", "return", "args" ]
args may need a bunch of logic to set proper defaults that argparse is not well suited for.
[ "args", "may", "need", "a", "bunch", "of", "logic", "to", "set", "proper", "defaults", "that", "argparse", "is", "not", "well", "suited", "for", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/install.py#L14-L29
233,444
ceph/ceph-deploy
ceph_deploy/install.py
should_use_custom_repo
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 False if cd_conf: if cd_conf.has_repos: has_valid_release = args.release in cd_conf.get_repos() has_default_repo = cd_conf.get_default_repo() if has_valid_release or has_default_repo: return True return False
python
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 False if cd_conf: if cd_conf.has_repos: has_valid_release = args.release in cd_conf.get_repos() has_default_repo = cd_conf.get_default_repo() if has_valid_release or has_default_repo: return True return False
[ "def", "should_use_custom_repo", "(", "args", ",", "cd_conf", ",", "repo_url", ")", ":", "if", "repo_url", ":", "# repo_url signals a CLI override, return False immediately", "return", "False", "if", "cd_conf", ":", "if", "cd_conf", ".", "has_repos", ":", "has_valid_release", "=", "args", ".", "release", "in", "cd_conf", ".", "get_repos", "(", ")", "has_default_repo", "=", "cd_conf", ".", "get_default_repo", "(", ")", "if", "has_valid_release", "or", "has_default_repo", ":", "return", "True", "return", "False" ]
A boolean to determine the logic needed to proceed with a custom repo installation instead of cramming everything nect to the logic operator.
[ "A", "boolean", "to", "determine", "the", "logic", "needed", "to", "proceed", "with", "a", "custom", "repo", "installation", "instead", "of", "cramming", "everything", "nect", "to", "the", "logic", "operator", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/install.py#L215-L229
233,445
ceph/ceph-deploy
ceph_deploy/install.py
make_uninstall
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, )
python
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, )
[ "def", "make_uninstall", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'host'", ",", "metavar", "=", "'HOST'", ",", "nargs", "=", "'+'", ",", "help", "=", "'hosts to uninstall Ceph from'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "uninstall", ",", ")" ]
Remove Ceph packages from remote hosts.
[ "Remove", "Ceph", "packages", "from", "remote", "hosts", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/install.py#L626-L638
233,446
ceph/ceph-deploy
ceph_deploy/install.py
make_purge
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, )
python
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, )
[ "def", "make_purge", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'host'", ",", "metavar", "=", "'HOST'", ",", "nargs", "=", "'+'", ",", "help", "=", "'hosts to purge Ceph from'", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "purge", ",", ")" ]
Remove Ceph packages from remote hosts and purge all data.
[ "Remove", "Ceph", "packages", "from", "remote", "hosts", "and", "purge", "all", "data", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/install.py#L642-L654
233,447
ceph/ceph-deploy
ceph_deploy/rgw.py
make
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='HOST[:NAME]', nargs='+', type=colon_separated, help='host (and optionally the daemon name) to deploy on. \ NAME is automatically prefixed with \'rgw.\'', ) parser.set_defaults( func=rgw, )
python
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='HOST[:NAME]', nargs='+', type=colon_separated, help='host (and optionally the daemon name) to deploy on. \ NAME is automatically prefixed with \'rgw.\'', ) parser.set_defaults( func=rgw, )
[ "def", "make", "(", "parser", ")", ":", "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", "=", "'HOST[:NAME]'", ",", "nargs", "=", "'+'", ",", "type", "=", "colon_separated", ",", "help", "=", "'host (and optionally the daemon name) to deploy on. \\\n NAME is automatically prefixed with \\'rgw.\\''", ",", ")", "parser", ".", "set_defaults", "(", "func", "=", "rgw", ",", ")" ]
Ceph RGW daemon management
[ "Ceph", "RGW", "daemon", "management" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/rgw.py#L213-L233
233,448
ceph/ceph-deploy
ceph_deploy/util/ssh.py
can_connect_passwordless
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. """ # Ensure we are not doing this for local hosts if not remoto.backends.needs_ssh(hostname): return True logger = logging.getLogger(hostname) with get_local_connection(logger) as conn: # Check to see if we can login, disabling password prompts command = ['ssh', '-CT', '-o', 'BatchMode=yes', hostname, 'true'] out, err, retval = remoto.process.check(conn, command, stop_on_error=False) permission_denied_error = 'Permission denied ' host_key_verify_error = 'Host key verification failed.' has_key_error = False for line in err: if permission_denied_error in line or host_key_verify_error in line: has_key_error = True if retval == 255 and has_key_error: return False return True
python
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. """ # Ensure we are not doing this for local hosts if not remoto.backends.needs_ssh(hostname): return True logger = logging.getLogger(hostname) with get_local_connection(logger) as conn: # Check to see if we can login, disabling password prompts command = ['ssh', '-CT', '-o', 'BatchMode=yes', hostname, 'true'] out, err, retval = remoto.process.check(conn, command, stop_on_error=False) permission_denied_error = 'Permission denied ' host_key_verify_error = 'Host key verification failed.' has_key_error = False for line in err: if permission_denied_error in line or host_key_verify_error in line: has_key_error = True if retval == 255 and has_key_error: return False return True
[ "def", "can_connect_passwordless", "(", "hostname", ")", ":", "# Ensure we are not doing this for local hosts", "if", "not", "remoto", ".", "backends", ".", "needs_ssh", "(", "hostname", ")", ":", "return", "True", "logger", "=", "logging", ".", "getLogger", "(", "hostname", ")", "with", "get_local_connection", "(", "logger", ")", "as", "conn", ":", "# Check to see if we can login, disabling password prompts", "command", "=", "[", "'ssh'", ",", "'-CT'", ",", "'-o'", ",", "'BatchMode=yes'", ",", "hostname", ",", "'true'", "]", "out", ",", "err", ",", "retval", "=", "remoto", ".", "process", ".", "check", "(", "conn", ",", "command", ",", "stop_on_error", "=", "False", ")", "permission_denied_error", "=", "'Permission denied '", "host_key_verify_error", "=", "'Host key verification failed.'", "has_key_error", "=", "False", "for", "line", "in", "err", ":", "if", "permission_denied_error", "in", "line", "or", "host_key_verify_error", "in", "line", ":", "has_key_error", "=", "True", "if", "retval", "==", "255", "and", "has_key_error", ":", "return", "False", "return", "True" ]
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.
[ "Ensure", "that", "current", "host", "can", "SSH", "remotely", "to", "the", "remote", "host", "using", "the", "BatchMode", "option", "to", "prevent", "a", "password", "prompt", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/ssh.py#L6-L32
233,449
ceph/ceph-deploy
ceph_deploy/util/net.py
ip_in_subnet
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 - int(bits))) & 0xffffffff return (ipaddr & mask) == (netaddr & mask)
python
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 - int(bits))) & 0xffffffff return (ipaddr & mask) == (netaddr & mask)
[ "def", "ip_in_subnet", "(", "ip", ",", "subnet", ")", ":", "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", "-", "int", "(", "bits", ")", ")", ")", "&", "0xffffffff", "return", "(", "ipaddr", "&", "mask", ")", "==", "(", "netaddr", "&", "mask", ")" ]
Does IP exists in a given subnet utility. Returns a boolean
[ "Does", "IP", "exists", "in", "a", "given", "subnet", "utility", ".", "Returns", "a", "boolean" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/net.py#L52-L58
233,450
ceph/ceph-deploy
ceph_deploy/util/net.py
in_subnet
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
python
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
[ "def", "in_subnet", "(", "cidr", ",", "addrs", "=", "None", ")", ":", "for", "address", "in", "addrs", ":", "if", "ip_in_subnet", "(", "address", ",", "cidr", ")", ":", "return", "True", "return", "False" ]
Returns True if host is within specified subnet, otherwise False
[ "Returns", "True", "if", "host", "is", "within", "specified", "subnet", "otherwise", "False" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/net.py#L61-L68
233,451
ceph/ceph-deploy
ceph_deploy/util/net.py
get_chacra_repo
def get_chacra_repo(shaman_url): """ From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string. """ shaman_response = get_request(shaman_url) chacra_url = shaman_response.geturl() chacra_response = get_request(chacra_url) return chacra_response.read()
python
def get_chacra_repo(shaman_url): """ From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string. """ shaman_response = get_request(shaman_url) chacra_url = shaman_response.geturl() chacra_response = get_request(chacra_url) return chacra_response.read()
[ "def", "get_chacra_repo", "(", "shaman_url", ")", ":", "shaman_response", "=", "get_request", "(", "shaman_url", ")", "chacra_url", "=", "shaman_response", ".", "geturl", "(", ")", "chacra_response", "=", "get_request", "(", "chacra_url", ")", "return", "chacra_response", ".", "read", "(", ")" ]
From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string.
[ "From", "a", "Shaman", "URL", "get", "the", "chacra", "url", "for", "a", "repository", "read", "the", "contents", "that", "point", "to", "the", "repo", "and", "return", "it", "as", "a", "string", "." ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/util/net.py#L390-L399
233,452
ceph/ceph-deploy
ceph_deploy/hosts/common.py
map_components
def map_components(notsplit_packages, components): """ Returns a list of packages to install based on component names This is done by checking if a component is in notsplit_packages, if it is, we know we need to install 'ceph' instead of the raw component name. Essentially, this component hasn't been 'split' from the master 'ceph' package yet. """ packages = set() for c in components: if c in notsplit_packages: packages.add('ceph') else: packages.add(c) return list(packages)
python
def map_components(notsplit_packages, components): """ Returns a list of packages to install based on component names This is done by checking if a component is in notsplit_packages, if it is, we know we need to install 'ceph' instead of the raw component name. Essentially, this component hasn't been 'split' from the master 'ceph' package yet. """ packages = set() for c in components: if c in notsplit_packages: packages.add('ceph') else: packages.add(c) return list(packages)
[ "def", "map_components", "(", "notsplit_packages", ",", "components", ")", ":", "packages", "=", "set", "(", ")", "for", "c", "in", "components", ":", "if", "c", "in", "notsplit_packages", ":", "packages", ".", "add", "(", "'ceph'", ")", "else", ":", "packages", ".", "add", "(", "c", ")", "return", "list", "(", "packages", ")" ]
Returns a list of packages to install based on component names This is done by checking if a component is in notsplit_packages, if it is, we know we need to install 'ceph' instead of the raw component name. Essentially, this component hasn't been 'split' from the master 'ceph' package yet.
[ "Returns", "a", "list", "of", "packages", "to", "install", "based", "on", "component", "names" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/common.py#L165-L182
233,453
ceph/ceph-deploy
ceph_deploy/hosts/common.py
start_mon_service
def start_mon_service(distro, cluster, hostname): """ start mon service depending on distro init """ if distro.init == 'sysvinit': service = distro.conn.remote_module.which_service() remoto.process.run( distro.conn, [ service, 'ceph', '-c', '/etc/ceph/{cluster}.conf'.format(cluster=cluster), 'start', 'mon.{hostname}'.format(hostname=hostname) ], timeout=7, ) system.enable_service(distro.conn) elif distro.init == 'upstart': remoto.process.run( distro.conn, [ 'initctl', 'emit', 'ceph-mon', 'cluster={cluster}'.format(cluster=cluster), 'id={hostname}'.format(hostname=hostname), ], timeout=7, ) elif distro.init == 'systemd': # enable ceph target for this host (in case it isn't already enabled) remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph.target' ], timeout=7, ) # enable and start this mon instance remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, ) remoto.process.run( distro.conn, [ 'systemctl', 'start', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, )
python
def start_mon_service(distro, cluster, hostname): """ start mon service depending on distro init """ if distro.init == 'sysvinit': service = distro.conn.remote_module.which_service() remoto.process.run( distro.conn, [ service, 'ceph', '-c', '/etc/ceph/{cluster}.conf'.format(cluster=cluster), 'start', 'mon.{hostname}'.format(hostname=hostname) ], timeout=7, ) system.enable_service(distro.conn) elif distro.init == 'upstart': remoto.process.run( distro.conn, [ 'initctl', 'emit', 'ceph-mon', 'cluster={cluster}'.format(cluster=cluster), 'id={hostname}'.format(hostname=hostname), ], timeout=7, ) elif distro.init == 'systemd': # enable ceph target for this host (in case it isn't already enabled) remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph.target' ], timeout=7, ) # enable and start this mon instance remoto.process.run( distro.conn, [ 'systemctl', 'enable', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, ) remoto.process.run( distro.conn, [ 'systemctl', 'start', 'ceph-mon@{hostname}'.format(hostname=hostname), ], timeout=7, )
[ "def", "start_mon_service", "(", "distro", ",", "cluster", ",", "hostname", ")", ":", "if", "distro", ".", "init", "==", "'sysvinit'", ":", "service", "=", "distro", ".", "conn", ".", "remote_module", ".", "which_service", "(", ")", "remoto", ".", "process", ".", "run", "(", "distro", ".", "conn", ",", "[", "service", ",", "'ceph'", ",", "'-c'", ",", "'/etc/ceph/{cluster}.conf'", ".", "format", "(", "cluster", "=", "cluster", ")", ",", "'start'", ",", "'mon.{hostname}'", ".", "format", "(", "hostname", "=", "hostname", ")", "]", ",", "timeout", "=", "7", ",", ")", "system", ".", "enable_service", "(", "distro", ".", "conn", ")", "elif", "distro", ".", "init", "==", "'upstart'", ":", "remoto", ".", "process", ".", "run", "(", "distro", ".", "conn", ",", "[", "'initctl'", ",", "'emit'", ",", "'ceph-mon'", ",", "'cluster={cluster}'", ".", "format", "(", "cluster", "=", "cluster", ")", ",", "'id={hostname}'", ".", "format", "(", "hostname", "=", "hostname", ")", ",", "]", ",", "timeout", "=", "7", ",", ")", "elif", "distro", ".", "init", "==", "'systemd'", ":", "# enable ceph target for this host (in case it isn't already enabled)", "remoto", ".", "process", ".", "run", "(", "distro", ".", "conn", ",", "[", "'systemctl'", ",", "'enable'", ",", "'ceph.target'", "]", ",", "timeout", "=", "7", ",", ")", "# enable and start this mon instance", "remoto", ".", "process", ".", "run", "(", "distro", ".", "conn", ",", "[", "'systemctl'", ",", "'enable'", ",", "'ceph-mon@{hostname}'", ".", "format", "(", "hostname", "=", "hostname", ")", ",", "]", ",", "timeout", "=", "7", ",", ")", "remoto", ".", "process", ".", "run", "(", "distro", ".", "conn", ",", "[", "'systemctl'", ",", "'start'", ",", "'ceph-mon@{hostname}'", ".", "format", "(", "hostname", "=", "hostname", ")", ",", "]", ",", "timeout", "=", "7", ",", ")" ]
start mon service depending on distro init
[ "start", "mon", "service", "depending", "on", "distro", "init" ]
86943fcc454cd4c99a86e3493e9e93a59c661fef
https://github.com/ceph/ceph-deploy/blob/86943fcc454cd4c99a86e3493e9e93a59c661fef/ceph_deploy/hosts/common.py#L185-L248
233,454
andrea-cuttone/geoplotlib
geoplotlib/layers.py
VoronoiLayer.__voronoi_finite_polygons_2d
def __voronoi_finite_polygons_2d(vor, radius=None): """ Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end. """ if vor.points.shape[1] != 2: raise ValueError("Requires 2D input") new_regions = [] new_vertices = vor.vertices.tolist() center = vor.points.mean(axis=0) if radius is None: radius = vor.points.ptp().max() # Construct a map containing all ridges for a given point all_ridges = {} for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices): all_ridges.setdefault(p1, []).append((p2, v1, v2)) all_ridges.setdefault(p2, []).append((p1, v1, v2)) # Reconstruct infinite regions for p1, region in enumerate(vor.point_region): vertices = vor.regions[region] if all(v >= 0 for v in vertices): # finite region new_regions.append(vertices) continue # reconstruct a non-finite region if p1 not in all_ridges: continue ridges = all_ridges[p1] new_region = [v for v in vertices if v >= 0] for p2, v1, v2 in ridges: if v2 < 0: v1, v2 = v2, v1 if v1 >= 0: # finite ridge: already in the region continue # Compute the missing endpoint of an infinite ridge t = vor.points[p2] - vor.points[p1] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[[p1, p2]].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[v2] + direction * radius new_region.append(len(new_vertices)) new_vertices.append(far_point.tolist()) # sort region counterclockwise vs = np.asarray([new_vertices[v] for v in new_region]) c = vs.mean(axis=0) angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0]) new_region = np.array(new_region)[np.argsort(angles)] # finish new_regions.append(new_region.tolist()) return new_regions, np.asarray(new_vertices)
python
def __voronoi_finite_polygons_2d(vor, radius=None): """ Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end. """ if vor.points.shape[1] != 2: raise ValueError("Requires 2D input") new_regions = [] new_vertices = vor.vertices.tolist() center = vor.points.mean(axis=0) if radius is None: radius = vor.points.ptp().max() # Construct a map containing all ridges for a given point all_ridges = {} for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices): all_ridges.setdefault(p1, []).append((p2, v1, v2)) all_ridges.setdefault(p2, []).append((p1, v1, v2)) # Reconstruct infinite regions for p1, region in enumerate(vor.point_region): vertices = vor.regions[region] if all(v >= 0 for v in vertices): # finite region new_regions.append(vertices) continue # reconstruct a non-finite region if p1 not in all_ridges: continue ridges = all_ridges[p1] new_region = [v for v in vertices if v >= 0] for p2, v1, v2 in ridges: if v2 < 0: v1, v2 = v2, v1 if v1 >= 0: # finite ridge: already in the region continue # Compute the missing endpoint of an infinite ridge t = vor.points[p2] - vor.points[p1] # tangent t /= np.linalg.norm(t) n = np.array([-t[1], t[0]]) # normal midpoint = vor.points[[p1, p2]].mean(axis=0) direction = np.sign(np.dot(midpoint - center, n)) * n far_point = vor.vertices[v2] + direction * radius new_region.append(len(new_vertices)) new_vertices.append(far_point.tolist()) # sort region counterclockwise vs = np.asarray([new_vertices[v] for v in new_region]) c = vs.mean(axis=0) angles = np.arctan2(vs[:,1] - c[1], vs[:,0] - c[0]) new_region = np.array(new_region)[np.argsort(angles)] # finish new_regions.append(new_region.tolist()) return new_regions, np.asarray(new_vertices)
[ "def", "__voronoi_finite_polygons_2d", "(", "vor", ",", "radius", "=", "None", ")", ":", "if", "vor", ".", "points", ".", "shape", "[", "1", "]", "!=", "2", ":", "raise", "ValueError", "(", "\"Requires 2D input\"", ")", "new_regions", "=", "[", "]", "new_vertices", "=", "vor", ".", "vertices", ".", "tolist", "(", ")", "center", "=", "vor", ".", "points", ".", "mean", "(", "axis", "=", "0", ")", "if", "radius", "is", "None", ":", "radius", "=", "vor", ".", "points", ".", "ptp", "(", ")", ".", "max", "(", ")", "# Construct a map containing all ridges for a given point", "all_ridges", "=", "{", "}", "for", "(", "p1", ",", "p2", ")", ",", "(", "v1", ",", "v2", ")", "in", "zip", "(", "vor", ".", "ridge_points", ",", "vor", ".", "ridge_vertices", ")", ":", "all_ridges", ".", "setdefault", "(", "p1", ",", "[", "]", ")", ".", "append", "(", "(", "p2", ",", "v1", ",", "v2", ")", ")", "all_ridges", ".", "setdefault", "(", "p2", ",", "[", "]", ")", ".", "append", "(", "(", "p1", ",", "v1", ",", "v2", ")", ")", "# Reconstruct infinite regions", "for", "p1", ",", "region", "in", "enumerate", "(", "vor", ".", "point_region", ")", ":", "vertices", "=", "vor", ".", "regions", "[", "region", "]", "if", "all", "(", "v", ">=", "0", "for", "v", "in", "vertices", ")", ":", "# finite region", "new_regions", ".", "append", "(", "vertices", ")", "continue", "# reconstruct a non-finite region", "if", "p1", "not", "in", "all_ridges", ":", "continue", "ridges", "=", "all_ridges", "[", "p1", "]", "new_region", "=", "[", "v", "for", "v", "in", "vertices", "if", "v", ">=", "0", "]", "for", "p2", ",", "v1", ",", "v2", "in", "ridges", ":", "if", "v2", "<", "0", ":", "v1", ",", "v2", "=", "v2", ",", "v1", "if", "v1", ">=", "0", ":", "# finite ridge: already in the region", "continue", "# Compute the missing endpoint of an infinite ridge", "t", "=", "vor", ".", "points", "[", "p2", "]", "-", "vor", ".", "points", "[", "p1", "]", "# tangent", "t", "/=", "np", ".", "linalg", ".", "norm", "(", "t", ")", "n", "=", "np", ".", "array", "(", "[", "-", "t", "[", "1", "]", ",", "t", "[", "0", "]", "]", ")", "# normal", "midpoint", "=", "vor", ".", "points", "[", "[", "p1", ",", "p2", "]", "]", ".", "mean", "(", "axis", "=", "0", ")", "direction", "=", "np", ".", "sign", "(", "np", ".", "dot", "(", "midpoint", "-", "center", ",", "n", ")", ")", "*", "n", "far_point", "=", "vor", ".", "vertices", "[", "v2", "]", "+", "direction", "*", "radius", "new_region", ".", "append", "(", "len", "(", "new_vertices", ")", ")", "new_vertices", ".", "append", "(", "far_point", ".", "tolist", "(", ")", ")", "# sort region counterclockwise", "vs", "=", "np", ".", "asarray", "(", "[", "new_vertices", "[", "v", "]", "for", "v", "in", "new_region", "]", ")", "c", "=", "vs", ".", "mean", "(", "axis", "=", "0", ")", "angles", "=", "np", ".", "arctan2", "(", "vs", "[", ":", ",", "1", "]", "-", "c", "[", "1", "]", ",", "vs", "[", ":", ",", "0", "]", "-", "c", "[", "0", "]", ")", "new_region", "=", "np", ".", "array", "(", "new_region", ")", "[", "np", ".", "argsort", "(", "angles", ")", "]", "# finish", "new_regions", ".", "append", "(", "new_region", ".", "tolist", "(", ")", ")", "return", "new_regions", ",", "np", ".", "asarray", "(", "new_vertices", ")" ]
Reconstruct infinite voronoi regions in a 2D diagram to finite regions. Parameters ---------- vor : Voronoi Input diagram radius : float, optional Distance to 'points at infinity'. Returns ------- regions : list of tuples Indices of vertices in each revised Voronoi regions. vertices : list of tuples Coordinates for revised Voronoi vertices. Same as coordinates of input vertices, with 'points at infinity' appended to the end.
[ "Reconstruct", "infinite", "voronoi", "regions", "in", "a", "2D", "diagram", "to", "finite", "regions", "." ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/layers.py#L505-L589
233,455
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
inline
def inline(width=900): """display the map inline in ipython :param width: image width for the browser """ from IPython.display import Image, HTML, display, clear_output import random import string import urllib import os while True: fname = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32)) if not os.path.isfile(fname + '.png'): break savefig(fname) if os.path.isfile(fname + '.png'): with open(fname + '.png', 'rb') as fin: encoded = base64.b64encode(fin.read()) b64 = urllib.parse.quote(encoded) image_html = "<img style='width: %dpx; margin: 0px; float: left; border: 1px solid black;' src='data:image/png;base64,%s' />" % (width, b64) display(HTML(image_html)) os.remove(fname + '.png')
python
def inline(width=900): """display the map inline in ipython :param width: image width for the browser """ from IPython.display import Image, HTML, display, clear_output import random import string import urllib import os while True: fname = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32)) if not os.path.isfile(fname + '.png'): break savefig(fname) if os.path.isfile(fname + '.png'): with open(fname + '.png', 'rb') as fin: encoded = base64.b64encode(fin.read()) b64 = urllib.parse.quote(encoded) image_html = "<img style='width: %dpx; margin: 0px; float: left; border: 1px solid black;' src='data:image/png;base64,%s' />" % (width, b64) display(HTML(image_html)) os.remove(fname + '.png')
[ "def", "inline", "(", "width", "=", "900", ")", ":", "from", "IPython", ".", "display", "import", "Image", ",", "HTML", ",", "display", ",", "clear_output", "import", "random", "import", "string", "import", "urllib", "import", "os", "while", "True", ":", "fname", "=", "''", ".", "join", "(", "random", ".", "choice", "(", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", "for", "_", "in", "range", "(", "32", ")", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "fname", "+", "'.png'", ")", ":", "break", "savefig", "(", "fname", ")", "if", "os", ".", "path", ".", "isfile", "(", "fname", "+", "'.png'", ")", ":", "with", "open", "(", "fname", "+", "'.png'", ",", "'rb'", ")", "as", "fin", ":", "encoded", "=", "base64", ".", "b64encode", "(", "fin", ".", "read", "(", ")", ")", "b64", "=", "urllib", ".", "parse", ".", "quote", "(", "encoded", ")", "image_html", "=", "\"<img style='width: %dpx; margin: 0px; float: left; border: 1px solid black;' src='data:image/png;base64,%s' />\"", "%", "(", "width", ",", "b64", ")", "display", "(", "HTML", "(", "image_html", ")", ")", "os", ".", "remove", "(", "fname", "+", "'.png'", ")" ]
display the map inline in ipython :param width: image width for the browser
[ "display", "the", "map", "inline", "in", "ipython" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L52-L78
233,456
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
dot
def dot(data, color=None, point_size=2, f_tooltip=None): """Create a dot density map :param data: data access object :param color: color :param point_size: point size :param f_tooltip: function to return a tooltip string for a point """ from geoplotlib.layers import DotDensityLayer _global_config.layers.append(DotDensityLayer(data, color=color, point_size=point_size, f_tooltip=f_tooltip))
python
def dot(data, color=None, point_size=2, f_tooltip=None): """Create a dot density map :param data: data access object :param color: color :param point_size: point size :param f_tooltip: function to return a tooltip string for a point """ from geoplotlib.layers import DotDensityLayer _global_config.layers.append(DotDensityLayer(data, color=color, point_size=point_size, f_tooltip=f_tooltip))
[ "def", "dot", "(", "data", ",", "color", "=", "None", ",", "point_size", "=", "2", ",", "f_tooltip", "=", "None", ")", ":", "from", "geoplotlib", ".", "layers", "import", "DotDensityLayer", "_global_config", ".", "layers", ".", "append", "(", "DotDensityLayer", "(", "data", ",", "color", "=", "color", ",", "point_size", "=", "point_size", ",", "f_tooltip", "=", "f_tooltip", ")", ")" ]
Create a dot density map :param data: data access object :param color: color :param point_size: point size :param f_tooltip: function to return a tooltip string for a point
[ "Create", "a", "dot", "density", "map" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L81-L90
233,457
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
hist
def hist(data, cmap='hot', alpha=220, colorscale='sqrt', binsize=16, show_tooltip=False, scalemin=0, scalemax=None, f_group=None, show_colorbar=True): """Create a 2D histogram :param data: data access object :param cmap: colormap name :param alpha: color alpha :param colorscale: scaling [lin, log, sqrt] :param binsize: size of the hist bins :param show_tooltip: if True, will show the value of bins on mouseover :param scalemin: min value for displaying a bin :param scalemax: max value for a bin :param f_group: function to apply to samples in the same bin. Default is to count :param show_colorbar: show colorbar """ from geoplotlib.layers import HistogramLayer _global_config.layers.append(HistogramLayer(data, cmap=cmap, alpha=alpha, colorscale=colorscale, binsize=binsize, show_tooltip=show_tooltip, scalemin=scalemin, scalemax=scalemax, f_group=f_group, show_colorbar=show_colorbar))
python
def hist(data, cmap='hot', alpha=220, colorscale='sqrt', binsize=16, show_tooltip=False, scalemin=0, scalemax=None, f_group=None, show_colorbar=True): """Create a 2D histogram :param data: data access object :param cmap: colormap name :param alpha: color alpha :param colorscale: scaling [lin, log, sqrt] :param binsize: size of the hist bins :param show_tooltip: if True, will show the value of bins on mouseover :param scalemin: min value for displaying a bin :param scalemax: max value for a bin :param f_group: function to apply to samples in the same bin. Default is to count :param show_colorbar: show colorbar """ from geoplotlib.layers import HistogramLayer _global_config.layers.append(HistogramLayer(data, cmap=cmap, alpha=alpha, colorscale=colorscale, binsize=binsize, show_tooltip=show_tooltip, scalemin=scalemin, scalemax=scalemax, f_group=f_group, show_colorbar=show_colorbar))
[ "def", "hist", "(", "data", ",", "cmap", "=", "'hot'", ",", "alpha", "=", "220", ",", "colorscale", "=", "'sqrt'", ",", "binsize", "=", "16", ",", "show_tooltip", "=", "False", ",", "scalemin", "=", "0", ",", "scalemax", "=", "None", ",", "f_group", "=", "None", ",", "show_colorbar", "=", "True", ")", ":", "from", "geoplotlib", ".", "layers", "import", "HistogramLayer", "_global_config", ".", "layers", ".", "append", "(", "HistogramLayer", "(", "data", ",", "cmap", "=", "cmap", ",", "alpha", "=", "alpha", ",", "colorscale", "=", "colorscale", ",", "binsize", "=", "binsize", ",", "show_tooltip", "=", "show_tooltip", ",", "scalemin", "=", "scalemin", ",", "scalemax", "=", "scalemax", ",", "f_group", "=", "f_group", ",", "show_colorbar", "=", "show_colorbar", ")", ")" ]
Create a 2D histogram :param data: data access object :param cmap: colormap name :param alpha: color alpha :param colorscale: scaling [lin, log, sqrt] :param binsize: size of the hist bins :param show_tooltip: if True, will show the value of bins on mouseover :param scalemin: min value for displaying a bin :param scalemax: max value for a bin :param f_group: function to apply to samples in the same bin. Default is to count :param show_colorbar: show colorbar
[ "Create", "a", "2D", "histogram" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L101-L119
233,458
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
shapefiles
def shapefiles(fname, f_tooltip=None, color=None, linewidth=3, shape_type='full'): """ Load and draws shapefiles :param fname: full path to the shapefile :param f_tooltip: function to generate a tooltip on mouseover :param color: color :param linewidth: line width :param shape_type: either full or bbox """ from geoplotlib.layers import ShapefileLayer _global_config.layers.append(ShapefileLayer(fname, f_tooltip, color, linewidth, shape_type))
python
def shapefiles(fname, f_tooltip=None, color=None, linewidth=3, shape_type='full'): """ Load and draws shapefiles :param fname: full path to the shapefile :param f_tooltip: function to generate a tooltip on mouseover :param color: color :param linewidth: line width :param shape_type: either full or bbox """ from geoplotlib.layers import ShapefileLayer _global_config.layers.append(ShapefileLayer(fname, f_tooltip, color, linewidth, shape_type))
[ "def", "shapefiles", "(", "fname", ",", "f_tooltip", "=", "None", ",", "color", "=", "None", ",", "linewidth", "=", "3", ",", "shape_type", "=", "'full'", ")", ":", "from", "geoplotlib", ".", "layers", "import", "ShapefileLayer", "_global_config", ".", "layers", ".", "append", "(", "ShapefileLayer", "(", "fname", ",", "f_tooltip", ",", "color", ",", "linewidth", ",", "shape_type", ")", ")" ]
Load and draws shapefiles :param fname: full path to the shapefile :param f_tooltip: function to generate a tooltip on mouseover :param color: color :param linewidth: line width :param shape_type: either full or bbox
[ "Load", "and", "draws", "shapefiles" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L138-L149
233,459
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
voronoi
def voronoi(data, line_color=None, line_width=2, f_tooltip=None, cmap=None, max_area=1e4, alpha=220): """ Draw the voronoi tesselation of the points :param data: data access object :param line_color: line color :param line_width: line width :param f_tooltip: function to generate a tooltip on mouseover :param cmap: color map :param max_area: scaling constant to determine the color of the voronoi areas :param alpha: color alpha """ from geoplotlib.layers import VoronoiLayer _global_config.layers.append(VoronoiLayer(data, line_color, line_width, f_tooltip, cmap, max_area, alpha))
python
def voronoi(data, line_color=None, line_width=2, f_tooltip=None, cmap=None, max_area=1e4, alpha=220): """ Draw the voronoi tesselation of the points :param data: data access object :param line_color: line color :param line_width: line width :param f_tooltip: function to generate a tooltip on mouseover :param cmap: color map :param max_area: scaling constant to determine the color of the voronoi areas :param alpha: color alpha """ from geoplotlib.layers import VoronoiLayer _global_config.layers.append(VoronoiLayer(data, line_color, line_width, f_tooltip, cmap, max_area, alpha))
[ "def", "voronoi", "(", "data", ",", "line_color", "=", "None", ",", "line_width", "=", "2", ",", "f_tooltip", "=", "None", ",", "cmap", "=", "None", ",", "max_area", "=", "1e4", ",", "alpha", "=", "220", ")", ":", "from", "geoplotlib", ".", "layers", "import", "VoronoiLayer", "_global_config", ".", "layers", ".", "append", "(", "VoronoiLayer", "(", "data", ",", "line_color", ",", "line_width", ",", "f_tooltip", ",", "cmap", ",", "max_area", ",", "alpha", ")", ")" ]
Draw the voronoi tesselation of the points :param data: data access object :param line_color: line color :param line_width: line width :param f_tooltip: function to generate a tooltip on mouseover :param cmap: color map :param max_area: scaling constant to determine the color of the voronoi areas :param alpha: color alpha
[ "Draw", "the", "voronoi", "tesselation", "of", "the", "points" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L152-L165
233,460
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
delaunay
def delaunay(data, line_color=None, line_width=2, cmap=None, max_lenght=100): """ Draw a delaunay triangulation of the points :param data: data access object :param line_color: line color :param line_width: line width :param cmap: color map :param max_lenght: scaling constant for coloring the edges """ from geoplotlib.layers import DelaunayLayer _global_config.layers.append(DelaunayLayer(data, line_color, line_width, cmap, max_lenght))
python
def delaunay(data, line_color=None, line_width=2, cmap=None, max_lenght=100): """ Draw a delaunay triangulation of the points :param data: data access object :param line_color: line color :param line_width: line width :param cmap: color map :param max_lenght: scaling constant for coloring the edges """ from geoplotlib.layers import DelaunayLayer _global_config.layers.append(DelaunayLayer(data, line_color, line_width, cmap, max_lenght))
[ "def", "delaunay", "(", "data", ",", "line_color", "=", "None", ",", "line_width", "=", "2", ",", "cmap", "=", "None", ",", "max_lenght", "=", "100", ")", ":", "from", "geoplotlib", ".", "layers", "import", "DelaunayLayer", "_global_config", ".", "layers", ".", "append", "(", "DelaunayLayer", "(", "data", ",", "line_color", ",", "line_width", ",", "cmap", ",", "max_lenght", ")", ")" ]
Draw a delaunay triangulation of the points :param data: data access object :param line_color: line color :param line_width: line width :param cmap: color map :param max_lenght: scaling constant for coloring the edges
[ "Draw", "a", "delaunay", "triangulation", "of", "the", "points" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L168-L179
233,461
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
convexhull
def convexhull(data, col, fill=True, point_size=4): """ Convex hull for a set of points :param data: points :param col: color :param fill: whether to fill the convexhull polygon or not :param point_size: size of the points on the convexhull. Points are not rendered if None """ from geoplotlib.layers import ConvexHullLayer _global_config.layers.append(ConvexHullLayer(data, col, fill, point_size))
python
def convexhull(data, col, fill=True, point_size=4): """ Convex hull for a set of points :param data: points :param col: color :param fill: whether to fill the convexhull polygon or not :param point_size: size of the points on the convexhull. Points are not rendered if None """ from geoplotlib.layers import ConvexHullLayer _global_config.layers.append(ConvexHullLayer(data, col, fill, point_size))
[ "def", "convexhull", "(", "data", ",", "col", ",", "fill", "=", "True", ",", "point_size", "=", "4", ")", ":", "from", "geoplotlib", ".", "layers", "import", "ConvexHullLayer", "_global_config", ".", "layers", ".", "append", "(", "ConvexHullLayer", "(", "data", ",", "col", ",", "fill", ",", "point_size", ")", ")" ]
Convex hull for a set of points :param data: points :param col: color :param fill: whether to fill the convexhull polygon or not :param point_size: size of the points on the convexhull. Points are not rendered if None
[ "Convex", "hull", "for", "a", "set", "of", "points" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L182-L192
233,462
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
kde
def kde(data, bw, cmap='hot', method='hist', scaling='sqrt', alpha=220, cut_below=None, clip_above=None, binsize=1, cmap_levels=10, show_colorbar=False): """ Kernel density estimation visualization :param data: data access object :param bw: kernel bandwidth (in screen coordinates) :param cmap: colormap :param method: if kde use KDEMultivariate from statsmodel, which provides a more accurate but much slower estimation. If hist, estimates density applying gaussian smoothing on a 2D histogram, which is much faster but less accurate :param scaling: colorscale, lin log or sqrt :param alpha: color alpha :param cut_below: densities below cut_below are not drawn :param clip_above: defines the max value for the colorscale :param binsize: size of the bins for hist estimator :param cmap_levels: discretize colors into cmap_levels levels :param show_colorbar: show colorbar """ from geoplotlib.layers import KDELayer _global_config.layers.append(KDELayer(data, bw, cmap, method, scaling, alpha, cut_below, clip_above, binsize, cmap_levels, show_colorbar))
python
def kde(data, bw, cmap='hot', method='hist', scaling='sqrt', alpha=220, cut_below=None, clip_above=None, binsize=1, cmap_levels=10, show_colorbar=False): """ Kernel density estimation visualization :param data: data access object :param bw: kernel bandwidth (in screen coordinates) :param cmap: colormap :param method: if kde use KDEMultivariate from statsmodel, which provides a more accurate but much slower estimation. If hist, estimates density applying gaussian smoothing on a 2D histogram, which is much faster but less accurate :param scaling: colorscale, lin log or sqrt :param alpha: color alpha :param cut_below: densities below cut_below are not drawn :param clip_above: defines the max value for the colorscale :param binsize: size of the bins for hist estimator :param cmap_levels: discretize colors into cmap_levels levels :param show_colorbar: show colorbar """ from geoplotlib.layers import KDELayer _global_config.layers.append(KDELayer(data, bw, cmap, method, scaling, alpha, cut_below, clip_above, binsize, cmap_levels, show_colorbar))
[ "def", "kde", "(", "data", ",", "bw", ",", "cmap", "=", "'hot'", ",", "method", "=", "'hist'", ",", "scaling", "=", "'sqrt'", ",", "alpha", "=", "220", ",", "cut_below", "=", "None", ",", "clip_above", "=", "None", ",", "binsize", "=", "1", ",", "cmap_levels", "=", "10", ",", "show_colorbar", "=", "False", ")", ":", "from", "geoplotlib", ".", "layers", "import", "KDELayer", "_global_config", ".", "layers", ".", "append", "(", "KDELayer", "(", "data", ",", "bw", ",", "cmap", ",", "method", ",", "scaling", ",", "alpha", ",", "cut_below", ",", "clip_above", ",", "binsize", ",", "cmap_levels", ",", "show_colorbar", ")", ")" ]
Kernel density estimation visualization :param data: data access object :param bw: kernel bandwidth (in screen coordinates) :param cmap: colormap :param method: if kde use KDEMultivariate from statsmodel, which provides a more accurate but much slower estimation. If hist, estimates density applying gaussian smoothing on a 2D histogram, which is much faster but less accurate :param scaling: colorscale, lin log or sqrt :param alpha: color alpha :param cut_below: densities below cut_below are not drawn :param clip_above: defines the max value for the colorscale :param binsize: size of the bins for hist estimator :param cmap_levels: discretize colors into cmap_levels levels :param show_colorbar: show colorbar
[ "Kernel", "density", "estimation", "visualization" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L195-L215
233,463
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
labels
def labels(data, label_column, color=None, font_name=FONT_NAME, font_size=14, anchor_x='left', anchor_y='top'): """ Draw a text label for each sample :param data: data access object :param label_column: column in the data access object where the labels text is stored :param color: color :param font_name: font name :param font_size: font size :param anchor_x: anchor x :param anchor_y: anchor y """ from geoplotlib.layers import LabelsLayer _global_config.layers.append(LabelsLayer(data, label_column, color, font_name, font_size, anchor_x, anchor_y))
python
def labels(data, label_column, color=None, font_name=FONT_NAME, font_size=14, anchor_x='left', anchor_y='top'): """ Draw a text label for each sample :param data: data access object :param label_column: column in the data access object where the labels text is stored :param color: color :param font_name: font name :param font_size: font size :param anchor_x: anchor x :param anchor_y: anchor y """ from geoplotlib.layers import LabelsLayer _global_config.layers.append(LabelsLayer(data, label_column, color, font_name, font_size, anchor_x, anchor_y))
[ "def", "labels", "(", "data", ",", "label_column", ",", "color", "=", "None", ",", "font_name", "=", "FONT_NAME", ",", "font_size", "=", "14", ",", "anchor_x", "=", "'left'", ",", "anchor_y", "=", "'top'", ")", ":", "from", "geoplotlib", ".", "layers", "import", "LabelsLayer", "_global_config", ".", "layers", ".", "append", "(", "LabelsLayer", "(", "data", ",", "label_column", ",", "color", ",", "font_name", ",", "font_size", ",", "anchor_x", ",", "anchor_y", ")", ")" ]
Draw a text label for each sample :param data: data access object :param label_column: column in the data access object where the labels text is stored :param color: color :param font_name: font name :param font_size: font size :param anchor_x: anchor x :param anchor_y: anchor y
[ "Draw", "a", "text", "label", "for", "each", "sample" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L245-L260
233,464
andrea-cuttone/geoplotlib
geoplotlib/__init__.py
set_map_alpha
def set_map_alpha(alpha): """ Alpha color of the map tiles :param alpha: int between 0 and 255. 0 is completely dark, 255 is full brightness """ if alpha < 0 or alpha > 255: raise Exception('invalid alpha ' + str(alpha)) _global_config.map_alpha = alpha
python
def set_map_alpha(alpha): """ Alpha color of the map tiles :param alpha: int between 0 and 255. 0 is completely dark, 255 is full brightness """ if alpha < 0 or alpha > 255: raise Exception('invalid alpha ' + str(alpha)) _global_config.map_alpha = alpha
[ "def", "set_map_alpha", "(", "alpha", ")", ":", "if", "alpha", "<", "0", "or", "alpha", ">", "255", ":", "raise", "Exception", "(", "'invalid alpha '", "+", "str", "(", "alpha", ")", ")", "_global_config", ".", "map_alpha", "=", "alpha" ]
Alpha color of the map tiles :param alpha: int between 0 and 255. 0 is completely dark, 255 is full brightness
[ "Alpha", "color", "of", "the", "map", "tiles" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/__init__.py#L332-L340
233,465
andrea-cuttone/geoplotlib
geoplotlib/utils.py
read_csv
def read_csv(fname): """ Read a csv file into a DataAccessObject :param fname: filename """ values = defaultdict(list) with open(fname) as f: reader = csv.DictReader(f) for row in reader: for (k,v) in row.items(): values[k].append(v) npvalues = {k: np.array(values[k]) for k in values.keys()} for k in npvalues.keys(): for datatype in [np.int, np.float]: try: npvalues[k][:1].astype(datatype) npvalues[k] = npvalues[k].astype(datatype) break except: pass dao = DataAccessObject(npvalues) return dao
python
def read_csv(fname): """ Read a csv file into a DataAccessObject :param fname: filename """ values = defaultdict(list) with open(fname) as f: reader = csv.DictReader(f) for row in reader: for (k,v) in row.items(): values[k].append(v) npvalues = {k: np.array(values[k]) for k in values.keys()} for k in npvalues.keys(): for datatype in [np.int, np.float]: try: npvalues[k][:1].astype(datatype) npvalues[k] = npvalues[k].astype(datatype) break except: pass dao = DataAccessObject(npvalues) return dao
[ "def", "read_csv", "(", "fname", ")", ":", "values", "=", "defaultdict", "(", "list", ")", "with", "open", "(", "fname", ")", "as", "f", ":", "reader", "=", "csv", ".", "DictReader", "(", "f", ")", "for", "row", "in", "reader", ":", "for", "(", "k", ",", "v", ")", "in", "row", ".", "items", "(", ")", ":", "values", "[", "k", "]", ".", "append", "(", "v", ")", "npvalues", "=", "{", "k", ":", "np", ".", "array", "(", "values", "[", "k", "]", ")", "for", "k", "in", "values", ".", "keys", "(", ")", "}", "for", "k", "in", "npvalues", ".", "keys", "(", ")", ":", "for", "datatype", "in", "[", "np", ".", "int", ",", "np", ".", "float", "]", ":", "try", ":", "npvalues", "[", "k", "]", "[", ":", "1", "]", ".", "astype", "(", "datatype", ")", "npvalues", "[", "k", "]", "=", "npvalues", "[", "k", "]", ".", "astype", "(", "datatype", ")", "break", "except", ":", "pass", "dao", "=", "DataAccessObject", "(", "npvalues", ")", "return", "dao" ]
Read a csv file into a DataAccessObject :param fname: filename
[ "Read", "a", "csv", "file", "into", "a", "DataAccessObject" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/utils.py#L141-L163
233,466
andrea-cuttone/geoplotlib
geoplotlib/utils.py
DataAccessObject.head
def head(self, n): """ Return a DataAccessObject containing the first n rows :param n: number of rows :return: DataAccessObject """ return DataAccessObject({k: self.dict[k][:n] for k in self.dict})
python
def head(self, n): """ Return a DataAccessObject containing the first n rows :param n: number of rows :return: DataAccessObject """ return DataAccessObject({k: self.dict[k][:n] for k in self.dict})
[ "def", "head", "(", "self", ",", "n", ")", ":", "return", "DataAccessObject", "(", "{", "k", ":", "self", ".", "dict", "[", "k", "]", "[", ":", "n", "]", "for", "k", "in", "self", ".", "dict", "}", ")" ]
Return a DataAccessObject containing the first n rows :param n: number of rows :return: DataAccessObject
[ "Return", "a", "DataAccessObject", "containing", "the", "first", "n", "rows" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/utils.py#L104-L111
233,467
andrea-cuttone/geoplotlib
geoplotlib/utils.py
BoundingBox.from_points
def from_points(lons, lats): """ Compute the BoundingBox from a set of latitudes and longitudes :param lons: longitudes :param lats: latitudes :return: BoundingBox """ north, west = max(lats), min(lons) south, east = min(lats), max(lons) return BoundingBox(north=north, west=west, south=south, east=east)
python
def from_points(lons, lats): """ Compute the BoundingBox from a set of latitudes and longitudes :param lons: longitudes :param lats: latitudes :return: BoundingBox """ north, west = max(lats), min(lons) south, east = min(lats), max(lons) return BoundingBox(north=north, west=west, south=south, east=east)
[ "def", "from_points", "(", "lons", ",", "lats", ")", ":", "north", ",", "west", "=", "max", "(", "lats", ")", ",", "min", "(", "lons", ")", "south", ",", "east", "=", "min", "(", "lats", ")", ",", "max", "(", "lons", ")", "return", "BoundingBox", "(", "north", "=", "north", ",", "west", "=", "west", ",", "south", "=", "south", ",", "east", "=", "east", ")" ]
Compute the BoundingBox from a set of latitudes and longitudes :param lons: longitudes :param lats: latitudes :return: BoundingBox
[ "Compute", "the", "BoundingBox", "from", "a", "set", "of", "latitudes", "and", "longitudes" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/utils.py#L207-L217
233,468
andrea-cuttone/geoplotlib
geoplotlib/utils.py
BoundingBox.from_bboxes
def from_bboxes(bboxes): """ Compute a BoundingBox enclosing all specified bboxes :param bboxes: a list of BoundingBoxes :return: BoundingBox """ north = max([b.north for b in bboxes]) south = min([b.south for b in bboxes]) west = min([b.west for b in bboxes]) east = max([b.east for b in bboxes]) return BoundingBox(north=north, west=west, south=south, east=east)
python
def from_bboxes(bboxes): """ Compute a BoundingBox enclosing all specified bboxes :param bboxes: a list of BoundingBoxes :return: BoundingBox """ north = max([b.north for b in bboxes]) south = min([b.south for b in bboxes]) west = min([b.west for b in bboxes]) east = max([b.east for b in bboxes]) return BoundingBox(north=north, west=west, south=south, east=east)
[ "def", "from_bboxes", "(", "bboxes", ")", ":", "north", "=", "max", "(", "[", "b", ".", "north", "for", "b", "in", "bboxes", "]", ")", "south", "=", "min", "(", "[", "b", ".", "south", "for", "b", "in", "bboxes", "]", ")", "west", "=", "min", "(", "[", "b", ".", "west", "for", "b", "in", "bboxes", "]", ")", "east", "=", "max", "(", "[", "b", ".", "east", "for", "b", "in", "bboxes", "]", ")", "return", "BoundingBox", "(", "north", "=", "north", ",", "west", "=", "west", ",", "south", "=", "south", ",", "east", "=", "east", ")" ]
Compute a BoundingBox enclosing all specified bboxes :param bboxes: a list of BoundingBoxes :return: BoundingBox
[ "Compute", "a", "BoundingBox", "enclosing", "all", "specified", "bboxes" ]
a1c355bccec91cabd157569fad6daf53cf7687a1
https://github.com/andrea-cuttone/geoplotlib/blob/a1c355bccec91cabd157569fad6daf53cf7687a1/geoplotlib/utils.py#L221-L232
233,469
jorgenschaefer/elpy
elpy/pydocutils.py
get_pydoc_completions
def get_pydoc_completions(modulename): """Get possible completions for modulename for pydoc. Returns a list of possible values to be passed to pydoc. """ modulename = compat.ensure_not_unicode(modulename) modulename = modulename.rstrip(".") if modulename == "": return sorted(get_modules()) candidates = get_completions(modulename) if candidates: return sorted(candidates) needle = modulename if "." in needle: modulename, part = needle.rsplit(".", 1) candidates = get_completions(modulename) else: candidates = get_modules() return sorted(candidate for candidate in candidates if candidate.startswith(needle))
python
def get_pydoc_completions(modulename): """Get possible completions for modulename for pydoc. Returns a list of possible values to be passed to pydoc. """ modulename = compat.ensure_not_unicode(modulename) modulename = modulename.rstrip(".") if modulename == "": return sorted(get_modules()) candidates = get_completions(modulename) if candidates: return sorted(candidates) needle = modulename if "." in needle: modulename, part = needle.rsplit(".", 1) candidates = get_completions(modulename) else: candidates = get_modules() return sorted(candidate for candidate in candidates if candidate.startswith(needle))
[ "def", "get_pydoc_completions", "(", "modulename", ")", ":", "modulename", "=", "compat", ".", "ensure_not_unicode", "(", "modulename", ")", "modulename", "=", "modulename", ".", "rstrip", "(", "\".\"", ")", "if", "modulename", "==", "\"\"", ":", "return", "sorted", "(", "get_modules", "(", ")", ")", "candidates", "=", "get_completions", "(", "modulename", ")", "if", "candidates", ":", "return", "sorted", "(", "candidates", ")", "needle", "=", "modulename", "if", "\".\"", "in", "needle", ":", "modulename", ",", "part", "=", "needle", ".", "rsplit", "(", "\".\"", ",", "1", ")", "candidates", "=", "get_completions", "(", "modulename", ")", "else", ":", "candidates", "=", "get_modules", "(", ")", "return", "sorted", "(", "candidate", "for", "candidate", "in", "candidates", "if", "candidate", ".", "startswith", "(", "needle", ")", ")" ]
Get possible completions for modulename for pydoc. Returns a list of possible values to be passed to pydoc.
[ "Get", "possible", "completions", "for", "modulename", "for", "pydoc", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/pydocutils.py#L24-L44
233,470
jorgenschaefer/elpy
elpy/pydocutils.py
get_modules
def get_modules(modulename=None): """Return a list of modules and packages under modulename. If modulename is not given, return a list of all top level modules and packages. """ modulename = compat.ensure_not_unicode(modulename) if not modulename: try: return ([modname for (importer, modname, ispkg) in iter_modules() if not modname.startswith("_")] + list(sys.builtin_module_names)) except OSError: # Bug in Python 2.6, see #275 return list(sys.builtin_module_names) try: module = safeimport(modulename) except ErrorDuringImport: return [] if module is None: return [] if hasattr(module, "__path__"): return [modname for (importer, modname, ispkg) in iter_modules(module.__path__) if not modname.startswith("_")] return []
python
def get_modules(modulename=None): """Return a list of modules and packages under modulename. If modulename is not given, return a list of all top level modules and packages. """ modulename = compat.ensure_not_unicode(modulename) if not modulename: try: return ([modname for (importer, modname, ispkg) in iter_modules() if not modname.startswith("_")] + list(sys.builtin_module_names)) except OSError: # Bug in Python 2.6, see #275 return list(sys.builtin_module_names) try: module = safeimport(modulename) except ErrorDuringImport: return [] if module is None: return [] if hasattr(module, "__path__"): return [modname for (importer, modname, ispkg) in iter_modules(module.__path__) if not modname.startswith("_")] return []
[ "def", "get_modules", "(", "modulename", "=", "None", ")", ":", "modulename", "=", "compat", ".", "ensure_not_unicode", "(", "modulename", ")", "if", "not", "modulename", ":", "try", ":", "return", "(", "[", "modname", "for", "(", "importer", ",", "modname", ",", "ispkg", ")", "in", "iter_modules", "(", ")", "if", "not", "modname", ".", "startswith", "(", "\"_\"", ")", "]", "+", "list", "(", "sys", ".", "builtin_module_names", ")", ")", "except", "OSError", ":", "# Bug in Python 2.6, see #275", "return", "list", "(", "sys", ".", "builtin_module_names", ")", "try", ":", "module", "=", "safeimport", "(", "modulename", ")", "except", "ErrorDuringImport", ":", "return", "[", "]", "if", "module", "is", "None", ":", "return", "[", "]", "if", "hasattr", "(", "module", ",", "\"__path__\"", ")", ":", "return", "[", "modname", "for", "(", "importer", ",", "modname", ",", "ispkg", ")", "in", "iter_modules", "(", "module", ".", "__path__", ")", "if", "not", "modname", ".", "startswith", "(", "\"_\"", ")", "]", "return", "[", "]" ]
Return a list of modules and packages under modulename. If modulename is not given, return a list of all top level modules and packages.
[ "Return", "a", "list", "of", "modules", "and", "packages", "under", "modulename", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/pydocutils.py#L64-L91
233,471
jorgenschaefer/elpy
elpy/rpc.py
JSONRPCServer.read_json
def read_json(self): """Read a single line and decode it as JSON. Can raise an EOFError() when the input source was closed. """ line = self.stdin.readline() if line == '': raise EOFError() return json.loads(line)
python
def read_json(self): """Read a single line and decode it as JSON. Can raise an EOFError() when the input source was closed. """ line = self.stdin.readline() if line == '': raise EOFError() return json.loads(line)
[ "def", "read_json", "(", "self", ")", ":", "line", "=", "self", ".", "stdin", ".", "readline", "(", ")", "if", "line", "==", "''", ":", "raise", "EOFError", "(", ")", "return", "json", ".", "loads", "(", "line", ")" ]
Read a single line and decode it as JSON. Can raise an EOFError() when the input source was closed.
[ "Read", "a", "single", "line", "and", "decode", "it", "as", "JSON", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/rpc.py#L59-L68
233,472
jorgenschaefer/elpy
elpy/rpc.py
JSONRPCServer.write_json
def write_json(self, **kwargs): """Write an JSON object on a single line. The keyword arguments are interpreted as a single JSON object. It's not possible with this method to write non-objects. """ self.stdout.write(json.dumps(kwargs) + "\n") self.stdout.flush()
python
def write_json(self, **kwargs): """Write an JSON object on a single line. The keyword arguments are interpreted as a single JSON object. It's not possible with this method to write non-objects. """ self.stdout.write(json.dumps(kwargs) + "\n") self.stdout.flush()
[ "def", "write_json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "stdout", ".", "write", "(", "json", ".", "dumps", "(", "kwargs", ")", "+", "\"\\n\"", ")", "self", ".", "stdout", ".", "flush", "(", ")" ]
Write an JSON object on a single line. The keyword arguments are interpreted as a single JSON object. It's not possible with this method to write non-objects.
[ "Write", "an", "JSON", "object", "on", "a", "single", "line", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/rpc.py#L70-L78
233,473
jorgenschaefer/elpy
elpy/rpc.py
JSONRPCServer.handle_request
def handle_request(self): """Handle a single JSON-RPC request. Read a request, call the appropriate handler method, and return the encoded result. Errors in the handler method are caught and encoded as error objects. Errors in the decoding phase are not caught, as we can not respond with an error response to them. """ request = self.read_json() if 'method' not in request: raise ValueError("Received a bad request: {0}" .format(request)) method_name = request['method'] request_id = request.get('id', None) params = request.get('params') or [] try: method = getattr(self, "rpc_" + method_name, None) if method is not None: result = method(*params) else: result = self.handle(method_name, params) if request_id is not None: self.write_json(result=result, id=request_id) except Fault as fault: error = {"message": fault.message, "code": fault.code} if fault.data is not None: error["data"] = fault.data self.write_json(error=error, id=request_id) except Exception as e: error = {"message": str(e), "code": 500, "data": {"traceback": traceback.format_exc()}} self.write_json(error=error, id=request_id)
python
def handle_request(self): """Handle a single JSON-RPC request. Read a request, call the appropriate handler method, and return the encoded result. Errors in the handler method are caught and encoded as error objects. Errors in the decoding phase are not caught, as we can not respond with an error response to them. """ request = self.read_json() if 'method' not in request: raise ValueError("Received a bad request: {0}" .format(request)) method_name = request['method'] request_id = request.get('id', None) params = request.get('params') or [] try: method = getattr(self, "rpc_" + method_name, None) if method is not None: result = method(*params) else: result = self.handle(method_name, params) if request_id is not None: self.write_json(result=result, id=request_id) except Fault as fault: error = {"message": fault.message, "code": fault.code} if fault.data is not None: error["data"] = fault.data self.write_json(error=error, id=request_id) except Exception as e: error = {"message": str(e), "code": 500, "data": {"traceback": traceback.format_exc()}} self.write_json(error=error, id=request_id)
[ "def", "handle_request", "(", "self", ")", ":", "request", "=", "self", ".", "read_json", "(", ")", "if", "'method'", "not", "in", "request", ":", "raise", "ValueError", "(", "\"Received a bad request: {0}\"", ".", "format", "(", "request", ")", ")", "method_name", "=", "request", "[", "'method'", "]", "request_id", "=", "request", ".", "get", "(", "'id'", ",", "None", ")", "params", "=", "request", ".", "get", "(", "'params'", ")", "or", "[", "]", "try", ":", "method", "=", "getattr", "(", "self", ",", "\"rpc_\"", "+", "method_name", ",", "None", ")", "if", "method", "is", "not", "None", ":", "result", "=", "method", "(", "*", "params", ")", "else", ":", "result", "=", "self", ".", "handle", "(", "method_name", ",", "params", ")", "if", "request_id", "is", "not", "None", ":", "self", ".", "write_json", "(", "result", "=", "result", ",", "id", "=", "request_id", ")", "except", "Fault", "as", "fault", ":", "error", "=", "{", "\"message\"", ":", "fault", ".", "message", ",", "\"code\"", ":", "fault", ".", "code", "}", "if", "fault", ".", "data", "is", "not", "None", ":", "error", "[", "\"data\"", "]", "=", "fault", ".", "data", "self", ".", "write_json", "(", "error", "=", "error", ",", "id", "=", "request_id", ")", "except", "Exception", "as", "e", ":", "error", "=", "{", "\"message\"", ":", "str", "(", "e", ")", ",", "\"code\"", ":", "500", ",", "\"data\"", ":", "{", "\"traceback\"", ":", "traceback", ".", "format_exc", "(", ")", "}", "}", "self", ".", "write_json", "(", "error", "=", "error", ",", "id", "=", "request_id", ")" ]
Handle a single JSON-RPC request. Read a request, call the appropriate handler method, and return the encoded result. Errors in the handler method are caught and encoded as error objects. Errors in the decoding phase are not caught, as we can not respond with an error response to them.
[ "Handle", "a", "single", "JSON", "-", "RPC", "request", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/rpc.py#L80-L116
233,474
jorgenschaefer/elpy
elpy/server.py
get_source
def get_source(fileobj): """Translate fileobj into file contents. fileobj is either a string or a dict. If it's a string, that's the file contents. If it's a string, then the filename key contains the name of the file whose contents we are to use. If the dict contains a true value for the key delete_after_use, the file should be deleted once read. """ if not isinstance(fileobj, dict): return fileobj else: try: with io.open(fileobj["filename"], encoding="utf-8", errors="ignore") as f: return f.read() finally: if fileobj.get('delete_after_use'): try: os.remove(fileobj["filename"]) except: # pragma: no cover pass
python
def get_source(fileobj): """Translate fileobj into file contents. fileobj is either a string or a dict. If it's a string, that's the file contents. If it's a string, then the filename key contains the name of the file whose contents we are to use. If the dict contains a true value for the key delete_after_use, the file should be deleted once read. """ if not isinstance(fileobj, dict): return fileobj else: try: with io.open(fileobj["filename"], encoding="utf-8", errors="ignore") as f: return f.read() finally: if fileobj.get('delete_after_use'): try: os.remove(fileobj["filename"]) except: # pragma: no cover pass
[ "def", "get_source", "(", "fileobj", ")", ":", "if", "not", "isinstance", "(", "fileobj", ",", "dict", ")", ":", "return", "fileobj", "else", ":", "try", ":", "with", "io", ".", "open", "(", "fileobj", "[", "\"filename\"", "]", ",", "encoding", "=", "\"utf-8\"", ",", "errors", "=", "\"ignore\"", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "finally", ":", "if", "fileobj", ".", "get", "(", "'delete_after_use'", ")", ":", "try", ":", "os", ".", "remove", "(", "fileobj", "[", "\"filename\"", "]", ")", "except", ":", "# pragma: no cover", "pass" ]
Translate fileobj into file contents. fileobj is either a string or a dict. If it's a string, that's the file contents. If it's a string, then the filename key contains the name of the file whose contents we are to use. If the dict contains a true value for the key delete_after_use, the file should be deleted once read.
[ "Translate", "fileobj", "into", "file", "contents", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L232-L255
233,475
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer._call_backend
def _call_backend(self, method, default, *args, **kwargs): """Call the backend method with args. If there is currently no backend, return default.""" meth = getattr(self.backend, method, None) if meth is None: return default else: return meth(*args, **kwargs)
python
def _call_backend(self, method, default, *args, **kwargs): """Call the backend method with args. If there is currently no backend, return default.""" meth = getattr(self.backend, method, None) if meth is None: return default else: return meth(*args, **kwargs)
[ "def", "_call_backend", "(", "self", ",", "method", ",", "default", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "meth", "=", "getattr", "(", "self", ".", "backend", ",", "method", ",", "None", ")", "if", "meth", "is", "None", ":", "return", "default", "else", ":", "return", "meth", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Call the backend method with args. If there is currently no backend, return default.
[ "Call", "the", "backend", "method", "with", "args", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L36-L44
233,476
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_calltip
def rpc_get_calltip(self, filename, source, offset): """Get the calltip for the function at the offset. """ return self._call_backend("rpc_get_calltip", None, filename, get_source(source), offset)
python
def rpc_get_calltip(self, filename, source, offset): """Get the calltip for the function at the offset. """ return self._call_backend("rpc_get_calltip", None, filename, get_source(source), offset)
[ "def", "rpc_get_calltip", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_calltip\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")" ]
Get the calltip for the function at the offset.
[ "Get", "the", "calltip", "for", "the", "function", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L67-L72
233,477
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_oneline_docstring
def rpc_get_oneline_docstring(self, filename, source, offset): """Get a oneline docstring for the symbol at the offset. """ return self._call_backend("rpc_get_oneline_docstring", None, filename, get_source(source), offset)
python
def rpc_get_oneline_docstring(self, filename, source, offset): """Get a oneline docstring for the symbol at the offset. """ return self._call_backend("rpc_get_oneline_docstring", None, filename, get_source(source), offset)
[ "def", "rpc_get_oneline_docstring", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_oneline_docstring\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")" ]
Get a oneline docstring for the symbol at the offset.
[ "Get", "a", "oneline", "docstring", "for", "the", "symbol", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L74-L79
233,478
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_completions
def rpc_get_completions(self, filename, source, offset): """Get a list of completion candidates for the symbol at offset. """ results = self._call_backend("rpc_get_completions", [], filename, get_source(source), offset) # Uniquify by name results = list(dict((res['name'], res) for res in results) .values()) results.sort(key=lambda cand: _pysymbol_key(cand["name"])) return results
python
def rpc_get_completions(self, filename, source, offset): """Get a list of completion candidates for the symbol at offset. """ results = self._call_backend("rpc_get_completions", [], filename, get_source(source), offset) # Uniquify by name results = list(dict((res['name'], res) for res in results) .values()) results.sort(key=lambda cand: _pysymbol_key(cand["name"])) return results
[ "def", "rpc_get_completions", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "results", "=", "self", ".", "_call_backend", "(", "\"rpc_get_completions\"", ",", "[", "]", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")", "# Uniquify by name", "results", "=", "list", "(", "dict", "(", "(", "res", "[", "'name'", "]", ",", "res", ")", "for", "res", "in", "results", ")", ".", "values", "(", ")", ")", "results", ".", "sort", "(", "key", "=", "lambda", "cand", ":", "_pysymbol_key", "(", "cand", "[", "\"name\"", "]", ")", ")", "return", "results" ]
Get a list of completion candidates for the symbol at offset.
[ "Get", "a", "list", "of", "completion", "candidates", "for", "the", "symbol", "at", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L81-L91
233,479
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_definition
def rpc_get_definition(self, filename, source, offset): """Get the location of the definition for the symbol at the offset. """ return self._call_backend("rpc_get_definition", None, filename, get_source(source), offset)
python
def rpc_get_definition(self, filename, source, offset): """Get the location of the definition for the symbol at the offset. """ return self._call_backend("rpc_get_definition", None, filename, get_source(source), offset)
[ "def", "rpc_get_definition", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_definition\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")" ]
Get the location of the definition for the symbol at the offset.
[ "Get", "the", "location", "of", "the", "definition", "for", "the", "symbol", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L109-L114
233,480
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_assignment
def rpc_get_assignment(self, filename, source, offset): """Get the location of the assignment for the symbol at the offset. """ return self._call_backend("rpc_get_assignment", None, filename, get_source(source), offset)
python
def rpc_get_assignment(self, filename, source, offset): """Get the location of the assignment for the symbol at the offset. """ return self._call_backend("rpc_get_assignment", None, filename, get_source(source), offset)
[ "def", "rpc_get_assignment", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_assignment\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")" ]
Get the location of the assignment for the symbol at the offset.
[ "Get", "the", "location", "of", "the", "assignment", "for", "the", "symbol", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L116-L121
233,481
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_docstring
def rpc_get_docstring(self, filename, source, offset): """Get the docstring for the symbol at the offset. """ return self._call_backend("rpc_get_docstring", None, filename, get_source(source), offset)
python
def rpc_get_docstring(self, filename, source, offset): """Get the docstring for the symbol at the offset. """ return self._call_backend("rpc_get_docstring", None, filename, get_source(source), offset)
[ "def", "rpc_get_docstring", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "return", "self", ".", "_call_backend", "(", "\"rpc_get_docstring\"", ",", "None", ",", "filename", ",", "get_source", "(", "source", ")", ",", "offset", ")" ]
Get the docstring for the symbol at the offset.
[ "Get", "the", "docstring", "for", "the", "symbol", "at", "the", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L123-L128
233,482
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_pydoc_documentation
def rpc_get_pydoc_documentation(self, symbol): """Get the Pydoc documentation for the given symbol. Uses pydoc and can return a string with backspace characters for bold highlighting. """ try: docstring = pydoc.render_doc(str(symbol), "Elpy Pydoc Documentation for %s", False) except (ImportError, pydoc.ErrorDuringImport): return None else: if isinstance(docstring, bytes): docstring = docstring.decode("utf-8", "replace") return docstring
python
def rpc_get_pydoc_documentation(self, symbol): """Get the Pydoc documentation for the given symbol. Uses pydoc and can return a string with backspace characters for bold highlighting. """ try: docstring = pydoc.render_doc(str(symbol), "Elpy Pydoc Documentation for %s", False) except (ImportError, pydoc.ErrorDuringImport): return None else: if isinstance(docstring, bytes): docstring = docstring.decode("utf-8", "replace") return docstring
[ "def", "rpc_get_pydoc_documentation", "(", "self", ",", "symbol", ")", ":", "try", ":", "docstring", "=", "pydoc", ".", "render_doc", "(", "str", "(", "symbol", ")", ",", "\"Elpy Pydoc Documentation for %s\"", ",", "False", ")", "except", "(", "ImportError", ",", "pydoc", ".", "ErrorDuringImport", ")", ":", "return", "None", "else", ":", "if", "isinstance", "(", "docstring", ",", "bytes", ")", ":", "docstring", "=", "docstring", ".", "decode", "(", "\"utf-8\"", ",", "\"replace\"", ")", "return", "docstring" ]
Get the Pydoc documentation for the given symbol. Uses pydoc and can return a string with backspace characters for bold highlighting.
[ "Get", "the", "Pydoc", "documentation", "for", "the", "given", "symbol", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L139-L155
233,483
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_refactor_options
def rpc_get_refactor_options(self, filename, start, end=None): """Return a list of possible refactoring options. This list will be filtered depending on whether it's applicable at the point START and possibly the region between START and END. """ try: from elpy import refactor except: raise ImportError("Rope not installed, refactorings unavailable") ref = refactor.Refactor(self.project_root, filename) return ref.get_refactor_options(start, end)
python
def rpc_get_refactor_options(self, filename, start, end=None): """Return a list of possible refactoring options. This list will be filtered depending on whether it's applicable at the point START and possibly the region between START and END. """ try: from elpy import refactor except: raise ImportError("Rope not installed, refactorings unavailable") ref = refactor.Refactor(self.project_root, filename) return ref.get_refactor_options(start, end)
[ "def", "rpc_get_refactor_options", "(", "self", ",", "filename", ",", "start", ",", "end", "=", "None", ")", ":", "try", ":", "from", "elpy", "import", "refactor", "except", ":", "raise", "ImportError", "(", "\"Rope not installed, refactorings unavailable\"", ")", "ref", "=", "refactor", ".", "Refactor", "(", "self", ".", "project_root", ",", "filename", ")", "return", "ref", ".", "get_refactor_options", "(", "start", ",", "end", ")" ]
Return a list of possible refactoring options. This list will be filtered depending on whether it's applicable at the point START and possibly the region between START and END.
[ "Return", "a", "list", "of", "possible", "refactoring", "options", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L157-L170
233,484
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_refactor
def rpc_refactor(self, filename, method, args): """Return a list of changes from the refactoring action. A change is a dictionary describing the change. See elpy.refactor.translate_changes for a description. """ try: from elpy import refactor except: raise ImportError("Rope not installed, refactorings unavailable") if args is None: args = () ref = refactor.Refactor(self.project_root, filename) return ref.get_changes(method, *args)
python
def rpc_refactor(self, filename, method, args): """Return a list of changes from the refactoring action. A change is a dictionary describing the change. See elpy.refactor.translate_changes for a description. """ try: from elpy import refactor except: raise ImportError("Rope not installed, refactorings unavailable") if args is None: args = () ref = refactor.Refactor(self.project_root, filename) return ref.get_changes(method, *args)
[ "def", "rpc_refactor", "(", "self", ",", "filename", ",", "method", ",", "args", ")", ":", "try", ":", "from", "elpy", "import", "refactor", "except", ":", "raise", "ImportError", "(", "\"Rope not installed, refactorings unavailable\"", ")", "if", "args", "is", "None", ":", "args", "=", "(", ")", "ref", "=", "refactor", ".", "Refactor", "(", "self", ".", "project_root", ",", "filename", ")", "return", "ref", ".", "get_changes", "(", "method", ",", "*", "args", ")" ]
Return a list of changes from the refactoring action. A change is a dictionary describing the change. See elpy.refactor.translate_changes for a description.
[ "Return", "a", "list", "of", "changes", "from", "the", "refactoring", "action", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L172-L186
233,485
jorgenschaefer/elpy
elpy/server.py
ElpyRPCServer.rpc_get_names
def rpc_get_names(self, filename, source, offset): """Get all possible names """ source = get_source(source) if hasattr(self.backend, "rpc_get_names"): return self.backend.rpc_get_names(filename, source, offset) else: raise Fault("get_names not implemented by current backend", code=400)
python
def rpc_get_names(self, filename, source, offset): """Get all possible names """ source = get_source(source) if hasattr(self.backend, "rpc_get_names"): return self.backend.rpc_get_names(filename, source, offset) else: raise Fault("get_names not implemented by current backend", code=400)
[ "def", "rpc_get_names", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "source", "=", "get_source", "(", "source", ")", "if", "hasattr", "(", "self", ".", "backend", ",", "\"rpc_get_names\"", ")", ":", "return", "self", ".", "backend", ".", "rpc_get_names", "(", "filename", ",", "source", ",", "offset", ")", "else", ":", "raise", "Fault", "(", "\"get_names not implemented by current backend\"", ",", "code", "=", "400", ")" ]
Get all possible names
[ "Get", "all", "possible", "names" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/server.py#L199-L208
233,486
jorgenschaefer/elpy
elpy/jedibackend.py
pos_to_linecol
def pos_to_linecol(text, pos): """Return a tuple of line and column for offset pos in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ line_start = text.rfind("\n", 0, pos) + 1 line = text.count("\n", 0, line_start) + 1 col = pos - line_start return line, col
python
def pos_to_linecol(text, pos): """Return a tuple of line and column for offset pos in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ line_start = text.rfind("\n", 0, pos) + 1 line = text.count("\n", 0, line_start) + 1 col = pos - line_start return line, col
[ "def", "pos_to_linecol", "(", "text", ",", "pos", ")", ":", "line_start", "=", "text", ".", "rfind", "(", "\"\\n\"", ",", "0", ",", "pos", ")", "+", "1", "line", "=", "text", ".", "count", "(", "\"\\n\"", ",", "0", ",", "line_start", ")", "+", "1", "col", "=", "pos", "-", "line_start", "return", "line", ",", "col" ]
Return a tuple of line and column for offset pos in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why.
[ "Return", "a", "tuple", "of", "line", "and", "column", "for", "offset", "pos", "in", "text", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L272-L283
233,487
jorgenschaefer/elpy
elpy/jedibackend.py
linecol_to_pos
def linecol_to_pos(text, line, col): """Return the offset of this line and column in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ nth_newline_offset = 0 for i in range(line - 1): new_offset = text.find("\n", nth_newline_offset) if new_offset < 0: raise ValueError("Text does not have {0} lines." .format(line)) nth_newline_offset = new_offset + 1 offset = nth_newline_offset + col if offset > len(text): raise ValueError("Line {0} column {1} is not within the text" .format(line, col)) return offset
python
def linecol_to_pos(text, line, col): """Return the offset of this line and column in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ nth_newline_offset = 0 for i in range(line - 1): new_offset = text.find("\n", nth_newline_offset) if new_offset < 0: raise ValueError("Text does not have {0} lines." .format(line)) nth_newline_offset = new_offset + 1 offset = nth_newline_offset + col if offset > len(text): raise ValueError("Line {0} column {1} is not within the text" .format(line, col)) return offset
[ "def", "linecol_to_pos", "(", "text", ",", "line", ",", "col", ")", ":", "nth_newline_offset", "=", "0", "for", "i", "in", "range", "(", "line", "-", "1", ")", ":", "new_offset", "=", "text", ".", "find", "(", "\"\\n\"", ",", "nth_newline_offset", ")", "if", "new_offset", "<", "0", ":", "raise", "ValueError", "(", "\"Text does not have {0} lines.\"", ".", "format", "(", "line", ")", ")", "nth_newline_offset", "=", "new_offset", "+", "1", "offset", "=", "nth_newline_offset", "+", "col", "if", "offset", ">", "len", "(", "text", ")", ":", "raise", "ValueError", "(", "\"Line {0} column {1} is not within the text\"", ".", "format", "(", "line", ",", "col", ")", ")", "return", "offset" ]
Return the offset of this line and column in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why.
[ "Return", "the", "offset", "of", "this", "line", "and", "column", "in", "text", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L286-L305
233,488
jorgenschaefer/elpy
elpy/jedibackend.py
JediBackend.rpc_get_oneline_docstring
def rpc_get_oneline_docstring(self, filename, source, offset): """Return a oneline docstring for the symbol at offset""" line, column = pos_to_linecol(source, offset) definitions = run_with_debug(jedi, 'goto_definitions', source=source, line=line, column=column, path=filename, encoding='utf-8') assignments = run_with_debug(jedi, 'goto_assignments', source=source, line=line, column=column, path=filename, encoding='utf-8') if definitions: definition = definitions[0] else: definition = None if assignments: assignment = assignments[0] else: assignment = None if definition: # Get name if definition.type in ['function', 'class']: raw_name = definition.name name = '{}()'.format(raw_name) doc = definition.docstring().split('\n') elif definition.type in ['module']: raw_name = definition.name name = '{} {}'.format(raw_name, definition.type) doc = definition.docstring().split('\n') elif (definition.type in ['instance'] and hasattr(assignment, "name")): raw_name = assignment.name name = raw_name doc = assignment.docstring().split('\n') else: return None # Keep only the first paragraph that is not a function declaration lines = [] call = "{}(".format(raw_name) # last line doc.append('') for i in range(len(doc)): if doc[i] == '' and len(lines) != 0: paragraph = " ".join(lines) lines = [] if call != paragraph[0:len(call)]: break paragraph = "" continue lines.append(doc[i]) # Keep only the first sentence onelinedoc = paragraph.split('. ', 1) if len(onelinedoc) == 2: onelinedoc = onelinedoc[0] + '.' else: onelinedoc = onelinedoc[0] if onelinedoc == '': onelinedoc = "No documentation" return {"name": name, "doc": onelinedoc} return None
python
def rpc_get_oneline_docstring(self, filename, source, offset): """Return a oneline docstring for the symbol at offset""" line, column = pos_to_linecol(source, offset) definitions = run_with_debug(jedi, 'goto_definitions', source=source, line=line, column=column, path=filename, encoding='utf-8') assignments = run_with_debug(jedi, 'goto_assignments', source=source, line=line, column=column, path=filename, encoding='utf-8') if definitions: definition = definitions[0] else: definition = None if assignments: assignment = assignments[0] else: assignment = None if definition: # Get name if definition.type in ['function', 'class']: raw_name = definition.name name = '{}()'.format(raw_name) doc = definition.docstring().split('\n') elif definition.type in ['module']: raw_name = definition.name name = '{} {}'.format(raw_name, definition.type) doc = definition.docstring().split('\n') elif (definition.type in ['instance'] and hasattr(assignment, "name")): raw_name = assignment.name name = raw_name doc = assignment.docstring().split('\n') else: return None # Keep only the first paragraph that is not a function declaration lines = [] call = "{}(".format(raw_name) # last line doc.append('') for i in range(len(doc)): if doc[i] == '' and len(lines) != 0: paragraph = " ".join(lines) lines = [] if call != paragraph[0:len(call)]: break paragraph = "" continue lines.append(doc[i]) # Keep only the first sentence onelinedoc = paragraph.split('. ', 1) if len(onelinedoc) == 2: onelinedoc = onelinedoc[0] + '.' else: onelinedoc = onelinedoc[0] if onelinedoc == '': onelinedoc = "No documentation" return {"name": name, "doc": onelinedoc} return None
[ "def", "rpc_get_oneline_docstring", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "line", ",", "column", "=", "pos_to_linecol", "(", "source", ",", "offset", ")", "definitions", "=", "run_with_debug", "(", "jedi", ",", "'goto_definitions'", ",", "source", "=", "source", ",", "line", "=", "line", ",", "column", "=", "column", ",", "path", "=", "filename", ",", "encoding", "=", "'utf-8'", ")", "assignments", "=", "run_with_debug", "(", "jedi", ",", "'goto_assignments'", ",", "source", "=", "source", ",", "line", "=", "line", ",", "column", "=", "column", ",", "path", "=", "filename", ",", "encoding", "=", "'utf-8'", ")", "if", "definitions", ":", "definition", "=", "definitions", "[", "0", "]", "else", ":", "definition", "=", "None", "if", "assignments", ":", "assignment", "=", "assignments", "[", "0", "]", "else", ":", "assignment", "=", "None", "if", "definition", ":", "# Get name", "if", "definition", ".", "type", "in", "[", "'function'", ",", "'class'", "]", ":", "raw_name", "=", "definition", ".", "name", "name", "=", "'{}()'", ".", "format", "(", "raw_name", ")", "doc", "=", "definition", ".", "docstring", "(", ")", ".", "split", "(", "'\\n'", ")", "elif", "definition", ".", "type", "in", "[", "'module'", "]", ":", "raw_name", "=", "definition", ".", "name", "name", "=", "'{} {}'", ".", "format", "(", "raw_name", ",", "definition", ".", "type", ")", "doc", "=", "definition", ".", "docstring", "(", ")", ".", "split", "(", "'\\n'", ")", "elif", "(", "definition", ".", "type", "in", "[", "'instance'", "]", "and", "hasattr", "(", "assignment", ",", "\"name\"", ")", ")", ":", "raw_name", "=", "assignment", ".", "name", "name", "=", "raw_name", "doc", "=", "assignment", ".", "docstring", "(", ")", ".", "split", "(", "'\\n'", ")", "else", ":", "return", "None", "# Keep only the first paragraph that is not a function declaration", "lines", "=", "[", "]", "call", "=", "\"{}(\"", ".", "format", "(", "raw_name", ")", "# last line", "doc", ".", "append", "(", "''", ")", "for", "i", "in", "range", "(", "len", "(", "doc", ")", ")", ":", "if", "doc", "[", "i", "]", "==", "''", "and", "len", "(", "lines", ")", "!=", "0", ":", "paragraph", "=", "\" \"", ".", "join", "(", "lines", ")", "lines", "=", "[", "]", "if", "call", "!=", "paragraph", "[", "0", ":", "len", "(", "call", ")", "]", ":", "break", "paragraph", "=", "\"\"", "continue", "lines", ".", "append", "(", "doc", "[", "i", "]", ")", "# Keep only the first sentence", "onelinedoc", "=", "paragraph", ".", "split", "(", "'. '", ",", "1", ")", "if", "len", "(", "onelinedoc", ")", "==", "2", ":", "onelinedoc", "=", "onelinedoc", "[", "0", "]", "+", "'.'", "else", ":", "onelinedoc", "=", "onelinedoc", "[", "0", "]", "if", "onelinedoc", "==", "''", ":", "onelinedoc", "=", "\"No documentation\"", "return", "{", "\"name\"", ":", "name", ",", "\"doc\"", ":", "onelinedoc", "}", "return", "None" ]
Return a oneline docstring for the symbol at offset
[ "Return", "a", "oneline", "docstring", "for", "the", "symbol", "at", "offset" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L155-L213
233,489
jorgenschaefer/elpy
elpy/jedibackend.py
JediBackend.rpc_get_usages
def rpc_get_usages(self, filename, source, offset): """Return the uses of the symbol at offset. Returns a list of occurrences of the symbol, as dicts with the fields name, filename, and offset. """ line, column = pos_to_linecol(source, offset) uses = run_with_debug(jedi, 'usages', source=source, line=line, column=column, path=filename, encoding='utf-8') if uses is None: return None result = [] for use in uses: if use.module_path == filename: offset = linecol_to_pos(source, use.line, use.column) elif use.module_path is not None: with open(use.module_path) as f: text = f.read() offset = linecol_to_pos(text, use.line, use.column) result.append({"name": use.name, "filename": use.module_path, "offset": offset}) return result
python
def rpc_get_usages(self, filename, source, offset): """Return the uses of the symbol at offset. Returns a list of occurrences of the symbol, as dicts with the fields name, filename, and offset. """ line, column = pos_to_linecol(source, offset) uses = run_with_debug(jedi, 'usages', source=source, line=line, column=column, path=filename, encoding='utf-8') if uses is None: return None result = [] for use in uses: if use.module_path == filename: offset = linecol_to_pos(source, use.line, use.column) elif use.module_path is not None: with open(use.module_path) as f: text = f.read() offset = linecol_to_pos(text, use.line, use.column) result.append({"name": use.name, "filename": use.module_path, "offset": offset}) return result
[ "def", "rpc_get_usages", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "line", ",", "column", "=", "pos_to_linecol", "(", "source", ",", "offset", ")", "uses", "=", "run_with_debug", "(", "jedi", ",", "'usages'", ",", "source", "=", "source", ",", "line", "=", "line", ",", "column", "=", "column", ",", "path", "=", "filename", ",", "encoding", "=", "'utf-8'", ")", "if", "uses", "is", "None", ":", "return", "None", "result", "=", "[", "]", "for", "use", "in", "uses", ":", "if", "use", ".", "module_path", "==", "filename", ":", "offset", "=", "linecol_to_pos", "(", "source", ",", "use", ".", "line", ",", "use", ".", "column", ")", "elif", "use", ".", "module_path", "is", "not", "None", ":", "with", "open", "(", "use", ".", "module_path", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", ")", "offset", "=", "linecol_to_pos", "(", "text", ",", "use", ".", "line", ",", "use", ".", "column", ")", "result", ".", "append", "(", "{", "\"name\"", ":", "use", ".", "name", ",", "\"filename\"", ":", "use", ".", "module_path", ",", "\"offset\"", ":", "offset", "}", ")", "return", "result" ]
Return the uses of the symbol at offset. Returns a list of occurrences of the symbol, as dicts with the fields name, filename, and offset.
[ "Return", "the", "uses", "of", "the", "symbol", "at", "offset", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L215-L241
233,490
jorgenschaefer/elpy
elpy/jedibackend.py
JediBackend.rpc_get_names
def rpc_get_names(self, filename, source, offset): """Return the list of possible names""" names = jedi.api.names(source=source, path=filename, encoding='utf-8', all_scopes=True, definitions=True, references=True) result = [] for name in names: if name.module_path == filename: offset = linecol_to_pos(source, name.line, name.column) elif name.module_path is not None: with open(name.module_path) as f: text = f.read() offset = linecol_to_pos(text, name.line, name.column) result.append({"name": name.name, "filename": name.module_path, "offset": offset}) return result
python
def rpc_get_names(self, filename, source, offset): """Return the list of possible names""" names = jedi.api.names(source=source, path=filename, encoding='utf-8', all_scopes=True, definitions=True, references=True) result = [] for name in names: if name.module_path == filename: offset = linecol_to_pos(source, name.line, name.column) elif name.module_path is not None: with open(name.module_path) as f: text = f.read() offset = linecol_to_pos(text, name.line, name.column) result.append({"name": name.name, "filename": name.module_path, "offset": offset}) return result
[ "def", "rpc_get_names", "(", "self", ",", "filename", ",", "source", ",", "offset", ")", ":", "names", "=", "jedi", ".", "api", ".", "names", "(", "source", "=", "source", ",", "path", "=", "filename", ",", "encoding", "=", "'utf-8'", ",", "all_scopes", "=", "True", ",", "definitions", "=", "True", ",", "references", "=", "True", ")", "result", "=", "[", "]", "for", "name", "in", "names", ":", "if", "name", ".", "module_path", "==", "filename", ":", "offset", "=", "linecol_to_pos", "(", "source", ",", "name", ".", "line", ",", "name", ".", "column", ")", "elif", "name", ".", "module_path", "is", "not", "None", ":", "with", "open", "(", "name", ".", "module_path", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", ")", "offset", "=", "linecol_to_pos", "(", "text", ",", "name", ".", "line", ",", "name", ".", "column", ")", "result", ".", "append", "(", "{", "\"name\"", ":", "name", ".", "name", ",", "\"filename\"", ":", "name", ".", "module_path", ",", "\"offset\"", ":", "offset", "}", ")", "return", "result" ]
Return the list of possible names
[ "Return", "the", "list", "of", "possible", "names" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/jedibackend.py#L243-L262
233,491
jorgenschaefer/elpy
elpy/refactor.py
options
def options(description, **kwargs): """Decorator to set some options on a method.""" def set_notes(function): function.refactor_notes = {'name': function.__name__, 'category': "Miscellaneous", 'description': description, 'doc': getattr(function, '__doc__', ''), 'args': []} function.refactor_notes.update(kwargs) return function return set_notes
python
def options(description, **kwargs): """Decorator to set some options on a method.""" def set_notes(function): function.refactor_notes = {'name': function.__name__, 'category': "Miscellaneous", 'description': description, 'doc': getattr(function, '__doc__', ''), 'args': []} function.refactor_notes.update(kwargs) return function return set_notes
[ "def", "options", "(", "description", ",", "*", "*", "kwargs", ")", ":", "def", "set_notes", "(", "function", ")", ":", "function", ".", "refactor_notes", "=", "{", "'name'", ":", "function", ".", "__name__", ",", "'category'", ":", "\"Miscellaneous\"", ",", "'description'", ":", "description", ",", "'doc'", ":", "getattr", "(", "function", ",", "'__doc__'", ",", "''", ")", ",", "'args'", ":", "[", "]", "}", "function", ".", "refactor_notes", ".", "update", "(", "kwargs", ")", "return", "function", "return", "set_notes" ]
Decorator to set some options on a method.
[ "Decorator", "to", "set", "some", "options", "on", "a", "method", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L75-L86
233,492
jorgenschaefer/elpy
elpy/refactor.py
translate_changes
def translate_changes(initial_change): """Translate rope.base.change.Change instances to dictionaries. See Refactor.get_changes for an explanation of the resulting dictionary. """ agenda = [initial_change] result = [] while agenda: change = agenda.pop(0) if isinstance(change, rope_change.ChangeSet): agenda.extend(change.changes) elif isinstance(change, rope_change.ChangeContents): result.append({'action': 'change', 'file': change.resource.real_path, 'contents': change.new_contents, 'diff': change.get_description()}) elif isinstance(change, rope_change.CreateFile): result.append({'action': 'create', 'type': 'file', 'file': change.resource.real_path}) elif isinstance(change, rope_change.CreateFolder): result.append({'action': 'create', 'type': 'directory', 'path': change.resource.real_path}) elif isinstance(change, rope_change.MoveResource): result.append({'action': 'move', 'type': ('directory' if change.new_resource.is_folder() else 'file'), 'source': change.resource.real_path, 'destination': change.new_resource.real_path}) elif isinstance(change, rope_change.RemoveResource): if change.resource.is_folder(): result.append({'action': 'delete', 'type': 'directory', 'path': change.resource.real_path}) else: result.append({'action': 'delete', 'type': 'file', 'file': change.resource.real_path}) return result
python
def translate_changes(initial_change): """Translate rope.base.change.Change instances to dictionaries. See Refactor.get_changes for an explanation of the resulting dictionary. """ agenda = [initial_change] result = [] while agenda: change = agenda.pop(0) if isinstance(change, rope_change.ChangeSet): agenda.extend(change.changes) elif isinstance(change, rope_change.ChangeContents): result.append({'action': 'change', 'file': change.resource.real_path, 'contents': change.new_contents, 'diff': change.get_description()}) elif isinstance(change, rope_change.CreateFile): result.append({'action': 'create', 'type': 'file', 'file': change.resource.real_path}) elif isinstance(change, rope_change.CreateFolder): result.append({'action': 'create', 'type': 'directory', 'path': change.resource.real_path}) elif isinstance(change, rope_change.MoveResource): result.append({'action': 'move', 'type': ('directory' if change.new_resource.is_folder() else 'file'), 'source': change.resource.real_path, 'destination': change.new_resource.real_path}) elif isinstance(change, rope_change.RemoveResource): if change.resource.is_folder(): result.append({'action': 'delete', 'type': 'directory', 'path': change.resource.real_path}) else: result.append({'action': 'delete', 'type': 'file', 'file': change.resource.real_path}) return result
[ "def", "translate_changes", "(", "initial_change", ")", ":", "agenda", "=", "[", "initial_change", "]", "result", "=", "[", "]", "while", "agenda", ":", "change", "=", "agenda", ".", "pop", "(", "0", ")", "if", "isinstance", "(", "change", ",", "rope_change", ".", "ChangeSet", ")", ":", "agenda", ".", "extend", "(", "change", ".", "changes", ")", "elif", "isinstance", "(", "change", ",", "rope_change", ".", "ChangeContents", ")", ":", "result", ".", "append", "(", "{", "'action'", ":", "'change'", ",", "'file'", ":", "change", ".", "resource", ".", "real_path", ",", "'contents'", ":", "change", ".", "new_contents", ",", "'diff'", ":", "change", ".", "get_description", "(", ")", "}", ")", "elif", "isinstance", "(", "change", ",", "rope_change", ".", "CreateFile", ")", ":", "result", ".", "append", "(", "{", "'action'", ":", "'create'", ",", "'type'", ":", "'file'", ",", "'file'", ":", "change", ".", "resource", ".", "real_path", "}", ")", "elif", "isinstance", "(", "change", ",", "rope_change", ".", "CreateFolder", ")", ":", "result", ".", "append", "(", "{", "'action'", ":", "'create'", ",", "'type'", ":", "'directory'", ",", "'path'", ":", "change", ".", "resource", ".", "real_path", "}", ")", "elif", "isinstance", "(", "change", ",", "rope_change", ".", "MoveResource", ")", ":", "result", ".", "append", "(", "{", "'action'", ":", "'move'", ",", "'type'", ":", "(", "'directory'", "if", "change", ".", "new_resource", ".", "is_folder", "(", ")", "else", "'file'", ")", ",", "'source'", ":", "change", ".", "resource", ".", "real_path", ",", "'destination'", ":", "change", ".", "new_resource", ".", "real_path", "}", ")", "elif", "isinstance", "(", "change", ",", "rope_change", ".", "RemoveResource", ")", ":", "if", "change", ".", "resource", ".", "is_folder", "(", ")", ":", "result", ".", "append", "(", "{", "'action'", ":", "'delete'", ",", "'type'", ":", "'directory'", ",", "'path'", ":", "change", ".", "resource", ".", "real_path", "}", ")", "else", ":", "result", ".", "append", "(", "{", "'action'", ":", "'delete'", ",", "'type'", ":", "'file'", ",", "'file'", ":", "change", ".", "resource", ".", "real_path", "}", ")", "return", "result" ]
Translate rope.base.change.Change instances to dictionaries. See Refactor.get_changes for an explanation of the resulting dictionary.
[ "Translate", "rope", ".", "base", ".", "change", ".", "Change", "instances", "to", "dictionaries", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L328-L370
233,493
jorgenschaefer/elpy
elpy/refactor.py
Refactor.get_refactor_options
def get_refactor_options(self, start, end=None): """Return a list of options for refactoring at the given position. If `end` is also given, refactoring on a region is assumed. Each option is a dictionary of key/value pairs. The value of the key 'name' is the one to be used for get_changes. The key 'args' contains a list of additional arguments required for get_changes. """ result = [] for symbol in dir(self): if not symbol.startswith("refactor_"): continue method = getattr(self, symbol) if not method.refactor_notes.get('available', True): continue category = method.refactor_notes['category'] if end is not None and category != 'Region': continue if end is None and category == 'Region': continue is_on_symbol = self._is_on_symbol(start) if not is_on_symbol and category in ('Symbol', 'Method'): continue requires_import = method.refactor_notes.get('only_on_imports', False) if requires_import and not self._is_on_import_statement(start): continue result.append(method.refactor_notes) return result
python
def get_refactor_options(self, start, end=None): """Return a list of options for refactoring at the given position. If `end` is also given, refactoring on a region is assumed. Each option is a dictionary of key/value pairs. The value of the key 'name' is the one to be used for get_changes. The key 'args' contains a list of additional arguments required for get_changes. """ result = [] for symbol in dir(self): if not symbol.startswith("refactor_"): continue method = getattr(self, symbol) if not method.refactor_notes.get('available', True): continue category = method.refactor_notes['category'] if end is not None and category != 'Region': continue if end is None and category == 'Region': continue is_on_symbol = self._is_on_symbol(start) if not is_on_symbol and category in ('Symbol', 'Method'): continue requires_import = method.refactor_notes.get('only_on_imports', False) if requires_import and not self._is_on_import_statement(start): continue result.append(method.refactor_notes) return result
[ "def", "get_refactor_options", "(", "self", ",", "start", ",", "end", "=", "None", ")", ":", "result", "=", "[", "]", "for", "symbol", "in", "dir", "(", "self", ")", ":", "if", "not", "symbol", ".", "startswith", "(", "\"refactor_\"", ")", ":", "continue", "method", "=", "getattr", "(", "self", ",", "symbol", ")", "if", "not", "method", ".", "refactor_notes", ".", "get", "(", "'available'", ",", "True", ")", ":", "continue", "category", "=", "method", ".", "refactor_notes", "[", "'category'", "]", "if", "end", "is", "not", "None", "and", "category", "!=", "'Region'", ":", "continue", "if", "end", "is", "None", "and", "category", "==", "'Region'", ":", "continue", "is_on_symbol", "=", "self", ".", "_is_on_symbol", "(", "start", ")", "if", "not", "is_on_symbol", "and", "category", "in", "(", "'Symbol'", ",", "'Method'", ")", ":", "continue", "requires_import", "=", "method", ".", "refactor_notes", ".", "get", "(", "'only_on_imports'", ",", "False", ")", "if", "requires_import", "and", "not", "self", ".", "_is_on_import_statement", "(", "start", ")", ":", "continue", "result", ".", "append", "(", "method", ".", "refactor_notes", ")", "return", "result" ]
Return a list of options for refactoring at the given position. If `end` is also given, refactoring on a region is assumed. Each option is a dictionary of key/value pairs. The value of the key 'name' is the one to be used for get_changes. The key 'args' contains a list of additional arguments required for get_changes.
[ "Return", "a", "list", "of", "options", "for", "refactoring", "at", "the", "given", "position", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L113-L145
233,494
jorgenschaefer/elpy
elpy/refactor.py
Refactor._is_on_import_statement
def _is_on_import_statement(self, offset): "Does this offset point to an import statement?" data = self.resource.read() bol = data.rfind("\n", 0, offset) + 1 eol = data.find("\n", 0, bol) if eol == -1: eol = len(data) line = data[bol:eol] line = line.strip() if line.startswith("import ") or line.startswith("from "): return True else: return False
python
def _is_on_import_statement(self, offset): "Does this offset point to an import statement?" data = self.resource.read() bol = data.rfind("\n", 0, offset) + 1 eol = data.find("\n", 0, bol) if eol == -1: eol = len(data) line = data[bol:eol] line = line.strip() if line.startswith("import ") or line.startswith("from "): return True else: return False
[ "def", "_is_on_import_statement", "(", "self", ",", "offset", ")", ":", "data", "=", "self", ".", "resource", ".", "read", "(", ")", "bol", "=", "data", ".", "rfind", "(", "\"\\n\"", ",", "0", ",", "offset", ")", "+", "1", "eol", "=", "data", ".", "find", "(", "\"\\n\"", ",", "0", ",", "bol", ")", "if", "eol", "==", "-", "1", ":", "eol", "=", "len", "(", "data", ")", "line", "=", "data", "[", "bol", ":", "eol", "]", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "\"import \"", ")", "or", "line", ".", "startswith", "(", "\"from \"", ")", ":", "return", "True", "else", ":", "return", "False" ]
Does this offset point to an import statement?
[ "Does", "this", "offset", "point", "to", "an", "import", "statement?" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L147-L159
233,495
jorgenschaefer/elpy
elpy/refactor.py
Refactor._is_on_symbol
def _is_on_symbol(self, offset): "Is this offset on a symbol?" if not ROPE_AVAILABLE: return False data = self.resource.read() if offset >= len(data): return False if data[offset] != '_' and not data[offset].isalnum(): return False word = worder.get_name_at(self.resource, offset) if word: return True else: return False
python
def _is_on_symbol(self, offset): "Is this offset on a symbol?" if not ROPE_AVAILABLE: return False data = self.resource.read() if offset >= len(data): return False if data[offset] != '_' and not data[offset].isalnum(): return False word = worder.get_name_at(self.resource, offset) if word: return True else: return False
[ "def", "_is_on_symbol", "(", "self", ",", "offset", ")", ":", "if", "not", "ROPE_AVAILABLE", ":", "return", "False", "data", "=", "self", ".", "resource", ".", "read", "(", ")", "if", "offset", ">=", "len", "(", "data", ")", ":", "return", "False", "if", "data", "[", "offset", "]", "!=", "'_'", "and", "not", "data", "[", "offset", "]", ".", "isalnum", "(", ")", ":", "return", "False", "word", "=", "worder", ".", "get_name_at", "(", "self", ".", "resource", ",", "offset", ")", "if", "word", ":", "return", "True", "else", ":", "return", "False" ]
Is this offset on a symbol?
[ "Is", "this", "offset", "on", "a", "symbol?" ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L161-L174
233,496
jorgenschaefer/elpy
elpy/refactor.py
Refactor.get_changes
def get_changes(self, name, *args): """Return a list of changes for the named refactoring action. Changes are dictionaries describing a single action to be taken for the refactoring to be successful. A change has an action and possibly a type. In the description below, the action is before the slash and the type after it. change: Change file contents - file: The path to the file to change - contents: The new contents for the file - Diff: A unified diff showing the changes introduced create/file: Create a new file - file: The file to create create/directory: Create a new directory - path: The directory to create move/file: Rename a file - source: The path to the source file - destination: The path to the destination file name move/directory: Rename a directory - source: The path to the source directory - destination: The path to the destination directory name delete/file: Delete a file - file: The file to delete delete/directory: Delete a directory - path: The directory to delete """ if not name.startswith("refactor_"): raise ValueError("Bad refactoring name {0}".format(name)) method = getattr(self, name) if not method.refactor_notes.get('available', True): raise RuntimeError("Method not available") return method(*args)
python
def get_changes(self, name, *args): """Return a list of changes for the named refactoring action. Changes are dictionaries describing a single action to be taken for the refactoring to be successful. A change has an action and possibly a type. In the description below, the action is before the slash and the type after it. change: Change file contents - file: The path to the file to change - contents: The new contents for the file - Diff: A unified diff showing the changes introduced create/file: Create a new file - file: The file to create create/directory: Create a new directory - path: The directory to create move/file: Rename a file - source: The path to the source file - destination: The path to the destination file name move/directory: Rename a directory - source: The path to the source directory - destination: The path to the destination directory name delete/file: Delete a file - file: The file to delete delete/directory: Delete a directory - path: The directory to delete """ if not name.startswith("refactor_"): raise ValueError("Bad refactoring name {0}".format(name)) method = getattr(self, name) if not method.refactor_notes.get('available', True): raise RuntimeError("Method not available") return method(*args)
[ "def", "get_changes", "(", "self", ",", "name", ",", "*", "args", ")", ":", "if", "not", "name", ".", "startswith", "(", "\"refactor_\"", ")", ":", "raise", "ValueError", "(", "\"Bad refactoring name {0}\"", ".", "format", "(", "name", ")", ")", "method", "=", "getattr", "(", "self", ",", "name", ")", "if", "not", "method", ".", "refactor_notes", ".", "get", "(", "'available'", ",", "True", ")", ":", "raise", "RuntimeError", "(", "\"Method not available\"", ")", "return", "method", "(", "*", "args", ")" ]
Return a list of changes for the named refactoring action. Changes are dictionaries describing a single action to be taken for the refactoring to be successful. A change has an action and possibly a type. In the description below, the action is before the slash and the type after it. change: Change file contents - file: The path to the file to change - contents: The new contents for the file - Diff: A unified diff showing the changes introduced create/file: Create a new file - file: The file to create create/directory: Create a new directory - path: The directory to create move/file: Rename a file - source: The path to the source file - destination: The path to the destination file name move/directory: Rename a directory - source: The path to the source directory - destination: The path to the destination directory name delete/file: Delete a file - file: The file to delete delete/directory: Delete a directory - path: The directory to delete
[ "Return", "a", "list", "of", "changes", "for", "the", "named", "refactoring", "action", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L176-L216
233,497
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_froms_to_imports
def refactor_froms_to_imports(self, offset): """Converting imports of the form "from ..." to "import ...".""" refactor = ImportOrganizer(self.project) changes = refactor.froms_to_imports(self.resource, offset) return translate_changes(changes)
python
def refactor_froms_to_imports(self, offset): """Converting imports of the form "from ..." to "import ...".""" refactor = ImportOrganizer(self.project) changes = refactor.froms_to_imports(self.resource, offset) return translate_changes(changes)
[ "def", "refactor_froms_to_imports", "(", "self", ",", "offset", ")", ":", "refactor", "=", "ImportOrganizer", "(", "self", ".", "project", ")", "changes", "=", "refactor", ".", "froms_to_imports", "(", "self", ".", "resource", ",", "offset", ")", "return", "translate_changes", "(", "changes", ")" ]
Converting imports of the form "from ..." to "import ...".
[ "Converting", "imports", "of", "the", "form", "from", "...", "to", "import", "...", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L222-L226
233,498
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_organize_imports
def refactor_organize_imports(self): """Clean up and organize imports.""" refactor = ImportOrganizer(self.project) changes = refactor.organize_imports(self.resource) return translate_changes(changes)
python
def refactor_organize_imports(self): """Clean up and organize imports.""" refactor = ImportOrganizer(self.project) changes = refactor.organize_imports(self.resource) return translate_changes(changes)
[ "def", "refactor_organize_imports", "(", "self", ")", ":", "refactor", "=", "ImportOrganizer", "(", "self", ".", "project", ")", "changes", "=", "refactor", ".", "organize_imports", "(", "self", ".", "resource", ")", "return", "translate_changes", "(", "changes", ")" ]
Clean up and organize imports.
[ "Clean", "up", "and", "organize", "imports", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L230-L234
233,499
jorgenschaefer/elpy
elpy/refactor.py
Refactor.refactor_module_to_package
def refactor_module_to_package(self): """Convert the current module into a package.""" refactor = ModuleToPackage(self.project, self.resource) return self._get_changes(refactor)
python
def refactor_module_to_package(self): """Convert the current module into a package.""" refactor = ModuleToPackage(self.project, self.resource) return self._get_changes(refactor)
[ "def", "refactor_module_to_package", "(", "self", ")", ":", "refactor", "=", "ModuleToPackage", "(", "self", ".", "project", ",", "self", ".", "resource", ")", "return", "self", ".", "_get_changes", "(", "refactor", ")" ]
Convert the current module into a package.
[ "Convert", "the", "current", "module", "into", "a", "package", "." ]
ffd982f829b11e53f2be187c7b770423341f29bc
https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L238-L241