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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
OSConfigRenderer.write
def write(self, config_file): """ Write a single config file, raises if config file is not registered. """ if config_file not in self.templates: log('Config not registered: %s' % config_file, level=ERROR) raise OSConfigException _out = self.render(config_file) if six.PY3: _out = _out.encode('UTF-8') with open(config_file, 'wb') as out: out.write(_out) log('Wrote template %s.' % config_file, level=INFO)
python
def write(self, config_file): """ Write a single config file, raises if config file is not registered. """ if config_file not in self.templates: log('Config not registered: %s' % config_file, level=ERROR) raise OSConfigException _out = self.render(config_file) if six.PY3: _out = _out.encode('UTF-8') with open(config_file, 'wb') as out: out.write(_out) log('Wrote template %s.' % config_file, level=INFO)
[ "def", "write", "(", "self", ",", "config_file", ")", ":", "if", "config_file", "not", "in", "self", ".", "templates", ":", "log", "(", "'Config not registered: %s'", "%", "config_file", ",", "level", "=", "ERROR", ")", "raise", "OSConfigException", "_out", "=", "self", ".", "render", "(", "config_file", ")", "if", "six", ".", "PY3", ":", "_out", "=", "_out", ".", "encode", "(", "'UTF-8'", ")", "with", "open", "(", "config_file", ",", "'wb'", ")", "as", "out", ":", "out", ".", "write", "(", "_out", ")", "log", "(", "'Wrote template %s.'", "%", "config_file", ",", "level", "=", "INFO", ")" ]
Write a single config file, raises if config file is not registered.
[ "Write", "a", "single", "config", "file", "raises", "if", "config", "file", "is", "not", "registered", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L313-L328
train
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
OSConfigRenderer.write_all
def write_all(self): """ Write out all registered config files. """ [self.write(k) for k in six.iterkeys(self.templates)]
python
def write_all(self): """ Write out all registered config files. """ [self.write(k) for k in six.iterkeys(self.templates)]
[ "def", "write_all", "(", "self", ")", ":", "[", "self", ".", "write", "(", "k", ")", "for", "k", "in", "six", ".", "iterkeys", "(", "self", ".", "templates", ")", "]" ]
Write out all registered config files.
[ "Write", "out", "all", "registered", "config", "files", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L330-L334
train
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
OSConfigRenderer.set_release
def set_release(self, openstack_release): """ Resets the template environment and generates a new template loader based on a the new openstack release. """ self._tmpl_env = None self.openstack_release = openstack_release self._get_tmpl_env()
python
def set_release(self, openstack_release): """ Resets the template environment and generates a new template loader based on a the new openstack release. """ self._tmpl_env = None self.openstack_release = openstack_release self._get_tmpl_env()
[ "def", "set_release", "(", "self", ",", "openstack_release", ")", ":", "self", ".", "_tmpl_env", "=", "None", "self", ".", "openstack_release", "=", "openstack_release", "self", ".", "_get_tmpl_env", "(", ")" ]
Resets the template environment and generates a new template loader based on a the new openstack release.
[ "Resets", "the", "template", "environment", "and", "generates", "a", "new", "template", "loader", "based", "on", "a", "the", "new", "openstack", "release", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L336-L343
train
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
OSConfigRenderer.complete_contexts
def complete_contexts(self): ''' Returns a list of context interfaces that yield a complete context. ''' interfaces = [] [interfaces.extend(i.complete_contexts()) for i in six.itervalues(self.templates)] return interfaces
python
def complete_contexts(self): ''' Returns a list of context interfaces that yield a complete context. ''' interfaces = [] [interfaces.extend(i.complete_contexts()) for i in six.itervalues(self.templates)] return interfaces
[ "def", "complete_contexts", "(", "self", ")", ":", "interfaces", "=", "[", "]", "[", "interfaces", ".", "extend", "(", "i", ".", "complete_contexts", "(", ")", ")", "for", "i", "in", "six", ".", "itervalues", "(", "self", ".", "templates", ")", "]", "return", "interfaces" ]
Returns a list of context interfaces that yield a complete context.
[ "Returns", "a", "list", "of", "context", "interfaces", "that", "yield", "a", "complete", "context", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L345-L352
train
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
is_elected_leader
def is_elected_leader(resource): """ Returns True if the charm executing this is the elected cluster leader. It relies on two mechanisms to determine leadership: 1. If juju is sufficiently new and leadership election is supported, the is_leader command will be used. 2. If the charm is part of a corosync cluster, call corosync to determine leadership. 3. If the charm is not part of a corosync cluster, the leader is determined as being "the alive unit with the lowest unit numer". In other words, the oldest surviving unit. """ try: return juju_is_leader() except NotImplementedError: log('Juju leadership election feature not enabled' ', using fallback support', level=WARNING) if is_clustered(): if not is_crm_leader(resource): log('Deferring action to CRM leader.', level=INFO) return False else: peers = peer_units() if peers and not oldest_peer(peers): log('Deferring action to oldest service unit.', level=INFO) return False return True
python
def is_elected_leader(resource): """ Returns True if the charm executing this is the elected cluster leader. It relies on two mechanisms to determine leadership: 1. If juju is sufficiently new and leadership election is supported, the is_leader command will be used. 2. If the charm is part of a corosync cluster, call corosync to determine leadership. 3. If the charm is not part of a corosync cluster, the leader is determined as being "the alive unit with the lowest unit numer". In other words, the oldest surviving unit. """ try: return juju_is_leader() except NotImplementedError: log('Juju leadership election feature not enabled' ', using fallback support', level=WARNING) if is_clustered(): if not is_crm_leader(resource): log('Deferring action to CRM leader.', level=INFO) return False else: peers = peer_units() if peers and not oldest_peer(peers): log('Deferring action to oldest service unit.', level=INFO) return False return True
[ "def", "is_elected_leader", "(", "resource", ")", ":", "try", ":", "return", "juju_is_leader", "(", ")", "except", "NotImplementedError", ":", "log", "(", "'Juju leadership election feature not enabled'", "', using fallback support'", ",", "level", "=", "WARNING", ")", "if", "is_clustered", "(", ")", ":", "if", "not", "is_crm_leader", "(", "resource", ")", ":", "log", "(", "'Deferring action to CRM leader.'", ",", "level", "=", "INFO", ")", "return", "False", "else", ":", "peers", "=", "peer_units", "(", ")", "if", "peers", "and", "not", "oldest_peer", "(", "peers", ")", ":", "log", "(", "'Deferring action to oldest service unit.'", ",", "level", "=", "INFO", ")", "return", "False", "return", "True" ]
Returns True if the charm executing this is the elected cluster leader. It relies on two mechanisms to determine leadership: 1. If juju is sufficiently new and leadership election is supported, the is_leader command will be used. 2. If the charm is part of a corosync cluster, call corosync to determine leadership. 3. If the charm is not part of a corosync cluster, the leader is determined as being "the alive unit with the lowest unit numer". In other words, the oldest surviving unit.
[ "Returns", "True", "if", "the", "charm", "executing", "this", "is", "the", "elected", "cluster", "leader", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L78-L107
train
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
is_crm_dc
def is_crm_dc(): """ Determine leadership by querying the pacemaker Designated Controller """ cmd = ['crm', 'status'] try: status = subprocess.check_output(cmd, stderr=subprocess.STDOUT) if not isinstance(status, six.text_type): status = six.text_type(status, "utf-8") except subprocess.CalledProcessError as ex: raise CRMDCNotFound(str(ex)) current_dc = '' for line in status.split('\n'): if line.startswith('Current DC'): # Current DC: juju-lytrusty-machine-2 (168108163) - partition with quorum current_dc = line.split(':')[1].split()[0] if current_dc == get_unit_hostname(): return True elif current_dc == 'NONE': raise CRMDCNotFound('Current DC: NONE') return False
python
def is_crm_dc(): """ Determine leadership by querying the pacemaker Designated Controller """ cmd = ['crm', 'status'] try: status = subprocess.check_output(cmd, stderr=subprocess.STDOUT) if not isinstance(status, six.text_type): status = six.text_type(status, "utf-8") except subprocess.CalledProcessError as ex: raise CRMDCNotFound(str(ex)) current_dc = '' for line in status.split('\n'): if line.startswith('Current DC'): # Current DC: juju-lytrusty-machine-2 (168108163) - partition with quorum current_dc = line.split(':')[1].split()[0] if current_dc == get_unit_hostname(): return True elif current_dc == 'NONE': raise CRMDCNotFound('Current DC: NONE') return False
[ "def", "is_crm_dc", "(", ")", ":", "cmd", "=", "[", "'crm'", ",", "'status'", "]", "try", ":", "status", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "if", "not", "isinstance", "(", "status", ",", "six", ".", "text_type", ")", ":", "status", "=", "six", ".", "text_type", "(", "status", ",", "\"utf-8\"", ")", "except", "subprocess", ".", "CalledProcessError", "as", "ex", ":", "raise", "CRMDCNotFound", "(", "str", "(", "ex", ")", ")", "current_dc", "=", "''", "for", "line", "in", "status", ".", "split", "(", "'\\n'", ")", ":", "if", "line", ".", "startswith", "(", "'Current DC'", ")", ":", "# Current DC: juju-lytrusty-machine-2 (168108163) - partition with quorum", "current_dc", "=", "line", ".", "split", "(", "':'", ")", "[", "1", "]", ".", "split", "(", ")", "[", "0", "]", "if", "current_dc", "==", "get_unit_hostname", "(", ")", ":", "return", "True", "elif", "current_dc", "==", "'NONE'", ":", "raise", "CRMDCNotFound", "(", "'Current DC: NONE'", ")", "return", "False" ]
Determine leadership by querying the pacemaker Designated Controller
[ "Determine", "leadership", "by", "querying", "the", "pacemaker", "Designated", "Controller" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L121-L143
train
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
is_crm_leader
def is_crm_leader(resource, retry=False): """ Returns True if the charm calling this is the elected corosync leader, as returned by calling the external "crm" command. We allow this operation to be retried to avoid the possibility of getting a false negative. See LP #1396246 for more info. """ if resource == DC_RESOURCE_NAME: return is_crm_dc() cmd = ['crm', 'resource', 'show', resource] try: status = subprocess.check_output(cmd, stderr=subprocess.STDOUT) if not isinstance(status, six.text_type): status = six.text_type(status, "utf-8") except subprocess.CalledProcessError: status = None if status and get_unit_hostname() in status: return True if status and "resource %s is NOT running" % (resource) in status: raise CRMResourceNotFound("CRM resource %s not found" % (resource)) return False
python
def is_crm_leader(resource, retry=False): """ Returns True if the charm calling this is the elected corosync leader, as returned by calling the external "crm" command. We allow this operation to be retried to avoid the possibility of getting a false negative. See LP #1396246 for more info. """ if resource == DC_RESOURCE_NAME: return is_crm_dc() cmd = ['crm', 'resource', 'show', resource] try: status = subprocess.check_output(cmd, stderr=subprocess.STDOUT) if not isinstance(status, six.text_type): status = six.text_type(status, "utf-8") except subprocess.CalledProcessError: status = None if status and get_unit_hostname() in status: return True if status and "resource %s is NOT running" % (resource) in status: raise CRMResourceNotFound("CRM resource %s not found" % (resource)) return False
[ "def", "is_crm_leader", "(", "resource", ",", "retry", "=", "False", ")", ":", "if", "resource", "==", "DC_RESOURCE_NAME", ":", "return", "is_crm_dc", "(", ")", "cmd", "=", "[", "'crm'", ",", "'resource'", ",", "'show'", ",", "resource", "]", "try", ":", "status", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "if", "not", "isinstance", "(", "status", ",", "six", ".", "text_type", ")", ":", "status", "=", "six", ".", "text_type", "(", "status", ",", "\"utf-8\"", ")", "except", "subprocess", ".", "CalledProcessError", ":", "status", "=", "None", "if", "status", "and", "get_unit_hostname", "(", ")", "in", "status", ":", "return", "True", "if", "status", "and", "\"resource %s is NOT running\"", "%", "(", "resource", ")", "in", "status", ":", "raise", "CRMResourceNotFound", "(", "\"CRM resource %s not found\"", "%", "(", "resource", ")", ")", "return", "False" ]
Returns True if the charm calling this is the elected corosync leader, as returned by calling the external "crm" command. We allow this operation to be retried to avoid the possibility of getting a false negative. See LP #1396246 for more info.
[ "Returns", "True", "if", "the", "charm", "calling", "this", "is", "the", "elected", "corosync", "leader", "as", "returned", "by", "calling", "the", "external", "crm", "command", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L148-L172
train
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
peer_ips
def peer_ips(peer_relation='cluster', addr_key='private-address'): '''Return a dict of peers and their private-address''' peers = {} for r_id in relation_ids(peer_relation): for unit in relation_list(r_id): peers[unit] = relation_get(addr_key, rid=r_id, unit=unit) return peers
python
def peer_ips(peer_relation='cluster', addr_key='private-address'): '''Return a dict of peers and their private-address''' peers = {} for r_id in relation_ids(peer_relation): for unit in relation_list(r_id): peers[unit] = relation_get(addr_key, rid=r_id, unit=unit) return peers
[ "def", "peer_ips", "(", "peer_relation", "=", "'cluster'", ",", "addr_key", "=", "'private-address'", ")", ":", "peers", "=", "{", "}", "for", "r_id", "in", "relation_ids", "(", "peer_relation", ")", ":", "for", "unit", "in", "relation_list", "(", "r_id", ")", ":", "peers", "[", "unit", "]", "=", "relation_get", "(", "addr_key", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "return", "peers" ]
Return a dict of peers and their private-address
[ "Return", "a", "dict", "of", "peers", "and", "their", "private", "-", "address" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L189-L195
train
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
oldest_peer
def oldest_peer(peers): """Determines who the oldest peer is by comparing unit numbers.""" local_unit_no = int(os.getenv('JUJU_UNIT_NAME').split('/')[1]) for peer in peers: remote_unit_no = int(peer.split('/')[1]) if remote_unit_no < local_unit_no: return False return True
python
def oldest_peer(peers): """Determines who the oldest peer is by comparing unit numbers.""" local_unit_no = int(os.getenv('JUJU_UNIT_NAME').split('/')[1]) for peer in peers: remote_unit_no = int(peer.split('/')[1]) if remote_unit_no < local_unit_no: return False return True
[ "def", "oldest_peer", "(", "peers", ")", ":", "local_unit_no", "=", "int", "(", "os", ".", "getenv", "(", "'JUJU_UNIT_NAME'", ")", ".", "split", "(", "'/'", ")", "[", "1", "]", ")", "for", "peer", "in", "peers", ":", "remote_unit_no", "=", "int", "(", "peer", ".", "split", "(", "'/'", ")", "[", "1", "]", ")", "if", "remote_unit_no", "<", "local_unit_no", ":", "return", "False", "return", "True" ]
Determines who the oldest peer is by comparing unit numbers.
[ "Determines", "who", "the", "oldest", "peer", "is", "by", "comparing", "unit", "numbers", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L198-L205
train
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
canonical_url
def canonical_url(configs, vip_setting='vip'): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration and hacluster. :configs : OSTemplateRenderer: A config tempating object to inspect for a complete https context. :vip_setting: str: Setting in charm config that specifies VIP address. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' if is_clustered(): addr = config_get(vip_setting) else: addr = unit_get('private-address') return '%s://%s' % (scheme, addr)
python
def canonical_url(configs, vip_setting='vip'): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration and hacluster. :configs : OSTemplateRenderer: A config tempating object to inspect for a complete https context. :vip_setting: str: Setting in charm config that specifies VIP address. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' if is_clustered(): addr = config_get(vip_setting) else: addr = unit_get('private-address') return '%s://%s' % (scheme, addr)
[ "def", "canonical_url", "(", "configs", ",", "vip_setting", "=", "'vip'", ")", ":", "scheme", "=", "'http'", "if", "'https'", "in", "configs", ".", "complete_contexts", "(", ")", ":", "scheme", "=", "'https'", "if", "is_clustered", "(", ")", ":", "addr", "=", "config_get", "(", "vip_setting", ")", "else", ":", "addr", "=", "unit_get", "(", "'private-address'", ")", "return", "'%s://%s'", "%", "(", "scheme", ",", "addr", ")" ]
Returns the correct HTTP URL to this host given the state of HTTPS configuration and hacluster. :configs : OSTemplateRenderer: A config tempating object to inspect for a complete https context. :vip_setting: str: Setting in charm config that specifies VIP address.
[ "Returns", "the", "correct", "HTTP", "URL", "to", "this", "host", "given", "the", "state", "of", "HTTPS", "configuration", "and", "hacluster", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L354-L372
train
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
distributed_wait
def distributed_wait(modulo=None, wait=None, operation_name='operation'): ''' Distribute operations by waiting based on modulo_distribution If modulo and or wait are not set, check config_get for those values. If config values are not set, default to modulo=3 and wait=30. :param modulo: int The modulo number creates the group distribution :param wait: int The constant time wait value :param operation_name: string Operation name for status message i.e. 'restart' :side effect: Calls config_get() :side effect: Calls log() :side effect: Calls status_set() :side effect: Calls time.sleep() ''' if modulo is None: modulo = config_get('modulo-nodes') or 3 if wait is None: wait = config_get('known-wait') or 30 if juju_is_leader(): # The leader should never wait calculated_wait = 0 else: # non_zero_wait=True guarantees the non-leader who gets modulo 0 # will still wait calculated_wait = modulo_distribution(modulo=modulo, wait=wait, non_zero_wait=True) msg = "Waiting {} seconds for {} ...".format(calculated_wait, operation_name) log(msg, DEBUG) status_set('maintenance', msg) time.sleep(calculated_wait)
python
def distributed_wait(modulo=None, wait=None, operation_name='operation'): ''' Distribute operations by waiting based on modulo_distribution If modulo and or wait are not set, check config_get for those values. If config values are not set, default to modulo=3 and wait=30. :param modulo: int The modulo number creates the group distribution :param wait: int The constant time wait value :param operation_name: string Operation name for status message i.e. 'restart' :side effect: Calls config_get() :side effect: Calls log() :side effect: Calls status_set() :side effect: Calls time.sleep() ''' if modulo is None: modulo = config_get('modulo-nodes') or 3 if wait is None: wait = config_get('known-wait') or 30 if juju_is_leader(): # The leader should never wait calculated_wait = 0 else: # non_zero_wait=True guarantees the non-leader who gets modulo 0 # will still wait calculated_wait = modulo_distribution(modulo=modulo, wait=wait, non_zero_wait=True) msg = "Waiting {} seconds for {} ...".format(calculated_wait, operation_name) log(msg, DEBUG) status_set('maintenance', msg) time.sleep(calculated_wait)
[ "def", "distributed_wait", "(", "modulo", "=", "None", ",", "wait", "=", "None", ",", "operation_name", "=", "'operation'", ")", ":", "if", "modulo", "is", "None", ":", "modulo", "=", "config_get", "(", "'modulo-nodes'", ")", "or", "3", "if", "wait", "is", "None", ":", "wait", "=", "config_get", "(", "'known-wait'", ")", "or", "30", "if", "juju_is_leader", "(", ")", ":", "# The leader should never wait", "calculated_wait", "=", "0", "else", ":", "# non_zero_wait=True guarantees the non-leader who gets modulo 0", "# will still wait", "calculated_wait", "=", "modulo_distribution", "(", "modulo", "=", "modulo", ",", "wait", "=", "wait", ",", "non_zero_wait", "=", "True", ")", "msg", "=", "\"Waiting {} seconds for {} ...\"", ".", "format", "(", "calculated_wait", ",", "operation_name", ")", "log", "(", "msg", ",", "DEBUG", ")", "status_set", "(", "'maintenance'", ",", "msg", ")", "time", ".", "sleep", "(", "calculated_wait", ")" ]
Distribute operations by waiting based on modulo_distribution If modulo and or wait are not set, check config_get for those values. If config values are not set, default to modulo=3 and wait=30. :param modulo: int The modulo number creates the group distribution :param wait: int The constant time wait value :param operation_name: string Operation name for status message i.e. 'restart' :side effect: Calls config_get() :side effect: Calls log() :side effect: Calls status_set() :side effect: Calls time.sleep()
[ "Distribute", "operations", "by", "waiting", "based", "on", "modulo_distribution" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L375-L406
train
juju/charm-helpers
charmhelpers/fetch/centos.py
update
def update(fatal=False): """Update local yum cache.""" cmd = ['yum', '--assumeyes', 'update'] log("Update with fatal: {}".format(fatal)) _run_yum_command(cmd, fatal)
python
def update(fatal=False): """Update local yum cache.""" cmd = ['yum', '--assumeyes', 'update'] log("Update with fatal: {}".format(fatal)) _run_yum_command(cmd, fatal)
[ "def", "update", "(", "fatal", "=", "False", ")", ":", "cmd", "=", "[", "'yum'", ",", "'--assumeyes'", ",", "'update'", "]", "log", "(", "\"Update with fatal: {}\"", ".", "format", "(", "fatal", ")", ")", "_run_yum_command", "(", "cmd", ",", "fatal", ")" ]
Update local yum cache.
[ "Update", "local", "yum", "cache", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/centos.py#L64-L68
train
juju/charm-helpers
charmhelpers/fetch/centos.py
yum_search
def yum_search(packages): """Search for a package.""" output = {} cmd = ['yum', 'search'] if isinstance(packages, six.string_types): cmd.append(packages) else: cmd.extend(packages) log("Searching for {}".format(packages)) result = subprocess.check_output(cmd) for package in list(packages): output[package] = package in result return output
python
def yum_search(packages): """Search for a package.""" output = {} cmd = ['yum', 'search'] if isinstance(packages, six.string_types): cmd.append(packages) else: cmd.extend(packages) log("Searching for {}".format(packages)) result = subprocess.check_output(cmd) for package in list(packages): output[package] = package in result return output
[ "def", "yum_search", "(", "packages", ")", ":", "output", "=", "{", "}", "cmd", "=", "[", "'yum'", ",", "'search'", "]", "if", "isinstance", "(", "packages", ",", "six", ".", "string_types", ")", ":", "cmd", ".", "append", "(", "packages", ")", "else", ":", "cmd", ".", "extend", "(", "packages", ")", "log", "(", "\"Searching for {}\"", ".", "format", "(", "packages", ")", ")", "result", "=", "subprocess", ".", "check_output", "(", "cmd", ")", "for", "package", "in", "list", "(", "packages", ")", ":", "output", "[", "package", "]", "=", "package", "in", "result", "return", "output" ]
Search for a package.
[ "Search", "for", "a", "package", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/centos.py#L82-L94
train
juju/charm-helpers
charmhelpers/fetch/centos.py
_run_yum_command
def _run_yum_command(cmd, fatal=False): """Run an YUM command. Checks the output and retry if the fatal flag is set to True. :param: cmd: str: The yum command to run. :param: fatal: bool: Whether the command's output should be checked and retried. """ env = os.environ.copy() if fatal: retry_count = 0 result = None # If the command is considered "fatal", we need to retry if the yum # lock was not acquired. while result is None or result == YUM_NO_LOCK: try: result = subprocess.check_call(cmd, env=env) except subprocess.CalledProcessError as e: retry_count = retry_count + 1 if retry_count > YUM_NO_LOCK_RETRY_COUNT: raise result = e.returncode log("Couldn't acquire YUM lock. Will retry in {} seconds." "".format(YUM_NO_LOCK_RETRY_DELAY)) time.sleep(YUM_NO_LOCK_RETRY_DELAY) else: subprocess.call(cmd, env=env)
python
def _run_yum_command(cmd, fatal=False): """Run an YUM command. Checks the output and retry if the fatal flag is set to True. :param: cmd: str: The yum command to run. :param: fatal: bool: Whether the command's output should be checked and retried. """ env = os.environ.copy() if fatal: retry_count = 0 result = None # If the command is considered "fatal", we need to retry if the yum # lock was not acquired. while result is None or result == YUM_NO_LOCK: try: result = subprocess.check_call(cmd, env=env) except subprocess.CalledProcessError as e: retry_count = retry_count + 1 if retry_count > YUM_NO_LOCK_RETRY_COUNT: raise result = e.returncode log("Couldn't acquire YUM lock. Will retry in {} seconds." "".format(YUM_NO_LOCK_RETRY_DELAY)) time.sleep(YUM_NO_LOCK_RETRY_DELAY) else: subprocess.call(cmd, env=env)
[ "def", "_run_yum_command", "(", "cmd", ",", "fatal", "=", "False", ")", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "fatal", ":", "retry_count", "=", "0", "result", "=", "None", "# If the command is considered \"fatal\", we need to retry if the yum", "# lock was not acquired.", "while", "result", "is", "None", "or", "result", "==", "YUM_NO_LOCK", ":", "try", ":", "result", "=", "subprocess", ".", "check_call", "(", "cmd", ",", "env", "=", "env", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "retry_count", "=", "retry_count", "+", "1", "if", "retry_count", ">", "YUM_NO_LOCK_RETRY_COUNT", ":", "raise", "result", "=", "e", ".", "returncode", "log", "(", "\"Couldn't acquire YUM lock. Will retry in {} seconds.\"", "\"\"", ".", "format", "(", "YUM_NO_LOCK_RETRY_DELAY", ")", ")", "time", ".", "sleep", "(", "YUM_NO_LOCK_RETRY_DELAY", ")", "else", ":", "subprocess", ".", "call", "(", "cmd", ",", "env", "=", "env", ")" ]
Run an YUM command. Checks the output and retry if the fatal flag is set to True. :param: cmd: str: The yum command to run. :param: fatal: bool: Whether the command's output should be checked and retried.
[ "Run", "an", "YUM", "command", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/centos.py#L140-L171
train
juju/charm-helpers
charmhelpers/cli/__init__.py
OutputFormatter.py
def py(self, output): """Output data as a nicely-formatted python data structure""" import pprint pprint.pprint(output, stream=self.outfile)
python
def py(self, output): """Output data as a nicely-formatted python data structure""" import pprint pprint.pprint(output, stream=self.outfile)
[ "def", "py", "(", "self", ",", "output", ")", ":", "import", "pprint", "pprint", ".", "pprint", "(", "output", ",", "stream", "=", "self", ".", "outfile", ")" ]
Output data as a nicely-formatted python data structure
[ "Output", "data", "as", "a", "nicely", "-", "formatted", "python", "data", "structure" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L60-L63
train
juju/charm-helpers
charmhelpers/cli/__init__.py
OutputFormatter.csv
def csv(self, output): """Output data as excel-compatible CSV""" import csv csvwriter = csv.writer(self.outfile) csvwriter.writerows(output)
python
def csv(self, output): """Output data as excel-compatible CSV""" import csv csvwriter = csv.writer(self.outfile) csvwriter.writerows(output)
[ "def", "csv", "(", "self", ",", "output", ")", ":", "import", "csv", "csvwriter", "=", "csv", ".", "writer", "(", "self", ".", "outfile", ")", "csvwriter", ".", "writerows", "(", "output", ")" ]
Output data as excel-compatible CSV
[ "Output", "data", "as", "excel", "-", "compatible", "CSV" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L75-L79
train
juju/charm-helpers
charmhelpers/cli/__init__.py
OutputFormatter.tab
def tab(self, output): """Output data in excel-compatible tab-delimited format""" import csv csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab) csvwriter.writerows(output)
python
def tab(self, output): """Output data in excel-compatible tab-delimited format""" import csv csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab) csvwriter.writerows(output)
[ "def", "tab", "(", "self", ",", "output", ")", ":", "import", "csv", "csvwriter", "=", "csv", ".", "writer", "(", "self", ".", "outfile", ",", "dialect", "=", "csv", ".", "excel_tab", ")", "csvwriter", ".", "writerows", "(", "output", ")" ]
Output data in excel-compatible tab-delimited format
[ "Output", "data", "in", "excel", "-", "compatible", "tab", "-", "delimited", "format" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L81-L85
train
juju/charm-helpers
charmhelpers/cli/__init__.py
CommandLine.subcommand
def subcommand(self, command_name=None): """ Decorate a function as a subcommand. Use its arguments as the command-line arguments""" def wrapper(decorated): cmd_name = command_name or decorated.__name__ subparser = self.subparsers.add_parser(cmd_name, description=decorated.__doc__) for args, kwargs in describe_arguments(decorated): subparser.add_argument(*args, **kwargs) subparser.set_defaults(func=decorated) return decorated return wrapper
python
def subcommand(self, command_name=None): """ Decorate a function as a subcommand. Use its arguments as the command-line arguments""" def wrapper(decorated): cmd_name = command_name or decorated.__name__ subparser = self.subparsers.add_parser(cmd_name, description=decorated.__doc__) for args, kwargs in describe_arguments(decorated): subparser.add_argument(*args, **kwargs) subparser.set_defaults(func=decorated) return decorated return wrapper
[ "def", "subcommand", "(", "self", ",", "command_name", "=", "None", ")", ":", "def", "wrapper", "(", "decorated", ")", ":", "cmd_name", "=", "command_name", "or", "decorated", ".", "__name__", "subparser", "=", "self", ".", "subparsers", ".", "add_parser", "(", "cmd_name", ",", "description", "=", "decorated", ".", "__doc__", ")", "for", "args", ",", "kwargs", "in", "describe_arguments", "(", "decorated", ")", ":", "subparser", ".", "add_argument", "(", "*", "args", ",", "*", "*", "kwargs", ")", "subparser", ".", "set_defaults", "(", "func", "=", "decorated", ")", "return", "decorated", "return", "wrapper" ]
Decorate a function as a subcommand. Use its arguments as the command-line arguments
[ "Decorate", "a", "function", "as", "a", "subcommand", ".", "Use", "its", "arguments", "as", "the", "command", "-", "line", "arguments" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L107-L119
train
juju/charm-helpers
charmhelpers/cli/__init__.py
CommandLine.run
def run(self): "Run cli, processing arguments and executing subcommands." arguments = self.argument_parser.parse_args() argspec = inspect.getargspec(arguments.func) vargs = [] for arg in argspec.args: vargs.append(getattr(arguments, arg)) if argspec.varargs: vargs.extend(getattr(arguments, argspec.varargs)) output = arguments.func(*vargs) if getattr(arguments.func, '_cli_test_command', False): self.exit_code = 0 if output else 1 output = '' if getattr(arguments.func, '_cli_no_output', False): output = '' self.formatter.format_output(output, arguments.format) if charmhelpers.core.unitdata._KV: charmhelpers.core.unitdata._KV.flush()
python
def run(self): "Run cli, processing arguments and executing subcommands." arguments = self.argument_parser.parse_args() argspec = inspect.getargspec(arguments.func) vargs = [] for arg in argspec.args: vargs.append(getattr(arguments, arg)) if argspec.varargs: vargs.extend(getattr(arguments, argspec.varargs)) output = arguments.func(*vargs) if getattr(arguments.func, '_cli_test_command', False): self.exit_code = 0 if output else 1 output = '' if getattr(arguments.func, '_cli_no_output', False): output = '' self.formatter.format_output(output, arguments.format) if charmhelpers.core.unitdata._KV: charmhelpers.core.unitdata._KV.flush()
[ "def", "run", "(", "self", ")", ":", "arguments", "=", "self", ".", "argument_parser", ".", "parse_args", "(", ")", "argspec", "=", "inspect", ".", "getargspec", "(", "arguments", ".", "func", ")", "vargs", "=", "[", "]", "for", "arg", "in", "argspec", ".", "args", ":", "vargs", ".", "append", "(", "getattr", "(", "arguments", ",", "arg", ")", ")", "if", "argspec", ".", "varargs", ":", "vargs", ".", "extend", "(", "getattr", "(", "arguments", ",", "argspec", ".", "varargs", ")", ")", "output", "=", "arguments", ".", "func", "(", "*", "vargs", ")", "if", "getattr", "(", "arguments", ".", "func", ",", "'_cli_test_command'", ",", "False", ")", ":", "self", ".", "exit_code", "=", "0", "if", "output", "else", "1", "output", "=", "''", "if", "getattr", "(", "arguments", ".", "func", ",", "'_cli_no_output'", ",", "False", ")", ":", "output", "=", "''", "self", ".", "formatter", ".", "format_output", "(", "output", ",", "arguments", ".", "format", ")", "if", "charmhelpers", ".", "core", ".", "unitdata", ".", "_KV", ":", "charmhelpers", ".", "core", ".", "unitdata", ".", "_KV", ".", "flush", "(", ")" ]
Run cli, processing arguments and executing subcommands.
[ "Run", "cli", "processing", "arguments", "and", "executing", "subcommands", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L148-L165
train
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
ssh_authorized_peers
def ssh_authorized_peers(peer_interface, user, group=None, ensure_local_user=False): """ Main setup function, should be called from both peer -changed and -joined hooks with the same parameters. """ if ensure_local_user: ensure_user(user, group) priv_key, pub_key = get_keypair(user) hook = hook_name() if hook == '%s-relation-joined' % peer_interface: relation_set(ssh_pub_key=pub_key) elif hook == '%s-relation-changed' % peer_interface or \ hook == '%s-relation-departed' % peer_interface: hosts = [] keys = [] for r_id in relation_ids(peer_interface): for unit in related_units(r_id): ssh_pub_key = relation_get('ssh_pub_key', rid=r_id, unit=unit) priv_addr = relation_get('private-address', rid=r_id, unit=unit) if ssh_pub_key: keys.append(ssh_pub_key) hosts.append(priv_addr) else: log('ssh_authorized_peers(): ssh_pub_key ' 'missing for unit %s, skipping.' % unit) write_authorized_keys(user, keys) write_known_hosts(user, hosts) authed_hosts = ':'.join(hosts) relation_set(ssh_authorized_hosts=authed_hosts)
python
def ssh_authorized_peers(peer_interface, user, group=None, ensure_local_user=False): """ Main setup function, should be called from both peer -changed and -joined hooks with the same parameters. """ if ensure_local_user: ensure_user(user, group) priv_key, pub_key = get_keypair(user) hook = hook_name() if hook == '%s-relation-joined' % peer_interface: relation_set(ssh_pub_key=pub_key) elif hook == '%s-relation-changed' % peer_interface or \ hook == '%s-relation-departed' % peer_interface: hosts = [] keys = [] for r_id in relation_ids(peer_interface): for unit in related_units(r_id): ssh_pub_key = relation_get('ssh_pub_key', rid=r_id, unit=unit) priv_addr = relation_get('private-address', rid=r_id, unit=unit) if ssh_pub_key: keys.append(ssh_pub_key) hosts.append(priv_addr) else: log('ssh_authorized_peers(): ssh_pub_key ' 'missing for unit %s, skipping.' % unit) write_authorized_keys(user, keys) write_known_hosts(user, hosts) authed_hosts = ':'.join(hosts) relation_set(ssh_authorized_hosts=authed_hosts)
[ "def", "ssh_authorized_peers", "(", "peer_interface", ",", "user", ",", "group", "=", "None", ",", "ensure_local_user", "=", "False", ")", ":", "if", "ensure_local_user", ":", "ensure_user", "(", "user", ",", "group", ")", "priv_key", ",", "pub_key", "=", "get_keypair", "(", "user", ")", "hook", "=", "hook_name", "(", ")", "if", "hook", "==", "'%s-relation-joined'", "%", "peer_interface", ":", "relation_set", "(", "ssh_pub_key", "=", "pub_key", ")", "elif", "hook", "==", "'%s-relation-changed'", "%", "peer_interface", "or", "hook", "==", "'%s-relation-departed'", "%", "peer_interface", ":", "hosts", "=", "[", "]", "keys", "=", "[", "]", "for", "r_id", "in", "relation_ids", "(", "peer_interface", ")", ":", "for", "unit", "in", "related_units", "(", "r_id", ")", ":", "ssh_pub_key", "=", "relation_get", "(", "'ssh_pub_key'", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "priv_addr", "=", "relation_get", "(", "'private-address'", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "if", "ssh_pub_key", ":", "keys", ".", "append", "(", "ssh_pub_key", ")", "hosts", ".", "append", "(", "priv_addr", ")", "else", ":", "log", "(", "'ssh_authorized_peers(): ssh_pub_key '", "'missing for unit %s, skipping.'", "%", "unit", ")", "write_authorized_keys", "(", "user", ",", "keys", ")", "write_known_hosts", "(", "user", ",", "hosts", ")", "authed_hosts", "=", "':'", ".", "join", "(", "hosts", ")", "relation_set", "(", "ssh_authorized_hosts", "=", "authed_hosts", ")" ]
Main setup function, should be called from both peer -changed and -joined hooks with the same parameters.
[ "Main", "setup", "function", "should", "be", "called", "from", "both", "peer", "-", "changed", "and", "-", "joined", "hooks", "with", "the", "same", "parameters", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L185-L219
train
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
collect_authed_hosts
def collect_authed_hosts(peer_interface): '''Iterate through the units on peer interface to find all that have the calling host in its authorized hosts list''' hosts = [] for r_id in (relation_ids(peer_interface) or []): for unit in related_units(r_id): private_addr = relation_get('private-address', rid=r_id, unit=unit) authed_hosts = relation_get('ssh_authorized_hosts', rid=r_id, unit=unit) if not authed_hosts: log('Peer %s has not authorized *any* hosts yet, skipping.' % (unit), level=INFO) continue if unit_private_ip() in authed_hosts.split(':'): hosts.append(private_addr) else: log('Peer %s has not authorized *this* host yet, skipping.' % (unit), level=INFO) return hosts
python
def collect_authed_hosts(peer_interface): '''Iterate through the units on peer interface to find all that have the calling host in its authorized hosts list''' hosts = [] for r_id in (relation_ids(peer_interface) or []): for unit in related_units(r_id): private_addr = relation_get('private-address', rid=r_id, unit=unit) authed_hosts = relation_get('ssh_authorized_hosts', rid=r_id, unit=unit) if not authed_hosts: log('Peer %s has not authorized *any* hosts yet, skipping.' % (unit), level=INFO) continue if unit_private_ip() in authed_hosts.split(':'): hosts.append(private_addr) else: log('Peer %s has not authorized *this* host yet, skipping.' % (unit), level=INFO) return hosts
[ "def", "collect_authed_hosts", "(", "peer_interface", ")", ":", "hosts", "=", "[", "]", "for", "r_id", "in", "(", "relation_ids", "(", "peer_interface", ")", "or", "[", "]", ")", ":", "for", "unit", "in", "related_units", "(", "r_id", ")", ":", "private_addr", "=", "relation_get", "(", "'private-address'", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "authed_hosts", "=", "relation_get", "(", "'ssh_authorized_hosts'", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "if", "not", "authed_hosts", ":", "log", "(", "'Peer %s has not authorized *any* hosts yet, skipping.'", "%", "(", "unit", ")", ",", "level", "=", "INFO", ")", "continue", "if", "unit_private_ip", "(", ")", "in", "authed_hosts", ".", "split", "(", "':'", ")", ":", "hosts", ".", "append", "(", "private_addr", ")", "else", ":", "log", "(", "'Peer %s has not authorized *this* host yet, skipping.'", "%", "(", "unit", ")", ",", "level", "=", "INFO", ")", "return", "hosts" ]
Iterate through the units on peer interface to find all that have the calling host in its authorized hosts list
[ "Iterate", "through", "the", "units", "on", "peer", "interface", "to", "find", "all", "that", "have", "the", "calling", "host", "in", "its", "authorized", "hosts", "list" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L242-L263
train
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
sync_path_to_host
def sync_path_to_host(path, host, user, verbose=False, cmd=None, gid=None, fatal=False): """Sync path to an specific peer host Propagates exception if operation fails and fatal=True. """ cmd = cmd or copy(BASE_CMD) if not verbose: cmd.append('-silent') # removing trailing slash from directory paths, unison # doesn't like these. if path.endswith('/'): path = path[:(len(path) - 1)] cmd = cmd + [path, 'ssh://%s@%s/%s' % (user, host, path)] try: log('Syncing local path %s to %s@%s:%s' % (path, user, host, path)) run_as_user(user, cmd, gid) except Exception: log('Error syncing remote files') if fatal: raise
python
def sync_path_to_host(path, host, user, verbose=False, cmd=None, gid=None, fatal=False): """Sync path to an specific peer host Propagates exception if operation fails and fatal=True. """ cmd = cmd or copy(BASE_CMD) if not verbose: cmd.append('-silent') # removing trailing slash from directory paths, unison # doesn't like these. if path.endswith('/'): path = path[:(len(path) - 1)] cmd = cmd + [path, 'ssh://%s@%s/%s' % (user, host, path)] try: log('Syncing local path %s to %s@%s:%s' % (path, user, host, path)) run_as_user(user, cmd, gid) except Exception: log('Error syncing remote files') if fatal: raise
[ "def", "sync_path_to_host", "(", "path", ",", "host", ",", "user", ",", "verbose", "=", "False", ",", "cmd", "=", "None", ",", "gid", "=", "None", ",", "fatal", "=", "False", ")", ":", "cmd", "=", "cmd", "or", "copy", "(", "BASE_CMD", ")", "if", "not", "verbose", ":", "cmd", ".", "append", "(", "'-silent'", ")", "# removing trailing slash from directory paths, unison", "# doesn't like these.", "if", "path", ".", "endswith", "(", "'/'", ")", ":", "path", "=", "path", "[", ":", "(", "len", "(", "path", ")", "-", "1", ")", "]", "cmd", "=", "cmd", "+", "[", "path", ",", "'ssh://%s@%s/%s'", "%", "(", "user", ",", "host", ",", "path", ")", "]", "try", ":", "log", "(", "'Syncing local path %s to %s@%s:%s'", "%", "(", "path", ",", "user", ",", "host", ",", "path", ")", ")", "run_as_user", "(", "user", ",", "cmd", ",", "gid", ")", "except", "Exception", ":", "log", "(", "'Error syncing remote files'", ")", "if", "fatal", ":", "raise" ]
Sync path to an specific peer host Propagates exception if operation fails and fatal=True.
[ "Sync", "path", "to", "an", "specific", "peer", "host" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L266-L289
train
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
sync_to_peer
def sync_to_peer(host, user, paths=None, verbose=False, cmd=None, gid=None, fatal=False): """Sync paths to an specific peer host Propagates exception if any operation fails and fatal=True. """ if paths: for p in paths: sync_path_to_host(p, host, user, verbose, cmd, gid, fatal)
python
def sync_to_peer(host, user, paths=None, verbose=False, cmd=None, gid=None, fatal=False): """Sync paths to an specific peer host Propagates exception if any operation fails and fatal=True. """ if paths: for p in paths: sync_path_to_host(p, host, user, verbose, cmd, gid, fatal)
[ "def", "sync_to_peer", "(", "host", ",", "user", ",", "paths", "=", "None", ",", "verbose", "=", "False", ",", "cmd", "=", "None", ",", "gid", "=", "None", ",", "fatal", "=", "False", ")", ":", "if", "paths", ":", "for", "p", "in", "paths", ":", "sync_path_to_host", "(", "p", ",", "host", ",", "user", ",", "verbose", ",", "cmd", ",", "gid", ",", "fatal", ")" ]
Sync paths to an specific peer host Propagates exception if any operation fails and fatal=True.
[ "Sync", "paths", "to", "an", "specific", "peer", "host" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L292-L300
train
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
sync_to_peers
def sync_to_peers(peer_interface, user, paths=None, verbose=False, cmd=None, gid=None, fatal=False): """Sync all hosts to an specific path The type of group is integer, it allows user has permissions to operate a directory have a different group id with the user id. Propagates exception if any operation fails and fatal=True. """ if paths: for host in collect_authed_hosts(peer_interface): sync_to_peer(host, user, paths, verbose, cmd, gid, fatal)
python
def sync_to_peers(peer_interface, user, paths=None, verbose=False, cmd=None, gid=None, fatal=False): """Sync all hosts to an specific path The type of group is integer, it allows user has permissions to operate a directory have a different group id with the user id. Propagates exception if any operation fails and fatal=True. """ if paths: for host in collect_authed_hosts(peer_interface): sync_to_peer(host, user, paths, verbose, cmd, gid, fatal)
[ "def", "sync_to_peers", "(", "peer_interface", ",", "user", ",", "paths", "=", "None", ",", "verbose", "=", "False", ",", "cmd", "=", "None", ",", "gid", "=", "None", ",", "fatal", "=", "False", ")", ":", "if", "paths", ":", "for", "host", "in", "collect_authed_hosts", "(", "peer_interface", ")", ":", "sync_to_peer", "(", "host", ",", "user", ",", "paths", ",", "verbose", ",", "cmd", ",", "gid", ",", "fatal", ")" ]
Sync all hosts to an specific path The type of group is integer, it allows user has permissions to operate a directory have a different group id with the user id. Propagates exception if any operation fails and fatal=True.
[ "Sync", "all", "hosts", "to", "an", "specific", "path" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L303-L314
train
juju/charm-helpers
charmhelpers/fetch/python/packages.py
parse_options
def parse_options(given, available): """Given a set of options, check if available""" for key, value in sorted(given.items()): if not value: continue if key in available: yield "--{0}={1}".format(key, value)
python
def parse_options(given, available): """Given a set of options, check if available""" for key, value in sorted(given.items()): if not value: continue if key in available: yield "--{0}={1}".format(key, value)
[ "def", "parse_options", "(", "given", ",", "available", ")", ":", "for", "key", ",", "value", "in", "sorted", "(", "given", ".", "items", "(", ")", ")", ":", "if", "not", "value", ":", "continue", "if", "key", "in", "available", ":", "yield", "\"--{0}={1}\"", ".", "format", "(", "key", ",", "value", ")" ]
Given a set of options, check if available
[ "Given", "a", "set", "of", "options", "check", "if", "available" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L53-L59
train
juju/charm-helpers
charmhelpers/fetch/python/packages.py
pip_install_requirements
def pip_install_requirements(requirements, constraints=None, **options): """Install a requirements file. :param constraints: Path to pip constraints file. http://pip.readthedocs.org/en/stable/user_guide/#constraints-files """ command = ["install"] available_options = ('proxy', 'src', 'log', ) for option in parse_options(options, available_options): command.append(option) command.append("-r {0}".format(requirements)) if constraints: command.append("-c {0}".format(constraints)) log("Installing from file: {} with constraints {} " "and options: {}".format(requirements, constraints, command)) else: log("Installing from file: {} with options: {}".format(requirements, command)) pip_execute(command)
python
def pip_install_requirements(requirements, constraints=None, **options): """Install a requirements file. :param constraints: Path to pip constraints file. http://pip.readthedocs.org/en/stable/user_guide/#constraints-files """ command = ["install"] available_options = ('proxy', 'src', 'log', ) for option in parse_options(options, available_options): command.append(option) command.append("-r {0}".format(requirements)) if constraints: command.append("-c {0}".format(constraints)) log("Installing from file: {} with constraints {} " "and options: {}".format(requirements, constraints, command)) else: log("Installing from file: {} with options: {}".format(requirements, command)) pip_execute(command)
[ "def", "pip_install_requirements", "(", "requirements", ",", "constraints", "=", "None", ",", "*", "*", "options", ")", ":", "command", "=", "[", "\"install\"", "]", "available_options", "=", "(", "'proxy'", ",", "'src'", ",", "'log'", ",", ")", "for", "option", "in", "parse_options", "(", "options", ",", "available_options", ")", ":", "command", ".", "append", "(", "option", ")", "command", ".", "append", "(", "\"-r {0}\"", ".", "format", "(", "requirements", ")", ")", "if", "constraints", ":", "command", ".", "append", "(", "\"-c {0}\"", ".", "format", "(", "constraints", ")", ")", "log", "(", "\"Installing from file: {} with constraints {} \"", "\"and options: {}\"", ".", "format", "(", "requirements", ",", "constraints", ",", "command", ")", ")", "else", ":", "log", "(", "\"Installing from file: {} with options: {}\"", ".", "format", "(", "requirements", ",", "command", ")", ")", "pip_execute", "(", "command", ")" ]
Install a requirements file. :param constraints: Path to pip constraints file. http://pip.readthedocs.org/en/stable/user_guide/#constraints-files
[ "Install", "a", "requirements", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L62-L82
train
juju/charm-helpers
charmhelpers/fetch/python/packages.py
pip_install
def pip_install(package, fatal=False, upgrade=False, venv=None, constraints=None, **options): """Install a python package""" if venv: venv_python = os.path.join(venv, 'bin/pip') command = [venv_python, "install"] else: command = ["install"] available_options = ('proxy', 'src', 'log', 'index-url', ) for option in parse_options(options, available_options): command.append(option) if upgrade: command.append('--upgrade') if constraints: command.extend(['-c', constraints]) if isinstance(package, list): command.extend(package) else: command.append(package) log("Installing {} package with options: {}".format(package, command)) if venv: subprocess.check_call(command) else: pip_execute(command)
python
def pip_install(package, fatal=False, upgrade=False, venv=None, constraints=None, **options): """Install a python package""" if venv: venv_python = os.path.join(venv, 'bin/pip') command = [venv_python, "install"] else: command = ["install"] available_options = ('proxy', 'src', 'log', 'index-url', ) for option in parse_options(options, available_options): command.append(option) if upgrade: command.append('--upgrade') if constraints: command.extend(['-c', constraints]) if isinstance(package, list): command.extend(package) else: command.append(package) log("Installing {} package with options: {}".format(package, command)) if venv: subprocess.check_call(command) else: pip_execute(command)
[ "def", "pip_install", "(", "package", ",", "fatal", "=", "False", ",", "upgrade", "=", "False", ",", "venv", "=", "None", ",", "constraints", "=", "None", ",", "*", "*", "options", ")", ":", "if", "venv", ":", "venv_python", "=", "os", ".", "path", ".", "join", "(", "venv", ",", "'bin/pip'", ")", "command", "=", "[", "venv_python", ",", "\"install\"", "]", "else", ":", "command", "=", "[", "\"install\"", "]", "available_options", "=", "(", "'proxy'", ",", "'src'", ",", "'log'", ",", "'index-url'", ",", ")", "for", "option", "in", "parse_options", "(", "options", ",", "available_options", ")", ":", "command", ".", "append", "(", "option", ")", "if", "upgrade", ":", "command", ".", "append", "(", "'--upgrade'", ")", "if", "constraints", ":", "command", ".", "extend", "(", "[", "'-c'", ",", "constraints", "]", ")", "if", "isinstance", "(", "package", ",", "list", ")", ":", "command", ".", "extend", "(", "package", ")", "else", ":", "command", ".", "append", "(", "package", ")", "log", "(", "\"Installing {} package with options: {}\"", ".", "format", "(", "package", ",", "command", ")", ")", "if", "venv", ":", "subprocess", ".", "check_call", "(", "command", ")", "else", ":", "pip_execute", "(", "command", ")" ]
Install a python package
[ "Install", "a", "python", "package" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L85-L114
train
juju/charm-helpers
charmhelpers/fetch/python/packages.py
pip_uninstall
def pip_uninstall(package, **options): """Uninstall a python package""" command = ["uninstall", "-q", "-y"] available_options = ('proxy', 'log', ) for option in parse_options(options, available_options): command.append(option) if isinstance(package, list): command.extend(package) else: command.append(package) log("Uninstalling {} package with options: {}".format(package, command)) pip_execute(command)
python
def pip_uninstall(package, **options): """Uninstall a python package""" command = ["uninstall", "-q", "-y"] available_options = ('proxy', 'log', ) for option in parse_options(options, available_options): command.append(option) if isinstance(package, list): command.extend(package) else: command.append(package) log("Uninstalling {} package with options: {}".format(package, command)) pip_execute(command)
[ "def", "pip_uninstall", "(", "package", ",", "*", "*", "options", ")", ":", "command", "=", "[", "\"uninstall\"", ",", "\"-q\"", ",", "\"-y\"", "]", "available_options", "=", "(", "'proxy'", ",", "'log'", ",", ")", "for", "option", "in", "parse_options", "(", "options", ",", "available_options", ")", ":", "command", ".", "append", "(", "option", ")", "if", "isinstance", "(", "package", ",", "list", ")", ":", "command", ".", "extend", "(", "package", ")", "else", ":", "command", ".", "append", "(", "package", ")", "log", "(", "\"Uninstalling {} package with options: {}\"", ".", "format", "(", "package", ",", "command", ")", ")", "pip_execute", "(", "command", ")" ]
Uninstall a python package
[ "Uninstall", "a", "python", "package" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L117-L132
train
juju/charm-helpers
charmhelpers/fetch/python/packages.py
pip_create_virtualenv
def pip_create_virtualenv(path=None): """Create an isolated Python environment.""" if six.PY2: apt_install('python-virtualenv') else: apt_install('python3-virtualenv') if path: venv_path = path else: venv_path = os.path.join(charm_dir(), 'venv') if not os.path.exists(venv_path): subprocess.check_call(['virtualenv', venv_path])
python
def pip_create_virtualenv(path=None): """Create an isolated Python environment.""" if six.PY2: apt_install('python-virtualenv') else: apt_install('python3-virtualenv') if path: venv_path = path else: venv_path = os.path.join(charm_dir(), 'venv') if not os.path.exists(venv_path): subprocess.check_call(['virtualenv', venv_path])
[ "def", "pip_create_virtualenv", "(", "path", "=", "None", ")", ":", "if", "six", ".", "PY2", ":", "apt_install", "(", "'python-virtualenv'", ")", "else", ":", "apt_install", "(", "'python3-virtualenv'", ")", "if", "path", ":", "venv_path", "=", "path", "else", ":", "venv_path", "=", "os", ".", "path", ".", "join", "(", "charm_dir", "(", ")", ",", "'venv'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "venv_path", ")", ":", "subprocess", ".", "check_call", "(", "[", "'virtualenv'", ",", "venv_path", "]", ")" ]
Create an isolated Python environment.
[ "Create", "an", "isolated", "Python", "environment", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L141-L154
train
juju/charm-helpers
charmhelpers/fetch/__init__.py
configure_sources
def configure_sources(update=False, sources_var='install_sources', keys_var='install_keys'): """Configure multiple sources from charm configuration. The lists are encoded as yaml fragments in the configuration. The fragment needs to be included as a string. Sources and their corresponding keys are of the types supported by add_source(). Example config: install_sources: | - "ppa:foo" - "http://example.com/repo precise main" install_keys: | - null - "a1b2c3d4" Note that 'null' (a.k.a. None) should not be quoted. """ sources = safe_load((config(sources_var) or '').strip()) or [] keys = safe_load((config(keys_var) or '').strip()) or None if isinstance(sources, six.string_types): sources = [sources] if keys is None: for source in sources: add_source(source, None) else: if isinstance(keys, six.string_types): keys = [keys] if len(sources) != len(keys): raise SourceConfigError( 'Install sources and keys lists are different lengths') for source, key in zip(sources, keys): add_source(source, key) if update: _fetch_update(fatal=True)
python
def configure_sources(update=False, sources_var='install_sources', keys_var='install_keys'): """Configure multiple sources from charm configuration. The lists are encoded as yaml fragments in the configuration. The fragment needs to be included as a string. Sources and their corresponding keys are of the types supported by add_source(). Example config: install_sources: | - "ppa:foo" - "http://example.com/repo precise main" install_keys: | - null - "a1b2c3d4" Note that 'null' (a.k.a. None) should not be quoted. """ sources = safe_load((config(sources_var) or '').strip()) or [] keys = safe_load((config(keys_var) or '').strip()) or None if isinstance(sources, six.string_types): sources = [sources] if keys is None: for source in sources: add_source(source, None) else: if isinstance(keys, six.string_types): keys = [keys] if len(sources) != len(keys): raise SourceConfigError( 'Install sources and keys lists are different lengths') for source, key in zip(sources, keys): add_source(source, key) if update: _fetch_update(fatal=True)
[ "def", "configure_sources", "(", "update", "=", "False", ",", "sources_var", "=", "'install_sources'", ",", "keys_var", "=", "'install_keys'", ")", ":", "sources", "=", "safe_load", "(", "(", "config", "(", "sources_var", ")", "or", "''", ")", ".", "strip", "(", ")", ")", "or", "[", "]", "keys", "=", "safe_load", "(", "(", "config", "(", "keys_var", ")", "or", "''", ")", ".", "strip", "(", ")", ")", "or", "None", "if", "isinstance", "(", "sources", ",", "six", ".", "string_types", ")", ":", "sources", "=", "[", "sources", "]", "if", "keys", "is", "None", ":", "for", "source", "in", "sources", ":", "add_source", "(", "source", ",", "None", ")", "else", ":", "if", "isinstance", "(", "keys", ",", "six", ".", "string_types", ")", ":", "keys", "=", "[", "keys", "]", "if", "len", "(", "sources", ")", "!=", "len", "(", "keys", ")", ":", "raise", "SourceConfigError", "(", "'Install sources and keys lists are different lengths'", ")", "for", "source", ",", "key", "in", "zip", "(", "sources", ",", "keys", ")", ":", "add_source", "(", "source", ",", "key", ")", "if", "update", ":", "_fetch_update", "(", "fatal", "=", "True", ")" ]
Configure multiple sources from charm configuration. The lists are encoded as yaml fragments in the configuration. The fragment needs to be included as a string. Sources and their corresponding keys are of the types supported by add_source(). Example config: install_sources: | - "ppa:foo" - "http://example.com/repo precise main" install_keys: | - null - "a1b2c3d4" Note that 'null' (a.k.a. None) should not be quoted.
[ "Configure", "multiple", "sources", "from", "charm", "configuration", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/__init__.py#L110-L148
train
juju/charm-helpers
charmhelpers/fetch/__init__.py
install_remote
def install_remote(source, *args, **kwargs): """Install a file tree from a remote source. The specified source should be a url of the form: scheme://[host]/path[#[option=value][&...]] Schemes supported are based on this modules submodules. Options supported are submodule-specific. Additional arguments are passed through to the submodule. For example:: dest = install_remote('http://example.com/archive.tgz', checksum='deadbeef', hash_type='sha1') This will download `archive.tgz`, validate it using SHA1 and, if the file is ok, extract it and return the directory in which it was extracted. If the checksum fails, it will raise :class:`charmhelpers.core.host.ChecksumError`. """ # We ONLY check for True here because can_handle may return a string # explaining why it can't handle a given source. handlers = [h for h in plugins() if h.can_handle(source) is True] for handler in handlers: try: return handler.install(source, *args, **kwargs) except UnhandledSource as e: log('Install source attempt unsuccessful: {}'.format(e), level='WARNING') raise UnhandledSource("No handler found for source {}".format(source))
python
def install_remote(source, *args, **kwargs): """Install a file tree from a remote source. The specified source should be a url of the form: scheme://[host]/path[#[option=value][&...]] Schemes supported are based on this modules submodules. Options supported are submodule-specific. Additional arguments are passed through to the submodule. For example:: dest = install_remote('http://example.com/archive.tgz', checksum='deadbeef', hash_type='sha1') This will download `archive.tgz`, validate it using SHA1 and, if the file is ok, extract it and return the directory in which it was extracted. If the checksum fails, it will raise :class:`charmhelpers.core.host.ChecksumError`. """ # We ONLY check for True here because can_handle may return a string # explaining why it can't handle a given source. handlers = [h for h in plugins() if h.can_handle(source) is True] for handler in handlers: try: return handler.install(source, *args, **kwargs) except UnhandledSource as e: log('Install source attempt unsuccessful: {}'.format(e), level='WARNING') raise UnhandledSource("No handler found for source {}".format(source))
[ "def", "install_remote", "(", "source", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# We ONLY check for True here because can_handle may return a string", "# explaining why it can't handle a given source.", "handlers", "=", "[", "h", "for", "h", "in", "plugins", "(", ")", "if", "h", ".", "can_handle", "(", "source", ")", "is", "True", "]", "for", "handler", "in", "handlers", ":", "try", ":", "return", "handler", ".", "install", "(", "source", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "UnhandledSource", "as", "e", ":", "log", "(", "'Install source attempt unsuccessful: {}'", ".", "format", "(", "e", ")", ",", "level", "=", "'WARNING'", ")", "raise", "UnhandledSource", "(", "\"No handler found for source {}\"", ".", "format", "(", "source", ")", ")" ]
Install a file tree from a remote source. The specified source should be a url of the form: scheme://[host]/path[#[option=value][&...]] Schemes supported are based on this modules submodules. Options supported are submodule-specific. Additional arguments are passed through to the submodule. For example:: dest = install_remote('http://example.com/archive.tgz', checksum='deadbeef', hash_type='sha1') This will download `archive.tgz`, validate it using SHA1 and, if the file is ok, extract it and return the directory in which it was extracted. If the checksum fails, it will raise :class:`charmhelpers.core.host.ChecksumError`.
[ "Install", "a", "file", "tree", "from", "a", "remote", "source", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/__init__.py#L151-L181
train
juju/charm-helpers
charmhelpers/fetch/__init__.py
BaseFetchHandler.base_url
def base_url(self, url): """Return url without querystring or fragment""" parts = list(self.parse_url(url)) parts[4:] = ['' for i in parts[4:]] return urlunparse(parts)
python
def base_url(self, url): """Return url without querystring or fragment""" parts = list(self.parse_url(url)) parts[4:] = ['' for i in parts[4:]] return urlunparse(parts)
[ "def", "base_url", "(", "self", ",", "url", ")", ":", "parts", "=", "list", "(", "self", ".", "parse_url", "(", "url", ")", ")", "parts", "[", "4", ":", "]", "=", "[", "''", "for", "i", "in", "parts", "[", "4", ":", "]", "]", "return", "urlunparse", "(", "parts", ")" ]
Return url without querystring or fragment
[ "Return", "url", "without", "querystring", "or", "fragment" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/__init__.py#L75-L79
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/utils.py
is_block_device
def is_block_device(path): ''' Confirm device at path is a valid block device node. :returns: boolean: True if path is a block device, False if not. ''' if not os.path.exists(path): return False return S_ISBLK(os.stat(path).st_mode)
python
def is_block_device(path): ''' Confirm device at path is a valid block device node. :returns: boolean: True if path is a block device, False if not. ''' if not os.path.exists(path): return False return S_ISBLK(os.stat(path).st_mode)
[ "def", "is_block_device", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "False", "return", "S_ISBLK", "(", "os", ".", "stat", "(", "path", ")", ".", "st_mode", ")" ]
Confirm device at path is a valid block device node. :returns: boolean: True if path is a block device, False if not.
[ "Confirm", "device", "at", "path", "is", "a", "valid", "block", "device", "node", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/utils.py#L67-L75
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/utils.py
zap_disk
def zap_disk(block_device): ''' Clear a block device of partition table. Relies on sgdisk, which is installed as pat of the 'gdisk' package in Ubuntu. :param block_device: str: Full path of block device to clean. ''' # https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b # sometimes sgdisk exits non-zero; this is OK, dd will clean up call(['sgdisk', '--zap-all', '--', block_device]) call(['sgdisk', '--clear', '--mbrtogpt', '--', block_device]) dev_end = check_output(['blockdev', '--getsz', block_device]).decode('UTF-8') gpt_end = int(dev_end.split()[0]) - 100 check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device), 'bs=1M', 'count=1']) check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device), 'bs=512', 'count=100', 'seek=%s' % (gpt_end)])
python
def zap_disk(block_device): ''' Clear a block device of partition table. Relies on sgdisk, which is installed as pat of the 'gdisk' package in Ubuntu. :param block_device: str: Full path of block device to clean. ''' # https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b # sometimes sgdisk exits non-zero; this is OK, dd will clean up call(['sgdisk', '--zap-all', '--', block_device]) call(['sgdisk', '--clear', '--mbrtogpt', '--', block_device]) dev_end = check_output(['blockdev', '--getsz', block_device]).decode('UTF-8') gpt_end = int(dev_end.split()[0]) - 100 check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device), 'bs=1M', 'count=1']) check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device), 'bs=512', 'count=100', 'seek=%s' % (gpt_end)])
[ "def", "zap_disk", "(", "block_device", ")", ":", "# https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b", "# sometimes sgdisk exits non-zero; this is OK, dd will clean up", "call", "(", "[", "'sgdisk'", ",", "'--zap-all'", ",", "'--'", ",", "block_device", "]", ")", "call", "(", "[", "'sgdisk'", ",", "'--clear'", ",", "'--mbrtogpt'", ",", "'--'", ",", "block_device", "]", ")", "dev_end", "=", "check_output", "(", "[", "'blockdev'", ",", "'--getsz'", ",", "block_device", "]", ")", ".", "decode", "(", "'UTF-8'", ")", "gpt_end", "=", "int", "(", "dev_end", ".", "split", "(", ")", "[", "0", "]", ")", "-", "100", "check_call", "(", "[", "'dd'", ",", "'if=/dev/zero'", ",", "'of=%s'", "%", "(", "block_device", ")", ",", "'bs=1M'", ",", "'count=1'", "]", ")", "check_call", "(", "[", "'dd'", ",", "'if=/dev/zero'", ",", "'of=%s'", "%", "(", "block_device", ")", ",", "'bs=512'", ",", "'count=100'", ",", "'seek=%s'", "%", "(", "gpt_end", ")", "]", ")" ]
Clear a block device of partition table. Relies on sgdisk, which is installed as pat of the 'gdisk' package in Ubuntu. :param block_device: str: Full path of block device to clean.
[ "Clear", "a", "block", "device", "of", "partition", "table", ".", "Relies", "on", "sgdisk", "which", "is", "installed", "as", "pat", "of", "the", "gdisk", "package", "in", "Ubuntu", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/utils.py#L78-L95
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/utils.py
is_device_mounted
def is_device_mounted(device): '''Given a device path, return True if that device is mounted, and False if it isn't. :param device: str: Full path of the device to check. :returns: boolean: True if the path represents a mounted device, False if it doesn't. ''' try: out = check_output(['lsblk', '-P', device]).decode('UTF-8') except Exception: return False return bool(re.search(r'MOUNTPOINT=".+"', out))
python
def is_device_mounted(device): '''Given a device path, return True if that device is mounted, and False if it isn't. :param device: str: Full path of the device to check. :returns: boolean: True if the path represents a mounted device, False if it doesn't. ''' try: out = check_output(['lsblk', '-P', device]).decode('UTF-8') except Exception: return False return bool(re.search(r'MOUNTPOINT=".+"', out))
[ "def", "is_device_mounted", "(", "device", ")", ":", "try", ":", "out", "=", "check_output", "(", "[", "'lsblk'", ",", "'-P'", ",", "device", "]", ")", ".", "decode", "(", "'UTF-8'", ")", "except", "Exception", ":", "return", "False", "return", "bool", "(", "re", ".", "search", "(", "r'MOUNTPOINT=\".+\"'", ",", "out", ")", ")" ]
Given a device path, return True if that device is mounted, and False if it isn't. :param device: str: Full path of the device to check. :returns: boolean: True if the path represents a mounted device, False if it doesn't.
[ "Given", "a", "device", "path", "return", "True", "if", "that", "device", "is", "mounted", "and", "False", "if", "it", "isn", "t", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/utils.py#L98-L110
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/utils.py
mkfs_xfs
def mkfs_xfs(device, force=False): """Format device with XFS filesystem. By default this should fail if the device already has a filesystem on it. :param device: Full path to device to format :ptype device: tr :param force: Force operation :ptype: force: boolean""" cmd = ['mkfs.xfs'] if force: cmd.append("-f") cmd += ['-i', 'size=1024', device] check_call(cmd)
python
def mkfs_xfs(device, force=False): """Format device with XFS filesystem. By default this should fail if the device already has a filesystem on it. :param device: Full path to device to format :ptype device: tr :param force: Force operation :ptype: force: boolean""" cmd = ['mkfs.xfs'] if force: cmd.append("-f") cmd += ['-i', 'size=1024', device] check_call(cmd)
[ "def", "mkfs_xfs", "(", "device", ",", "force", "=", "False", ")", ":", "cmd", "=", "[", "'mkfs.xfs'", "]", "if", "force", ":", "cmd", ".", "append", "(", "\"-f\"", ")", "cmd", "+=", "[", "'-i'", ",", "'size=1024'", ",", "device", "]", "check_call", "(", "cmd", ")" ]
Format device with XFS filesystem. By default this should fail if the device already has a filesystem on it. :param device: Full path to device to format :ptype device: tr :param force: Force operation :ptype: force: boolean
[ "Format", "device", "with", "XFS", "filesystem", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/utils.py#L113-L126
train
juju/charm-helpers
charmhelpers/contrib/charmhelpers/__init__.py
wait_for_machine
def wait_for_machine(num_machines=1, timeout=300): """Wait `timeout` seconds for `num_machines` machines to come up. This wait_for... function can be called by other wait_for functions whose timeouts might be too short in situations where only a bare Juju setup has been bootstrapped. :return: A tuple of (num_machines, time_taken). This is used for testing. """ # You may think this is a hack, and you'd be right. The easiest way # to tell what environment we're working in (LXC vs EC2) is to check # the dns-name of the first machine. If it's localhost we're in LXC # and we can just return here. if get_machine_data()[0]['dns-name'] == 'localhost': return 1, 0 start_time = time.time() while True: # Drop the first machine, since it's the Zookeeper and that's # not a machine that we need to wait for. This will only work # for EC2 environments, which is why we return early above if # we're in LXC. machine_data = get_machine_data() non_zookeeper_machines = [ machine_data[key] for key in list(machine_data.keys())[1:]] if len(non_zookeeper_machines) >= num_machines: all_machines_running = True for machine in non_zookeeper_machines: if machine.get('instance-state') != 'running': all_machines_running = False break if all_machines_running: break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for service to start') time.sleep(SLEEP_AMOUNT) return num_machines, time.time() - start_time
python
def wait_for_machine(num_machines=1, timeout=300): """Wait `timeout` seconds for `num_machines` machines to come up. This wait_for... function can be called by other wait_for functions whose timeouts might be too short in situations where only a bare Juju setup has been bootstrapped. :return: A tuple of (num_machines, time_taken). This is used for testing. """ # You may think this is a hack, and you'd be right. The easiest way # to tell what environment we're working in (LXC vs EC2) is to check # the dns-name of the first machine. If it's localhost we're in LXC # and we can just return here. if get_machine_data()[0]['dns-name'] == 'localhost': return 1, 0 start_time = time.time() while True: # Drop the first machine, since it's the Zookeeper and that's # not a machine that we need to wait for. This will only work # for EC2 environments, which is why we return early above if # we're in LXC. machine_data = get_machine_data() non_zookeeper_machines = [ machine_data[key] for key in list(machine_data.keys())[1:]] if len(non_zookeeper_machines) >= num_machines: all_machines_running = True for machine in non_zookeeper_machines: if machine.get('instance-state') != 'running': all_machines_running = False break if all_machines_running: break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for service to start') time.sleep(SLEEP_AMOUNT) return num_machines, time.time() - start_time
[ "def", "wait_for_machine", "(", "num_machines", "=", "1", ",", "timeout", "=", "300", ")", ":", "# You may think this is a hack, and you'd be right. The easiest way", "# to tell what environment we're working in (LXC vs EC2) is to check", "# the dns-name of the first machine. If it's localhost we're in LXC", "# and we can just return here.", "if", "get_machine_data", "(", ")", "[", "0", "]", "[", "'dns-name'", "]", "==", "'localhost'", ":", "return", "1", ",", "0", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "# Drop the first machine, since it's the Zookeeper and that's", "# not a machine that we need to wait for. This will only work", "# for EC2 environments, which is why we return early above if", "# we're in LXC.", "machine_data", "=", "get_machine_data", "(", ")", "non_zookeeper_machines", "=", "[", "machine_data", "[", "key", "]", "for", "key", "in", "list", "(", "machine_data", ".", "keys", "(", ")", ")", "[", "1", ":", "]", "]", "if", "len", "(", "non_zookeeper_machines", ")", ">=", "num_machines", ":", "all_machines_running", "=", "True", "for", "machine", "in", "non_zookeeper_machines", ":", "if", "machine", ".", "get", "(", "'instance-state'", ")", "!=", "'running'", ":", "all_machines_running", "=", "False", "break", "if", "all_machines_running", ":", "break", "if", "time", ".", "time", "(", ")", "-", "start_time", ">=", "timeout", ":", "raise", "RuntimeError", "(", "'timeout waiting for service to start'", ")", "time", ".", "sleep", "(", "SLEEP_AMOUNT", ")", "return", "num_machines", ",", "time", ".", "time", "(", ")", "-", "start_time" ]
Wait `timeout` seconds for `num_machines` machines to come up. This wait_for... function can be called by other wait_for functions whose timeouts might be too short in situations where only a bare Juju setup has been bootstrapped. :return: A tuple of (num_machines, time_taken). This is used for testing.
[ "Wait", "timeout", "seconds", "for", "num_machines", "machines", "to", "come", "up", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmhelpers/__init__.py#L119-L155
train
juju/charm-helpers
charmhelpers/contrib/charmhelpers/__init__.py
wait_for_unit
def wait_for_unit(service_name, timeout=480): """Wait `timeout` seconds for a given service name to come up.""" wait_for_machine(num_machines=1) start_time = time.time() while True: state = unit_info(service_name, 'agent-state') if 'error' in state or state == 'started': break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for service to start') time.sleep(SLEEP_AMOUNT) if state != 'started': raise RuntimeError('unit did not start, agent-state: ' + state)
python
def wait_for_unit(service_name, timeout=480): """Wait `timeout` seconds for a given service name to come up.""" wait_for_machine(num_machines=1) start_time = time.time() while True: state = unit_info(service_name, 'agent-state') if 'error' in state or state == 'started': break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for service to start') time.sleep(SLEEP_AMOUNT) if state != 'started': raise RuntimeError('unit did not start, agent-state: ' + state)
[ "def", "wait_for_unit", "(", "service_name", ",", "timeout", "=", "480", ")", ":", "wait_for_machine", "(", "num_machines", "=", "1", ")", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "state", "=", "unit_info", "(", "service_name", ",", "'agent-state'", ")", "if", "'error'", "in", "state", "or", "state", "==", "'started'", ":", "break", "if", "time", ".", "time", "(", ")", "-", "start_time", ">=", "timeout", ":", "raise", "RuntimeError", "(", "'timeout waiting for service to start'", ")", "time", ".", "sleep", "(", "SLEEP_AMOUNT", ")", "if", "state", "!=", "'started'", ":", "raise", "RuntimeError", "(", "'unit did not start, agent-state: '", "+", "state", ")" ]
Wait `timeout` seconds for a given service name to come up.
[ "Wait", "timeout", "seconds", "for", "a", "given", "service", "name", "to", "come", "up", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmhelpers/__init__.py#L159-L171
train
juju/charm-helpers
charmhelpers/contrib/charmhelpers/__init__.py
wait_for_relation
def wait_for_relation(service_name, relation_name, timeout=120): """Wait `timeout` seconds for a given relation to come up.""" start_time = time.time() while True: relation = unit_info(service_name, 'relations').get(relation_name) if relation is not None and relation['state'] == 'up': break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for relation to be up') time.sleep(SLEEP_AMOUNT)
python
def wait_for_relation(service_name, relation_name, timeout=120): """Wait `timeout` seconds for a given relation to come up.""" start_time = time.time() while True: relation = unit_info(service_name, 'relations').get(relation_name) if relation is not None and relation['state'] == 'up': break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for relation to be up') time.sleep(SLEEP_AMOUNT)
[ "def", "wait_for_relation", "(", "service_name", ",", "relation_name", ",", "timeout", "=", "120", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "relation", "=", "unit_info", "(", "service_name", ",", "'relations'", ")", ".", "get", "(", "relation_name", ")", "if", "relation", "is", "not", "None", "and", "relation", "[", "'state'", "]", "==", "'up'", ":", "break", "if", "time", ".", "time", "(", ")", "-", "start_time", ">=", "timeout", ":", "raise", "RuntimeError", "(", "'timeout waiting for relation to be up'", ")", "time", ".", "sleep", "(", "SLEEP_AMOUNT", ")" ]
Wait `timeout` seconds for a given relation to come up.
[ "Wait", "timeout", "seconds", "for", "a", "given", "relation", "to", "come", "up", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmhelpers/__init__.py#L175-L184
train
juju/charm-helpers
charmhelpers/core/host_factory/ubuntu.py
service_available
def service_available(service_name): """Determine whether a system service is available""" try: subprocess.check_output( ['service', service_name, 'status'], stderr=subprocess.STDOUT).decode('UTF-8') except subprocess.CalledProcessError as e: return b'unrecognized service' not in e.output else: return True
python
def service_available(service_name): """Determine whether a system service is available""" try: subprocess.check_output( ['service', service_name, 'status'], stderr=subprocess.STDOUT).decode('UTF-8') except subprocess.CalledProcessError as e: return b'unrecognized service' not in e.output else: return True
[ "def", "service_available", "(", "service_name", ")", ":", "try", ":", "subprocess", ".", "check_output", "(", "[", "'service'", ",", "service_name", ",", "'status'", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ".", "decode", "(", "'UTF-8'", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "return", "b'unrecognized service'", "not", "in", "e", ".", "output", "else", ":", "return", "True" ]
Determine whether a system service is available
[ "Determine", "whether", "a", "system", "service", "is", "available" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host_factory/ubuntu.py#L41-L50
train
juju/charm-helpers
charmhelpers/contrib/saltstack/__init__.py
install_salt_support
def install_salt_support(from_ppa=True): """Installs the salt-minion helper for machine state. By default the salt-minion package is installed from the saltstack PPA. If from_ppa is False you must ensure that the salt-minion package is available in the apt cache. """ if from_ppa: subprocess.check_call([ '/usr/bin/add-apt-repository', '--yes', 'ppa:saltstack/salt', ]) subprocess.check_call(['/usr/bin/apt-get', 'update']) # We install salt-common as salt-minion would run the salt-minion # daemon. charmhelpers.fetch.apt_install('salt-common')
python
def install_salt_support(from_ppa=True): """Installs the salt-minion helper for machine state. By default the salt-minion package is installed from the saltstack PPA. If from_ppa is False you must ensure that the salt-minion package is available in the apt cache. """ if from_ppa: subprocess.check_call([ '/usr/bin/add-apt-repository', '--yes', 'ppa:saltstack/salt', ]) subprocess.check_call(['/usr/bin/apt-get', 'update']) # We install salt-common as salt-minion would run the salt-minion # daemon. charmhelpers.fetch.apt_install('salt-common')
[ "def", "install_salt_support", "(", "from_ppa", "=", "True", ")", ":", "if", "from_ppa", ":", "subprocess", ".", "check_call", "(", "[", "'/usr/bin/add-apt-repository'", ",", "'--yes'", ",", "'ppa:saltstack/salt'", ",", "]", ")", "subprocess", ".", "check_call", "(", "[", "'/usr/bin/apt-get'", ",", "'update'", "]", ")", "# We install salt-common as salt-minion would run the salt-minion", "# daemon.", "charmhelpers", ".", "fetch", ".", "apt_install", "(", "'salt-common'", ")" ]
Installs the salt-minion helper for machine state. By default the salt-minion package is installed from the saltstack PPA. If from_ppa is False you must ensure that the salt-minion package is available in the apt cache.
[ "Installs", "the", "salt", "-", "minion", "helper", "for", "machine", "state", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/saltstack/__init__.py#L88-L104
train
juju/charm-helpers
charmhelpers/contrib/saltstack/__init__.py
update_machine_state
def update_machine_state(state_path): """Update the machine state using the provided state declaration.""" charmhelpers.contrib.templating.contexts.juju_state_to_yaml( salt_grains_path) subprocess.check_call([ 'salt-call', '--local', 'state.template', state_path, ])
python
def update_machine_state(state_path): """Update the machine state using the provided state declaration.""" charmhelpers.contrib.templating.contexts.juju_state_to_yaml( salt_grains_path) subprocess.check_call([ 'salt-call', '--local', 'state.template', state_path, ])
[ "def", "update_machine_state", "(", "state_path", ")", ":", "charmhelpers", ".", "contrib", ".", "templating", ".", "contexts", ".", "juju_state_to_yaml", "(", "salt_grains_path", ")", "subprocess", ".", "check_call", "(", "[", "'salt-call'", ",", "'--local'", ",", "'state.template'", ",", "state_path", ",", "]", ")" ]
Update the machine state using the provided state declaration.
[ "Update", "the", "machine", "state", "using", "the", "provided", "state", "declaration", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/saltstack/__init__.py#L107-L116
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
pool_exists
def pool_exists(service, name): """Check to see if a RADOS pool already exists.""" try: out = check_output(['rados', '--id', service, 'lspools']) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return name in out.split()
python
def pool_exists(service, name): """Check to see if a RADOS pool already exists.""" try: out = check_output(['rados', '--id', service, 'lspools']) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return name in out.split()
[ "def", "pool_exists", "(", "service", ",", "name", ")", ":", "try", ":", "out", "=", "check_output", "(", "[", "'rados'", ",", "'--id'", ",", "service", ",", "'lspools'", "]", ")", "if", "six", ".", "PY3", ":", "out", "=", "out", ".", "decode", "(", "'UTF-8'", ")", "except", "CalledProcessError", ":", "return", "False", "return", "name", "in", "out", ".", "split", "(", ")" ]
Check to see if a RADOS pool already exists.
[ "Check", "to", "see", "if", "a", "RADOS", "pool", "already", "exists", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L753-L762
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
install
def install(): """Basic Ceph client installation.""" ceph_dir = "/etc/ceph" if not os.path.exists(ceph_dir): os.mkdir(ceph_dir) apt_install('ceph-common', fatal=True)
python
def install(): """Basic Ceph client installation.""" ceph_dir = "/etc/ceph" if not os.path.exists(ceph_dir): os.mkdir(ceph_dir) apt_install('ceph-common', fatal=True)
[ "def", "install", "(", ")", ":", "ceph_dir", "=", "\"/etc/ceph\"", "if", "not", "os", ".", "path", ".", "exists", "(", "ceph_dir", ")", ":", "os", ".", "mkdir", "(", "ceph_dir", ")", "apt_install", "(", "'ceph-common'", ",", "fatal", "=", "True", ")" ]
Basic Ceph client installation.
[ "Basic", "Ceph", "client", "installation", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L787-L793
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
rbd_exists
def rbd_exists(service, pool, rbd_img): """Check to see if a RADOS block device exists.""" try: out = check_output(['rbd', 'list', '--id', service, '--pool', pool]) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return rbd_img in out
python
def rbd_exists(service, pool, rbd_img): """Check to see if a RADOS block device exists.""" try: out = check_output(['rbd', 'list', '--id', service, '--pool', pool]) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return rbd_img in out
[ "def", "rbd_exists", "(", "service", ",", "pool", ",", "rbd_img", ")", ":", "try", ":", "out", "=", "check_output", "(", "[", "'rbd'", ",", "'list'", ",", "'--id'", ",", "service", ",", "'--pool'", ",", "pool", "]", ")", "if", "six", ".", "PY3", ":", "out", "=", "out", ".", "decode", "(", "'UTF-8'", ")", "except", "CalledProcessError", ":", "return", "False", "return", "rbd_img", "in", "out" ]
Check to see if a RADOS block device exists.
[ "Check", "to", "see", "if", "a", "RADOS", "block", "device", "exists", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L796-L806
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
create_rbd_image
def create_rbd_image(service, pool, image, sizemb): """Create a new RADOS block device.""" cmd = ['rbd', 'create', image, '--size', str(sizemb), '--id', service, '--pool', pool] check_call(cmd)
python
def create_rbd_image(service, pool, image, sizemb): """Create a new RADOS block device.""" cmd = ['rbd', 'create', image, '--size', str(sizemb), '--id', service, '--pool', pool] check_call(cmd)
[ "def", "create_rbd_image", "(", "service", ",", "pool", ",", "image", ",", "sizemb", ")", ":", "cmd", "=", "[", "'rbd'", ",", "'create'", ",", "image", ",", "'--size'", ",", "str", "(", "sizemb", ")", ",", "'--id'", ",", "service", ",", "'--pool'", ",", "pool", "]", "check_call", "(", "cmd", ")" ]
Create a new RADOS block device.
[ "Create", "a", "new", "RADOS", "block", "device", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L809-L813
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
set_app_name_for_pool
def set_app_name_for_pool(client, pool, name): """ Calls `osd pool application enable` for the specified pool name :param client: Name of the ceph client to use :type client: str :param pool: Pool to set app name for :type pool: str :param name: app name for the specified pool :type name: str :raises: CalledProcessError if ceph call fails """ if cmp_pkgrevno('ceph-common', '12.0.0') >= 0: cmd = ['ceph', '--id', client, 'osd', 'pool', 'application', 'enable', pool, name] check_call(cmd)
python
def set_app_name_for_pool(client, pool, name): """ Calls `osd pool application enable` for the specified pool name :param client: Name of the ceph client to use :type client: str :param pool: Pool to set app name for :type pool: str :param name: app name for the specified pool :type name: str :raises: CalledProcessError if ceph call fails """ if cmp_pkgrevno('ceph-common', '12.0.0') >= 0: cmd = ['ceph', '--id', client, 'osd', 'pool', 'application', 'enable', pool, name] check_call(cmd)
[ "def", "set_app_name_for_pool", "(", "client", ",", "pool", ",", "name", ")", ":", "if", "cmp_pkgrevno", "(", "'ceph-common'", ",", "'12.0.0'", ")", ">=", "0", ":", "cmd", "=", "[", "'ceph'", ",", "'--id'", ",", "client", ",", "'osd'", ",", "'pool'", ",", "'application'", ",", "'enable'", ",", "pool", ",", "name", "]", "check_call", "(", "cmd", ")" ]
Calls `osd pool application enable` for the specified pool name :param client: Name of the ceph client to use :type client: str :param pool: Pool to set app name for :type pool: str :param name: app name for the specified pool :type name: str :raises: CalledProcessError if ceph call fails
[ "Calls", "osd", "pool", "application", "enable", "for", "the", "specified", "pool", "name" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L825-L841
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
create_pool
def create_pool(service, name, replicas=3, pg_num=None): """Create a new RADOS pool.""" if pool_exists(service, name): log("Ceph pool {} already exists, skipping creation".format(name), level=WARNING) return if not pg_num: # Calculate the number of placement groups based # on upstream recommended best practices. osds = get_osds(service) if osds: pg_num = (len(osds) * 100 // replicas) else: # NOTE(james-page): Default to 200 for older ceph versions # which don't support OSD query from cli pg_num = 200 cmd = ['ceph', '--id', service, 'osd', 'pool', 'create', name, str(pg_num)] check_call(cmd) update_pool(service, name, settings={'size': str(replicas)})
python
def create_pool(service, name, replicas=3, pg_num=None): """Create a new RADOS pool.""" if pool_exists(service, name): log("Ceph pool {} already exists, skipping creation".format(name), level=WARNING) return if not pg_num: # Calculate the number of placement groups based # on upstream recommended best practices. osds = get_osds(service) if osds: pg_num = (len(osds) * 100 // replicas) else: # NOTE(james-page): Default to 200 for older ceph versions # which don't support OSD query from cli pg_num = 200 cmd = ['ceph', '--id', service, 'osd', 'pool', 'create', name, str(pg_num)] check_call(cmd) update_pool(service, name, settings={'size': str(replicas)})
[ "def", "create_pool", "(", "service", ",", "name", ",", "replicas", "=", "3", ",", "pg_num", "=", "None", ")", ":", "if", "pool_exists", "(", "service", ",", "name", ")", ":", "log", "(", "\"Ceph pool {} already exists, skipping creation\"", ".", "format", "(", "name", ")", ",", "level", "=", "WARNING", ")", "return", "if", "not", "pg_num", ":", "# Calculate the number of placement groups based", "# on upstream recommended best practices.", "osds", "=", "get_osds", "(", "service", ")", "if", "osds", ":", "pg_num", "=", "(", "len", "(", "osds", ")", "*", "100", "//", "replicas", ")", "else", ":", "# NOTE(james-page): Default to 200 for older ceph versions", "# which don't support OSD query from cli", "pg_num", "=", "200", "cmd", "=", "[", "'ceph'", ",", "'--id'", ",", "service", ",", "'osd'", ",", "'pool'", ",", "'create'", ",", "name", ",", "str", "(", "pg_num", ")", "]", "check_call", "(", "cmd", ")", "update_pool", "(", "service", ",", "name", ",", "settings", "=", "{", "'size'", ":", "str", "(", "replicas", ")", "}", ")" ]
Create a new RADOS pool.
[ "Create", "a", "new", "RADOS", "pool", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L844-L865
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
add_key
def add_key(service, key): """ Add a key to a keyring. Creates the keyring if it doesn't already exist. Logs and returns if the key is already in the keyring. """ keyring = _keyring_path(service) if os.path.exists(keyring): with open(keyring, 'r') as ring: if key in ring.read(): log('Ceph keyring exists at %s and has not changed.' % keyring, level=DEBUG) return log('Updating existing keyring %s.' % keyring, level=DEBUG) cmd = ['ceph-authtool', keyring, '--create-keyring', '--name=client.{}'.format(service), '--add-key={}'.format(key)] check_call(cmd) log('Created new ceph keyring at %s.' % keyring, level=DEBUG)
python
def add_key(service, key): """ Add a key to a keyring. Creates the keyring if it doesn't already exist. Logs and returns if the key is already in the keyring. """ keyring = _keyring_path(service) if os.path.exists(keyring): with open(keyring, 'r') as ring: if key in ring.read(): log('Ceph keyring exists at %s and has not changed.' % keyring, level=DEBUG) return log('Updating existing keyring %s.' % keyring, level=DEBUG) cmd = ['ceph-authtool', keyring, '--create-keyring', '--name=client.{}'.format(service), '--add-key={}'.format(key)] check_call(cmd) log('Created new ceph keyring at %s.' % keyring, level=DEBUG)
[ "def", "add_key", "(", "service", ",", "key", ")", ":", "keyring", "=", "_keyring_path", "(", "service", ")", "if", "os", ".", "path", ".", "exists", "(", "keyring", ")", ":", "with", "open", "(", "keyring", ",", "'r'", ")", "as", "ring", ":", "if", "key", "in", "ring", ".", "read", "(", ")", ":", "log", "(", "'Ceph keyring exists at %s and has not changed.'", "%", "keyring", ",", "level", "=", "DEBUG", ")", "return", "log", "(", "'Updating existing keyring %s.'", "%", "keyring", ",", "level", "=", "DEBUG", ")", "cmd", "=", "[", "'ceph-authtool'", ",", "keyring", ",", "'--create-keyring'", ",", "'--name=client.{}'", ".", "format", "(", "service", ")", ",", "'--add-key={}'", ".", "format", "(", "key", ")", "]", "check_call", "(", "cmd", ")", "log", "(", "'Created new ceph keyring at %s.'", "%", "keyring", ",", "level", "=", "DEBUG", ")" ]
Add a key to a keyring. Creates the keyring if it doesn't already exist. Logs and returns if the key is already in the keyring.
[ "Add", "a", "key", "to", "a", "keyring", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L883-L903
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
delete_keyring
def delete_keyring(service): """Delete an existing Ceph keyring.""" keyring = _keyring_path(service) if not os.path.exists(keyring): log('Keyring does not exist at %s' % keyring, level=WARNING) return os.remove(keyring) log('Deleted ring at %s.' % keyring, level=INFO)
python
def delete_keyring(service): """Delete an existing Ceph keyring.""" keyring = _keyring_path(service) if not os.path.exists(keyring): log('Keyring does not exist at %s' % keyring, level=WARNING) return os.remove(keyring) log('Deleted ring at %s.' % keyring, level=INFO)
[ "def", "delete_keyring", "(", "service", ")", ":", "keyring", "=", "_keyring_path", "(", "service", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "keyring", ")", ":", "log", "(", "'Keyring does not exist at %s'", "%", "keyring", ",", "level", "=", "WARNING", ")", "return", "os", ".", "remove", "(", "keyring", ")", "log", "(", "'Deleted ring at %s.'", "%", "keyring", ",", "level", "=", "INFO", ")" ]
Delete an existing Ceph keyring.
[ "Delete", "an", "existing", "Ceph", "keyring", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L911-L919
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
create_key_file
def create_key_file(service, key): """Create a file containing key.""" keyfile = _keyfile_path(service) if os.path.exists(keyfile): log('Keyfile exists at %s.' % keyfile, level=WARNING) return with open(keyfile, 'w') as fd: fd.write(key) log('Created new keyfile at %s.' % keyfile, level=INFO)
python
def create_key_file(service, key): """Create a file containing key.""" keyfile = _keyfile_path(service) if os.path.exists(keyfile): log('Keyfile exists at %s.' % keyfile, level=WARNING) return with open(keyfile, 'w') as fd: fd.write(key) log('Created new keyfile at %s.' % keyfile, level=INFO)
[ "def", "create_key_file", "(", "service", ",", "key", ")", ":", "keyfile", "=", "_keyfile_path", "(", "service", ")", "if", "os", ".", "path", ".", "exists", "(", "keyfile", ")", ":", "log", "(", "'Keyfile exists at %s.'", "%", "keyfile", ",", "level", "=", "WARNING", ")", "return", "with", "open", "(", "keyfile", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "key", ")", "log", "(", "'Created new keyfile at %s.'", "%", "keyfile", ",", "level", "=", "INFO", ")" ]
Create a file containing key.
[ "Create", "a", "file", "containing", "key", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L922-L932
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
get_ceph_nodes
def get_ceph_nodes(relation='ceph'): """Query named relation to determine current nodes.""" hosts = [] for r_id in relation_ids(relation): for unit in related_units(r_id): hosts.append(relation_get('private-address', unit=unit, rid=r_id)) return hosts
python
def get_ceph_nodes(relation='ceph'): """Query named relation to determine current nodes.""" hosts = [] for r_id in relation_ids(relation): for unit in related_units(r_id): hosts.append(relation_get('private-address', unit=unit, rid=r_id)) return hosts
[ "def", "get_ceph_nodes", "(", "relation", "=", "'ceph'", ")", ":", "hosts", "=", "[", "]", "for", "r_id", "in", "relation_ids", "(", "relation", ")", ":", "for", "unit", "in", "related_units", "(", "r_id", ")", ":", "hosts", ".", "append", "(", "relation_get", "(", "'private-address'", ",", "unit", "=", "unit", ",", "rid", "=", "r_id", ")", ")", "return", "hosts" ]
Query named relation to determine current nodes.
[ "Query", "named", "relation", "to", "determine", "current", "nodes", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L935-L942
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
configure
def configure(service, key, auth, use_syslog): """Perform basic configuration of Ceph.""" add_key(service, key) create_key_file(service, key) hosts = get_ceph_nodes() with open('/etc/ceph/ceph.conf', 'w') as ceph_conf: ceph_conf.write(CEPH_CONF.format(auth=auth, keyring=_keyring_path(service), mon_hosts=",".join(map(str, hosts)), use_syslog=use_syslog)) modprobe('rbd')
python
def configure(service, key, auth, use_syslog): """Perform basic configuration of Ceph.""" add_key(service, key) create_key_file(service, key) hosts = get_ceph_nodes() with open('/etc/ceph/ceph.conf', 'w') as ceph_conf: ceph_conf.write(CEPH_CONF.format(auth=auth, keyring=_keyring_path(service), mon_hosts=",".join(map(str, hosts)), use_syslog=use_syslog)) modprobe('rbd')
[ "def", "configure", "(", "service", ",", "key", ",", "auth", ",", "use_syslog", ")", ":", "add_key", "(", "service", ",", "key", ")", "create_key_file", "(", "service", ",", "key", ")", "hosts", "=", "get_ceph_nodes", "(", ")", "with", "open", "(", "'/etc/ceph/ceph.conf'", ",", "'w'", ")", "as", "ceph_conf", ":", "ceph_conf", ".", "write", "(", "CEPH_CONF", ".", "format", "(", "auth", "=", "auth", ",", "keyring", "=", "_keyring_path", "(", "service", ")", ",", "mon_hosts", "=", "\",\"", ".", "join", "(", "map", "(", "str", ",", "hosts", ")", ")", ",", "use_syslog", "=", "use_syslog", ")", ")", "modprobe", "(", "'rbd'", ")" ]
Perform basic configuration of Ceph.
[ "Perform", "basic", "configuration", "of", "Ceph", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L945-L955
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
image_mapped
def image_mapped(name): """Determine whether a RADOS block device is mapped locally.""" try: out = check_output(['rbd', 'showmapped']) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return name in out
python
def image_mapped(name): """Determine whether a RADOS block device is mapped locally.""" try: out = check_output(['rbd', 'showmapped']) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return name in out
[ "def", "image_mapped", "(", "name", ")", ":", "try", ":", "out", "=", "check_output", "(", "[", "'rbd'", ",", "'showmapped'", "]", ")", "if", "six", ".", "PY3", ":", "out", "=", "out", ".", "decode", "(", "'UTF-8'", ")", "except", "CalledProcessError", ":", "return", "False", "return", "name", "in", "out" ]
Determine whether a RADOS block device is mapped locally.
[ "Determine", "whether", "a", "RADOS", "block", "device", "is", "mapped", "locally", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L958-L967
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
map_block_storage
def map_block_storage(service, pool, image): """Map a RADOS block device for local use.""" cmd = [ 'rbd', 'map', '{}/{}'.format(pool, image), '--user', service, '--secret', _keyfile_path(service), ] check_call(cmd)
python
def map_block_storage(service, pool, image): """Map a RADOS block device for local use.""" cmd = [ 'rbd', 'map', '{}/{}'.format(pool, image), '--user', service, '--secret', _keyfile_path(service), ] check_call(cmd)
[ "def", "map_block_storage", "(", "service", ",", "pool", ",", "image", ")", ":", "cmd", "=", "[", "'rbd'", ",", "'map'", ",", "'{}/{}'", ".", "format", "(", "pool", ",", "image", ")", ",", "'--user'", ",", "service", ",", "'--secret'", ",", "_keyfile_path", "(", "service", ")", ",", "]", "check_call", "(", "cmd", ")" ]
Map a RADOS block device for local use.
[ "Map", "a", "RADOS", "block", "device", "for", "local", "use", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L970-L981
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
make_filesystem
def make_filesystem(blk_device, fstype='ext4', timeout=10): """Make a new filesystem on the specified block device.""" count = 0 e_noent = os.errno.ENOENT while not os.path.exists(blk_device): if count >= timeout: log('Gave up waiting on block device %s' % blk_device, level=ERROR) raise IOError(e_noent, os.strerror(e_noent), blk_device) log('Waiting for block device %s to appear' % blk_device, level=DEBUG) count += 1 time.sleep(1) else: log('Formatting block device %s as filesystem %s.' % (blk_device, fstype), level=INFO) check_call(['mkfs', '-t', fstype, blk_device])
python
def make_filesystem(blk_device, fstype='ext4', timeout=10): """Make a new filesystem on the specified block device.""" count = 0 e_noent = os.errno.ENOENT while not os.path.exists(blk_device): if count >= timeout: log('Gave up waiting on block device %s' % blk_device, level=ERROR) raise IOError(e_noent, os.strerror(e_noent), blk_device) log('Waiting for block device %s to appear' % blk_device, level=DEBUG) count += 1 time.sleep(1) else: log('Formatting block device %s as filesystem %s.' % (blk_device, fstype), level=INFO) check_call(['mkfs', '-t', fstype, blk_device])
[ "def", "make_filesystem", "(", "blk_device", ",", "fstype", "=", "'ext4'", ",", "timeout", "=", "10", ")", ":", "count", "=", "0", "e_noent", "=", "os", ".", "errno", ".", "ENOENT", "while", "not", "os", ".", "path", ".", "exists", "(", "blk_device", ")", ":", "if", "count", ">=", "timeout", ":", "log", "(", "'Gave up waiting on block device %s'", "%", "blk_device", ",", "level", "=", "ERROR", ")", "raise", "IOError", "(", "e_noent", ",", "os", ".", "strerror", "(", "e_noent", ")", ",", "blk_device", ")", "log", "(", "'Waiting for block device %s to appear'", "%", "blk_device", ",", "level", "=", "DEBUG", ")", "count", "+=", "1", "time", ".", "sleep", "(", "1", ")", "else", ":", "log", "(", "'Formatting block device %s as filesystem %s.'", "%", "(", "blk_device", ",", "fstype", ")", ",", "level", "=", "INFO", ")", "check_call", "(", "[", "'mkfs'", ",", "'-t'", ",", "fstype", ",", "blk_device", "]", ")" ]
Make a new filesystem on the specified block device.
[ "Make", "a", "new", "filesystem", "on", "the", "specified", "block", "device", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L989-L1006
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
place_data_on_block_device
def place_data_on_block_device(blk_device, data_src_dst): """Migrate data in data_src_dst to blk_device and then remount.""" # mount block device into /mnt mount(blk_device, '/mnt') # copy data to /mnt copy_files(data_src_dst, '/mnt') # umount block device umount('/mnt') # Grab user/group ID's from original source _dir = os.stat(data_src_dst) uid = _dir.st_uid gid = _dir.st_gid # re-mount where the data should originally be # TODO: persist is currently a NO-OP in core.host mount(blk_device, data_src_dst, persist=True) # ensure original ownership of new mount. os.chown(data_src_dst, uid, gid)
python
def place_data_on_block_device(blk_device, data_src_dst): """Migrate data in data_src_dst to blk_device and then remount.""" # mount block device into /mnt mount(blk_device, '/mnt') # copy data to /mnt copy_files(data_src_dst, '/mnt') # umount block device umount('/mnt') # Grab user/group ID's from original source _dir = os.stat(data_src_dst) uid = _dir.st_uid gid = _dir.st_gid # re-mount where the data should originally be # TODO: persist is currently a NO-OP in core.host mount(blk_device, data_src_dst, persist=True) # ensure original ownership of new mount. os.chown(data_src_dst, uid, gid)
[ "def", "place_data_on_block_device", "(", "blk_device", ",", "data_src_dst", ")", ":", "# mount block device into /mnt", "mount", "(", "blk_device", ",", "'/mnt'", ")", "# copy data to /mnt", "copy_files", "(", "data_src_dst", ",", "'/mnt'", ")", "# umount block device", "umount", "(", "'/mnt'", ")", "# Grab user/group ID's from original source", "_dir", "=", "os", ".", "stat", "(", "data_src_dst", ")", "uid", "=", "_dir", ".", "st_uid", "gid", "=", "_dir", ".", "st_gid", "# re-mount where the data should originally be", "# TODO: persist is currently a NO-OP in core.host", "mount", "(", "blk_device", ",", "data_src_dst", ",", "persist", "=", "True", ")", "# ensure original ownership of new mount.", "os", ".", "chown", "(", "data_src_dst", ",", "uid", ",", "gid", ")" ]
Migrate data in data_src_dst to blk_device and then remount.
[ "Migrate", "data", "in", "data_src_dst", "to", "blk_device", "and", "then", "remount", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1009-L1025
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
ensure_ceph_keyring
def ensure_ceph_keyring(service, user=None, group=None, relation='ceph', key=None): """Ensures a ceph keyring is created for a named service and optionally ensures user and group ownership. @returns boolean: Flag to indicate whether a key was successfully written to disk based on either relation data or a supplied key """ if not key: for rid in relation_ids(relation): for unit in related_units(rid): key = relation_get('key', rid=rid, unit=unit) if key: break if not key: return False add_key(service=service, key=key) keyring = _keyring_path(service) if user and group: check_call(['chown', '%s.%s' % (user, group), keyring]) return True
python
def ensure_ceph_keyring(service, user=None, group=None, relation='ceph', key=None): """Ensures a ceph keyring is created for a named service and optionally ensures user and group ownership. @returns boolean: Flag to indicate whether a key was successfully written to disk based on either relation data or a supplied key """ if not key: for rid in relation_ids(relation): for unit in related_units(rid): key = relation_get('key', rid=rid, unit=unit) if key: break if not key: return False add_key(service=service, key=key) keyring = _keyring_path(service) if user and group: check_call(['chown', '%s.%s' % (user, group), keyring]) return True
[ "def", "ensure_ceph_keyring", "(", "service", ",", "user", "=", "None", ",", "group", "=", "None", ",", "relation", "=", "'ceph'", ",", "key", "=", "None", ")", ":", "if", "not", "key", ":", "for", "rid", "in", "relation_ids", "(", "relation", ")", ":", "for", "unit", "in", "related_units", "(", "rid", ")", ":", "key", "=", "relation_get", "(", "'key'", ",", "rid", "=", "rid", ",", "unit", "=", "unit", ")", "if", "key", ":", "break", "if", "not", "key", ":", "return", "False", "add_key", "(", "service", "=", "service", ",", "key", "=", "key", ")", "keyring", "=", "_keyring_path", "(", "service", ")", "if", "user", "and", "group", ":", "check_call", "(", "[", "'chown'", ",", "'%s.%s'", "%", "(", "user", ",", "group", ")", ",", "keyring", "]", ")", "return", "True" ]
Ensures a ceph keyring is created for a named service and optionally ensures user and group ownership. @returns boolean: Flag to indicate whether a key was successfully written to disk based on either relation data or a supplied key
[ "Ensures", "a", "ceph", "keyring", "is", "created", "for", "a", "named", "service", "and", "optionally", "ensures", "user", "and", "group", "ownership", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1092-L1115
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
get_previous_request
def get_previous_request(rid): """Return the last ceph broker request sent on a given relation @param rid: Relation id to query for request """ request = None broker_req = relation_get(attribute='broker_req', rid=rid, unit=local_unit()) if broker_req: request_data = json.loads(broker_req) request = CephBrokerRq(api_version=request_data['api-version'], request_id=request_data['request-id']) request.set_ops(request_data['ops']) return request
python
def get_previous_request(rid): """Return the last ceph broker request sent on a given relation @param rid: Relation id to query for request """ request = None broker_req = relation_get(attribute='broker_req', rid=rid, unit=local_unit()) if broker_req: request_data = json.loads(broker_req) request = CephBrokerRq(api_version=request_data['api-version'], request_id=request_data['request-id']) request.set_ops(request_data['ops']) return request
[ "def", "get_previous_request", "(", "rid", ")", ":", "request", "=", "None", "broker_req", "=", "relation_get", "(", "attribute", "=", "'broker_req'", ",", "rid", "=", "rid", ",", "unit", "=", "local_unit", "(", ")", ")", "if", "broker_req", ":", "request_data", "=", "json", ".", "loads", "(", "broker_req", ")", "request", "=", "CephBrokerRq", "(", "api_version", "=", "request_data", "[", "'api-version'", "]", ",", "request_id", "=", "request_data", "[", "'request-id'", "]", ")", "request", ".", "set_ops", "(", "request_data", "[", "'ops'", "]", ")", "return", "request" ]
Return the last ceph broker request sent on a given relation @param rid: Relation id to query for request
[ "Return", "the", "last", "ceph", "broker", "request", "sent", "on", "a", "given", "relation" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1351-L1365
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
get_request_states
def get_request_states(request, relation='ceph'): """Return a dict of requests per relation id with their corresponding completion state. This allows a charm, which has a request for ceph, to see whether there is an equivalent request already being processed and if so what state that request is in. @param request: A CephBrokerRq object """ complete = [] requests = {} for rid in relation_ids(relation): complete = False previous_request = get_previous_request(rid) if request == previous_request: sent = True complete = is_request_complete_for_rid(previous_request, rid) else: sent = False complete = False requests[rid] = { 'sent': sent, 'complete': complete, } return requests
python
def get_request_states(request, relation='ceph'): """Return a dict of requests per relation id with their corresponding completion state. This allows a charm, which has a request for ceph, to see whether there is an equivalent request already being processed and if so what state that request is in. @param request: A CephBrokerRq object """ complete = [] requests = {} for rid in relation_ids(relation): complete = False previous_request = get_previous_request(rid) if request == previous_request: sent = True complete = is_request_complete_for_rid(previous_request, rid) else: sent = False complete = False requests[rid] = { 'sent': sent, 'complete': complete, } return requests
[ "def", "get_request_states", "(", "request", ",", "relation", "=", "'ceph'", ")", ":", "complete", "=", "[", "]", "requests", "=", "{", "}", "for", "rid", "in", "relation_ids", "(", "relation", ")", ":", "complete", "=", "False", "previous_request", "=", "get_previous_request", "(", "rid", ")", "if", "request", "==", "previous_request", ":", "sent", "=", "True", "complete", "=", "is_request_complete_for_rid", "(", "previous_request", ",", "rid", ")", "else", ":", "sent", "=", "False", "complete", "=", "False", "requests", "[", "rid", "]", "=", "{", "'sent'", ":", "sent", ",", "'complete'", ":", "complete", ",", "}", "return", "requests" ]
Return a dict of requests per relation id with their corresponding completion state. This allows a charm, which has a request for ceph, to see whether there is an equivalent request already being processed and if so what state that request is in. @param request: A CephBrokerRq object
[ "Return", "a", "dict", "of", "requests", "per", "relation", "id", "with", "their", "corresponding", "completion", "state", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1368-L1395
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
is_request_sent
def is_request_sent(request, relation='ceph'): """Check to see if a functionally equivalent request has already been sent Returns True if a similair request has been sent @param request: A CephBrokerRq object """ states = get_request_states(request, relation=relation) for rid in states.keys(): if not states[rid]['sent']: return False return True
python
def is_request_sent(request, relation='ceph'): """Check to see if a functionally equivalent request has already been sent Returns True if a similair request has been sent @param request: A CephBrokerRq object """ states = get_request_states(request, relation=relation) for rid in states.keys(): if not states[rid]['sent']: return False return True
[ "def", "is_request_sent", "(", "request", ",", "relation", "=", "'ceph'", ")", ":", "states", "=", "get_request_states", "(", "request", ",", "relation", "=", "relation", ")", "for", "rid", "in", "states", ".", "keys", "(", ")", ":", "if", "not", "states", "[", "rid", "]", "[", "'sent'", "]", ":", "return", "False", "return", "True" ]
Check to see if a functionally equivalent request has already been sent Returns True if a similair request has been sent @param request: A CephBrokerRq object
[ "Check", "to", "see", "if", "a", "functionally", "equivalent", "request", "has", "already", "been", "sent" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1398-L1410
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
is_request_complete_for_rid
def is_request_complete_for_rid(request, rid): """Check if a given request has been completed on the given relation @param request: A CephBrokerRq object @param rid: Relation ID """ broker_key = get_broker_rsp_key() for unit in related_units(rid): rdata = relation_get(rid=rid, unit=unit) if rdata.get(broker_key): rsp = CephBrokerRsp(rdata.get(broker_key)) if rsp.request_id == request.request_id: if not rsp.exit_code: return True else: # The remote unit sent no reply targeted at this unit so either the # remote ceph cluster does not support unit targeted replies or it # has not processed our request yet. if rdata.get('broker_rsp'): request_data = json.loads(rdata['broker_rsp']) if request_data.get('request-id'): log('Ignoring legacy broker_rsp without unit key as remote ' 'service supports unit specific replies', level=DEBUG) else: log('Using legacy broker_rsp as remote service does not ' 'supports unit specific replies', level=DEBUG) rsp = CephBrokerRsp(rdata['broker_rsp']) if not rsp.exit_code: return True return False
python
def is_request_complete_for_rid(request, rid): """Check if a given request has been completed on the given relation @param request: A CephBrokerRq object @param rid: Relation ID """ broker_key = get_broker_rsp_key() for unit in related_units(rid): rdata = relation_get(rid=rid, unit=unit) if rdata.get(broker_key): rsp = CephBrokerRsp(rdata.get(broker_key)) if rsp.request_id == request.request_id: if not rsp.exit_code: return True else: # The remote unit sent no reply targeted at this unit so either the # remote ceph cluster does not support unit targeted replies or it # has not processed our request yet. if rdata.get('broker_rsp'): request_data = json.loads(rdata['broker_rsp']) if request_data.get('request-id'): log('Ignoring legacy broker_rsp without unit key as remote ' 'service supports unit specific replies', level=DEBUG) else: log('Using legacy broker_rsp as remote service does not ' 'supports unit specific replies', level=DEBUG) rsp = CephBrokerRsp(rdata['broker_rsp']) if not rsp.exit_code: return True return False
[ "def", "is_request_complete_for_rid", "(", "request", ",", "rid", ")", ":", "broker_key", "=", "get_broker_rsp_key", "(", ")", "for", "unit", "in", "related_units", "(", "rid", ")", ":", "rdata", "=", "relation_get", "(", "rid", "=", "rid", ",", "unit", "=", "unit", ")", "if", "rdata", ".", "get", "(", "broker_key", ")", ":", "rsp", "=", "CephBrokerRsp", "(", "rdata", ".", "get", "(", "broker_key", ")", ")", "if", "rsp", ".", "request_id", "==", "request", ".", "request_id", ":", "if", "not", "rsp", ".", "exit_code", ":", "return", "True", "else", ":", "# The remote unit sent no reply targeted at this unit so either the", "# remote ceph cluster does not support unit targeted replies or it", "# has not processed our request yet.", "if", "rdata", ".", "get", "(", "'broker_rsp'", ")", ":", "request_data", "=", "json", ".", "loads", "(", "rdata", "[", "'broker_rsp'", "]", ")", "if", "request_data", ".", "get", "(", "'request-id'", ")", ":", "log", "(", "'Ignoring legacy broker_rsp without unit key as remote '", "'service supports unit specific replies'", ",", "level", "=", "DEBUG", ")", "else", ":", "log", "(", "'Using legacy broker_rsp as remote service does not '", "'supports unit specific replies'", ",", "level", "=", "DEBUG", ")", "rsp", "=", "CephBrokerRsp", "(", "rdata", "[", "'broker_rsp'", "]", ")", "if", "not", "rsp", ".", "exit_code", ":", "return", "True", "return", "False" ]
Check if a given request has been completed on the given relation @param request: A CephBrokerRq object @param rid: Relation ID
[ "Check", "if", "a", "given", "request", "has", "been", "completed", "on", "the", "given", "relation" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1429-L1459
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
send_request_if_needed
def send_request_if_needed(request, relation='ceph'): """Send broker request if an equivalent request has not already been sent @param request: A CephBrokerRq object """ if is_request_sent(request, relation=relation): log('Request already sent but not complete, not sending new request', level=DEBUG) else: for rid in relation_ids(relation): log('Sending request {}'.format(request.request_id), level=DEBUG) relation_set(relation_id=rid, broker_req=request.request)
python
def send_request_if_needed(request, relation='ceph'): """Send broker request if an equivalent request has not already been sent @param request: A CephBrokerRq object """ if is_request_sent(request, relation=relation): log('Request already sent but not complete, not sending new request', level=DEBUG) else: for rid in relation_ids(relation): log('Sending request {}'.format(request.request_id), level=DEBUG) relation_set(relation_id=rid, broker_req=request.request)
[ "def", "send_request_if_needed", "(", "request", ",", "relation", "=", "'ceph'", ")", ":", "if", "is_request_sent", "(", "request", ",", "relation", "=", "relation", ")", ":", "log", "(", "'Request already sent but not complete, not sending new request'", ",", "level", "=", "DEBUG", ")", "else", ":", "for", "rid", "in", "relation_ids", "(", "relation", ")", ":", "log", "(", "'Sending request {}'", ".", "format", "(", "request", ".", "request_id", ")", ",", "level", "=", "DEBUG", ")", "relation_set", "(", "relation_id", "=", "rid", ",", "broker_req", "=", "request", ".", "request", ")" ]
Send broker request if an equivalent request has not already been sent @param request: A CephBrokerRq object
[ "Send", "broker", "request", "if", "an", "equivalent", "request", "has", "not", "already", "been", "sent" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1471-L1482
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
is_broker_action_done
def is_broker_action_done(action, rid=None, unit=None): """Check whether broker action has completed yet. @param action: name of action to be performed @returns True if action complete otherwise False """ rdata = relation_get(rid, unit) or {} broker_rsp = rdata.get(get_broker_rsp_key()) if not broker_rsp: return False rsp = CephBrokerRsp(broker_rsp) unit_name = local_unit().partition('/')[2] key = "unit_{}_ceph_broker_action.{}".format(unit_name, action) kvstore = kv() val = kvstore.get(key=key) if val and val == rsp.request_id: return True return False
python
def is_broker_action_done(action, rid=None, unit=None): """Check whether broker action has completed yet. @param action: name of action to be performed @returns True if action complete otherwise False """ rdata = relation_get(rid, unit) or {} broker_rsp = rdata.get(get_broker_rsp_key()) if not broker_rsp: return False rsp = CephBrokerRsp(broker_rsp) unit_name = local_unit().partition('/')[2] key = "unit_{}_ceph_broker_action.{}".format(unit_name, action) kvstore = kv() val = kvstore.get(key=key) if val and val == rsp.request_id: return True return False
[ "def", "is_broker_action_done", "(", "action", ",", "rid", "=", "None", ",", "unit", "=", "None", ")", ":", "rdata", "=", "relation_get", "(", "rid", ",", "unit", ")", "or", "{", "}", "broker_rsp", "=", "rdata", ".", "get", "(", "get_broker_rsp_key", "(", ")", ")", "if", "not", "broker_rsp", ":", "return", "False", "rsp", "=", "CephBrokerRsp", "(", "broker_rsp", ")", "unit_name", "=", "local_unit", "(", ")", ".", "partition", "(", "'/'", ")", "[", "2", "]", "key", "=", "\"unit_{}_ceph_broker_action.{}\"", ".", "format", "(", "unit_name", ",", "action", ")", "kvstore", "=", "kv", "(", ")", "val", "=", "kvstore", ".", "get", "(", "key", "=", "key", ")", "if", "val", "and", "val", "==", "rsp", ".", "request_id", ":", "return", "True", "return", "False" ]
Check whether broker action has completed yet. @param action: name of action to be performed @returns True if action complete otherwise False
[ "Check", "whether", "broker", "action", "has", "completed", "yet", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1485-L1504
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
mark_broker_action_done
def mark_broker_action_done(action, rid=None, unit=None): """Mark action as having been completed. @param action: name of action to be performed @returns None """ rdata = relation_get(rid, unit) or {} broker_rsp = rdata.get(get_broker_rsp_key()) if not broker_rsp: return rsp = CephBrokerRsp(broker_rsp) unit_name = local_unit().partition('/')[2] key = "unit_{}_ceph_broker_action.{}".format(unit_name, action) kvstore = kv() kvstore.set(key=key, value=rsp.request_id) kvstore.flush()
python
def mark_broker_action_done(action, rid=None, unit=None): """Mark action as having been completed. @param action: name of action to be performed @returns None """ rdata = relation_get(rid, unit) or {} broker_rsp = rdata.get(get_broker_rsp_key()) if not broker_rsp: return rsp = CephBrokerRsp(broker_rsp) unit_name = local_unit().partition('/')[2] key = "unit_{}_ceph_broker_action.{}".format(unit_name, action) kvstore = kv() kvstore.set(key=key, value=rsp.request_id) kvstore.flush()
[ "def", "mark_broker_action_done", "(", "action", ",", "rid", "=", "None", ",", "unit", "=", "None", ")", ":", "rdata", "=", "relation_get", "(", "rid", ",", "unit", ")", "or", "{", "}", "broker_rsp", "=", "rdata", ".", "get", "(", "get_broker_rsp_key", "(", ")", ")", "if", "not", "broker_rsp", ":", "return", "rsp", "=", "CephBrokerRsp", "(", "broker_rsp", ")", "unit_name", "=", "local_unit", "(", ")", ".", "partition", "(", "'/'", ")", "[", "2", "]", "key", "=", "\"unit_{}_ceph_broker_action.{}\"", ".", "format", "(", "unit_name", ",", "action", ")", "kvstore", "=", "kv", "(", ")", "kvstore", ".", "set", "(", "key", "=", "key", ",", "value", "=", "rsp", ".", "request_id", ")", "kvstore", ".", "flush", "(", ")" ]
Mark action as having been completed. @param action: name of action to be performed @returns None
[ "Mark", "action", "as", "having", "been", "completed", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1507-L1523
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
Pool.get_pgs
def get_pgs(self, pool_size, percent_data=DEFAULT_POOL_WEIGHT, device_class=None): """Return the number of placement groups to use when creating the pool. Returns the number of placement groups which should be specified when creating the pool. This is based upon the calculation guidelines provided by the Ceph Placement Group Calculator (located online at http://ceph.com/pgcalc/). The number of placement groups are calculated using the following: (Target PGs per OSD) * (OSD #) * (%Data) ---------------------------------------- (Pool size) Per the upstream guidelines, the OSD # should really be considered based on the number of OSDs which are eligible to be selected by the pool. Since the pool creation doesn't specify any of CRUSH set rules, the default rule will be dependent upon the type of pool being created (replicated or erasure). This code makes no attempt to determine the number of OSDs which can be selected for the specific rule, rather it is left to the user to tune in the form of 'expected-osd-count' config option. :param pool_size: int. pool_size is either the number of replicas for replicated pools or the K+M sum for erasure coded pools :param percent_data: float. the percentage of data that is expected to be contained in the pool for the specific OSD set. Default value is to assume 10% of the data is for this pool, which is a relatively low % of the data but allows for the pg_num to be increased. NOTE: the default is primarily to handle the scenario where related charms requiring pools has not been upgraded to include an update to indicate their relative usage of the pools. :param device_class: str. class of storage to use for basis of pgs calculation; ceph supports nvme, ssd and hdd by default based on presence of devices of each type in the deployment. :return: int. The number of pgs to use. """ # Note: This calculation follows the approach that is provided # by the Ceph PG Calculator located at http://ceph.com/pgcalc/. validator(value=pool_size, valid_type=int) # Ensure that percent data is set to something - even with a default # it can be set to None, which would wreak havoc below. if percent_data is None: percent_data = DEFAULT_POOL_WEIGHT # If the expected-osd-count is specified, then use the max between # the expected-osd-count and the actual osd_count osd_list = get_osds(self.service, device_class) expected = config('expected-osd-count') or 0 if osd_list: if device_class: osd_count = len(osd_list) else: osd_count = max(expected, len(osd_list)) # Log a message to provide some insight if the calculations claim # to be off because someone is setting the expected count and # there are more OSDs in reality. Try to make a proper guess # based upon the cluster itself. if not device_class and expected and osd_count != expected: log("Found more OSDs than provided expected count. " "Using the actual count instead", INFO) elif expected: # Use the expected-osd-count in older ceph versions to allow for # a more accurate pg calculations osd_count = expected else: # NOTE(james-page): Default to 200 for older ceph versions # which don't support OSD query from cli return LEGACY_PG_COUNT percent_data /= 100.0 target_pgs_per_osd = config('pgs-per-osd') or DEFAULT_PGS_PER_OSD_TARGET num_pg = (target_pgs_per_osd * osd_count * percent_data) // pool_size # NOTE: ensure a sane minimum number of PGS otherwise we don't get any # reasonable data distribution in minimal OSD configurations if num_pg < DEFAULT_MINIMUM_PGS: num_pg = DEFAULT_MINIMUM_PGS # The CRUSH algorithm has a slight optimization for placement groups # with powers of 2 so find the nearest power of 2. If the nearest # power of 2 is more than 25% below the original value, the next # highest value is used. To do this, find the nearest power of 2 such # that 2^n <= num_pg, check to see if its within the 25% tolerance. exponent = math.floor(math.log(num_pg, 2)) nearest = 2 ** exponent if (num_pg - nearest) > (num_pg * 0.25): # Choose the next highest power of 2 since the nearest is more # than 25% below the original value. return int(nearest * 2) else: return int(nearest)
python
def get_pgs(self, pool_size, percent_data=DEFAULT_POOL_WEIGHT, device_class=None): """Return the number of placement groups to use when creating the pool. Returns the number of placement groups which should be specified when creating the pool. This is based upon the calculation guidelines provided by the Ceph Placement Group Calculator (located online at http://ceph.com/pgcalc/). The number of placement groups are calculated using the following: (Target PGs per OSD) * (OSD #) * (%Data) ---------------------------------------- (Pool size) Per the upstream guidelines, the OSD # should really be considered based on the number of OSDs which are eligible to be selected by the pool. Since the pool creation doesn't specify any of CRUSH set rules, the default rule will be dependent upon the type of pool being created (replicated or erasure). This code makes no attempt to determine the number of OSDs which can be selected for the specific rule, rather it is left to the user to tune in the form of 'expected-osd-count' config option. :param pool_size: int. pool_size is either the number of replicas for replicated pools or the K+M sum for erasure coded pools :param percent_data: float. the percentage of data that is expected to be contained in the pool for the specific OSD set. Default value is to assume 10% of the data is for this pool, which is a relatively low % of the data but allows for the pg_num to be increased. NOTE: the default is primarily to handle the scenario where related charms requiring pools has not been upgraded to include an update to indicate their relative usage of the pools. :param device_class: str. class of storage to use for basis of pgs calculation; ceph supports nvme, ssd and hdd by default based on presence of devices of each type in the deployment. :return: int. The number of pgs to use. """ # Note: This calculation follows the approach that is provided # by the Ceph PG Calculator located at http://ceph.com/pgcalc/. validator(value=pool_size, valid_type=int) # Ensure that percent data is set to something - even with a default # it can be set to None, which would wreak havoc below. if percent_data is None: percent_data = DEFAULT_POOL_WEIGHT # If the expected-osd-count is specified, then use the max between # the expected-osd-count and the actual osd_count osd_list = get_osds(self.service, device_class) expected = config('expected-osd-count') or 0 if osd_list: if device_class: osd_count = len(osd_list) else: osd_count = max(expected, len(osd_list)) # Log a message to provide some insight if the calculations claim # to be off because someone is setting the expected count and # there are more OSDs in reality. Try to make a proper guess # based upon the cluster itself. if not device_class and expected and osd_count != expected: log("Found more OSDs than provided expected count. " "Using the actual count instead", INFO) elif expected: # Use the expected-osd-count in older ceph versions to allow for # a more accurate pg calculations osd_count = expected else: # NOTE(james-page): Default to 200 for older ceph versions # which don't support OSD query from cli return LEGACY_PG_COUNT percent_data /= 100.0 target_pgs_per_osd = config('pgs-per-osd') or DEFAULT_PGS_PER_OSD_TARGET num_pg = (target_pgs_per_osd * osd_count * percent_data) // pool_size # NOTE: ensure a sane minimum number of PGS otherwise we don't get any # reasonable data distribution in minimal OSD configurations if num_pg < DEFAULT_MINIMUM_PGS: num_pg = DEFAULT_MINIMUM_PGS # The CRUSH algorithm has a slight optimization for placement groups # with powers of 2 so find the nearest power of 2. If the nearest # power of 2 is more than 25% below the original value, the next # highest value is used. To do this, find the nearest power of 2 such # that 2^n <= num_pg, check to see if its within the 25% tolerance. exponent = math.floor(math.log(num_pg, 2)) nearest = 2 ** exponent if (num_pg - nearest) > (num_pg * 0.25): # Choose the next highest power of 2 since the nearest is more # than 25% below the original value. return int(nearest * 2) else: return int(nearest)
[ "def", "get_pgs", "(", "self", ",", "pool_size", ",", "percent_data", "=", "DEFAULT_POOL_WEIGHT", ",", "device_class", "=", "None", ")", ":", "# Note: This calculation follows the approach that is provided", "# by the Ceph PG Calculator located at http://ceph.com/pgcalc/.", "validator", "(", "value", "=", "pool_size", ",", "valid_type", "=", "int", ")", "# Ensure that percent data is set to something - even with a default", "# it can be set to None, which would wreak havoc below.", "if", "percent_data", "is", "None", ":", "percent_data", "=", "DEFAULT_POOL_WEIGHT", "# If the expected-osd-count is specified, then use the max between", "# the expected-osd-count and the actual osd_count", "osd_list", "=", "get_osds", "(", "self", ".", "service", ",", "device_class", ")", "expected", "=", "config", "(", "'expected-osd-count'", ")", "or", "0", "if", "osd_list", ":", "if", "device_class", ":", "osd_count", "=", "len", "(", "osd_list", ")", "else", ":", "osd_count", "=", "max", "(", "expected", ",", "len", "(", "osd_list", ")", ")", "# Log a message to provide some insight if the calculations claim", "# to be off because someone is setting the expected count and", "# there are more OSDs in reality. Try to make a proper guess", "# based upon the cluster itself.", "if", "not", "device_class", "and", "expected", "and", "osd_count", "!=", "expected", ":", "log", "(", "\"Found more OSDs than provided expected count. \"", "\"Using the actual count instead\"", ",", "INFO", ")", "elif", "expected", ":", "# Use the expected-osd-count in older ceph versions to allow for", "# a more accurate pg calculations", "osd_count", "=", "expected", "else", ":", "# NOTE(james-page): Default to 200 for older ceph versions", "# which don't support OSD query from cli", "return", "LEGACY_PG_COUNT", "percent_data", "/=", "100.0", "target_pgs_per_osd", "=", "config", "(", "'pgs-per-osd'", ")", "or", "DEFAULT_PGS_PER_OSD_TARGET", "num_pg", "=", "(", "target_pgs_per_osd", "*", "osd_count", "*", "percent_data", ")", "//", "pool_size", "# NOTE: ensure a sane minimum number of PGS otherwise we don't get any", "# reasonable data distribution in minimal OSD configurations", "if", "num_pg", "<", "DEFAULT_MINIMUM_PGS", ":", "num_pg", "=", "DEFAULT_MINIMUM_PGS", "# The CRUSH algorithm has a slight optimization for placement groups", "# with powers of 2 so find the nearest power of 2. If the nearest", "# power of 2 is more than 25% below the original value, the next", "# highest value is used. To do this, find the nearest power of 2 such", "# that 2^n <= num_pg, check to see if its within the 25% tolerance.", "exponent", "=", "math", ".", "floor", "(", "math", ".", "log", "(", "num_pg", ",", "2", ")", ")", "nearest", "=", "2", "**", "exponent", "if", "(", "num_pg", "-", "nearest", ")", ">", "(", "num_pg", "*", "0.25", ")", ":", "# Choose the next highest power of 2 since the nearest is more", "# than 25% below the original value.", "return", "int", "(", "nearest", "*", "2", ")", "else", ":", "return", "int", "(", "nearest", ")" ]
Return the number of placement groups to use when creating the pool. Returns the number of placement groups which should be specified when creating the pool. This is based upon the calculation guidelines provided by the Ceph Placement Group Calculator (located online at http://ceph.com/pgcalc/). The number of placement groups are calculated using the following: (Target PGs per OSD) * (OSD #) * (%Data) ---------------------------------------- (Pool size) Per the upstream guidelines, the OSD # should really be considered based on the number of OSDs which are eligible to be selected by the pool. Since the pool creation doesn't specify any of CRUSH set rules, the default rule will be dependent upon the type of pool being created (replicated or erasure). This code makes no attempt to determine the number of OSDs which can be selected for the specific rule, rather it is left to the user to tune in the form of 'expected-osd-count' config option. :param pool_size: int. pool_size is either the number of replicas for replicated pools or the K+M sum for erasure coded pools :param percent_data: float. the percentage of data that is expected to be contained in the pool for the specific OSD set. Default value is to assume 10% of the data is for this pool, which is a relatively low % of the data but allows for the pg_num to be increased. NOTE: the default is primarily to handle the scenario where related charms requiring pools has not been upgraded to include an update to indicate their relative usage of the pools. :param device_class: str. class of storage to use for basis of pgs calculation; ceph supports nvme, ssd and hdd by default based on presence of devices of each type in the deployment. :return: int. The number of pgs to use.
[ "Return", "the", "number", "of", "placement", "groups", "to", "use", "when", "creating", "the", "pool", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L199-L296
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
CephBrokerRq.add_op_create_replicated_pool
def add_op_create_replicated_pool(self, name, replica_count=3, pg_num=None, weight=None, group=None, namespace=None, app_name=None, max_bytes=None, max_objects=None): """Adds an operation to create a replicated pool. :param name: Name of pool to create :type name: str :param replica_count: Number of copies Ceph should keep of your data. :type replica_count: int :param pg_num: Request specific number of Placement Groups to create for pool. :type pg_num: int :param weight: The percentage of data that is expected to be contained in the pool from the total available space on the OSDs. Used to calculate number of Placement Groups to create for pool. :type weight: float :param group: Group to add pool to :type group: str :param namespace: Group namespace :type namespace: str :param app_name: (Optional) Tag pool with application name. Note that there is certain protocols emerging upstream with regard to meaningful application names to use. Examples are ``rbd`` and ``rgw``. :type app_name: str :param max_bytes: Maximum bytes quota to apply :type max_bytes: int :param max_objects: Maximum objects quota to apply :type max_objects: int """ if pg_num and weight: raise ValueError('pg_num and weight are mutually exclusive') self.ops.append({'op': 'create-pool', 'name': name, 'replicas': replica_count, 'pg_num': pg_num, 'weight': weight, 'group': group, 'group-namespace': namespace, 'app-name': app_name, 'max-bytes': max_bytes, 'max-objects': max_objects})
python
def add_op_create_replicated_pool(self, name, replica_count=3, pg_num=None, weight=None, group=None, namespace=None, app_name=None, max_bytes=None, max_objects=None): """Adds an operation to create a replicated pool. :param name: Name of pool to create :type name: str :param replica_count: Number of copies Ceph should keep of your data. :type replica_count: int :param pg_num: Request specific number of Placement Groups to create for pool. :type pg_num: int :param weight: The percentage of data that is expected to be contained in the pool from the total available space on the OSDs. Used to calculate number of Placement Groups to create for pool. :type weight: float :param group: Group to add pool to :type group: str :param namespace: Group namespace :type namespace: str :param app_name: (Optional) Tag pool with application name. Note that there is certain protocols emerging upstream with regard to meaningful application names to use. Examples are ``rbd`` and ``rgw``. :type app_name: str :param max_bytes: Maximum bytes quota to apply :type max_bytes: int :param max_objects: Maximum objects quota to apply :type max_objects: int """ if pg_num and weight: raise ValueError('pg_num and weight are mutually exclusive') self.ops.append({'op': 'create-pool', 'name': name, 'replicas': replica_count, 'pg_num': pg_num, 'weight': weight, 'group': group, 'group-namespace': namespace, 'app-name': app_name, 'max-bytes': max_bytes, 'max-objects': max_objects})
[ "def", "add_op_create_replicated_pool", "(", "self", ",", "name", ",", "replica_count", "=", "3", ",", "pg_num", "=", "None", ",", "weight", "=", "None", ",", "group", "=", "None", ",", "namespace", "=", "None", ",", "app_name", "=", "None", ",", "max_bytes", "=", "None", ",", "max_objects", "=", "None", ")", ":", "if", "pg_num", "and", "weight", ":", "raise", "ValueError", "(", "'pg_num and weight are mutually exclusive'", ")", "self", ".", "ops", ".", "append", "(", "{", "'op'", ":", "'create-pool'", ",", "'name'", ":", "name", ",", "'replicas'", ":", "replica_count", ",", "'pg_num'", ":", "pg_num", ",", "'weight'", ":", "weight", ",", "'group'", ":", "group", ",", "'group-namespace'", ":", "namespace", ",", "'app-name'", ":", "app_name", ",", "'max-bytes'", ":", "max_bytes", ",", "'max-objects'", ":", "max_objects", "}", ")" ]
Adds an operation to create a replicated pool. :param name: Name of pool to create :type name: str :param replica_count: Number of copies Ceph should keep of your data. :type replica_count: int :param pg_num: Request specific number of Placement Groups to create for pool. :type pg_num: int :param weight: The percentage of data that is expected to be contained in the pool from the total available space on the OSDs. Used to calculate number of Placement Groups to create for pool. :type weight: float :param group: Group to add pool to :type group: str :param namespace: Group namespace :type namespace: str :param app_name: (Optional) Tag pool with application name. Note that there is certain protocols emerging upstream with regard to meaningful application names to use. Examples are ``rbd`` and ``rgw``. :type app_name: str :param max_bytes: Maximum bytes quota to apply :type max_bytes: int :param max_objects: Maximum objects quota to apply :type max_objects: int
[ "Adds", "an", "operation", "to", "create", "a", "replicated", "pool", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1168-L1207
train
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
CephBrokerRq.add_op_create_erasure_pool
def add_op_create_erasure_pool(self, name, erasure_profile=None, weight=None, group=None, app_name=None, max_bytes=None, max_objects=None): """Adds an operation to create a erasure coded pool. :param name: Name of pool to create :type name: str :param erasure_profile: Name of erasure code profile to use. If not set the ceph-mon unit handling the broker request will set its default value. :type erasure_profile: str :param weight: The percentage of data that is expected to be contained in the pool from the total available space on the OSDs. :type weight: float :param group: Group to add pool to :type group: str :param app_name: (Optional) Tag pool with application name. Note that there is certain protocols emerging upstream with regard to meaningful application names to use. Examples are ``rbd`` and ``rgw``. :type app_name: str :param max_bytes: Maximum bytes quota to apply :type max_bytes: int :param max_objects: Maximum objects quota to apply :type max_objects: int """ self.ops.append({'op': 'create-pool', 'name': name, 'pool-type': 'erasure', 'erasure-profile': erasure_profile, 'weight': weight, 'group': group, 'app-name': app_name, 'max-bytes': max_bytes, 'max-objects': max_objects})
python
def add_op_create_erasure_pool(self, name, erasure_profile=None, weight=None, group=None, app_name=None, max_bytes=None, max_objects=None): """Adds an operation to create a erasure coded pool. :param name: Name of pool to create :type name: str :param erasure_profile: Name of erasure code profile to use. If not set the ceph-mon unit handling the broker request will set its default value. :type erasure_profile: str :param weight: The percentage of data that is expected to be contained in the pool from the total available space on the OSDs. :type weight: float :param group: Group to add pool to :type group: str :param app_name: (Optional) Tag pool with application name. Note that there is certain protocols emerging upstream with regard to meaningful application names to use. Examples are ``rbd`` and ``rgw``. :type app_name: str :param max_bytes: Maximum bytes quota to apply :type max_bytes: int :param max_objects: Maximum objects quota to apply :type max_objects: int """ self.ops.append({'op': 'create-pool', 'name': name, 'pool-type': 'erasure', 'erasure-profile': erasure_profile, 'weight': weight, 'group': group, 'app-name': app_name, 'max-bytes': max_bytes, 'max-objects': max_objects})
[ "def", "add_op_create_erasure_pool", "(", "self", ",", "name", ",", "erasure_profile", "=", "None", ",", "weight", "=", "None", ",", "group", "=", "None", ",", "app_name", "=", "None", ",", "max_bytes", "=", "None", ",", "max_objects", "=", "None", ")", ":", "self", ".", "ops", ".", "append", "(", "{", "'op'", ":", "'create-pool'", ",", "'name'", ":", "name", ",", "'pool-type'", ":", "'erasure'", ",", "'erasure-profile'", ":", "erasure_profile", ",", "'weight'", ":", "weight", ",", "'group'", ":", "group", ",", "'app-name'", ":", "app_name", ",", "'max-bytes'", ":", "max_bytes", ",", "'max-objects'", ":", "max_objects", "}", ")" ]
Adds an operation to create a erasure coded pool. :param name: Name of pool to create :type name: str :param erasure_profile: Name of erasure code profile to use. If not set the ceph-mon unit handling the broker request will set its default value. :type erasure_profile: str :param weight: The percentage of data that is expected to be contained in the pool from the total available space on the OSDs. :type weight: float :param group: Group to add pool to :type group: str :param app_name: (Optional) Tag pool with application name. Note that there is certain protocols emerging upstream with regard to meaningful application names to use. Examples are ``rbd`` and ``rgw``. :type app_name: str :param max_bytes: Maximum bytes quota to apply :type max_bytes: int :param max_objects: Maximum objects quota to apply :type max_objects: int
[ "Adds", "an", "operation", "to", "create", "a", "erasure", "coded", "pool", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1209-L1240
train
juju/charm-helpers
charmhelpers/contrib/charmsupport/nrpe.py
get_nagios_unit_name
def get_nagios_unit_name(relation_name='nrpe-external-master'): """ Return the nagios unit name prepended with host_context if needed :param str relation_name: Name of relation nrpe sub joined to """ host_context = get_nagios_hostcontext(relation_name) if host_context: unit = "%s:%s" % (host_context, local_unit()) else: unit = local_unit() return unit
python
def get_nagios_unit_name(relation_name='nrpe-external-master'): """ Return the nagios unit name prepended with host_context if needed :param str relation_name: Name of relation nrpe sub joined to """ host_context = get_nagios_hostcontext(relation_name) if host_context: unit = "%s:%s" % (host_context, local_unit()) else: unit = local_unit() return unit
[ "def", "get_nagios_unit_name", "(", "relation_name", "=", "'nrpe-external-master'", ")", ":", "host_context", "=", "get_nagios_hostcontext", "(", "relation_name", ")", "if", "host_context", ":", "unit", "=", "\"%s:%s\"", "%", "(", "host_context", ",", "local_unit", "(", ")", ")", "else", ":", "unit", "=", "local_unit", "(", ")", "return", "unit" ]
Return the nagios unit name prepended with host_context if needed :param str relation_name: Name of relation nrpe sub joined to
[ "Return", "the", "nagios", "unit", "name", "prepended", "with", "host_context", "if", "needed" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmsupport/nrpe.py#L341-L352
train
juju/charm-helpers
charmhelpers/contrib/charmsupport/nrpe.py
copy_nrpe_checks
def copy_nrpe_checks(nrpe_files_dir=None): """ Copy the nrpe checks into place """ NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins' if nrpe_files_dir is None: # determine if "charmhelpers" is in CHARMDIR or CHARMDIR/hooks for segment in ['.', 'hooks']: nrpe_files_dir = os.path.abspath(os.path.join( os.getenv('CHARM_DIR'), segment, 'charmhelpers', 'contrib', 'openstack', 'files')) if os.path.isdir(nrpe_files_dir): break else: raise RuntimeError("Couldn't find charmhelpers directory") if not os.path.exists(NAGIOS_PLUGINS): os.makedirs(NAGIOS_PLUGINS) for fname in glob.glob(os.path.join(nrpe_files_dir, "check_*")): if os.path.isfile(fname): shutil.copy2(fname, os.path.join(NAGIOS_PLUGINS, os.path.basename(fname)))
python
def copy_nrpe_checks(nrpe_files_dir=None): """ Copy the nrpe checks into place """ NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins' if nrpe_files_dir is None: # determine if "charmhelpers" is in CHARMDIR or CHARMDIR/hooks for segment in ['.', 'hooks']: nrpe_files_dir = os.path.abspath(os.path.join( os.getenv('CHARM_DIR'), segment, 'charmhelpers', 'contrib', 'openstack', 'files')) if os.path.isdir(nrpe_files_dir): break else: raise RuntimeError("Couldn't find charmhelpers directory") if not os.path.exists(NAGIOS_PLUGINS): os.makedirs(NAGIOS_PLUGINS) for fname in glob.glob(os.path.join(nrpe_files_dir, "check_*")): if os.path.isfile(fname): shutil.copy2(fname, os.path.join(NAGIOS_PLUGINS, os.path.basename(fname)))
[ "def", "copy_nrpe_checks", "(", "nrpe_files_dir", "=", "None", ")", ":", "NAGIOS_PLUGINS", "=", "'/usr/local/lib/nagios/plugins'", "if", "nrpe_files_dir", "is", "None", ":", "# determine if \"charmhelpers\" is in CHARMDIR or CHARMDIR/hooks", "for", "segment", "in", "[", "'.'", ",", "'hooks'", "]", ":", "nrpe_files_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getenv", "(", "'CHARM_DIR'", ")", ",", "segment", ",", "'charmhelpers'", ",", "'contrib'", ",", "'openstack'", ",", "'files'", ")", ")", "if", "os", ".", "path", ".", "isdir", "(", "nrpe_files_dir", ")", ":", "break", "else", ":", "raise", "RuntimeError", "(", "\"Couldn't find charmhelpers directory\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "NAGIOS_PLUGINS", ")", ":", "os", ".", "makedirs", "(", "NAGIOS_PLUGINS", ")", "for", "fname", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "nrpe_files_dir", ",", "\"check_*\"", ")", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "fname", ")", ":", "shutil", ".", "copy2", "(", "fname", ",", "os", ".", "path", ".", "join", "(", "NAGIOS_PLUGINS", ",", "os", ".", "path", ".", "basename", "(", "fname", ")", ")", ")" ]
Copy the nrpe checks into place
[ "Copy", "the", "nrpe", "checks", "into", "place" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmsupport/nrpe.py#L413-L438
train
juju/charm-helpers
charmhelpers/contrib/openstack/vaultlocker.py
write_vaultlocker_conf
def write_vaultlocker_conf(context, priority=100): """Write vaultlocker configuration to disk and install alternative :param context: Dict of data from vault-kv relation :ptype: context: dict :param priority: Priority of alternative configuration :ptype: priority: int""" charm_vl_path = "/var/lib/charm/{}/vaultlocker.conf".format( hookenv.service_name() ) host.mkdir(os.path.dirname(charm_vl_path), perms=0o700) templating.render(source='vaultlocker.conf.j2', target=charm_vl_path, context=context, perms=0o600), alternatives.install_alternative('vaultlocker.conf', '/etc/vaultlocker/vaultlocker.conf', charm_vl_path, priority)
python
def write_vaultlocker_conf(context, priority=100): """Write vaultlocker configuration to disk and install alternative :param context: Dict of data from vault-kv relation :ptype: context: dict :param priority: Priority of alternative configuration :ptype: priority: int""" charm_vl_path = "/var/lib/charm/{}/vaultlocker.conf".format( hookenv.service_name() ) host.mkdir(os.path.dirname(charm_vl_path), perms=0o700) templating.render(source='vaultlocker.conf.j2', target=charm_vl_path, context=context, perms=0o600), alternatives.install_alternative('vaultlocker.conf', '/etc/vaultlocker/vaultlocker.conf', charm_vl_path, priority)
[ "def", "write_vaultlocker_conf", "(", "context", ",", "priority", "=", "100", ")", ":", "charm_vl_path", "=", "\"/var/lib/charm/{}/vaultlocker.conf\"", ".", "format", "(", "hookenv", ".", "service_name", "(", ")", ")", "host", ".", "mkdir", "(", "os", ".", "path", ".", "dirname", "(", "charm_vl_path", ")", ",", "perms", "=", "0o700", ")", "templating", ".", "render", "(", "source", "=", "'vaultlocker.conf.j2'", ",", "target", "=", "charm_vl_path", ",", "context", "=", "context", ",", "perms", "=", "0o600", ")", ",", "alternatives", ".", "install_alternative", "(", "'vaultlocker.conf'", ",", "'/etc/vaultlocker/vaultlocker.conf'", ",", "charm_vl_path", ",", "priority", ")" ]
Write vaultlocker configuration to disk and install alternative :param context: Dict of data from vault-kv relation :ptype: context: dict :param priority: Priority of alternative configuration :ptype: priority: int
[ "Write", "vaultlocker", "configuration", "to", "disk", "and", "install", "alternative" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/vaultlocker.py#L80-L96
train
juju/charm-helpers
charmhelpers/contrib/openstack/vaultlocker.py
vault_relation_complete
def vault_relation_complete(backend=None): """Determine whether vault relation is complete :param backend: Name of secrets backend requested :ptype backend: string :returns: whether the relation to vault is complete :rtype: bool""" vault_kv = VaultKVContext(secret_backend=backend or VAULTLOCKER_BACKEND) vault_kv() return vault_kv.complete
python
def vault_relation_complete(backend=None): """Determine whether vault relation is complete :param backend: Name of secrets backend requested :ptype backend: string :returns: whether the relation to vault is complete :rtype: bool""" vault_kv = VaultKVContext(secret_backend=backend or VAULTLOCKER_BACKEND) vault_kv() return vault_kv.complete
[ "def", "vault_relation_complete", "(", "backend", "=", "None", ")", ":", "vault_kv", "=", "VaultKVContext", "(", "secret_backend", "=", "backend", "or", "VAULTLOCKER_BACKEND", ")", "vault_kv", "(", ")", "return", "vault_kv", ".", "complete" ]
Determine whether vault relation is complete :param backend: Name of secrets backend requested :ptype backend: string :returns: whether the relation to vault is complete :rtype: bool
[ "Determine", "whether", "vault", "relation", "is", "complete" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/vaultlocker.py#L99-L108
train
juju/charm-helpers
charmhelpers/contrib/openstack/vaultlocker.py
retrieve_secret_id
def retrieve_secret_id(url, token): """Retrieve a response-wrapped secret_id from Vault :param url: URL to Vault Server :ptype url: str :param token: One shot Token to use :ptype token: str :returns: secret_id to use for Vault Access :rtype: str""" import hvac client = hvac.Client(url=url, token=token) response = client._post('/v1/sys/wrapping/unwrap') if response.status_code == 200: data = response.json() return data['data']['secret_id']
python
def retrieve_secret_id(url, token): """Retrieve a response-wrapped secret_id from Vault :param url: URL to Vault Server :ptype url: str :param token: One shot Token to use :ptype token: str :returns: secret_id to use for Vault Access :rtype: str""" import hvac client = hvac.Client(url=url, token=token) response = client._post('/v1/sys/wrapping/unwrap') if response.status_code == 200: data = response.json() return data['data']['secret_id']
[ "def", "retrieve_secret_id", "(", "url", ",", "token", ")", ":", "import", "hvac", "client", "=", "hvac", ".", "Client", "(", "url", "=", "url", ",", "token", "=", "token", ")", "response", "=", "client", ".", "_post", "(", "'/v1/sys/wrapping/unwrap'", ")", "if", "response", ".", "status_code", "==", "200", ":", "data", "=", "response", ".", "json", "(", ")", "return", "data", "[", "'data'", "]", "[", "'secret_id'", "]" ]
Retrieve a response-wrapped secret_id from Vault :param url: URL to Vault Server :ptype url: str :param token: One shot Token to use :ptype token: str :returns: secret_id to use for Vault Access :rtype: str
[ "Retrieve", "a", "response", "-", "wrapped", "secret_id", "from", "Vault" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/vaultlocker.py#L112-L126
train
juju/charm-helpers
charmhelpers/core/decorators.py
retry_on_exception
def retry_on_exception(num_retries, base_delay=0, exc_type=Exception): """If the decorated function raises exception exc_type, allow num_retries retry attempts before raise the exception. """ def _retry_on_exception_inner_1(f): def _retry_on_exception_inner_2(*args, **kwargs): retries = num_retries multiplier = 1 while True: try: return f(*args, **kwargs) except exc_type: if not retries: raise delay = base_delay * multiplier multiplier += 1 log("Retrying '%s' %d more times (delay=%s)" % (f.__name__, retries, delay), level=INFO) retries -= 1 if delay: time.sleep(delay) return _retry_on_exception_inner_2 return _retry_on_exception_inner_1
python
def retry_on_exception(num_retries, base_delay=0, exc_type=Exception): """If the decorated function raises exception exc_type, allow num_retries retry attempts before raise the exception. """ def _retry_on_exception_inner_1(f): def _retry_on_exception_inner_2(*args, **kwargs): retries = num_retries multiplier = 1 while True: try: return f(*args, **kwargs) except exc_type: if not retries: raise delay = base_delay * multiplier multiplier += 1 log("Retrying '%s' %d more times (delay=%s)" % (f.__name__, retries, delay), level=INFO) retries -= 1 if delay: time.sleep(delay) return _retry_on_exception_inner_2 return _retry_on_exception_inner_1
[ "def", "retry_on_exception", "(", "num_retries", ",", "base_delay", "=", "0", ",", "exc_type", "=", "Exception", ")", ":", "def", "_retry_on_exception_inner_1", "(", "f", ")", ":", "def", "_retry_on_exception_inner_2", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "retries", "=", "num_retries", "multiplier", "=", "1", "while", "True", ":", "try", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "exc_type", ":", "if", "not", "retries", ":", "raise", "delay", "=", "base_delay", "*", "multiplier", "multiplier", "+=", "1", "log", "(", "\"Retrying '%s' %d more times (delay=%s)\"", "%", "(", "f", ".", "__name__", ",", "retries", ",", "delay", ")", ",", "level", "=", "INFO", ")", "retries", "-=", "1", "if", "delay", ":", "time", ".", "sleep", "(", "delay", ")", "return", "_retry_on_exception_inner_2", "return", "_retry_on_exception_inner_1" ]
If the decorated function raises exception exc_type, allow num_retries retry attempts before raise the exception.
[ "If", "the", "decorated", "function", "raises", "exception", "exc_type", "allow", "num_retries", "retry", "attempts", "before", "raise", "the", "exception", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/decorators.py#L30-L55
train
juju/charm-helpers
charmhelpers/fetch/snap.py
_snap_exec
def _snap_exec(commands): """ Execute snap commands. :param commands: List commands :return: Integer exit code """ assert type(commands) == list retry_count = 0 return_code = None while return_code is None or return_code == SNAP_NO_LOCK: try: return_code = subprocess.check_call(['snap'] + commands, env=os.environ) except subprocess.CalledProcessError as e: retry_count += + 1 if retry_count > SNAP_NO_LOCK_RETRY_COUNT: raise CouldNotAcquireLockException( 'Could not aquire lock after {} attempts' .format(SNAP_NO_LOCK_RETRY_COUNT)) return_code = e.returncode log('Snap failed to acquire lock, trying again in {} seconds.' .format(SNAP_NO_LOCK_RETRY_DELAY, level='WARN')) sleep(SNAP_NO_LOCK_RETRY_DELAY) return return_code
python
def _snap_exec(commands): """ Execute snap commands. :param commands: List commands :return: Integer exit code """ assert type(commands) == list retry_count = 0 return_code = None while return_code is None or return_code == SNAP_NO_LOCK: try: return_code = subprocess.check_call(['snap'] + commands, env=os.environ) except subprocess.CalledProcessError as e: retry_count += + 1 if retry_count > SNAP_NO_LOCK_RETRY_COUNT: raise CouldNotAcquireLockException( 'Could not aquire lock after {} attempts' .format(SNAP_NO_LOCK_RETRY_COUNT)) return_code = e.returncode log('Snap failed to acquire lock, trying again in {} seconds.' .format(SNAP_NO_LOCK_RETRY_DELAY, level='WARN')) sleep(SNAP_NO_LOCK_RETRY_DELAY) return return_code
[ "def", "_snap_exec", "(", "commands", ")", ":", "assert", "type", "(", "commands", ")", "==", "list", "retry_count", "=", "0", "return_code", "=", "None", "while", "return_code", "is", "None", "or", "return_code", "==", "SNAP_NO_LOCK", ":", "try", ":", "return_code", "=", "subprocess", ".", "check_call", "(", "[", "'snap'", "]", "+", "commands", ",", "env", "=", "os", ".", "environ", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "retry_count", "+=", "+", "1", "if", "retry_count", ">", "SNAP_NO_LOCK_RETRY_COUNT", ":", "raise", "CouldNotAcquireLockException", "(", "'Could not aquire lock after {} attempts'", ".", "format", "(", "SNAP_NO_LOCK_RETRY_COUNT", ")", ")", "return_code", "=", "e", ".", "returncode", "log", "(", "'Snap failed to acquire lock, trying again in {} seconds.'", ".", "format", "(", "SNAP_NO_LOCK_RETRY_DELAY", ",", "level", "=", "'WARN'", ")", ")", "sleep", "(", "SNAP_NO_LOCK_RETRY_DELAY", ")", "return", "return_code" ]
Execute snap commands. :param commands: List commands :return: Integer exit code
[ "Execute", "snap", "commands", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/snap.py#L48-L75
train
juju/charm-helpers
charmhelpers/fetch/snap.py
snap_remove
def snap_remove(packages, *flags): """ Remove a snap package. :param packages: String or List String package name :param flags: List String flags to pass to remove command :return: Integer return code from snap """ if type(packages) is not list: packages = [packages] flags = list(flags) message = 'Removing snap(s) "%s"' % ', '.join(packages) if flags: message += ' with options "%s"' % ', '.join(flags) log(message, level='INFO') return _snap_exec(['remove'] + flags + packages)
python
def snap_remove(packages, *flags): """ Remove a snap package. :param packages: String or List String package name :param flags: List String flags to pass to remove command :return: Integer return code from snap """ if type(packages) is not list: packages = [packages] flags = list(flags) message = 'Removing snap(s) "%s"' % ', '.join(packages) if flags: message += ' with options "%s"' % ', '.join(flags) log(message, level='INFO') return _snap_exec(['remove'] + flags + packages)
[ "def", "snap_remove", "(", "packages", ",", "*", "flags", ")", ":", "if", "type", "(", "packages", ")", "is", "not", "list", ":", "packages", "=", "[", "packages", "]", "flags", "=", "list", "(", "flags", ")", "message", "=", "'Removing snap(s) \"%s\"'", "%", "', '", ".", "join", "(", "packages", ")", "if", "flags", ":", "message", "+=", "' with options \"%s\"'", "%", "', '", ".", "join", "(", "flags", ")", "log", "(", "message", ",", "level", "=", "'INFO'", ")", "return", "_snap_exec", "(", "[", "'remove'", "]", "+", "flags", "+", "packages", ")" ]
Remove a snap package. :param packages: String or List String package name :param flags: List String flags to pass to remove command :return: Integer return code from snap
[ "Remove", "a", "snap", "package", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/snap.py#L99-L117
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_v2_endpoint_data
def validate_v2_endpoint_data(self, endpoints, admin_port, internal_port, public_port, expected): """Validate endpoint data. Validate actual endpoint data vs expected endpoint data. The ports are used to find the matching endpoint. """ self.log.debug('Validating endpoint data...') self.log.debug('actual: {}'.format(repr(endpoints))) found = False for ep in endpoints: self.log.debug('endpoint: {}'.format(repr(ep))) if (admin_port in ep.adminurl and internal_port in ep.internalurl and public_port in ep.publicurl): found = True actual = {'id': ep.id, 'region': ep.region, 'adminurl': ep.adminurl, 'internalurl': ep.internalurl, 'publicurl': ep.publicurl, 'service_id': ep.service_id} ret = self._validate_dict_data(expected, actual) if ret: return 'unexpected endpoint data - {}'.format(ret) if not found: return 'endpoint not found'
python
def validate_v2_endpoint_data(self, endpoints, admin_port, internal_port, public_port, expected): """Validate endpoint data. Validate actual endpoint data vs expected endpoint data. The ports are used to find the matching endpoint. """ self.log.debug('Validating endpoint data...') self.log.debug('actual: {}'.format(repr(endpoints))) found = False for ep in endpoints: self.log.debug('endpoint: {}'.format(repr(ep))) if (admin_port in ep.adminurl and internal_port in ep.internalurl and public_port in ep.publicurl): found = True actual = {'id': ep.id, 'region': ep.region, 'adminurl': ep.adminurl, 'internalurl': ep.internalurl, 'publicurl': ep.publicurl, 'service_id': ep.service_id} ret = self._validate_dict_data(expected, actual) if ret: return 'unexpected endpoint data - {}'.format(ret) if not found: return 'endpoint not found'
[ "def", "validate_v2_endpoint_data", "(", "self", ",", "endpoints", ",", "admin_port", ",", "internal_port", ",", "public_port", ",", "expected", ")", ":", "self", ".", "log", ".", "debug", "(", "'Validating endpoint data...'", ")", "self", ".", "log", ".", "debug", "(", "'actual: {}'", ".", "format", "(", "repr", "(", "endpoints", ")", ")", ")", "found", "=", "False", "for", "ep", "in", "endpoints", ":", "self", ".", "log", ".", "debug", "(", "'endpoint: {}'", ".", "format", "(", "repr", "(", "ep", ")", ")", ")", "if", "(", "admin_port", "in", "ep", ".", "adminurl", "and", "internal_port", "in", "ep", ".", "internalurl", "and", "public_port", "in", "ep", ".", "publicurl", ")", ":", "found", "=", "True", "actual", "=", "{", "'id'", ":", "ep", ".", "id", ",", "'region'", ":", "ep", ".", "region", ",", "'adminurl'", ":", "ep", ".", "adminurl", ",", "'internalurl'", ":", "ep", ".", "internalurl", ",", "'publicurl'", ":", "ep", ".", "publicurl", ",", "'service_id'", ":", "ep", ".", "service_id", "}", "ret", "=", "self", ".", "_validate_dict_data", "(", "expected", ",", "actual", ")", "if", "ret", ":", "return", "'unexpected endpoint data - {}'", ".", "format", "(", "ret", ")", "if", "not", "found", ":", "return", "'endpoint not found'" ]
Validate endpoint data. Validate actual endpoint data vs expected endpoint data. The ports are used to find the matching endpoint.
[ "Validate", "endpoint", "data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L102-L129
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_v3_endpoint_data
def validate_v3_endpoint_data(self, endpoints, admin_port, internal_port, public_port, expected, expected_num_eps=3): """Validate keystone v3 endpoint data. Validate the v3 endpoint data which has changed from v2. The ports are used to find the matching endpoint. The new v3 endpoint data looks like: [<Endpoint enabled=True, id=0432655fc2f74d1e9fa17bdaa6f6e60b, interface=admin, links={u'self': u'<RESTful URL of this endpoint>'}, region=RegionOne, region_id=RegionOne, service_id=17f842a0dc084b928e476fafe67e4095, url=http://10.5.6.5:9312>, <Endpoint enabled=True, id=6536cb6cb92f4f41bf22b079935c7707, interface=admin, links={u'self': u'<RESTful url of this endpoint>'}, region=RegionOne, region_id=RegionOne, service_id=72fc8736fb41435e8b3584205bb2cfa3, url=http://10.5.6.6:35357/v3>, ... ] """ self.log.debug('Validating v3 endpoint data...') self.log.debug('actual: {}'.format(repr(endpoints))) found = [] for ep in endpoints: self.log.debug('endpoint: {}'.format(repr(ep))) if ((admin_port in ep.url and ep.interface == 'admin') or (internal_port in ep.url and ep.interface == 'internal') or (public_port in ep.url and ep.interface == 'public')): found.append(ep.interface) # note we ignore the links member. actual = {'id': ep.id, 'region': ep.region, 'region_id': ep.region_id, 'interface': self.not_null, 'url': ep.url, 'service_id': ep.service_id, } ret = self._validate_dict_data(expected, actual) if ret: return 'unexpected endpoint data - {}'.format(ret) if len(found) != expected_num_eps: return 'Unexpected number of endpoints found'
python
def validate_v3_endpoint_data(self, endpoints, admin_port, internal_port, public_port, expected, expected_num_eps=3): """Validate keystone v3 endpoint data. Validate the v3 endpoint data which has changed from v2. The ports are used to find the matching endpoint. The new v3 endpoint data looks like: [<Endpoint enabled=True, id=0432655fc2f74d1e9fa17bdaa6f6e60b, interface=admin, links={u'self': u'<RESTful URL of this endpoint>'}, region=RegionOne, region_id=RegionOne, service_id=17f842a0dc084b928e476fafe67e4095, url=http://10.5.6.5:9312>, <Endpoint enabled=True, id=6536cb6cb92f4f41bf22b079935c7707, interface=admin, links={u'self': u'<RESTful url of this endpoint>'}, region=RegionOne, region_id=RegionOne, service_id=72fc8736fb41435e8b3584205bb2cfa3, url=http://10.5.6.6:35357/v3>, ... ] """ self.log.debug('Validating v3 endpoint data...') self.log.debug('actual: {}'.format(repr(endpoints))) found = [] for ep in endpoints: self.log.debug('endpoint: {}'.format(repr(ep))) if ((admin_port in ep.url and ep.interface == 'admin') or (internal_port in ep.url and ep.interface == 'internal') or (public_port in ep.url and ep.interface == 'public')): found.append(ep.interface) # note we ignore the links member. actual = {'id': ep.id, 'region': ep.region, 'region_id': ep.region_id, 'interface': self.not_null, 'url': ep.url, 'service_id': ep.service_id, } ret = self._validate_dict_data(expected, actual) if ret: return 'unexpected endpoint data - {}'.format(ret) if len(found) != expected_num_eps: return 'Unexpected number of endpoints found'
[ "def", "validate_v3_endpoint_data", "(", "self", ",", "endpoints", ",", "admin_port", ",", "internal_port", ",", "public_port", ",", "expected", ",", "expected_num_eps", "=", "3", ")", ":", "self", ".", "log", ".", "debug", "(", "'Validating v3 endpoint data...'", ")", "self", ".", "log", ".", "debug", "(", "'actual: {}'", ".", "format", "(", "repr", "(", "endpoints", ")", ")", ")", "found", "=", "[", "]", "for", "ep", "in", "endpoints", ":", "self", ".", "log", ".", "debug", "(", "'endpoint: {}'", ".", "format", "(", "repr", "(", "ep", ")", ")", ")", "if", "(", "(", "admin_port", "in", "ep", ".", "url", "and", "ep", ".", "interface", "==", "'admin'", ")", "or", "(", "internal_port", "in", "ep", ".", "url", "and", "ep", ".", "interface", "==", "'internal'", ")", "or", "(", "public_port", "in", "ep", ".", "url", "and", "ep", ".", "interface", "==", "'public'", ")", ")", ":", "found", ".", "append", "(", "ep", ".", "interface", ")", "# note we ignore the links member.", "actual", "=", "{", "'id'", ":", "ep", ".", "id", ",", "'region'", ":", "ep", ".", "region", ",", "'region_id'", ":", "ep", ".", "region_id", ",", "'interface'", ":", "self", ".", "not_null", ",", "'url'", ":", "ep", ".", "url", ",", "'service_id'", ":", "ep", ".", "service_id", ",", "}", "ret", "=", "self", ".", "_validate_dict_data", "(", "expected", ",", "actual", ")", "if", "ret", ":", "return", "'unexpected endpoint data - {}'", ".", "format", "(", "ret", ")", "if", "len", "(", "found", ")", "!=", "expected_num_eps", ":", "return", "'Unexpected number of endpoints found'" ]
Validate keystone v3 endpoint data. Validate the v3 endpoint data which has changed from v2. The ports are used to find the matching endpoint. The new v3 endpoint data looks like: [<Endpoint enabled=True, id=0432655fc2f74d1e9fa17bdaa6f6e60b, interface=admin, links={u'self': u'<RESTful URL of this endpoint>'}, region=RegionOne, region_id=RegionOne, service_id=17f842a0dc084b928e476fafe67e4095, url=http://10.5.6.5:9312>, <Endpoint enabled=True, id=6536cb6cb92f4f41bf22b079935c7707, interface=admin, links={u'self': u'<RESTful url of this endpoint>'}, region=RegionOne, region_id=RegionOne, service_id=72fc8736fb41435e8b3584205bb2cfa3, url=http://10.5.6.6:35357/v3>, ... ]
[ "Validate", "keystone", "v3", "endpoint", "data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L131-L179
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.convert_svc_catalog_endpoint_data_to_v3
def convert_svc_catalog_endpoint_data_to_v3(self, ep_data): """Convert v2 endpoint data into v3. { 'service_name1': [ { 'adminURL': adminURL, 'id': id, 'region': region. 'publicURL': publicURL, 'internalURL': internalURL }], 'service_name2': [ { 'adminURL': adminURL, 'id': id, 'region': region. 'publicURL': publicURL, 'internalURL': internalURL }], } """ self.log.warn("Endpoint ID and Region ID validation is limited to not " "null checks after v2 to v3 conversion") for svc in ep_data.keys(): assert len(ep_data[svc]) == 1, "Unknown data format" svc_ep_data = ep_data[svc][0] ep_data[svc] = [ { 'url': svc_ep_data['adminURL'], 'interface': 'admin', 'region': svc_ep_data['region'], 'region_id': self.not_null, 'id': self.not_null}, { 'url': svc_ep_data['publicURL'], 'interface': 'public', 'region': svc_ep_data['region'], 'region_id': self.not_null, 'id': self.not_null}, { 'url': svc_ep_data['internalURL'], 'interface': 'internal', 'region': svc_ep_data['region'], 'region_id': self.not_null, 'id': self.not_null}] return ep_data
python
def convert_svc_catalog_endpoint_data_to_v3(self, ep_data): """Convert v2 endpoint data into v3. { 'service_name1': [ { 'adminURL': adminURL, 'id': id, 'region': region. 'publicURL': publicURL, 'internalURL': internalURL }], 'service_name2': [ { 'adminURL': adminURL, 'id': id, 'region': region. 'publicURL': publicURL, 'internalURL': internalURL }], } """ self.log.warn("Endpoint ID and Region ID validation is limited to not " "null checks after v2 to v3 conversion") for svc in ep_data.keys(): assert len(ep_data[svc]) == 1, "Unknown data format" svc_ep_data = ep_data[svc][0] ep_data[svc] = [ { 'url': svc_ep_data['adminURL'], 'interface': 'admin', 'region': svc_ep_data['region'], 'region_id': self.not_null, 'id': self.not_null}, { 'url': svc_ep_data['publicURL'], 'interface': 'public', 'region': svc_ep_data['region'], 'region_id': self.not_null, 'id': self.not_null}, { 'url': svc_ep_data['internalURL'], 'interface': 'internal', 'region': svc_ep_data['region'], 'region_id': self.not_null, 'id': self.not_null}] return ep_data
[ "def", "convert_svc_catalog_endpoint_data_to_v3", "(", "self", ",", "ep_data", ")", ":", "self", ".", "log", ".", "warn", "(", "\"Endpoint ID and Region ID validation is limited to not \"", "\"null checks after v2 to v3 conversion\"", ")", "for", "svc", "in", "ep_data", ".", "keys", "(", ")", ":", "assert", "len", "(", "ep_data", "[", "svc", "]", ")", "==", "1", ",", "\"Unknown data format\"", "svc_ep_data", "=", "ep_data", "[", "svc", "]", "[", "0", "]", "ep_data", "[", "svc", "]", "=", "[", "{", "'url'", ":", "svc_ep_data", "[", "'adminURL'", "]", ",", "'interface'", ":", "'admin'", ",", "'region'", ":", "svc_ep_data", "[", "'region'", "]", ",", "'region_id'", ":", "self", ".", "not_null", ",", "'id'", ":", "self", ".", "not_null", "}", ",", "{", "'url'", ":", "svc_ep_data", "[", "'publicURL'", "]", ",", "'interface'", ":", "'public'", ",", "'region'", ":", "svc_ep_data", "[", "'region'", "]", ",", "'region_id'", ":", "self", ".", "not_null", ",", "'id'", ":", "self", ".", "not_null", "}", ",", "{", "'url'", ":", "svc_ep_data", "[", "'internalURL'", "]", ",", "'interface'", ":", "'internal'", ",", "'region'", ":", "svc_ep_data", "[", "'region'", "]", ",", "'region_id'", ":", "self", ".", "not_null", ",", "'id'", ":", "self", ".", "not_null", "}", "]", "return", "ep_data" ]
Convert v2 endpoint data into v3. { 'service_name1': [ { 'adminURL': adminURL, 'id': id, 'region': region. 'publicURL': publicURL, 'internalURL': internalURL }], 'service_name2': [ { 'adminURL': adminURL, 'id': id, 'region': region. 'publicURL': publicURL, 'internalURL': internalURL }], }
[ "Convert", "v2", "endpoint", "data", "into", "v3", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L181-L227
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_v2_svc_catalog_endpoint_data
def validate_v2_svc_catalog_endpoint_data(self, expected, actual): """Validate service catalog endpoint data. Validate a list of actual service catalog endpoints vs a list of expected service catalog endpoints. """ self.log.debug('Validating service catalog endpoint data...') self.log.debug('actual: {}'.format(repr(actual))) for k, v in six.iteritems(expected): if k in actual: ret = self._validate_dict_data(expected[k][0], actual[k][0]) if ret: return self.endpoint_error(k, ret) else: return "endpoint {} does not exist".format(k) return ret
python
def validate_v2_svc_catalog_endpoint_data(self, expected, actual): """Validate service catalog endpoint data. Validate a list of actual service catalog endpoints vs a list of expected service catalog endpoints. """ self.log.debug('Validating service catalog endpoint data...') self.log.debug('actual: {}'.format(repr(actual))) for k, v in six.iteritems(expected): if k in actual: ret = self._validate_dict_data(expected[k][0], actual[k][0]) if ret: return self.endpoint_error(k, ret) else: return "endpoint {} does not exist".format(k) return ret
[ "def", "validate_v2_svc_catalog_endpoint_data", "(", "self", ",", "expected", ",", "actual", ")", ":", "self", ".", "log", ".", "debug", "(", "'Validating service catalog endpoint data...'", ")", "self", ".", "log", ".", "debug", "(", "'actual: {}'", ".", "format", "(", "repr", "(", "actual", ")", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "expected", ")", ":", "if", "k", "in", "actual", ":", "ret", "=", "self", ".", "_validate_dict_data", "(", "expected", "[", "k", "]", "[", "0", "]", ",", "actual", "[", "k", "]", "[", "0", "]", ")", "if", "ret", ":", "return", "self", ".", "endpoint_error", "(", "k", ",", "ret", ")", "else", ":", "return", "\"endpoint {} does not exist\"", ".", "format", "(", "k", ")", "return", "ret" ]
Validate service catalog endpoint data. Validate a list of actual service catalog endpoints vs a list of expected service catalog endpoints.
[ "Validate", "service", "catalog", "endpoint", "data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L260-L275
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_v3_svc_catalog_endpoint_data
def validate_v3_svc_catalog_endpoint_data(self, expected, actual): """Validate the keystone v3 catalog endpoint data. Validate a list of dictinaries that make up the keystone v3 service catalogue. It is in the form of: {u'identity': [{u'id': u'48346b01c6804b298cdd7349aadb732e', u'interface': u'admin', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.224:35357/v3'}, {u'id': u'8414f7352a4b47a69fddd9dbd2aef5cf', u'interface': u'public', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.224:5000/v3'}, {u'id': u'd5ca31440cc24ee1bf625e2996fb6a5b', u'interface': u'internal', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.224:5000/v3'}], u'key-manager': [{u'id': u'68ebc17df0b045fcb8a8a433ebea9e62', u'interface': u'public', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.223:9311'}, {u'id': u'9cdfe2a893c34afd8f504eb218cd2f9d', u'interface': u'internal', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.223:9311'}, {u'id': u'f629388955bc407f8b11d8b7ca168086', u'interface': u'admin', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.223:9312'}]} Note, that an added complication is that the order of admin, public, internal against 'interface' in each region. Thus, the function sorts the expected and actual lists using the interface key as a sort key, prior to the comparison. """ self.log.debug('Validating v3 service catalog endpoint data...') self.log.debug('actual: {}'.format(repr(actual))) for k, v in six.iteritems(expected): if k in actual: l_expected = sorted(v, key=lambda x: x['interface']) l_actual = sorted(actual[k], key=lambda x: x['interface']) if len(l_actual) != len(l_expected): return ("endpoint {} has differing number of interfaces " " - expected({}), actual({})" .format(k, len(l_expected), len(l_actual))) for i_expected, i_actual in zip(l_expected, l_actual): self.log.debug("checking interface {}" .format(i_expected['interface'])) ret = self._validate_dict_data(i_expected, i_actual) if ret: return self.endpoint_error(k, ret) else: return "endpoint {} does not exist".format(k) return ret
python
def validate_v3_svc_catalog_endpoint_data(self, expected, actual): """Validate the keystone v3 catalog endpoint data. Validate a list of dictinaries that make up the keystone v3 service catalogue. It is in the form of: {u'identity': [{u'id': u'48346b01c6804b298cdd7349aadb732e', u'interface': u'admin', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.224:35357/v3'}, {u'id': u'8414f7352a4b47a69fddd9dbd2aef5cf', u'interface': u'public', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.224:5000/v3'}, {u'id': u'd5ca31440cc24ee1bf625e2996fb6a5b', u'interface': u'internal', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.224:5000/v3'}], u'key-manager': [{u'id': u'68ebc17df0b045fcb8a8a433ebea9e62', u'interface': u'public', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.223:9311'}, {u'id': u'9cdfe2a893c34afd8f504eb218cd2f9d', u'interface': u'internal', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.223:9311'}, {u'id': u'f629388955bc407f8b11d8b7ca168086', u'interface': u'admin', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.223:9312'}]} Note, that an added complication is that the order of admin, public, internal against 'interface' in each region. Thus, the function sorts the expected and actual lists using the interface key as a sort key, prior to the comparison. """ self.log.debug('Validating v3 service catalog endpoint data...') self.log.debug('actual: {}'.format(repr(actual))) for k, v in six.iteritems(expected): if k in actual: l_expected = sorted(v, key=lambda x: x['interface']) l_actual = sorted(actual[k], key=lambda x: x['interface']) if len(l_actual) != len(l_expected): return ("endpoint {} has differing number of interfaces " " - expected({}), actual({})" .format(k, len(l_expected), len(l_actual))) for i_expected, i_actual in zip(l_expected, l_actual): self.log.debug("checking interface {}" .format(i_expected['interface'])) ret = self._validate_dict_data(i_expected, i_actual) if ret: return self.endpoint_error(k, ret) else: return "endpoint {} does not exist".format(k) return ret
[ "def", "validate_v3_svc_catalog_endpoint_data", "(", "self", ",", "expected", ",", "actual", ")", ":", "self", ".", "log", ".", "debug", "(", "'Validating v3 service catalog endpoint data...'", ")", "self", ".", "log", ".", "debug", "(", "'actual: {}'", ".", "format", "(", "repr", "(", "actual", ")", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "expected", ")", ":", "if", "k", "in", "actual", ":", "l_expected", "=", "sorted", "(", "v", ",", "key", "=", "lambda", "x", ":", "x", "[", "'interface'", "]", ")", "l_actual", "=", "sorted", "(", "actual", "[", "k", "]", ",", "key", "=", "lambda", "x", ":", "x", "[", "'interface'", "]", ")", "if", "len", "(", "l_actual", ")", "!=", "len", "(", "l_expected", ")", ":", "return", "(", "\"endpoint {} has differing number of interfaces \"", "\" - expected({}), actual({})\"", ".", "format", "(", "k", ",", "len", "(", "l_expected", ")", ",", "len", "(", "l_actual", ")", ")", ")", "for", "i_expected", ",", "i_actual", "in", "zip", "(", "l_expected", ",", "l_actual", ")", ":", "self", ".", "log", ".", "debug", "(", "\"checking interface {}\"", ".", "format", "(", "i_expected", "[", "'interface'", "]", ")", ")", "ret", "=", "self", ".", "_validate_dict_data", "(", "i_expected", ",", "i_actual", ")", "if", "ret", ":", "return", "self", ".", "endpoint_error", "(", "k", ",", "ret", ")", "else", ":", "return", "\"endpoint {} does not exist\"", ".", "format", "(", "k", ")", "return", "ret" ]
Validate the keystone v3 catalog endpoint data. Validate a list of dictinaries that make up the keystone v3 service catalogue. It is in the form of: {u'identity': [{u'id': u'48346b01c6804b298cdd7349aadb732e', u'interface': u'admin', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.224:35357/v3'}, {u'id': u'8414f7352a4b47a69fddd9dbd2aef5cf', u'interface': u'public', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.224:5000/v3'}, {u'id': u'd5ca31440cc24ee1bf625e2996fb6a5b', u'interface': u'internal', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.224:5000/v3'}], u'key-manager': [{u'id': u'68ebc17df0b045fcb8a8a433ebea9e62', u'interface': u'public', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.223:9311'}, {u'id': u'9cdfe2a893c34afd8f504eb218cd2f9d', u'interface': u'internal', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.223:9311'}, {u'id': u'f629388955bc407f8b11d8b7ca168086', u'interface': u'admin', u'region': u'RegionOne', u'region_id': u'RegionOne', u'url': u'http://10.5.5.223:9312'}]} Note, that an added complication is that the order of admin, public, internal against 'interface' in each region. Thus, the function sorts the expected and actual lists using the interface key as a sort key, prior to the comparison.
[ "Validate", "the", "keystone", "v3", "catalog", "endpoint", "data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L277-L341
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_tenant_data
def validate_tenant_data(self, expected, actual): """Validate tenant data. Validate a list of actual tenant data vs list of expected tenant data. """ self.log.debug('Validating tenant data...') self.log.debug('actual: {}'.format(repr(actual))) for e in expected: found = False for act in actual: a = {'enabled': act.enabled, 'description': act.description, 'name': act.name, 'id': act.id} if e['name'] == a['name']: found = True ret = self._validate_dict_data(e, a) if ret: return "unexpected tenant data - {}".format(ret) if not found: return "tenant {} does not exist".format(e['name']) return ret
python
def validate_tenant_data(self, expected, actual): """Validate tenant data. Validate a list of actual tenant data vs list of expected tenant data. """ self.log.debug('Validating tenant data...') self.log.debug('actual: {}'.format(repr(actual))) for e in expected: found = False for act in actual: a = {'enabled': act.enabled, 'description': act.description, 'name': act.name, 'id': act.id} if e['name'] == a['name']: found = True ret = self._validate_dict_data(e, a) if ret: return "unexpected tenant data - {}".format(ret) if not found: return "tenant {} does not exist".format(e['name']) return ret
[ "def", "validate_tenant_data", "(", "self", ",", "expected", ",", "actual", ")", ":", "self", ".", "log", ".", "debug", "(", "'Validating tenant data...'", ")", "self", ".", "log", ".", "debug", "(", "'actual: {}'", ".", "format", "(", "repr", "(", "actual", ")", ")", ")", "for", "e", "in", "expected", ":", "found", "=", "False", "for", "act", "in", "actual", ":", "a", "=", "{", "'enabled'", ":", "act", ".", "enabled", ",", "'description'", ":", "act", ".", "description", ",", "'name'", ":", "act", ".", "name", ",", "'id'", ":", "act", ".", "id", "}", "if", "e", "[", "'name'", "]", "==", "a", "[", "'name'", "]", ":", "found", "=", "True", "ret", "=", "self", ".", "_validate_dict_data", "(", "e", ",", "a", ")", "if", "ret", ":", "return", "\"unexpected tenant data - {}\"", ".", "format", "(", "ret", ")", "if", "not", "found", ":", "return", "\"tenant {} does not exist\"", ".", "format", "(", "e", "[", "'name'", "]", ")", "return", "ret" ]
Validate tenant data. Validate a list of actual tenant data vs list of expected tenant data.
[ "Validate", "tenant", "data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L343-L363
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_user_data
def validate_user_data(self, expected, actual, api_version=None): """Validate user data. Validate a list of actual user data vs a list of expected user data. """ self.log.debug('Validating user data...') self.log.debug('actual: {}'.format(repr(actual))) for e in expected: found = False for act in actual: if e['name'] == act.name: a = {'enabled': act.enabled, 'name': act.name, 'email': act.email, 'id': act.id} if api_version == 3: a['default_project_id'] = getattr(act, 'default_project_id', 'none') else: a['tenantId'] = act.tenantId found = True ret = self._validate_dict_data(e, a) if ret: return "unexpected user data - {}".format(ret) if not found: return "user {} does not exist".format(e['name']) return ret
python
def validate_user_data(self, expected, actual, api_version=None): """Validate user data. Validate a list of actual user data vs a list of expected user data. """ self.log.debug('Validating user data...') self.log.debug('actual: {}'.format(repr(actual))) for e in expected: found = False for act in actual: if e['name'] == act.name: a = {'enabled': act.enabled, 'name': act.name, 'email': act.email, 'id': act.id} if api_version == 3: a['default_project_id'] = getattr(act, 'default_project_id', 'none') else: a['tenantId'] = act.tenantId found = True ret = self._validate_dict_data(e, a) if ret: return "unexpected user data - {}".format(ret) if not found: return "user {} does not exist".format(e['name']) return ret
[ "def", "validate_user_data", "(", "self", ",", "expected", ",", "actual", ",", "api_version", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "'Validating user data...'", ")", "self", ".", "log", ".", "debug", "(", "'actual: {}'", ".", "format", "(", "repr", "(", "actual", ")", ")", ")", "for", "e", "in", "expected", ":", "found", "=", "False", "for", "act", "in", "actual", ":", "if", "e", "[", "'name'", "]", "==", "act", ".", "name", ":", "a", "=", "{", "'enabled'", ":", "act", ".", "enabled", ",", "'name'", ":", "act", ".", "name", ",", "'email'", ":", "act", ".", "email", ",", "'id'", ":", "act", ".", "id", "}", "if", "api_version", "==", "3", ":", "a", "[", "'default_project_id'", "]", "=", "getattr", "(", "act", ",", "'default_project_id'", ",", "'none'", ")", "else", ":", "a", "[", "'tenantId'", "]", "=", "act", ".", "tenantId", "found", "=", "True", "ret", "=", "self", ".", "_validate_dict_data", "(", "e", ",", "a", ")", "if", "ret", ":", "return", "\"unexpected user data - {}\"", ".", "format", "(", "ret", ")", "if", "not", "found", ":", "return", "\"user {} does not exist\"", ".", "format", "(", "e", "[", "'name'", "]", ")", "return", "ret" ]
Validate user data. Validate a list of actual user data vs a list of expected user data.
[ "Validate", "user", "data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L386-L412
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.validate_flavor_data
def validate_flavor_data(self, expected, actual): """Validate flavor data. Validate a list of actual flavors vs a list of expected flavors. """ self.log.debug('Validating flavor data...') self.log.debug('actual: {}'.format(repr(actual))) act = [a.name for a in actual] return self._validate_list_data(expected, act)
python
def validate_flavor_data(self, expected, actual): """Validate flavor data. Validate a list of actual flavors vs a list of expected flavors. """ self.log.debug('Validating flavor data...') self.log.debug('actual: {}'.format(repr(actual))) act = [a.name for a in actual] return self._validate_list_data(expected, act)
[ "def", "validate_flavor_data", "(", "self", ",", "expected", ",", "actual", ")", ":", "self", ".", "log", ".", "debug", "(", "'Validating flavor data...'", ")", "self", ".", "log", ".", "debug", "(", "'actual: {}'", ".", "format", "(", "repr", "(", "actual", ")", ")", ")", "act", "=", "[", "a", ".", "name", "for", "a", "in", "actual", "]", "return", "self", ".", "_validate_list_data", "(", "expected", ",", "act", ")" ]
Validate flavor data. Validate a list of actual flavors vs a list of expected flavors.
[ "Validate", "flavor", "data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L414-L422
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.tenant_exists
def tenant_exists(self, keystone, tenant): """Return True if tenant exists.""" self.log.debug('Checking if tenant exists ({})...'.format(tenant)) return tenant in [t.name for t in keystone.tenants.list()]
python
def tenant_exists(self, keystone, tenant): """Return True if tenant exists.""" self.log.debug('Checking if tenant exists ({})...'.format(tenant)) return tenant in [t.name for t in keystone.tenants.list()]
[ "def", "tenant_exists", "(", "self", ",", "keystone", ",", "tenant", ")", ":", "self", ".", "log", ".", "debug", "(", "'Checking if tenant exists ({})...'", ".", "format", "(", "tenant", ")", ")", "return", "tenant", "in", "[", "t", ".", "name", "for", "t", "in", "keystone", ".", "tenants", ".", "list", "(", ")", "]" ]
Return True if tenant exists.
[ "Return", "True", "if", "tenant", "exists", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L424-L427
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.keystone_wait_for_propagation
def keystone_wait_for_propagation(self, sentry_relation_pairs, api_version): """Iterate over list of sentry and relation tuples and verify that api_version has the expected value. :param sentry_relation_pairs: list of sentry, relation name tuples used for monitoring propagation of relation data :param api_version: api_version to expect in relation data :returns: None if successful. Raise on error. """ for (sentry, relation_name) in sentry_relation_pairs: rel = sentry.relation('identity-service', relation_name) self.log.debug('keystone relation data: {}'.format(rel)) if rel.get('api_version') != str(api_version): raise Exception("api_version not propagated through relation" " data yet ('{}' != '{}')." "".format(rel.get('api_version'), api_version))
python
def keystone_wait_for_propagation(self, sentry_relation_pairs, api_version): """Iterate over list of sentry and relation tuples and verify that api_version has the expected value. :param sentry_relation_pairs: list of sentry, relation name tuples used for monitoring propagation of relation data :param api_version: api_version to expect in relation data :returns: None if successful. Raise on error. """ for (sentry, relation_name) in sentry_relation_pairs: rel = sentry.relation('identity-service', relation_name) self.log.debug('keystone relation data: {}'.format(rel)) if rel.get('api_version') != str(api_version): raise Exception("api_version not propagated through relation" " data yet ('{}' != '{}')." "".format(rel.get('api_version'), api_version))
[ "def", "keystone_wait_for_propagation", "(", "self", ",", "sentry_relation_pairs", ",", "api_version", ")", ":", "for", "(", "sentry", ",", "relation_name", ")", "in", "sentry_relation_pairs", ":", "rel", "=", "sentry", ".", "relation", "(", "'identity-service'", ",", "relation_name", ")", "self", ".", "log", ".", "debug", "(", "'keystone relation data: {}'", ".", "format", "(", "rel", ")", ")", "if", "rel", ".", "get", "(", "'api_version'", ")", "!=", "str", "(", "api_version", ")", ":", "raise", "Exception", "(", "\"api_version not propagated through relation\"", "\" data yet ('{}' != '{}').\"", "\"\"", ".", "format", "(", "rel", ".", "get", "(", "'api_version'", ")", ",", "api_version", ")", ")" ]
Iterate over list of sentry and relation tuples and verify that api_version has the expected value. :param sentry_relation_pairs: list of sentry, relation name tuples used for monitoring propagation of relation data :param api_version: api_version to expect in relation data :returns: None if successful. Raise on error.
[ "Iterate", "over", "list", "of", "sentry", "and", "relation", "tuples", "and", "verify", "that", "api_version", "has", "the", "expected", "value", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L430-L448
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.keystone_configure_api_version
def keystone_configure_api_version(self, sentry_relation_pairs, deployment, api_version): """Configure preferred-api-version of keystone in deployment and monitor provided list of relation objects for propagation before returning to caller. :param sentry_relation_pairs: list of sentry, relation tuples used for monitoring propagation of relation data :param deployment: deployment to configure :param api_version: value preferred-api-version will be set to :returns: None if successful. Raise on error. """ self.log.debug("Setting keystone preferred-api-version: '{}'" "".format(api_version)) config = {'preferred-api-version': api_version} deployment.d.configure('keystone', config) deployment._auto_wait_for_status() self.keystone_wait_for_propagation(sentry_relation_pairs, api_version)
python
def keystone_configure_api_version(self, sentry_relation_pairs, deployment, api_version): """Configure preferred-api-version of keystone in deployment and monitor provided list of relation objects for propagation before returning to caller. :param sentry_relation_pairs: list of sentry, relation tuples used for monitoring propagation of relation data :param deployment: deployment to configure :param api_version: value preferred-api-version will be set to :returns: None if successful. Raise on error. """ self.log.debug("Setting keystone preferred-api-version: '{}'" "".format(api_version)) config = {'preferred-api-version': api_version} deployment.d.configure('keystone', config) deployment._auto_wait_for_status() self.keystone_wait_for_propagation(sentry_relation_pairs, api_version)
[ "def", "keystone_configure_api_version", "(", "self", ",", "sentry_relation_pairs", ",", "deployment", ",", "api_version", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Setting keystone preferred-api-version: '{}'\"", "\"\"", ".", "format", "(", "api_version", ")", ")", "config", "=", "{", "'preferred-api-version'", ":", "api_version", "}", "deployment", ".", "d", ".", "configure", "(", "'keystone'", ",", "config", ")", "deployment", ".", "_auto_wait_for_status", "(", ")", "self", ".", "keystone_wait_for_propagation", "(", "sentry_relation_pairs", ",", "api_version", ")" ]
Configure preferred-api-version of keystone in deployment and monitor provided list of relation objects for propagation before returning to caller. :param sentry_relation_pairs: list of sentry, relation tuples used for monitoring propagation of relation data :param deployment: deployment to configure :param api_version: value preferred-api-version will be set to :returns: None if successful. Raise on error.
[ "Configure", "preferred", "-", "api", "-", "version", "of", "keystone", "in", "deployment", "and", "monitor", "provided", "list", "of", "relation", "objects", "for", "propagation", "before", "returning", "to", "caller", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L450-L468
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.authenticate_cinder_admin
def authenticate_cinder_admin(self, keystone, api_version=2): """Authenticates admin user with cinder.""" self.log.debug('Authenticating cinder admin...') _clients = { 1: cinder_client.Client, 2: cinder_clientv2.Client} return _clients[api_version](session=keystone.session)
python
def authenticate_cinder_admin(self, keystone, api_version=2): """Authenticates admin user with cinder.""" self.log.debug('Authenticating cinder admin...') _clients = { 1: cinder_client.Client, 2: cinder_clientv2.Client} return _clients[api_version](session=keystone.session)
[ "def", "authenticate_cinder_admin", "(", "self", ",", "keystone", ",", "api_version", "=", "2", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating cinder admin...'", ")", "_clients", "=", "{", "1", ":", "cinder_client", ".", "Client", ",", "2", ":", "cinder_clientv2", ".", "Client", "}", "return", "_clients", "[", "api_version", "]", "(", "session", "=", "keystone", ".", "session", ")" ]
Authenticates admin user with cinder.
[ "Authenticates", "admin", "user", "with", "cinder", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L470-L476
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.authenticate_keystone
def authenticate_keystone(self, keystone_ip, username, password, api_version=False, admin_port=False, user_domain_name=None, domain_name=None, project_domain_name=None, project_name=None): """Authenticate with Keystone""" self.log.debug('Authenticating with keystone...') if not api_version: api_version = 2 sess, auth = self.get_keystone_session( keystone_ip=keystone_ip, username=username, password=password, api_version=api_version, admin_port=admin_port, user_domain_name=user_domain_name, domain_name=domain_name, project_domain_name=project_domain_name, project_name=project_name ) if api_version == 2: client = keystone_client.Client(session=sess) else: client = keystone_client_v3.Client(session=sess) # This populates the client.service_catalog client.auth_ref = auth.get_access(sess) return client
python
def authenticate_keystone(self, keystone_ip, username, password, api_version=False, admin_port=False, user_domain_name=None, domain_name=None, project_domain_name=None, project_name=None): """Authenticate with Keystone""" self.log.debug('Authenticating with keystone...') if not api_version: api_version = 2 sess, auth = self.get_keystone_session( keystone_ip=keystone_ip, username=username, password=password, api_version=api_version, admin_port=admin_port, user_domain_name=user_domain_name, domain_name=domain_name, project_domain_name=project_domain_name, project_name=project_name ) if api_version == 2: client = keystone_client.Client(session=sess) else: client = keystone_client_v3.Client(session=sess) # This populates the client.service_catalog client.auth_ref = auth.get_access(sess) return client
[ "def", "authenticate_keystone", "(", "self", ",", "keystone_ip", ",", "username", ",", "password", ",", "api_version", "=", "False", ",", "admin_port", "=", "False", ",", "user_domain_name", "=", "None", ",", "domain_name", "=", "None", ",", "project_domain_name", "=", "None", ",", "project_name", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating with keystone...'", ")", "if", "not", "api_version", ":", "api_version", "=", "2", "sess", ",", "auth", "=", "self", ".", "get_keystone_session", "(", "keystone_ip", "=", "keystone_ip", ",", "username", "=", "username", ",", "password", "=", "password", ",", "api_version", "=", "api_version", ",", "admin_port", "=", "admin_port", ",", "user_domain_name", "=", "user_domain_name", ",", "domain_name", "=", "domain_name", ",", "project_domain_name", "=", "project_domain_name", ",", "project_name", "=", "project_name", ")", "if", "api_version", "==", "2", ":", "client", "=", "keystone_client", ".", "Client", "(", "session", "=", "sess", ")", "else", ":", "client", "=", "keystone_client_v3", ".", "Client", "(", "session", "=", "sess", ")", "# This populates the client.service_catalog", "client", ".", "auth_ref", "=", "auth", ".", "get_access", "(", "sess", ")", "return", "client" ]
Authenticate with Keystone
[ "Authenticate", "with", "Keystone" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L478-L503
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.get_keystone_session
def get_keystone_session(self, keystone_ip, username, password, api_version=False, admin_port=False, user_domain_name=None, domain_name=None, project_domain_name=None, project_name=None): """Return a keystone session object""" ep = self.get_keystone_endpoint(keystone_ip, api_version=api_version, admin_port=admin_port) if api_version == 2: auth = v2.Password( username=username, password=password, tenant_name=project_name, auth_url=ep ) sess = keystone_session.Session(auth=auth) else: auth = v3.Password( user_domain_name=user_domain_name, username=username, password=password, domain_name=domain_name, project_domain_name=project_domain_name, project_name=project_name, auth_url=ep ) sess = keystone_session.Session(auth=auth) return (sess, auth)
python
def get_keystone_session(self, keystone_ip, username, password, api_version=False, admin_port=False, user_domain_name=None, domain_name=None, project_domain_name=None, project_name=None): """Return a keystone session object""" ep = self.get_keystone_endpoint(keystone_ip, api_version=api_version, admin_port=admin_port) if api_version == 2: auth = v2.Password( username=username, password=password, tenant_name=project_name, auth_url=ep ) sess = keystone_session.Session(auth=auth) else: auth = v3.Password( user_domain_name=user_domain_name, username=username, password=password, domain_name=domain_name, project_domain_name=project_domain_name, project_name=project_name, auth_url=ep ) sess = keystone_session.Session(auth=auth) return (sess, auth)
[ "def", "get_keystone_session", "(", "self", ",", "keystone_ip", ",", "username", ",", "password", ",", "api_version", "=", "False", ",", "admin_port", "=", "False", ",", "user_domain_name", "=", "None", ",", "domain_name", "=", "None", ",", "project_domain_name", "=", "None", ",", "project_name", "=", "None", ")", ":", "ep", "=", "self", ".", "get_keystone_endpoint", "(", "keystone_ip", ",", "api_version", "=", "api_version", ",", "admin_port", "=", "admin_port", ")", "if", "api_version", "==", "2", ":", "auth", "=", "v2", ".", "Password", "(", "username", "=", "username", ",", "password", "=", "password", ",", "tenant_name", "=", "project_name", ",", "auth_url", "=", "ep", ")", "sess", "=", "keystone_session", ".", "Session", "(", "auth", "=", "auth", ")", "else", ":", "auth", "=", "v3", ".", "Password", "(", "user_domain_name", "=", "user_domain_name", ",", "username", "=", "username", ",", "password", "=", "password", ",", "domain_name", "=", "domain_name", ",", "project_domain_name", "=", "project_domain_name", ",", "project_name", "=", "project_name", ",", "auth_url", "=", "ep", ")", "sess", "=", "keystone_session", ".", "Session", "(", "auth", "=", "auth", ")", "return", "(", "sess", ",", "auth", ")" ]
Return a keystone session object
[ "Return", "a", "keystone", "session", "object" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L505-L532
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.get_keystone_endpoint
def get_keystone_endpoint(self, keystone_ip, api_version=None, admin_port=False): """Return keystone endpoint""" port = 5000 if admin_port: port = 35357 base_ep = "http://{}:{}".format(keystone_ip.strip().decode('utf-8'), port) if api_version == 2: ep = base_ep + "/v2.0" else: ep = base_ep + "/v3" return ep
python
def get_keystone_endpoint(self, keystone_ip, api_version=None, admin_port=False): """Return keystone endpoint""" port = 5000 if admin_port: port = 35357 base_ep = "http://{}:{}".format(keystone_ip.strip().decode('utf-8'), port) if api_version == 2: ep = base_ep + "/v2.0" else: ep = base_ep + "/v3" return ep
[ "def", "get_keystone_endpoint", "(", "self", ",", "keystone_ip", ",", "api_version", "=", "None", ",", "admin_port", "=", "False", ")", ":", "port", "=", "5000", "if", "admin_port", ":", "port", "=", "35357", "base_ep", "=", "\"http://{}:{}\"", ".", "format", "(", "keystone_ip", ".", "strip", "(", ")", ".", "decode", "(", "'utf-8'", ")", ",", "port", ")", "if", "api_version", "==", "2", ":", "ep", "=", "base_ep", "+", "\"/v2.0\"", "else", ":", "ep", "=", "base_ep", "+", "\"/v3\"", "return", "ep" ]
Return keystone endpoint
[ "Return", "keystone", "endpoint" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L534-L546
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.get_default_keystone_session
def get_default_keystone_session(self, keystone_sentry, openstack_release=None, api_version=2): """Return a keystone session object and client object assuming standard default settings Example call in amulet tests: self.keystone_session, self.keystone = u.get_default_keystone_session( self.keystone_sentry, openstack_release=self._get_openstack_release()) The session can then be used to auth other clients: neutronclient.Client(session=session) aodh_client.Client(session=session) eyc """ self.log.debug('Authenticating keystone admin...') # 11 => xenial_queens if api_version == 3 or (openstack_release and openstack_release >= 11): client_class = keystone_client_v3.Client api_version = 3 else: client_class = keystone_client.Client keystone_ip = keystone_sentry.info['public-address'] session, auth = self.get_keystone_session( keystone_ip, api_version=api_version, username='admin', password='openstack', project_name='admin', user_domain_name='admin_domain', project_domain_name='admin_domain') client = client_class(session=session) # This populates the client.service_catalog client.auth_ref = auth.get_access(session) return session, client
python
def get_default_keystone_session(self, keystone_sentry, openstack_release=None, api_version=2): """Return a keystone session object and client object assuming standard default settings Example call in amulet tests: self.keystone_session, self.keystone = u.get_default_keystone_session( self.keystone_sentry, openstack_release=self._get_openstack_release()) The session can then be used to auth other clients: neutronclient.Client(session=session) aodh_client.Client(session=session) eyc """ self.log.debug('Authenticating keystone admin...') # 11 => xenial_queens if api_version == 3 or (openstack_release and openstack_release >= 11): client_class = keystone_client_v3.Client api_version = 3 else: client_class = keystone_client.Client keystone_ip = keystone_sentry.info['public-address'] session, auth = self.get_keystone_session( keystone_ip, api_version=api_version, username='admin', password='openstack', project_name='admin', user_domain_name='admin_domain', project_domain_name='admin_domain') client = client_class(session=session) # This populates the client.service_catalog client.auth_ref = auth.get_access(session) return session, client
[ "def", "get_default_keystone_session", "(", "self", ",", "keystone_sentry", ",", "openstack_release", "=", "None", ",", "api_version", "=", "2", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating keystone admin...'", ")", "# 11 => xenial_queens", "if", "api_version", "==", "3", "or", "(", "openstack_release", "and", "openstack_release", ">=", "11", ")", ":", "client_class", "=", "keystone_client_v3", ".", "Client", "api_version", "=", "3", "else", ":", "client_class", "=", "keystone_client", ".", "Client", "keystone_ip", "=", "keystone_sentry", ".", "info", "[", "'public-address'", "]", "session", ",", "auth", "=", "self", ".", "get_keystone_session", "(", "keystone_ip", ",", "api_version", "=", "api_version", ",", "username", "=", "'admin'", ",", "password", "=", "'openstack'", ",", "project_name", "=", "'admin'", ",", "user_domain_name", "=", "'admin_domain'", ",", "project_domain_name", "=", "'admin_domain'", ")", "client", "=", "client_class", "(", "session", "=", "session", ")", "# This populates the client.service_catalog", "client", ".", "auth_ref", "=", "auth", ".", "get_access", "(", "session", ")", "return", "session", ",", "client" ]
Return a keystone session object and client object assuming standard default settings Example call in amulet tests: self.keystone_session, self.keystone = u.get_default_keystone_session( self.keystone_sentry, openstack_release=self._get_openstack_release()) The session can then be used to auth other clients: neutronclient.Client(session=session) aodh_client.Client(session=session) eyc
[ "Return", "a", "keystone", "session", "object", "and", "client", "object", "assuming", "standard", "default", "settings" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L548-L582
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.authenticate_keystone_admin
def authenticate_keystone_admin(self, keystone_sentry, user, password, tenant=None, api_version=None, keystone_ip=None, user_domain_name=None, project_domain_name=None, project_name=None): """Authenticates admin user with the keystone admin endpoint.""" self.log.debug('Authenticating keystone admin...') if not keystone_ip: keystone_ip = keystone_sentry.info['public-address'] # To support backward compatibility usage of this function if not project_name: project_name = tenant if api_version == 3 and not user_domain_name: user_domain_name = 'admin_domain' if api_version == 3 and not project_domain_name: project_domain_name = 'admin_domain' if api_version == 3 and not project_name: project_name = 'admin' return self.authenticate_keystone( keystone_ip, user, password, api_version=api_version, user_domain_name=user_domain_name, project_domain_name=project_domain_name, project_name=project_name, admin_port=True)
python
def authenticate_keystone_admin(self, keystone_sentry, user, password, tenant=None, api_version=None, keystone_ip=None, user_domain_name=None, project_domain_name=None, project_name=None): """Authenticates admin user with the keystone admin endpoint.""" self.log.debug('Authenticating keystone admin...') if not keystone_ip: keystone_ip = keystone_sentry.info['public-address'] # To support backward compatibility usage of this function if not project_name: project_name = tenant if api_version == 3 and not user_domain_name: user_domain_name = 'admin_domain' if api_version == 3 and not project_domain_name: project_domain_name = 'admin_domain' if api_version == 3 and not project_name: project_name = 'admin' return self.authenticate_keystone( keystone_ip, user, password, api_version=api_version, user_domain_name=user_domain_name, project_domain_name=project_domain_name, project_name=project_name, admin_port=True)
[ "def", "authenticate_keystone_admin", "(", "self", ",", "keystone_sentry", ",", "user", ",", "password", ",", "tenant", "=", "None", ",", "api_version", "=", "None", ",", "keystone_ip", "=", "None", ",", "user_domain_name", "=", "None", ",", "project_domain_name", "=", "None", ",", "project_name", "=", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating keystone admin...'", ")", "if", "not", "keystone_ip", ":", "keystone_ip", "=", "keystone_sentry", ".", "info", "[", "'public-address'", "]", "# To support backward compatibility usage of this function", "if", "not", "project_name", ":", "project_name", "=", "tenant", "if", "api_version", "==", "3", "and", "not", "user_domain_name", ":", "user_domain_name", "=", "'admin_domain'", "if", "api_version", "==", "3", "and", "not", "project_domain_name", ":", "project_domain_name", "=", "'admin_domain'", "if", "api_version", "==", "3", "and", "not", "project_name", ":", "project_name", "=", "'admin'", "return", "self", ".", "authenticate_keystone", "(", "keystone_ip", ",", "user", ",", "password", ",", "api_version", "=", "api_version", ",", "user_domain_name", "=", "user_domain_name", ",", "project_domain_name", "=", "project_domain_name", ",", "project_name", "=", "project_name", ",", "admin_port", "=", "True", ")" ]
Authenticates admin user with the keystone admin endpoint.
[ "Authenticates", "admin", "user", "with", "the", "keystone", "admin", "endpoint", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L584-L610
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.authenticate_keystone_user
def authenticate_keystone_user(self, keystone, user, password, tenant): """Authenticates a regular user with the keystone public endpoint.""" self.log.debug('Authenticating keystone user ({})...'.format(user)) ep = keystone.service_catalog.url_for(service_type='identity', interface='publicURL') keystone_ip = urlparse.urlparse(ep).hostname return self.authenticate_keystone(keystone_ip, user, password, project_name=tenant)
python
def authenticate_keystone_user(self, keystone, user, password, tenant): """Authenticates a regular user with the keystone public endpoint.""" self.log.debug('Authenticating keystone user ({})...'.format(user)) ep = keystone.service_catalog.url_for(service_type='identity', interface='publicURL') keystone_ip = urlparse.urlparse(ep).hostname return self.authenticate_keystone(keystone_ip, user, password, project_name=tenant)
[ "def", "authenticate_keystone_user", "(", "self", ",", "keystone", ",", "user", ",", "password", ",", "tenant", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating keystone user ({})...'", ".", "format", "(", "user", ")", ")", "ep", "=", "keystone", ".", "service_catalog", ".", "url_for", "(", "service_type", "=", "'identity'", ",", "interface", "=", "'publicURL'", ")", "keystone_ip", "=", "urlparse", ".", "urlparse", "(", "ep", ")", ".", "hostname", "return", "self", ".", "authenticate_keystone", "(", "keystone_ip", ",", "user", ",", "password", ",", "project_name", "=", "tenant", ")" ]
Authenticates a regular user with the keystone public endpoint.
[ "Authenticates", "a", "regular", "user", "with", "the", "keystone", "public", "endpoint", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L612-L620
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.authenticate_glance_admin
def authenticate_glance_admin(self, keystone, force_v1_client=False): """Authenticates admin user with glance.""" self.log.debug('Authenticating glance admin...') ep = keystone.service_catalog.url_for(service_type='image', interface='adminURL') if not force_v1_client and keystone.session: return glance_clientv2.Client("2", session=keystone.session) else: return glance_client.Client(ep, token=keystone.auth_token)
python
def authenticate_glance_admin(self, keystone, force_v1_client=False): """Authenticates admin user with glance.""" self.log.debug('Authenticating glance admin...') ep = keystone.service_catalog.url_for(service_type='image', interface='adminURL') if not force_v1_client and keystone.session: return glance_clientv2.Client("2", session=keystone.session) else: return glance_client.Client(ep, token=keystone.auth_token)
[ "def", "authenticate_glance_admin", "(", "self", ",", "keystone", ",", "force_v1_client", "=", "False", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating glance admin...'", ")", "ep", "=", "keystone", ".", "service_catalog", ".", "url_for", "(", "service_type", "=", "'image'", ",", "interface", "=", "'adminURL'", ")", "if", "not", "force_v1_client", "and", "keystone", ".", "session", ":", "return", "glance_clientv2", ".", "Client", "(", "\"2\"", ",", "session", "=", "keystone", ".", "session", ")", "else", ":", "return", "glance_client", ".", "Client", "(", "ep", ",", "token", "=", "keystone", ".", "auth_token", ")" ]
Authenticates admin user with glance.
[ "Authenticates", "admin", "user", "with", "glance", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L622-L630
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.authenticate_heat_admin
def authenticate_heat_admin(self, keystone): """Authenticates the admin user with heat.""" self.log.debug('Authenticating heat admin...') ep = keystone.service_catalog.url_for(service_type='orchestration', interface='publicURL') if keystone.session: return heat_client.Client(endpoint=ep, session=keystone.session) else: return heat_client.Client(endpoint=ep, token=keystone.auth_token)
python
def authenticate_heat_admin(self, keystone): """Authenticates the admin user with heat.""" self.log.debug('Authenticating heat admin...') ep = keystone.service_catalog.url_for(service_type='orchestration', interface='publicURL') if keystone.session: return heat_client.Client(endpoint=ep, session=keystone.session) else: return heat_client.Client(endpoint=ep, token=keystone.auth_token)
[ "def", "authenticate_heat_admin", "(", "self", ",", "keystone", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating heat admin...'", ")", "ep", "=", "keystone", ".", "service_catalog", ".", "url_for", "(", "service_type", "=", "'orchestration'", ",", "interface", "=", "'publicURL'", ")", "if", "keystone", ".", "session", ":", "return", "heat_client", ".", "Client", "(", "endpoint", "=", "ep", ",", "session", "=", "keystone", ".", "session", ")", "else", ":", "return", "heat_client", ".", "Client", "(", "endpoint", "=", "ep", ",", "token", "=", "keystone", ".", "auth_token", ")" ]
Authenticates the admin user with heat.
[ "Authenticates", "the", "admin", "user", "with", "heat", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L632-L640
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.authenticate_nova_user
def authenticate_nova_user(self, keystone, user, password, tenant): """Authenticates a regular user with nova-api.""" self.log.debug('Authenticating nova user ({})...'.format(user)) ep = keystone.service_catalog.url_for(service_type='identity', interface='publicURL') if keystone.session: return nova_client.Client(NOVA_CLIENT_VERSION, session=keystone.session, auth_url=ep) elif novaclient.__version__[0] >= "7": return nova_client.Client(NOVA_CLIENT_VERSION, username=user, password=password, project_name=tenant, auth_url=ep) else: return nova_client.Client(NOVA_CLIENT_VERSION, username=user, api_key=password, project_id=tenant, auth_url=ep)
python
def authenticate_nova_user(self, keystone, user, password, tenant): """Authenticates a regular user with nova-api.""" self.log.debug('Authenticating nova user ({})...'.format(user)) ep = keystone.service_catalog.url_for(service_type='identity', interface='publicURL') if keystone.session: return nova_client.Client(NOVA_CLIENT_VERSION, session=keystone.session, auth_url=ep) elif novaclient.__version__[0] >= "7": return nova_client.Client(NOVA_CLIENT_VERSION, username=user, password=password, project_name=tenant, auth_url=ep) else: return nova_client.Client(NOVA_CLIENT_VERSION, username=user, api_key=password, project_id=tenant, auth_url=ep)
[ "def", "authenticate_nova_user", "(", "self", ",", "keystone", ",", "user", ",", "password", ",", "tenant", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating nova user ({})...'", ".", "format", "(", "user", ")", ")", "ep", "=", "keystone", ".", "service_catalog", ".", "url_for", "(", "service_type", "=", "'identity'", ",", "interface", "=", "'publicURL'", ")", "if", "keystone", ".", "session", ":", "return", "nova_client", ".", "Client", "(", "NOVA_CLIENT_VERSION", ",", "session", "=", "keystone", ".", "session", ",", "auth_url", "=", "ep", ")", "elif", "novaclient", ".", "__version__", "[", "0", "]", ">=", "\"7\"", ":", "return", "nova_client", ".", "Client", "(", "NOVA_CLIENT_VERSION", ",", "username", "=", "user", ",", "password", "=", "password", ",", "project_name", "=", "tenant", ",", "auth_url", "=", "ep", ")", "else", ":", "return", "nova_client", ".", "Client", "(", "NOVA_CLIENT_VERSION", ",", "username", "=", "user", ",", "api_key", "=", "password", ",", "project_id", "=", "tenant", ",", "auth_url", "=", "ep", ")" ]
Authenticates a regular user with nova-api.
[ "Authenticates", "a", "regular", "user", "with", "nova", "-", "api", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L642-L658
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.authenticate_swift_user
def authenticate_swift_user(self, keystone, user, password, tenant): """Authenticates a regular user with swift api.""" self.log.debug('Authenticating swift user ({})...'.format(user)) ep = keystone.service_catalog.url_for(service_type='identity', interface='publicURL') if keystone.session: return swiftclient.Connection(session=keystone.session) else: return swiftclient.Connection(authurl=ep, user=user, key=password, tenant_name=tenant, auth_version='2.0')
python
def authenticate_swift_user(self, keystone, user, password, tenant): """Authenticates a regular user with swift api.""" self.log.debug('Authenticating swift user ({})...'.format(user)) ep = keystone.service_catalog.url_for(service_type='identity', interface='publicURL') if keystone.session: return swiftclient.Connection(session=keystone.session) else: return swiftclient.Connection(authurl=ep, user=user, key=password, tenant_name=tenant, auth_version='2.0')
[ "def", "authenticate_swift_user", "(", "self", ",", "keystone", ",", "user", ",", "password", ",", "tenant", ")", ":", "self", ".", "log", ".", "debug", "(", "'Authenticating swift user ({})...'", ".", "format", "(", "user", ")", ")", "ep", "=", "keystone", ".", "service_catalog", ".", "url_for", "(", "service_type", "=", "'identity'", ",", "interface", "=", "'publicURL'", ")", "if", "keystone", ".", "session", ":", "return", "swiftclient", ".", "Connection", "(", "session", "=", "keystone", ".", "session", ")", "else", ":", "return", "swiftclient", ".", "Connection", "(", "authurl", "=", "ep", ",", "user", "=", "user", ",", "key", "=", "password", ",", "tenant_name", "=", "tenant", ",", "auth_version", "=", "'2.0'", ")" ]
Authenticates a regular user with swift api.
[ "Authenticates", "a", "regular", "user", "with", "swift", "api", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L660-L672
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.create_flavor
def create_flavor(self, nova, name, ram, vcpus, disk, flavorid="auto", ephemeral=0, swap=0, rxtx_factor=1.0, is_public=True): """Create the specified flavor.""" try: nova.flavors.find(name=name) except (exceptions.NotFound, exceptions.NoUniqueMatch): self.log.debug('Creating flavor ({})'.format(name)) nova.flavors.create(name, ram, vcpus, disk, flavorid, ephemeral, swap, rxtx_factor, is_public)
python
def create_flavor(self, nova, name, ram, vcpus, disk, flavorid="auto", ephemeral=0, swap=0, rxtx_factor=1.0, is_public=True): """Create the specified flavor.""" try: nova.flavors.find(name=name) except (exceptions.NotFound, exceptions.NoUniqueMatch): self.log.debug('Creating flavor ({})'.format(name)) nova.flavors.create(name, ram, vcpus, disk, flavorid, ephemeral, swap, rxtx_factor, is_public)
[ "def", "create_flavor", "(", "self", ",", "nova", ",", "name", ",", "ram", ",", "vcpus", ",", "disk", ",", "flavorid", "=", "\"auto\"", ",", "ephemeral", "=", "0", ",", "swap", "=", "0", ",", "rxtx_factor", "=", "1.0", ",", "is_public", "=", "True", ")", ":", "try", ":", "nova", ".", "flavors", ".", "find", "(", "name", "=", "name", ")", "except", "(", "exceptions", ".", "NotFound", ",", "exceptions", ".", "NoUniqueMatch", ")", ":", "self", ".", "log", ".", "debug", "(", "'Creating flavor ({})'", ".", "format", "(", "name", ")", ")", "nova", ".", "flavors", ".", "create", "(", "name", ",", "ram", ",", "vcpus", ",", "disk", ",", "flavorid", ",", "ephemeral", ",", "swap", ",", "rxtx_factor", ",", "is_public", ")" ]
Create the specified flavor.
[ "Create", "the", "specified", "flavor", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L674-L682
train
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/utils.py
OpenStackAmuletUtils.glance_create_image
def glance_create_image(self, glance, image_name, image_url, download_dir='tests', hypervisor_type=None, disk_format='qcow2', architecture='x86_64', container_format='bare'): """Download an image and upload it to glance, validate its status and return an image object pointer. KVM defaults, can override for LXD. :param glance: pointer to authenticated glance api connection :param image_name: display name for new image :param image_url: url to retrieve :param download_dir: directory to store downloaded image file :param hypervisor_type: glance image hypervisor property :param disk_format: glance image disk format :param architecture: glance image architecture property :param container_format: glance image container format :returns: glance image pointer """ self.log.debug('Creating glance image ({}) from ' '{}...'.format(image_name, image_url)) # Download image http_proxy = os.getenv('AMULET_HTTP_PROXY') self.log.debug('AMULET_HTTP_PROXY: {}'.format(http_proxy)) if http_proxy: proxies = {'http': http_proxy} opener = urllib.FancyURLopener(proxies) else: opener = urllib.FancyURLopener() abs_file_name = os.path.join(download_dir, image_name) if not os.path.exists(abs_file_name): opener.retrieve(image_url, abs_file_name) # Create glance image glance_properties = { 'architecture': architecture, } if hypervisor_type: glance_properties['hypervisor_type'] = hypervisor_type # Create glance image if float(glance.version) < 2.0: with open(abs_file_name) as f: image = glance.images.create( name=image_name, is_public=True, disk_format=disk_format, container_format=container_format, properties=glance_properties, data=f) else: image = glance.images.create( name=image_name, visibility="public", disk_format=disk_format, container_format=container_format) glance.images.upload(image.id, open(abs_file_name, 'rb')) glance.images.update(image.id, **glance_properties) # Wait for image to reach active status img_id = image.id ret = self.resource_reaches_status(glance.images, img_id, expected_stat='active', msg='Image status wait') if not ret: msg = 'Glance image failed to reach expected state.' amulet.raise_status(amulet.FAIL, msg=msg) # Re-validate new image self.log.debug('Validating image attributes...') val_img_name = glance.images.get(img_id).name val_img_stat = glance.images.get(img_id).status val_img_cfmt = glance.images.get(img_id).container_format val_img_dfmt = glance.images.get(img_id).disk_format if float(glance.version) < 2.0: val_img_pub = glance.images.get(img_id).is_public else: val_img_pub = glance.images.get(img_id).visibility == "public" msg_attr = ('Image attributes - name:{} public:{} id:{} stat:{} ' 'container fmt:{} disk fmt:{}'.format( val_img_name, val_img_pub, img_id, val_img_stat, val_img_cfmt, val_img_dfmt)) if val_img_name == image_name and val_img_stat == 'active' \ and val_img_pub is True and val_img_cfmt == container_format \ and val_img_dfmt == disk_format: self.log.debug(msg_attr) else: msg = ('Image validation failed, {}'.format(msg_attr)) amulet.raise_status(amulet.FAIL, msg=msg) return image
python
def glance_create_image(self, glance, image_name, image_url, download_dir='tests', hypervisor_type=None, disk_format='qcow2', architecture='x86_64', container_format='bare'): """Download an image and upload it to glance, validate its status and return an image object pointer. KVM defaults, can override for LXD. :param glance: pointer to authenticated glance api connection :param image_name: display name for new image :param image_url: url to retrieve :param download_dir: directory to store downloaded image file :param hypervisor_type: glance image hypervisor property :param disk_format: glance image disk format :param architecture: glance image architecture property :param container_format: glance image container format :returns: glance image pointer """ self.log.debug('Creating glance image ({}) from ' '{}...'.format(image_name, image_url)) # Download image http_proxy = os.getenv('AMULET_HTTP_PROXY') self.log.debug('AMULET_HTTP_PROXY: {}'.format(http_proxy)) if http_proxy: proxies = {'http': http_proxy} opener = urllib.FancyURLopener(proxies) else: opener = urllib.FancyURLopener() abs_file_name = os.path.join(download_dir, image_name) if not os.path.exists(abs_file_name): opener.retrieve(image_url, abs_file_name) # Create glance image glance_properties = { 'architecture': architecture, } if hypervisor_type: glance_properties['hypervisor_type'] = hypervisor_type # Create glance image if float(glance.version) < 2.0: with open(abs_file_name) as f: image = glance.images.create( name=image_name, is_public=True, disk_format=disk_format, container_format=container_format, properties=glance_properties, data=f) else: image = glance.images.create( name=image_name, visibility="public", disk_format=disk_format, container_format=container_format) glance.images.upload(image.id, open(abs_file_name, 'rb')) glance.images.update(image.id, **glance_properties) # Wait for image to reach active status img_id = image.id ret = self.resource_reaches_status(glance.images, img_id, expected_stat='active', msg='Image status wait') if not ret: msg = 'Glance image failed to reach expected state.' amulet.raise_status(amulet.FAIL, msg=msg) # Re-validate new image self.log.debug('Validating image attributes...') val_img_name = glance.images.get(img_id).name val_img_stat = glance.images.get(img_id).status val_img_cfmt = glance.images.get(img_id).container_format val_img_dfmt = glance.images.get(img_id).disk_format if float(glance.version) < 2.0: val_img_pub = glance.images.get(img_id).is_public else: val_img_pub = glance.images.get(img_id).visibility == "public" msg_attr = ('Image attributes - name:{} public:{} id:{} stat:{} ' 'container fmt:{} disk fmt:{}'.format( val_img_name, val_img_pub, img_id, val_img_stat, val_img_cfmt, val_img_dfmt)) if val_img_name == image_name and val_img_stat == 'active' \ and val_img_pub is True and val_img_cfmt == container_format \ and val_img_dfmt == disk_format: self.log.debug(msg_attr) else: msg = ('Image validation failed, {}'.format(msg_attr)) amulet.raise_status(amulet.FAIL, msg=msg) return image
[ "def", "glance_create_image", "(", "self", ",", "glance", ",", "image_name", ",", "image_url", ",", "download_dir", "=", "'tests'", ",", "hypervisor_type", "=", "None", ",", "disk_format", "=", "'qcow2'", ",", "architecture", "=", "'x86_64'", ",", "container_format", "=", "'bare'", ")", ":", "self", ".", "log", ".", "debug", "(", "'Creating glance image ({}) from '", "'{}...'", ".", "format", "(", "image_name", ",", "image_url", ")", ")", "# Download image", "http_proxy", "=", "os", ".", "getenv", "(", "'AMULET_HTTP_PROXY'", ")", "self", ".", "log", ".", "debug", "(", "'AMULET_HTTP_PROXY: {}'", ".", "format", "(", "http_proxy", ")", ")", "if", "http_proxy", ":", "proxies", "=", "{", "'http'", ":", "http_proxy", "}", "opener", "=", "urllib", ".", "FancyURLopener", "(", "proxies", ")", "else", ":", "opener", "=", "urllib", ".", "FancyURLopener", "(", ")", "abs_file_name", "=", "os", ".", "path", ".", "join", "(", "download_dir", ",", "image_name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "abs_file_name", ")", ":", "opener", ".", "retrieve", "(", "image_url", ",", "abs_file_name", ")", "# Create glance image", "glance_properties", "=", "{", "'architecture'", ":", "architecture", ",", "}", "if", "hypervisor_type", ":", "glance_properties", "[", "'hypervisor_type'", "]", "=", "hypervisor_type", "# Create glance image", "if", "float", "(", "glance", ".", "version", ")", "<", "2.0", ":", "with", "open", "(", "abs_file_name", ")", "as", "f", ":", "image", "=", "glance", ".", "images", ".", "create", "(", "name", "=", "image_name", ",", "is_public", "=", "True", ",", "disk_format", "=", "disk_format", ",", "container_format", "=", "container_format", ",", "properties", "=", "glance_properties", ",", "data", "=", "f", ")", "else", ":", "image", "=", "glance", ".", "images", ".", "create", "(", "name", "=", "image_name", ",", "visibility", "=", "\"public\"", ",", "disk_format", "=", "disk_format", ",", "container_format", "=", "container_format", ")", "glance", ".", "images", ".", "upload", "(", "image", ".", "id", ",", "open", "(", "abs_file_name", ",", "'rb'", ")", ")", "glance", ".", "images", ".", "update", "(", "image", ".", "id", ",", "*", "*", "glance_properties", ")", "# Wait for image to reach active status", "img_id", "=", "image", ".", "id", "ret", "=", "self", ".", "resource_reaches_status", "(", "glance", ".", "images", ",", "img_id", ",", "expected_stat", "=", "'active'", ",", "msg", "=", "'Image status wait'", ")", "if", "not", "ret", ":", "msg", "=", "'Glance image failed to reach expected state.'", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "msg", ")", "# Re-validate new image", "self", ".", "log", ".", "debug", "(", "'Validating image attributes...'", ")", "val_img_name", "=", "glance", ".", "images", ".", "get", "(", "img_id", ")", ".", "name", "val_img_stat", "=", "glance", ".", "images", ".", "get", "(", "img_id", ")", ".", "status", "val_img_cfmt", "=", "glance", ".", "images", ".", "get", "(", "img_id", ")", ".", "container_format", "val_img_dfmt", "=", "glance", ".", "images", ".", "get", "(", "img_id", ")", ".", "disk_format", "if", "float", "(", "glance", ".", "version", ")", "<", "2.0", ":", "val_img_pub", "=", "glance", ".", "images", ".", "get", "(", "img_id", ")", ".", "is_public", "else", ":", "val_img_pub", "=", "glance", ".", "images", ".", "get", "(", "img_id", ")", ".", "visibility", "==", "\"public\"", "msg_attr", "=", "(", "'Image attributes - name:{} public:{} id:{} stat:{} '", "'container fmt:{} disk fmt:{}'", ".", "format", "(", "val_img_name", ",", "val_img_pub", ",", "img_id", ",", "val_img_stat", ",", "val_img_cfmt", ",", "val_img_dfmt", ")", ")", "if", "val_img_name", "==", "image_name", "and", "val_img_stat", "==", "'active'", "and", "val_img_pub", "is", "True", "and", "val_img_cfmt", "==", "container_format", "and", "val_img_dfmt", "==", "disk_format", ":", "self", ".", "log", ".", "debug", "(", "msg_attr", ")", "else", ":", "msg", "=", "(", "'Image validation failed, {}'", ".", "format", "(", "msg_attr", ")", ")", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "msg", ")", "return", "image" ]
Download an image and upload it to glance, validate its status and return an image object pointer. KVM defaults, can override for LXD. :param glance: pointer to authenticated glance api connection :param image_name: display name for new image :param image_url: url to retrieve :param download_dir: directory to store downloaded image file :param hypervisor_type: glance image hypervisor property :param disk_format: glance image disk format :param architecture: glance image architecture property :param container_format: glance image container format :returns: glance image pointer
[ "Download", "an", "image", "and", "upload", "it", "to", "glance", "validate", "its", "status", "and", "return", "an", "image", "object", "pointer", ".", "KVM", "defaults", "can", "override", "for", "LXD", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L684-L779
train