id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
12,500
|
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
|
12,501
|
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
|
12,502
|
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
|
12,503
|
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
|
12,504
|
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
|
12,505
|
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
|
12,506
|
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
|
12,507
|
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
|
12,508
|
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
|
12,509
|
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
|
12,510
|
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
|
12,511
|
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
|
12,512
|
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
|
12,513
|
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
|
12,514
|
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
|
12,515
|
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
|
12,516
|
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
|
12,517
|
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
|
12,518
|
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
|
12,519
|
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
|
12,520
|
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
|
12,521
|
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
|
12,522
|
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
|
12,523
|
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
|
12,524
|
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
|
12,525
|
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
|
12,526
|
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
|
12,527
|
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
|
12,528
|
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
|
12,529
|
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
|
12,530
|
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
|
12,531
|
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
|
12,532
|
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
|
12,533
|
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
|
12,534
|
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
|
12,535
|
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
|
12,536
|
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
|
12,537
|
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
|
12,538
|
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
|
12,539
|
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
|
12,540
|
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
|
12,541
|
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
|
12,542
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.create_cirros_image
|
def create_cirros_image(self, glance, image_name, hypervisor_type=None):
"""Download the latest cirros image and upload it to glance,
validate and return a resource pointer.
:param glance: pointer to authenticated glance connection
:param image_name: display name for new image
:param hypervisor_type: glance image hypervisor property
:returns: glance image pointer
"""
# /!\ DEPRECATION WARNING
self.log.warn('/!\\ DEPRECATION WARNING: use '
'glance_create_image instead of '
'create_cirros_image.')
self.log.debug('Creating glance cirros image '
'({})...'.format(image_name))
# Get cirros image URL
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()
f = opener.open('http://download.cirros-cloud.net/version/released')
version = f.read().strip()
cirros_img = 'cirros-{}-x86_64-disk.img'.format(version)
cirros_url = 'http://{}/{}/{}'.format('download.cirros-cloud.net',
version, cirros_img)
f.close()
return self.glance_create_image(
glance,
image_name,
cirros_url,
hypervisor_type=hypervisor_type)
|
python
|
def create_cirros_image(self, glance, image_name, hypervisor_type=None):
"""Download the latest cirros image and upload it to glance,
validate and return a resource pointer.
:param glance: pointer to authenticated glance connection
:param image_name: display name for new image
:param hypervisor_type: glance image hypervisor property
:returns: glance image pointer
"""
# /!\ DEPRECATION WARNING
self.log.warn('/!\\ DEPRECATION WARNING: use '
'glance_create_image instead of '
'create_cirros_image.')
self.log.debug('Creating glance cirros image '
'({})...'.format(image_name))
# Get cirros image URL
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()
f = opener.open('http://download.cirros-cloud.net/version/released')
version = f.read().strip()
cirros_img = 'cirros-{}-x86_64-disk.img'.format(version)
cirros_url = 'http://{}/{}/{}'.format('download.cirros-cloud.net',
version, cirros_img)
f.close()
return self.glance_create_image(
glance,
image_name,
cirros_url,
hypervisor_type=hypervisor_type)
|
[
"def",
"create_cirros_image",
"(",
"self",
",",
"glance",
",",
"image_name",
",",
"hypervisor_type",
"=",
"None",
")",
":",
"# /!\\ DEPRECATION WARNING",
"self",
".",
"log",
".",
"warn",
"(",
"'/!\\\\ DEPRECATION WARNING: use '",
"'glance_create_image instead of '",
"'create_cirros_image.'",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating glance cirros image '",
"'({})...'",
".",
"format",
"(",
"image_name",
")",
")",
"# Get cirros image URL",
"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",
"(",
")",
"f",
"=",
"opener",
".",
"open",
"(",
"'http://download.cirros-cloud.net/version/released'",
")",
"version",
"=",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"cirros_img",
"=",
"'cirros-{}-x86_64-disk.img'",
".",
"format",
"(",
"version",
")",
"cirros_url",
"=",
"'http://{}/{}/{}'",
".",
"format",
"(",
"'download.cirros-cloud.net'",
",",
"version",
",",
"cirros_img",
")",
"f",
".",
"close",
"(",
")",
"return",
"self",
".",
"glance_create_image",
"(",
"glance",
",",
"image_name",
",",
"cirros_url",
",",
"hypervisor_type",
"=",
"hypervisor_type",
")"
] |
Download the latest cirros image and upload it to glance,
validate and return a resource pointer.
:param glance: pointer to authenticated glance connection
:param image_name: display name for new image
:param hypervisor_type: glance image hypervisor property
:returns: glance image pointer
|
[
"Download",
"the",
"latest",
"cirros",
"image",
"and",
"upload",
"it",
"to",
"glance",
"validate",
"and",
"return",
"a",
"resource",
"pointer",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L781-L818
|
12,543
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.delete_image
|
def delete_image(self, glance, image):
"""Delete the specified image."""
# /!\ DEPRECATION WARNING
self.log.warn('/!\\ DEPRECATION WARNING: use '
'delete_resource instead of delete_image.')
self.log.debug('Deleting glance image ({})...'.format(image))
return self.delete_resource(glance.images, image, msg='glance image')
|
python
|
def delete_image(self, glance, image):
"""Delete the specified image."""
# /!\ DEPRECATION WARNING
self.log.warn('/!\\ DEPRECATION WARNING: use '
'delete_resource instead of delete_image.')
self.log.debug('Deleting glance image ({})...'.format(image))
return self.delete_resource(glance.images, image, msg='glance image')
|
[
"def",
"delete_image",
"(",
"self",
",",
"glance",
",",
"image",
")",
":",
"# /!\\ DEPRECATION WARNING",
"self",
".",
"log",
".",
"warn",
"(",
"'/!\\\\ DEPRECATION WARNING: use '",
"'delete_resource instead of delete_image.'",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Deleting glance image ({})...'",
".",
"format",
"(",
"image",
")",
")",
"return",
"self",
".",
"delete_resource",
"(",
"glance",
".",
"images",
",",
"image",
",",
"msg",
"=",
"'glance image'",
")"
] |
Delete the specified image.
|
[
"Delete",
"the",
"specified",
"image",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L820-L827
|
12,544
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.create_instance
|
def create_instance(self, nova, image_name, instance_name, flavor):
"""Create the specified instance."""
self.log.debug('Creating instance '
'({}|{}|{})'.format(instance_name, image_name, flavor))
image = nova.glance.find_image(image_name)
flavor = nova.flavors.find(name=flavor)
instance = nova.servers.create(name=instance_name, image=image,
flavor=flavor)
count = 1
status = instance.status
while status != 'ACTIVE' and count < 60:
time.sleep(3)
instance = nova.servers.get(instance.id)
status = instance.status
self.log.debug('instance status: {}'.format(status))
count += 1
if status != 'ACTIVE':
self.log.error('instance creation timed out')
return None
return instance
|
python
|
def create_instance(self, nova, image_name, instance_name, flavor):
"""Create the specified instance."""
self.log.debug('Creating instance '
'({}|{}|{})'.format(instance_name, image_name, flavor))
image = nova.glance.find_image(image_name)
flavor = nova.flavors.find(name=flavor)
instance = nova.servers.create(name=instance_name, image=image,
flavor=flavor)
count = 1
status = instance.status
while status != 'ACTIVE' and count < 60:
time.sleep(3)
instance = nova.servers.get(instance.id)
status = instance.status
self.log.debug('instance status: {}'.format(status))
count += 1
if status != 'ACTIVE':
self.log.error('instance creation timed out')
return None
return instance
|
[
"def",
"create_instance",
"(",
"self",
",",
"nova",
",",
"image_name",
",",
"instance_name",
",",
"flavor",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating instance '",
"'({}|{}|{})'",
".",
"format",
"(",
"instance_name",
",",
"image_name",
",",
"flavor",
")",
")",
"image",
"=",
"nova",
".",
"glance",
".",
"find_image",
"(",
"image_name",
")",
"flavor",
"=",
"nova",
".",
"flavors",
".",
"find",
"(",
"name",
"=",
"flavor",
")",
"instance",
"=",
"nova",
".",
"servers",
".",
"create",
"(",
"name",
"=",
"instance_name",
",",
"image",
"=",
"image",
",",
"flavor",
"=",
"flavor",
")",
"count",
"=",
"1",
"status",
"=",
"instance",
".",
"status",
"while",
"status",
"!=",
"'ACTIVE'",
"and",
"count",
"<",
"60",
":",
"time",
".",
"sleep",
"(",
"3",
")",
"instance",
"=",
"nova",
".",
"servers",
".",
"get",
"(",
"instance",
".",
"id",
")",
"status",
"=",
"instance",
".",
"status",
"self",
".",
"log",
".",
"debug",
"(",
"'instance status: {}'",
".",
"format",
"(",
"status",
")",
")",
"count",
"+=",
"1",
"if",
"status",
"!=",
"'ACTIVE'",
":",
"self",
".",
"log",
".",
"error",
"(",
"'instance creation timed out'",
")",
"return",
"None",
"return",
"instance"
] |
Create the specified instance.
|
[
"Create",
"the",
"specified",
"instance",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L829-L851
|
12,545
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.delete_instance
|
def delete_instance(self, nova, instance):
"""Delete the specified instance."""
# /!\ DEPRECATION WARNING
self.log.warn('/!\\ DEPRECATION WARNING: use '
'delete_resource instead of delete_instance.')
self.log.debug('Deleting instance ({})...'.format(instance))
return self.delete_resource(nova.servers, instance,
msg='nova instance')
|
python
|
def delete_instance(self, nova, instance):
"""Delete the specified instance."""
# /!\ DEPRECATION WARNING
self.log.warn('/!\\ DEPRECATION WARNING: use '
'delete_resource instead of delete_instance.')
self.log.debug('Deleting instance ({})...'.format(instance))
return self.delete_resource(nova.servers, instance,
msg='nova instance')
|
[
"def",
"delete_instance",
"(",
"self",
",",
"nova",
",",
"instance",
")",
":",
"# /!\\ DEPRECATION WARNING",
"self",
".",
"log",
".",
"warn",
"(",
"'/!\\\\ DEPRECATION WARNING: use '",
"'delete_resource instead of delete_instance.'",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Deleting instance ({})...'",
".",
"format",
"(",
"instance",
")",
")",
"return",
"self",
".",
"delete_resource",
"(",
"nova",
".",
"servers",
",",
"instance",
",",
"msg",
"=",
"'nova instance'",
")"
] |
Delete the specified instance.
|
[
"Delete",
"the",
"specified",
"instance",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L853-L861
|
12,546
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.create_or_get_keypair
|
def create_or_get_keypair(self, nova, keypair_name="testkey"):
"""Create a new keypair, or return pointer if it already exists."""
try:
_keypair = nova.keypairs.get(keypair_name)
self.log.debug('Keypair ({}) already exists, '
'using it.'.format(keypair_name))
return _keypair
except Exception:
self.log.debug('Keypair ({}) does not exist, '
'creating it.'.format(keypair_name))
_keypair = nova.keypairs.create(name=keypair_name)
return _keypair
|
python
|
def create_or_get_keypair(self, nova, keypair_name="testkey"):
"""Create a new keypair, or return pointer if it already exists."""
try:
_keypair = nova.keypairs.get(keypair_name)
self.log.debug('Keypair ({}) already exists, '
'using it.'.format(keypair_name))
return _keypair
except Exception:
self.log.debug('Keypair ({}) does not exist, '
'creating it.'.format(keypair_name))
_keypair = nova.keypairs.create(name=keypair_name)
return _keypair
|
[
"def",
"create_or_get_keypair",
"(",
"self",
",",
"nova",
",",
"keypair_name",
"=",
"\"testkey\"",
")",
":",
"try",
":",
"_keypair",
"=",
"nova",
".",
"keypairs",
".",
"get",
"(",
"keypair_name",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Keypair ({}) already exists, '",
"'using it.'",
".",
"format",
"(",
"keypair_name",
")",
")",
"return",
"_keypair",
"except",
"Exception",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Keypair ({}) does not exist, '",
"'creating it.'",
".",
"format",
"(",
"keypair_name",
")",
")",
"_keypair",
"=",
"nova",
".",
"keypairs",
".",
"create",
"(",
"name",
"=",
"keypair_name",
")",
"return",
"_keypair"
] |
Create a new keypair, or return pointer if it already exists.
|
[
"Create",
"a",
"new",
"keypair",
"or",
"return",
"pointer",
"if",
"it",
"already",
"exists",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L863-L875
|
12,547
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.create_cinder_volume
|
def create_cinder_volume(self, cinder, vol_name="demo-vol", vol_size=1,
img_id=None, src_vol_id=None, snap_id=None):
"""Create cinder volume, optionally from a glance image, OR
optionally as a clone of an existing volume, OR optionally
from a snapshot. Wait for the new volume status to reach
the expected status, validate and return a resource pointer.
:param vol_name: cinder volume display name
:param vol_size: size in gigabytes
:param img_id: optional glance image id
:param src_vol_id: optional source volume id to clone
:param snap_id: optional snapshot id to use
:returns: cinder volume pointer
"""
# Handle parameter input and avoid impossible combinations
if img_id and not src_vol_id and not snap_id:
# Create volume from image
self.log.debug('Creating cinder volume from glance image...')
bootable = 'true'
elif src_vol_id and not img_id and not snap_id:
# Clone an existing volume
self.log.debug('Cloning cinder volume...')
bootable = cinder.volumes.get(src_vol_id).bootable
elif snap_id and not src_vol_id and not img_id:
# Create volume from snapshot
self.log.debug('Creating cinder volume from snapshot...')
snap = cinder.volume_snapshots.find(id=snap_id)
vol_size = snap.size
snap_vol_id = cinder.volume_snapshots.get(snap_id).volume_id
bootable = cinder.volumes.get(snap_vol_id).bootable
elif not img_id and not src_vol_id and not snap_id:
# Create volume
self.log.debug('Creating cinder volume...')
bootable = 'false'
else:
# Impossible combination of parameters
msg = ('Invalid method use - name:{} size:{} img_id:{} '
'src_vol_id:{} snap_id:{}'.format(vol_name, vol_size,
img_id, src_vol_id,
snap_id))
amulet.raise_status(amulet.FAIL, msg=msg)
# Create new volume
try:
vol_new = cinder.volumes.create(display_name=vol_name,
imageRef=img_id,
size=vol_size,
source_volid=src_vol_id,
snapshot_id=snap_id)
vol_id = vol_new.id
except TypeError:
vol_new = cinder.volumes.create(name=vol_name,
imageRef=img_id,
size=vol_size,
source_volid=src_vol_id,
snapshot_id=snap_id)
vol_id = vol_new.id
except Exception as e:
msg = 'Failed to create volume: {}'.format(e)
amulet.raise_status(amulet.FAIL, msg=msg)
# Wait for volume to reach available status
ret = self.resource_reaches_status(cinder.volumes, vol_id,
expected_stat="available",
msg="Volume status wait")
if not ret:
msg = 'Cinder volume failed to reach expected state.'
amulet.raise_status(amulet.FAIL, msg=msg)
# Re-validate new volume
self.log.debug('Validating volume attributes...')
val_vol_name = self._get_cinder_obj_name(cinder.volumes.get(vol_id))
val_vol_boot = cinder.volumes.get(vol_id).bootable
val_vol_stat = cinder.volumes.get(vol_id).status
val_vol_size = cinder.volumes.get(vol_id).size
msg_attr = ('Volume attributes - name:{} id:{} stat:{} boot:'
'{} size:{}'.format(val_vol_name, vol_id,
val_vol_stat, val_vol_boot,
val_vol_size))
if val_vol_boot == bootable and val_vol_stat == 'available' \
and val_vol_name == vol_name and val_vol_size == vol_size:
self.log.debug(msg_attr)
else:
msg = ('Volume validation failed, {}'.format(msg_attr))
amulet.raise_status(amulet.FAIL, msg=msg)
return vol_new
|
python
|
def create_cinder_volume(self, cinder, vol_name="demo-vol", vol_size=1,
img_id=None, src_vol_id=None, snap_id=None):
"""Create cinder volume, optionally from a glance image, OR
optionally as a clone of an existing volume, OR optionally
from a snapshot. Wait for the new volume status to reach
the expected status, validate and return a resource pointer.
:param vol_name: cinder volume display name
:param vol_size: size in gigabytes
:param img_id: optional glance image id
:param src_vol_id: optional source volume id to clone
:param snap_id: optional snapshot id to use
:returns: cinder volume pointer
"""
# Handle parameter input and avoid impossible combinations
if img_id and not src_vol_id and not snap_id:
# Create volume from image
self.log.debug('Creating cinder volume from glance image...')
bootable = 'true'
elif src_vol_id and not img_id and not snap_id:
# Clone an existing volume
self.log.debug('Cloning cinder volume...')
bootable = cinder.volumes.get(src_vol_id).bootable
elif snap_id and not src_vol_id and not img_id:
# Create volume from snapshot
self.log.debug('Creating cinder volume from snapshot...')
snap = cinder.volume_snapshots.find(id=snap_id)
vol_size = snap.size
snap_vol_id = cinder.volume_snapshots.get(snap_id).volume_id
bootable = cinder.volumes.get(snap_vol_id).bootable
elif not img_id and not src_vol_id and not snap_id:
# Create volume
self.log.debug('Creating cinder volume...')
bootable = 'false'
else:
# Impossible combination of parameters
msg = ('Invalid method use - name:{} size:{} img_id:{} '
'src_vol_id:{} snap_id:{}'.format(vol_name, vol_size,
img_id, src_vol_id,
snap_id))
amulet.raise_status(amulet.FAIL, msg=msg)
# Create new volume
try:
vol_new = cinder.volumes.create(display_name=vol_name,
imageRef=img_id,
size=vol_size,
source_volid=src_vol_id,
snapshot_id=snap_id)
vol_id = vol_new.id
except TypeError:
vol_new = cinder.volumes.create(name=vol_name,
imageRef=img_id,
size=vol_size,
source_volid=src_vol_id,
snapshot_id=snap_id)
vol_id = vol_new.id
except Exception as e:
msg = 'Failed to create volume: {}'.format(e)
amulet.raise_status(amulet.FAIL, msg=msg)
# Wait for volume to reach available status
ret = self.resource_reaches_status(cinder.volumes, vol_id,
expected_stat="available",
msg="Volume status wait")
if not ret:
msg = 'Cinder volume failed to reach expected state.'
amulet.raise_status(amulet.FAIL, msg=msg)
# Re-validate new volume
self.log.debug('Validating volume attributes...')
val_vol_name = self._get_cinder_obj_name(cinder.volumes.get(vol_id))
val_vol_boot = cinder.volumes.get(vol_id).bootable
val_vol_stat = cinder.volumes.get(vol_id).status
val_vol_size = cinder.volumes.get(vol_id).size
msg_attr = ('Volume attributes - name:{} id:{} stat:{} boot:'
'{} size:{}'.format(val_vol_name, vol_id,
val_vol_stat, val_vol_boot,
val_vol_size))
if val_vol_boot == bootable and val_vol_stat == 'available' \
and val_vol_name == vol_name and val_vol_size == vol_size:
self.log.debug(msg_attr)
else:
msg = ('Volume validation failed, {}'.format(msg_attr))
amulet.raise_status(amulet.FAIL, msg=msg)
return vol_new
|
[
"def",
"create_cinder_volume",
"(",
"self",
",",
"cinder",
",",
"vol_name",
"=",
"\"demo-vol\"",
",",
"vol_size",
"=",
"1",
",",
"img_id",
"=",
"None",
",",
"src_vol_id",
"=",
"None",
",",
"snap_id",
"=",
"None",
")",
":",
"# Handle parameter input and avoid impossible combinations",
"if",
"img_id",
"and",
"not",
"src_vol_id",
"and",
"not",
"snap_id",
":",
"# Create volume from image",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating cinder volume from glance image...'",
")",
"bootable",
"=",
"'true'",
"elif",
"src_vol_id",
"and",
"not",
"img_id",
"and",
"not",
"snap_id",
":",
"# Clone an existing volume",
"self",
".",
"log",
".",
"debug",
"(",
"'Cloning cinder volume...'",
")",
"bootable",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"src_vol_id",
")",
".",
"bootable",
"elif",
"snap_id",
"and",
"not",
"src_vol_id",
"and",
"not",
"img_id",
":",
"# Create volume from snapshot",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating cinder volume from snapshot...'",
")",
"snap",
"=",
"cinder",
".",
"volume_snapshots",
".",
"find",
"(",
"id",
"=",
"snap_id",
")",
"vol_size",
"=",
"snap",
".",
"size",
"snap_vol_id",
"=",
"cinder",
".",
"volume_snapshots",
".",
"get",
"(",
"snap_id",
")",
".",
"volume_id",
"bootable",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"snap_vol_id",
")",
".",
"bootable",
"elif",
"not",
"img_id",
"and",
"not",
"src_vol_id",
"and",
"not",
"snap_id",
":",
"# Create volume",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating cinder volume...'",
")",
"bootable",
"=",
"'false'",
"else",
":",
"# Impossible combination of parameters",
"msg",
"=",
"(",
"'Invalid method use - name:{} size:{} img_id:{} '",
"'src_vol_id:{} snap_id:{}'",
".",
"format",
"(",
"vol_name",
",",
"vol_size",
",",
"img_id",
",",
"src_vol_id",
",",
"snap_id",
")",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"# Create new volume",
"try",
":",
"vol_new",
"=",
"cinder",
".",
"volumes",
".",
"create",
"(",
"display_name",
"=",
"vol_name",
",",
"imageRef",
"=",
"img_id",
",",
"size",
"=",
"vol_size",
",",
"source_volid",
"=",
"src_vol_id",
",",
"snapshot_id",
"=",
"snap_id",
")",
"vol_id",
"=",
"vol_new",
".",
"id",
"except",
"TypeError",
":",
"vol_new",
"=",
"cinder",
".",
"volumes",
".",
"create",
"(",
"name",
"=",
"vol_name",
",",
"imageRef",
"=",
"img_id",
",",
"size",
"=",
"vol_size",
",",
"source_volid",
"=",
"src_vol_id",
",",
"snapshot_id",
"=",
"snap_id",
")",
"vol_id",
"=",
"vol_new",
".",
"id",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"'Failed to create volume: {}'",
".",
"format",
"(",
"e",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"# Wait for volume to reach available status",
"ret",
"=",
"self",
".",
"resource_reaches_status",
"(",
"cinder",
".",
"volumes",
",",
"vol_id",
",",
"expected_stat",
"=",
"\"available\"",
",",
"msg",
"=",
"\"Volume status wait\"",
")",
"if",
"not",
"ret",
":",
"msg",
"=",
"'Cinder volume failed to reach expected state.'",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"# Re-validate new volume",
"self",
".",
"log",
".",
"debug",
"(",
"'Validating volume attributes...'",
")",
"val_vol_name",
"=",
"self",
".",
"_get_cinder_obj_name",
"(",
"cinder",
".",
"volumes",
".",
"get",
"(",
"vol_id",
")",
")",
"val_vol_boot",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"vol_id",
")",
".",
"bootable",
"val_vol_stat",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"vol_id",
")",
".",
"status",
"val_vol_size",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"vol_id",
")",
".",
"size",
"msg_attr",
"=",
"(",
"'Volume attributes - name:{} id:{} stat:{} boot:'",
"'{} size:{}'",
".",
"format",
"(",
"val_vol_name",
",",
"vol_id",
",",
"val_vol_stat",
",",
"val_vol_boot",
",",
"val_vol_size",
")",
")",
"if",
"val_vol_boot",
"==",
"bootable",
"and",
"val_vol_stat",
"==",
"'available'",
"and",
"val_vol_name",
"==",
"vol_name",
"and",
"val_vol_size",
"==",
"vol_size",
":",
"self",
".",
"log",
".",
"debug",
"(",
"msg_attr",
")",
"else",
":",
"msg",
"=",
"(",
"'Volume validation failed, {}'",
".",
"format",
"(",
"msg_attr",
")",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"return",
"vol_new"
] |
Create cinder volume, optionally from a glance image, OR
optionally as a clone of an existing volume, OR optionally
from a snapshot. Wait for the new volume status to reach
the expected status, validate and return a resource pointer.
:param vol_name: cinder volume display name
:param vol_size: size in gigabytes
:param img_id: optional glance image id
:param src_vol_id: optional source volume id to clone
:param snap_id: optional snapshot id to use
:returns: cinder volume pointer
|
[
"Create",
"cinder",
"volume",
"optionally",
"from",
"a",
"glance",
"image",
"OR",
"optionally",
"as",
"a",
"clone",
"of",
"an",
"existing",
"volume",
"OR",
"optionally",
"from",
"a",
"snapshot",
".",
"Wait",
"for",
"the",
"new",
"volume",
"status",
"to",
"reach",
"the",
"expected",
"status",
"validate",
"and",
"return",
"a",
"resource",
"pointer",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L889-L976
|
12,548
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.delete_resource
|
def delete_resource(self, resource, resource_id,
msg="resource", max_wait=120):
"""Delete one openstack resource, such as one instance, keypair,
image, volume, stack, etc., and confirm deletion within max wait time.
:param resource: pointer to os resource type, ex:glance_client.images
:param resource_id: unique name or id for the openstack resource
:param msg: text to identify purpose in logging
:param max_wait: maximum wait time in seconds
:returns: True if successful, otherwise False
"""
self.log.debug('Deleting OpenStack resource '
'{} ({})'.format(resource_id, msg))
num_before = len(list(resource.list()))
resource.delete(resource_id)
tries = 0
num_after = len(list(resource.list()))
while num_after != (num_before - 1) and tries < (max_wait / 4):
self.log.debug('{} delete check: '
'{} [{}:{}] {}'.format(msg, tries,
num_before,
num_after,
resource_id))
time.sleep(4)
num_after = len(list(resource.list()))
tries += 1
self.log.debug('{}: expected, actual count = {}, '
'{}'.format(msg, num_before - 1, num_after))
if num_after == (num_before - 1):
return True
else:
self.log.error('{} delete timed out'.format(msg))
return False
|
python
|
def delete_resource(self, resource, resource_id,
msg="resource", max_wait=120):
"""Delete one openstack resource, such as one instance, keypair,
image, volume, stack, etc., and confirm deletion within max wait time.
:param resource: pointer to os resource type, ex:glance_client.images
:param resource_id: unique name or id for the openstack resource
:param msg: text to identify purpose in logging
:param max_wait: maximum wait time in seconds
:returns: True if successful, otherwise False
"""
self.log.debug('Deleting OpenStack resource '
'{} ({})'.format(resource_id, msg))
num_before = len(list(resource.list()))
resource.delete(resource_id)
tries = 0
num_after = len(list(resource.list()))
while num_after != (num_before - 1) and tries < (max_wait / 4):
self.log.debug('{} delete check: '
'{} [{}:{}] {}'.format(msg, tries,
num_before,
num_after,
resource_id))
time.sleep(4)
num_after = len(list(resource.list()))
tries += 1
self.log.debug('{}: expected, actual count = {}, '
'{}'.format(msg, num_before - 1, num_after))
if num_after == (num_before - 1):
return True
else:
self.log.error('{} delete timed out'.format(msg))
return False
|
[
"def",
"delete_resource",
"(",
"self",
",",
"resource",
",",
"resource_id",
",",
"msg",
"=",
"\"resource\"",
",",
"max_wait",
"=",
"120",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Deleting OpenStack resource '",
"'{} ({})'",
".",
"format",
"(",
"resource_id",
",",
"msg",
")",
")",
"num_before",
"=",
"len",
"(",
"list",
"(",
"resource",
".",
"list",
"(",
")",
")",
")",
"resource",
".",
"delete",
"(",
"resource_id",
")",
"tries",
"=",
"0",
"num_after",
"=",
"len",
"(",
"list",
"(",
"resource",
".",
"list",
"(",
")",
")",
")",
"while",
"num_after",
"!=",
"(",
"num_before",
"-",
"1",
")",
"and",
"tries",
"<",
"(",
"max_wait",
"/",
"4",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'{} delete check: '",
"'{} [{}:{}] {}'",
".",
"format",
"(",
"msg",
",",
"tries",
",",
"num_before",
",",
"num_after",
",",
"resource_id",
")",
")",
"time",
".",
"sleep",
"(",
"4",
")",
"num_after",
"=",
"len",
"(",
"list",
"(",
"resource",
".",
"list",
"(",
")",
")",
")",
"tries",
"+=",
"1",
"self",
".",
"log",
".",
"debug",
"(",
"'{}: expected, actual count = {}, '",
"'{}'",
".",
"format",
"(",
"msg",
",",
"num_before",
"-",
"1",
",",
"num_after",
")",
")",
"if",
"num_after",
"==",
"(",
"num_before",
"-",
"1",
")",
":",
"return",
"True",
"else",
":",
"self",
".",
"log",
".",
"error",
"(",
"'{} delete timed out'",
".",
"format",
"(",
"msg",
")",
")",
"return",
"False"
] |
Delete one openstack resource, such as one instance, keypair,
image, volume, stack, etc., and confirm deletion within max wait time.
:param resource: pointer to os resource type, ex:glance_client.images
:param resource_id: unique name or id for the openstack resource
:param msg: text to identify purpose in logging
:param max_wait: maximum wait time in seconds
:returns: True if successful, otherwise False
|
[
"Delete",
"one",
"openstack",
"resource",
"such",
"as",
"one",
"instance",
"keypair",
"image",
"volume",
"stack",
"etc",
".",
"and",
"confirm",
"deletion",
"within",
"max",
"wait",
"time",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L978-L1013
|
12,549
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.resource_reaches_status
|
def resource_reaches_status(self, resource, resource_id,
expected_stat='available',
msg='resource', max_wait=120):
"""Wait for an openstack resources status to reach an
expected status within a specified time. Useful to confirm that
nova instances, cinder vols, snapshots, glance images, heat stacks
and other resources eventually reach the expected status.
:param resource: pointer to os resource type, ex: heat_client.stacks
:param resource_id: unique id for the openstack resource
:param expected_stat: status to expect resource to reach
:param msg: text to identify purpose in logging
:param max_wait: maximum wait time in seconds
:returns: True if successful, False if status is not reached
"""
tries = 0
resource_stat = resource.get(resource_id).status
while resource_stat != expected_stat and tries < (max_wait / 4):
self.log.debug('{} status check: '
'{} [{}:{}] {}'.format(msg, tries,
resource_stat,
expected_stat,
resource_id))
time.sleep(4)
resource_stat = resource.get(resource_id).status
tries += 1
self.log.debug('{}: expected, actual status = {}, '
'{}'.format(msg, resource_stat, expected_stat))
if resource_stat == expected_stat:
return True
else:
self.log.debug('{} never reached expected status: '
'{}'.format(resource_id, expected_stat))
return False
|
python
|
def resource_reaches_status(self, resource, resource_id,
expected_stat='available',
msg='resource', max_wait=120):
"""Wait for an openstack resources status to reach an
expected status within a specified time. Useful to confirm that
nova instances, cinder vols, snapshots, glance images, heat stacks
and other resources eventually reach the expected status.
:param resource: pointer to os resource type, ex: heat_client.stacks
:param resource_id: unique id for the openstack resource
:param expected_stat: status to expect resource to reach
:param msg: text to identify purpose in logging
:param max_wait: maximum wait time in seconds
:returns: True if successful, False if status is not reached
"""
tries = 0
resource_stat = resource.get(resource_id).status
while resource_stat != expected_stat and tries < (max_wait / 4):
self.log.debug('{} status check: '
'{} [{}:{}] {}'.format(msg, tries,
resource_stat,
expected_stat,
resource_id))
time.sleep(4)
resource_stat = resource.get(resource_id).status
tries += 1
self.log.debug('{}: expected, actual status = {}, '
'{}'.format(msg, resource_stat, expected_stat))
if resource_stat == expected_stat:
return True
else:
self.log.debug('{} never reached expected status: '
'{}'.format(resource_id, expected_stat))
return False
|
[
"def",
"resource_reaches_status",
"(",
"self",
",",
"resource",
",",
"resource_id",
",",
"expected_stat",
"=",
"'available'",
",",
"msg",
"=",
"'resource'",
",",
"max_wait",
"=",
"120",
")",
":",
"tries",
"=",
"0",
"resource_stat",
"=",
"resource",
".",
"get",
"(",
"resource_id",
")",
".",
"status",
"while",
"resource_stat",
"!=",
"expected_stat",
"and",
"tries",
"<",
"(",
"max_wait",
"/",
"4",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'{} status check: '",
"'{} [{}:{}] {}'",
".",
"format",
"(",
"msg",
",",
"tries",
",",
"resource_stat",
",",
"expected_stat",
",",
"resource_id",
")",
")",
"time",
".",
"sleep",
"(",
"4",
")",
"resource_stat",
"=",
"resource",
".",
"get",
"(",
"resource_id",
")",
".",
"status",
"tries",
"+=",
"1",
"self",
".",
"log",
".",
"debug",
"(",
"'{}: expected, actual status = {}, '",
"'{}'",
".",
"format",
"(",
"msg",
",",
"resource_stat",
",",
"expected_stat",
")",
")",
"if",
"resource_stat",
"==",
"expected_stat",
":",
"return",
"True",
"else",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'{} never reached expected status: '",
"'{}'",
".",
"format",
"(",
"resource_id",
",",
"expected_stat",
")",
")",
"return",
"False"
] |
Wait for an openstack resources status to reach an
expected status within a specified time. Useful to confirm that
nova instances, cinder vols, snapshots, glance images, heat stacks
and other resources eventually reach the expected status.
:param resource: pointer to os resource type, ex: heat_client.stacks
:param resource_id: unique id for the openstack resource
:param expected_stat: status to expect resource to reach
:param msg: text to identify purpose in logging
:param max_wait: maximum wait time in seconds
:returns: True if successful, False if status is not reached
|
[
"Wait",
"for",
"an",
"openstack",
"resources",
"status",
"to",
"reach",
"an",
"expected",
"status",
"within",
"a",
"specified",
"time",
".",
"Useful",
"to",
"confirm",
"that",
"nova",
"instances",
"cinder",
"vols",
"snapshots",
"glance",
"images",
"heat",
"stacks",
"and",
"other",
"resources",
"eventually",
"reach",
"the",
"expected",
"status",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1015-L1051
|
12,550
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.get_ceph_pools
|
def get_ceph_pools(self, sentry_unit):
"""Return a dict of ceph pools from a single ceph unit, with
pool name as keys, pool id as vals."""
pools = {}
cmd = 'sudo ceph osd lspools'
output, code = sentry_unit.run(cmd)
if code != 0:
msg = ('{} `{}` returned {} '
'{}'.format(sentry_unit.info['unit_name'],
cmd, code, output))
amulet.raise_status(amulet.FAIL, msg=msg)
# For mimic ceph osd lspools output
output = output.replace("\n", ",")
# Example output: 0 data,1 metadata,2 rbd,3 cinder,4 glance,
for pool in str(output).split(','):
pool_id_name = pool.split(' ')
if len(pool_id_name) == 2:
pool_id = pool_id_name[0]
pool_name = pool_id_name[1]
pools[pool_name] = int(pool_id)
self.log.debug('Pools on {}: {}'.format(sentry_unit.info['unit_name'],
pools))
return pools
|
python
|
def get_ceph_pools(self, sentry_unit):
"""Return a dict of ceph pools from a single ceph unit, with
pool name as keys, pool id as vals."""
pools = {}
cmd = 'sudo ceph osd lspools'
output, code = sentry_unit.run(cmd)
if code != 0:
msg = ('{} `{}` returned {} '
'{}'.format(sentry_unit.info['unit_name'],
cmd, code, output))
amulet.raise_status(amulet.FAIL, msg=msg)
# For mimic ceph osd lspools output
output = output.replace("\n", ",")
# Example output: 0 data,1 metadata,2 rbd,3 cinder,4 glance,
for pool in str(output).split(','):
pool_id_name = pool.split(' ')
if len(pool_id_name) == 2:
pool_id = pool_id_name[0]
pool_name = pool_id_name[1]
pools[pool_name] = int(pool_id)
self.log.debug('Pools on {}: {}'.format(sentry_unit.info['unit_name'],
pools))
return pools
|
[
"def",
"get_ceph_pools",
"(",
"self",
",",
"sentry_unit",
")",
":",
"pools",
"=",
"{",
"}",
"cmd",
"=",
"'sudo ceph osd lspools'",
"output",
",",
"code",
"=",
"sentry_unit",
".",
"run",
"(",
"cmd",
")",
"if",
"code",
"!=",
"0",
":",
"msg",
"=",
"(",
"'{} `{}` returned {} '",
"'{}'",
".",
"format",
"(",
"sentry_unit",
".",
"info",
"[",
"'unit_name'",
"]",
",",
"cmd",
",",
"code",
",",
"output",
")",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"# For mimic ceph osd lspools output",
"output",
"=",
"output",
".",
"replace",
"(",
"\"\\n\"",
",",
"\",\"",
")",
"# Example output: 0 data,1 metadata,2 rbd,3 cinder,4 glance,",
"for",
"pool",
"in",
"str",
"(",
"output",
")",
".",
"split",
"(",
"','",
")",
":",
"pool_id_name",
"=",
"pool",
".",
"split",
"(",
"' '",
")",
"if",
"len",
"(",
"pool_id_name",
")",
"==",
"2",
":",
"pool_id",
"=",
"pool_id_name",
"[",
"0",
"]",
"pool_name",
"=",
"pool_id_name",
"[",
"1",
"]",
"pools",
"[",
"pool_name",
"]",
"=",
"int",
"(",
"pool_id",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Pools on {}: {}'",
".",
"format",
"(",
"sentry_unit",
".",
"info",
"[",
"'unit_name'",
"]",
",",
"pools",
")",
")",
"return",
"pools"
] |
Return a dict of ceph pools from a single ceph unit, with
pool name as keys, pool id as vals.
|
[
"Return",
"a",
"dict",
"of",
"ceph",
"pools",
"from",
"a",
"single",
"ceph",
"unit",
"with",
"pool",
"name",
"as",
"keys",
"pool",
"id",
"as",
"vals",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1059-L1084
|
12,551
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.get_ceph_df
|
def get_ceph_df(self, sentry_unit):
"""Return dict of ceph df json output, including ceph pool state.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:returns: Dict of ceph df output
"""
cmd = 'sudo ceph df --format=json'
output, code = sentry_unit.run(cmd)
if code != 0:
msg = ('{} `{}` returned {} '
'{}'.format(sentry_unit.info['unit_name'],
cmd, code, output))
amulet.raise_status(amulet.FAIL, msg=msg)
return json.loads(output)
|
python
|
def get_ceph_df(self, sentry_unit):
"""Return dict of ceph df json output, including ceph pool state.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:returns: Dict of ceph df output
"""
cmd = 'sudo ceph df --format=json'
output, code = sentry_unit.run(cmd)
if code != 0:
msg = ('{} `{}` returned {} '
'{}'.format(sentry_unit.info['unit_name'],
cmd, code, output))
amulet.raise_status(amulet.FAIL, msg=msg)
return json.loads(output)
|
[
"def",
"get_ceph_df",
"(",
"self",
",",
"sentry_unit",
")",
":",
"cmd",
"=",
"'sudo ceph df --format=json'",
"output",
",",
"code",
"=",
"sentry_unit",
".",
"run",
"(",
"cmd",
")",
"if",
"code",
"!=",
"0",
":",
"msg",
"=",
"(",
"'{} `{}` returned {} '",
"'{}'",
".",
"format",
"(",
"sentry_unit",
".",
"info",
"[",
"'unit_name'",
"]",
",",
"cmd",
",",
"code",
",",
"output",
")",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"return",
"json",
".",
"loads",
"(",
"output",
")"
] |
Return dict of ceph df json output, including ceph pool state.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:returns: Dict of ceph df output
|
[
"Return",
"dict",
"of",
"ceph",
"df",
"json",
"output",
"including",
"ceph",
"pool",
"state",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1086-L1099
|
12,552
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.get_ceph_pool_sample
|
def get_ceph_pool_sample(self, sentry_unit, pool_id=0):
"""Take a sample of attributes of a ceph pool, returning ceph
pool name, object count and disk space used for the specified
pool ID number.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:param pool_id: Ceph pool ID
:returns: List of pool name, object count, kb disk space used
"""
df = self.get_ceph_df(sentry_unit)
for pool in df['pools']:
if pool['id'] == pool_id:
pool_name = pool['name']
obj_count = pool['stats']['objects']
kb_used = pool['stats']['kb_used']
self.log.debug('Ceph {} pool (ID {}): {} objects, '
'{} kb used'.format(pool_name, pool_id,
obj_count, kb_used))
return pool_name, obj_count, kb_used
|
python
|
def get_ceph_pool_sample(self, sentry_unit, pool_id=0):
"""Take a sample of attributes of a ceph pool, returning ceph
pool name, object count and disk space used for the specified
pool ID number.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:param pool_id: Ceph pool ID
:returns: List of pool name, object count, kb disk space used
"""
df = self.get_ceph_df(sentry_unit)
for pool in df['pools']:
if pool['id'] == pool_id:
pool_name = pool['name']
obj_count = pool['stats']['objects']
kb_used = pool['stats']['kb_used']
self.log.debug('Ceph {} pool (ID {}): {} objects, '
'{} kb used'.format(pool_name, pool_id,
obj_count, kb_used))
return pool_name, obj_count, kb_used
|
[
"def",
"get_ceph_pool_sample",
"(",
"self",
",",
"sentry_unit",
",",
"pool_id",
"=",
"0",
")",
":",
"df",
"=",
"self",
".",
"get_ceph_df",
"(",
"sentry_unit",
")",
"for",
"pool",
"in",
"df",
"[",
"'pools'",
"]",
":",
"if",
"pool",
"[",
"'id'",
"]",
"==",
"pool_id",
":",
"pool_name",
"=",
"pool",
"[",
"'name'",
"]",
"obj_count",
"=",
"pool",
"[",
"'stats'",
"]",
"[",
"'objects'",
"]",
"kb_used",
"=",
"pool",
"[",
"'stats'",
"]",
"[",
"'kb_used'",
"]",
"self",
".",
"log",
".",
"debug",
"(",
"'Ceph {} pool (ID {}): {} objects, '",
"'{} kb used'",
".",
"format",
"(",
"pool_name",
",",
"pool_id",
",",
"obj_count",
",",
"kb_used",
")",
")",
"return",
"pool_name",
",",
"obj_count",
",",
"kb_used"
] |
Take a sample of attributes of a ceph pool, returning ceph
pool name, object count and disk space used for the specified
pool ID number.
:param sentry_unit: Pointer to amulet sentry instance (juju unit)
:param pool_id: Ceph pool ID
:returns: List of pool name, object count, kb disk space used
|
[
"Take",
"a",
"sample",
"of",
"attributes",
"of",
"a",
"ceph",
"pool",
"returning",
"ceph",
"pool",
"name",
"object",
"count",
"and",
"disk",
"space",
"used",
"for",
"the",
"specified",
"pool",
"ID",
"number",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1101-L1120
|
12,553
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.validate_ceph_pool_samples
|
def validate_ceph_pool_samples(self, samples, sample_type="resource pool"):
"""Validate ceph pool samples taken over time, such as pool
object counts or pool kb used, before adding, after adding, and
after deleting items which affect those pool attributes. The
2nd element is expected to be greater than the 1st; 3rd is expected
to be less than the 2nd.
:param samples: List containing 3 data samples
:param sample_type: String for logging and usage context
:returns: None if successful, Failure message otherwise
"""
original, created, deleted = range(3)
if samples[created] <= samples[original] or \
samples[deleted] >= samples[created]:
return ('Ceph {} samples ({}) '
'unexpected.'.format(sample_type, samples))
else:
self.log.debug('Ceph {} samples (OK): '
'{}'.format(sample_type, samples))
return None
|
python
|
def validate_ceph_pool_samples(self, samples, sample_type="resource pool"):
"""Validate ceph pool samples taken over time, such as pool
object counts or pool kb used, before adding, after adding, and
after deleting items which affect those pool attributes. The
2nd element is expected to be greater than the 1st; 3rd is expected
to be less than the 2nd.
:param samples: List containing 3 data samples
:param sample_type: String for logging and usage context
:returns: None if successful, Failure message otherwise
"""
original, created, deleted = range(3)
if samples[created] <= samples[original] or \
samples[deleted] >= samples[created]:
return ('Ceph {} samples ({}) '
'unexpected.'.format(sample_type, samples))
else:
self.log.debug('Ceph {} samples (OK): '
'{}'.format(sample_type, samples))
return None
|
[
"def",
"validate_ceph_pool_samples",
"(",
"self",
",",
"samples",
",",
"sample_type",
"=",
"\"resource pool\"",
")",
":",
"original",
",",
"created",
",",
"deleted",
"=",
"range",
"(",
"3",
")",
"if",
"samples",
"[",
"created",
"]",
"<=",
"samples",
"[",
"original",
"]",
"or",
"samples",
"[",
"deleted",
"]",
">=",
"samples",
"[",
"created",
"]",
":",
"return",
"(",
"'Ceph {} samples ({}) '",
"'unexpected.'",
".",
"format",
"(",
"sample_type",
",",
"samples",
")",
")",
"else",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Ceph {} samples (OK): '",
"'{}'",
".",
"format",
"(",
"sample_type",
",",
"samples",
")",
")",
"return",
"None"
] |
Validate ceph pool samples taken over time, such as pool
object counts or pool kb used, before adding, after adding, and
after deleting items which affect those pool attributes. The
2nd element is expected to be greater than the 1st; 3rd is expected
to be less than the 2nd.
:param samples: List containing 3 data samples
:param sample_type: String for logging and usage context
:returns: None if successful, Failure message otherwise
|
[
"Validate",
"ceph",
"pool",
"samples",
"taken",
"over",
"time",
"such",
"as",
"pool",
"object",
"counts",
"or",
"pool",
"kb",
"used",
"before",
"adding",
"after",
"adding",
"and",
"after",
"deleting",
"items",
"which",
"affect",
"those",
"pool",
"attributes",
".",
"The",
"2nd",
"element",
"is",
"expected",
"to",
"be",
"greater",
"than",
"the",
"1st",
";",
"3rd",
"is",
"expected",
"to",
"be",
"less",
"than",
"the",
"2nd",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1122-L1141
|
12,554
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.rmq_wait_for_cluster
|
def rmq_wait_for_cluster(self, deployment, init_sleep=15, timeout=1200):
"""Wait for rmq units extended status to show cluster readiness,
after an optional initial sleep period. Initial sleep is likely
necessary to be effective following a config change, as status
message may not instantly update to non-ready."""
if init_sleep:
time.sleep(init_sleep)
message = re.compile('^Unit is ready and clustered$')
deployment._auto_wait_for_status(message=message,
timeout=timeout,
include_only=['rabbitmq-server'])
|
python
|
def rmq_wait_for_cluster(self, deployment, init_sleep=15, timeout=1200):
"""Wait for rmq units extended status to show cluster readiness,
after an optional initial sleep period. Initial sleep is likely
necessary to be effective following a config change, as status
message may not instantly update to non-ready."""
if init_sleep:
time.sleep(init_sleep)
message = re.compile('^Unit is ready and clustered$')
deployment._auto_wait_for_status(message=message,
timeout=timeout,
include_only=['rabbitmq-server'])
|
[
"def",
"rmq_wait_for_cluster",
"(",
"self",
",",
"deployment",
",",
"init_sleep",
"=",
"15",
",",
"timeout",
"=",
"1200",
")",
":",
"if",
"init_sleep",
":",
"time",
".",
"sleep",
"(",
"init_sleep",
")",
"message",
"=",
"re",
".",
"compile",
"(",
"'^Unit is ready and clustered$'",
")",
"deployment",
".",
"_auto_wait_for_status",
"(",
"message",
"=",
"message",
",",
"timeout",
"=",
"timeout",
",",
"include_only",
"=",
"[",
"'rabbitmq-server'",
"]",
")"
] |
Wait for rmq units extended status to show cluster readiness,
after an optional initial sleep period. Initial sleep is likely
necessary to be effective following a config change, as status
message may not instantly update to non-ready.
|
[
"Wait",
"for",
"rmq",
"units",
"extended",
"status",
"to",
"show",
"cluster",
"readiness",
"after",
"an",
"optional",
"initial",
"sleep",
"period",
".",
"Initial",
"sleep",
"is",
"likely",
"necessary",
"to",
"be",
"effective",
"following",
"a",
"config",
"change",
"as",
"status",
"message",
"may",
"not",
"instantly",
"update",
"to",
"non",
"-",
"ready",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1145-L1157
|
12,555
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.get_rmq_cluster_status
|
def get_rmq_cluster_status(self, sentry_unit):
"""Execute rabbitmq cluster status command on a unit and return
the full output.
:param unit: sentry unit
:returns: String containing console output of cluster status command
"""
cmd = 'rabbitmqctl cluster_status'
output, _ = self.run_cmd_unit(sentry_unit, cmd)
self.log.debug('{} cluster_status:\n{}'.format(
sentry_unit.info['unit_name'], output))
return str(output)
|
python
|
def get_rmq_cluster_status(self, sentry_unit):
"""Execute rabbitmq cluster status command on a unit and return
the full output.
:param unit: sentry unit
:returns: String containing console output of cluster status command
"""
cmd = 'rabbitmqctl cluster_status'
output, _ = self.run_cmd_unit(sentry_unit, cmd)
self.log.debug('{} cluster_status:\n{}'.format(
sentry_unit.info['unit_name'], output))
return str(output)
|
[
"def",
"get_rmq_cluster_status",
"(",
"self",
",",
"sentry_unit",
")",
":",
"cmd",
"=",
"'rabbitmqctl cluster_status'",
"output",
",",
"_",
"=",
"self",
".",
"run_cmd_unit",
"(",
"sentry_unit",
",",
"cmd",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'{} cluster_status:\\n{}'",
".",
"format",
"(",
"sentry_unit",
".",
"info",
"[",
"'unit_name'",
"]",
",",
"output",
")",
")",
"return",
"str",
"(",
"output",
")"
] |
Execute rabbitmq cluster status command on a unit and return
the full output.
:param unit: sentry unit
:returns: String containing console output of cluster status command
|
[
"Execute",
"rabbitmq",
"cluster",
"status",
"command",
"on",
"a",
"unit",
"and",
"return",
"the",
"full",
"output",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1218-L1229
|
12,556
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.get_rmq_cluster_running_nodes
|
def get_rmq_cluster_running_nodes(self, sentry_unit):
"""Parse rabbitmqctl cluster_status output string, return list of
running rabbitmq cluster nodes.
:param unit: sentry unit
:returns: List containing node names of running nodes
"""
# NOTE(beisner): rabbitmqctl cluster_status output is not
# json-parsable, do string chop foo, then json.loads that.
str_stat = self.get_rmq_cluster_status(sentry_unit)
if 'running_nodes' in str_stat:
pos_start = str_stat.find("{running_nodes,") + 15
pos_end = str_stat.find("]},", pos_start) + 1
str_run_nodes = str_stat[pos_start:pos_end].replace("'", '"')
run_nodes = json.loads(str_run_nodes)
return run_nodes
else:
return []
|
python
|
def get_rmq_cluster_running_nodes(self, sentry_unit):
"""Parse rabbitmqctl cluster_status output string, return list of
running rabbitmq cluster nodes.
:param unit: sentry unit
:returns: List containing node names of running nodes
"""
# NOTE(beisner): rabbitmqctl cluster_status output is not
# json-parsable, do string chop foo, then json.loads that.
str_stat = self.get_rmq_cluster_status(sentry_unit)
if 'running_nodes' in str_stat:
pos_start = str_stat.find("{running_nodes,") + 15
pos_end = str_stat.find("]},", pos_start) + 1
str_run_nodes = str_stat[pos_start:pos_end].replace("'", '"')
run_nodes = json.loads(str_run_nodes)
return run_nodes
else:
return []
|
[
"def",
"get_rmq_cluster_running_nodes",
"(",
"self",
",",
"sentry_unit",
")",
":",
"# NOTE(beisner): rabbitmqctl cluster_status output is not",
"# json-parsable, do string chop foo, then json.loads that.",
"str_stat",
"=",
"self",
".",
"get_rmq_cluster_status",
"(",
"sentry_unit",
")",
"if",
"'running_nodes'",
"in",
"str_stat",
":",
"pos_start",
"=",
"str_stat",
".",
"find",
"(",
"\"{running_nodes,\"",
")",
"+",
"15",
"pos_end",
"=",
"str_stat",
".",
"find",
"(",
"\"]},\"",
",",
"pos_start",
")",
"+",
"1",
"str_run_nodes",
"=",
"str_stat",
"[",
"pos_start",
":",
"pos_end",
"]",
".",
"replace",
"(",
"\"'\"",
",",
"'\"'",
")",
"run_nodes",
"=",
"json",
".",
"loads",
"(",
"str_run_nodes",
")",
"return",
"run_nodes",
"else",
":",
"return",
"[",
"]"
] |
Parse rabbitmqctl cluster_status output string, return list of
running rabbitmq cluster nodes.
:param unit: sentry unit
:returns: List containing node names of running nodes
|
[
"Parse",
"rabbitmqctl",
"cluster_status",
"output",
"string",
"return",
"list",
"of",
"running",
"rabbitmq",
"cluster",
"nodes",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1231-L1248
|
12,557
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.validate_rmq_cluster_running_nodes
|
def validate_rmq_cluster_running_nodes(self, sentry_units):
"""Check that all rmq unit hostnames are represented in the
cluster_status output of all units.
:param host_names: dict of juju unit names to host names
:param units: list of sentry unit pointers (all rmq units)
:returns: None if successful, otherwise return error message
"""
host_names = self.get_unit_hostnames(sentry_units)
errors = []
# Query every unit for cluster_status running nodes
for query_unit in sentry_units:
query_unit_name = query_unit.info['unit_name']
running_nodes = self.get_rmq_cluster_running_nodes(query_unit)
# Confirm that every unit is represented in the queried unit's
# cluster_status running nodes output.
for validate_unit in sentry_units:
val_host_name = host_names[validate_unit.info['unit_name']]
val_node_name = 'rabbit@{}'.format(val_host_name)
if val_node_name not in running_nodes:
errors.append('Cluster member check failed on {}: {} not '
'in {}\n'.format(query_unit_name,
val_node_name,
running_nodes))
if errors:
return ''.join(errors)
|
python
|
def validate_rmq_cluster_running_nodes(self, sentry_units):
"""Check that all rmq unit hostnames are represented in the
cluster_status output of all units.
:param host_names: dict of juju unit names to host names
:param units: list of sentry unit pointers (all rmq units)
:returns: None if successful, otherwise return error message
"""
host_names = self.get_unit_hostnames(sentry_units)
errors = []
# Query every unit for cluster_status running nodes
for query_unit in sentry_units:
query_unit_name = query_unit.info['unit_name']
running_nodes = self.get_rmq_cluster_running_nodes(query_unit)
# Confirm that every unit is represented in the queried unit's
# cluster_status running nodes output.
for validate_unit in sentry_units:
val_host_name = host_names[validate_unit.info['unit_name']]
val_node_name = 'rabbit@{}'.format(val_host_name)
if val_node_name not in running_nodes:
errors.append('Cluster member check failed on {}: {} not '
'in {}\n'.format(query_unit_name,
val_node_name,
running_nodes))
if errors:
return ''.join(errors)
|
[
"def",
"validate_rmq_cluster_running_nodes",
"(",
"self",
",",
"sentry_units",
")",
":",
"host_names",
"=",
"self",
".",
"get_unit_hostnames",
"(",
"sentry_units",
")",
"errors",
"=",
"[",
"]",
"# Query every unit for cluster_status running nodes",
"for",
"query_unit",
"in",
"sentry_units",
":",
"query_unit_name",
"=",
"query_unit",
".",
"info",
"[",
"'unit_name'",
"]",
"running_nodes",
"=",
"self",
".",
"get_rmq_cluster_running_nodes",
"(",
"query_unit",
")",
"# Confirm that every unit is represented in the queried unit's",
"# cluster_status running nodes output.",
"for",
"validate_unit",
"in",
"sentry_units",
":",
"val_host_name",
"=",
"host_names",
"[",
"validate_unit",
".",
"info",
"[",
"'unit_name'",
"]",
"]",
"val_node_name",
"=",
"'rabbit@{}'",
".",
"format",
"(",
"val_host_name",
")",
"if",
"val_node_name",
"not",
"in",
"running_nodes",
":",
"errors",
".",
"append",
"(",
"'Cluster member check failed on {}: {} not '",
"'in {}\\n'",
".",
"format",
"(",
"query_unit_name",
",",
"val_node_name",
",",
"running_nodes",
")",
")",
"if",
"errors",
":",
"return",
"''",
".",
"join",
"(",
"errors",
")"
] |
Check that all rmq unit hostnames are represented in the
cluster_status output of all units.
:param host_names: dict of juju unit names to host names
:param units: list of sentry unit pointers (all rmq units)
:returns: None if successful, otherwise return error message
|
[
"Check",
"that",
"all",
"rmq",
"unit",
"hostnames",
"are",
"represented",
"in",
"the",
"cluster_status",
"output",
"of",
"all",
"units",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1250-L1278
|
12,558
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.rmq_ssl_is_enabled_on_unit
|
def rmq_ssl_is_enabled_on_unit(self, sentry_unit, port=None):
"""Check a single juju rmq unit for ssl and port in the config file."""
host = sentry_unit.info['public-address']
unit_name = sentry_unit.info['unit_name']
conf_file = '/etc/rabbitmq/rabbitmq.config'
conf_contents = str(self.file_contents_safe(sentry_unit,
conf_file, max_wait=16))
# Checks
conf_ssl = 'ssl' in conf_contents
conf_port = str(port) in conf_contents
# Port explicitly checked in config
if port and conf_port and conf_ssl:
self.log.debug('SSL is enabled @{}:{} '
'({})'.format(host, port, unit_name))
return True
elif port and not conf_port and conf_ssl:
self.log.debug('SSL is enabled @{} but not on port {} '
'({})'.format(host, port, unit_name))
return False
# Port not checked (useful when checking that ssl is disabled)
elif not port and conf_ssl:
self.log.debug('SSL is enabled @{}:{} '
'({})'.format(host, port, unit_name))
return True
elif not conf_ssl:
self.log.debug('SSL not enabled @{}:{} '
'({})'.format(host, port, unit_name))
return False
else:
msg = ('Unknown condition when checking SSL status @{}:{} '
'({})'.format(host, port, unit_name))
amulet.raise_status(amulet.FAIL, msg)
|
python
|
def rmq_ssl_is_enabled_on_unit(self, sentry_unit, port=None):
"""Check a single juju rmq unit for ssl and port in the config file."""
host = sentry_unit.info['public-address']
unit_name = sentry_unit.info['unit_name']
conf_file = '/etc/rabbitmq/rabbitmq.config'
conf_contents = str(self.file_contents_safe(sentry_unit,
conf_file, max_wait=16))
# Checks
conf_ssl = 'ssl' in conf_contents
conf_port = str(port) in conf_contents
# Port explicitly checked in config
if port and conf_port and conf_ssl:
self.log.debug('SSL is enabled @{}:{} '
'({})'.format(host, port, unit_name))
return True
elif port and not conf_port and conf_ssl:
self.log.debug('SSL is enabled @{} but not on port {} '
'({})'.format(host, port, unit_name))
return False
# Port not checked (useful when checking that ssl is disabled)
elif not port and conf_ssl:
self.log.debug('SSL is enabled @{}:{} '
'({})'.format(host, port, unit_name))
return True
elif not conf_ssl:
self.log.debug('SSL not enabled @{}:{} '
'({})'.format(host, port, unit_name))
return False
else:
msg = ('Unknown condition when checking SSL status @{}:{} '
'({})'.format(host, port, unit_name))
amulet.raise_status(amulet.FAIL, msg)
|
[
"def",
"rmq_ssl_is_enabled_on_unit",
"(",
"self",
",",
"sentry_unit",
",",
"port",
"=",
"None",
")",
":",
"host",
"=",
"sentry_unit",
".",
"info",
"[",
"'public-address'",
"]",
"unit_name",
"=",
"sentry_unit",
".",
"info",
"[",
"'unit_name'",
"]",
"conf_file",
"=",
"'/etc/rabbitmq/rabbitmq.config'",
"conf_contents",
"=",
"str",
"(",
"self",
".",
"file_contents_safe",
"(",
"sentry_unit",
",",
"conf_file",
",",
"max_wait",
"=",
"16",
")",
")",
"# Checks",
"conf_ssl",
"=",
"'ssl'",
"in",
"conf_contents",
"conf_port",
"=",
"str",
"(",
"port",
")",
"in",
"conf_contents",
"# Port explicitly checked in config",
"if",
"port",
"and",
"conf_port",
"and",
"conf_ssl",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'SSL is enabled @{}:{} '",
"'({})'",
".",
"format",
"(",
"host",
",",
"port",
",",
"unit_name",
")",
")",
"return",
"True",
"elif",
"port",
"and",
"not",
"conf_port",
"and",
"conf_ssl",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'SSL is enabled @{} but not on port {} '",
"'({})'",
".",
"format",
"(",
"host",
",",
"port",
",",
"unit_name",
")",
")",
"return",
"False",
"# Port not checked (useful when checking that ssl is disabled)",
"elif",
"not",
"port",
"and",
"conf_ssl",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'SSL is enabled @{}:{} '",
"'({})'",
".",
"format",
"(",
"host",
",",
"port",
",",
"unit_name",
")",
")",
"return",
"True",
"elif",
"not",
"conf_ssl",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'SSL not enabled @{}:{} '",
"'({})'",
".",
"format",
"(",
"host",
",",
"port",
",",
"unit_name",
")",
")",
"return",
"False",
"else",
":",
"msg",
"=",
"(",
"'Unknown condition when checking SSL status @{}:{} '",
"'({})'",
".",
"format",
"(",
"host",
",",
"port",
",",
"unit_name",
")",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
")"
] |
Check a single juju rmq unit for ssl and port in the config file.
|
[
"Check",
"a",
"single",
"juju",
"rmq",
"unit",
"for",
"ssl",
"and",
"port",
"in",
"the",
"config",
"file",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1280-L1313
|
12,559
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.validate_rmq_ssl_enabled_units
|
def validate_rmq_ssl_enabled_units(self, sentry_units, port=None):
"""Check that ssl is enabled on rmq juju sentry units.
:param sentry_units: list of all rmq sentry units
:param port: optional ssl port override to validate
:returns: None if successful, otherwise return error message
"""
for sentry_unit in sentry_units:
if not self.rmq_ssl_is_enabled_on_unit(sentry_unit, port=port):
return ('Unexpected condition: ssl is disabled on unit '
'({})'.format(sentry_unit.info['unit_name']))
return None
|
python
|
def validate_rmq_ssl_enabled_units(self, sentry_units, port=None):
"""Check that ssl is enabled on rmq juju sentry units.
:param sentry_units: list of all rmq sentry units
:param port: optional ssl port override to validate
:returns: None if successful, otherwise return error message
"""
for sentry_unit in sentry_units:
if not self.rmq_ssl_is_enabled_on_unit(sentry_unit, port=port):
return ('Unexpected condition: ssl is disabled on unit '
'({})'.format(sentry_unit.info['unit_name']))
return None
|
[
"def",
"validate_rmq_ssl_enabled_units",
"(",
"self",
",",
"sentry_units",
",",
"port",
"=",
"None",
")",
":",
"for",
"sentry_unit",
"in",
"sentry_units",
":",
"if",
"not",
"self",
".",
"rmq_ssl_is_enabled_on_unit",
"(",
"sentry_unit",
",",
"port",
"=",
"port",
")",
":",
"return",
"(",
"'Unexpected condition: ssl is disabled on unit '",
"'({})'",
".",
"format",
"(",
"sentry_unit",
".",
"info",
"[",
"'unit_name'",
"]",
")",
")",
"return",
"None"
] |
Check that ssl is enabled on rmq juju sentry units.
:param sentry_units: list of all rmq sentry units
:param port: optional ssl port override to validate
:returns: None if successful, otherwise return error message
|
[
"Check",
"that",
"ssl",
"is",
"enabled",
"on",
"rmq",
"juju",
"sentry",
"units",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1315-L1326
|
12,560
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.validate_rmq_ssl_disabled_units
|
def validate_rmq_ssl_disabled_units(self, sentry_units):
"""Check that ssl is enabled on listed rmq juju sentry units.
:param sentry_units: list of all rmq sentry units
:returns: True if successful. Raise on error.
"""
for sentry_unit in sentry_units:
if self.rmq_ssl_is_enabled_on_unit(sentry_unit):
return ('Unexpected condition: ssl is enabled on unit '
'({})'.format(sentry_unit.info['unit_name']))
return None
|
python
|
def validate_rmq_ssl_disabled_units(self, sentry_units):
"""Check that ssl is enabled on listed rmq juju sentry units.
:param sentry_units: list of all rmq sentry units
:returns: True if successful. Raise on error.
"""
for sentry_unit in sentry_units:
if self.rmq_ssl_is_enabled_on_unit(sentry_unit):
return ('Unexpected condition: ssl is enabled on unit '
'({})'.format(sentry_unit.info['unit_name']))
return None
|
[
"def",
"validate_rmq_ssl_disabled_units",
"(",
"self",
",",
"sentry_units",
")",
":",
"for",
"sentry_unit",
"in",
"sentry_units",
":",
"if",
"self",
".",
"rmq_ssl_is_enabled_on_unit",
"(",
"sentry_unit",
")",
":",
"return",
"(",
"'Unexpected condition: ssl is enabled on unit '",
"'({})'",
".",
"format",
"(",
"sentry_unit",
".",
"info",
"[",
"'unit_name'",
"]",
")",
")",
"return",
"None"
] |
Check that ssl is enabled on listed rmq juju sentry units.
:param sentry_units: list of all rmq sentry units
:returns: True if successful. Raise on error.
|
[
"Check",
"that",
"ssl",
"is",
"enabled",
"on",
"listed",
"rmq",
"juju",
"sentry",
"units",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1328-L1338
|
12,561
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.configure_rmq_ssl_on
|
def configure_rmq_ssl_on(self, sentry_units, deployment,
port=None, max_wait=60):
"""Turn ssl charm config option on, with optional non-default
ssl port specification. Confirm that it is enabled on every
unit.
:param sentry_units: list of sentry units
:param deployment: amulet deployment object pointer
:param port: amqp port, use defaults if None
:param max_wait: maximum time to wait in seconds to confirm
:returns: None if successful. Raise on error.
"""
self.log.debug('Setting ssl charm config option: on')
# Enable RMQ SSL
config = {'ssl': 'on'}
if port:
config['ssl_port'] = port
deployment.d.configure('rabbitmq-server', config)
# Wait for unit status
self.rmq_wait_for_cluster(deployment)
# Confirm
tries = 0
ret = self.validate_rmq_ssl_enabled_units(sentry_units, port=port)
while ret and tries < (max_wait / 4):
time.sleep(4)
self.log.debug('Attempt {}: {}'.format(tries, ret))
ret = self.validate_rmq_ssl_enabled_units(sentry_units, port=port)
tries += 1
if ret:
amulet.raise_status(amulet.FAIL, ret)
|
python
|
def configure_rmq_ssl_on(self, sentry_units, deployment,
port=None, max_wait=60):
"""Turn ssl charm config option on, with optional non-default
ssl port specification. Confirm that it is enabled on every
unit.
:param sentry_units: list of sentry units
:param deployment: amulet deployment object pointer
:param port: amqp port, use defaults if None
:param max_wait: maximum time to wait in seconds to confirm
:returns: None if successful. Raise on error.
"""
self.log.debug('Setting ssl charm config option: on')
# Enable RMQ SSL
config = {'ssl': 'on'}
if port:
config['ssl_port'] = port
deployment.d.configure('rabbitmq-server', config)
# Wait for unit status
self.rmq_wait_for_cluster(deployment)
# Confirm
tries = 0
ret = self.validate_rmq_ssl_enabled_units(sentry_units, port=port)
while ret and tries < (max_wait / 4):
time.sleep(4)
self.log.debug('Attempt {}: {}'.format(tries, ret))
ret = self.validate_rmq_ssl_enabled_units(sentry_units, port=port)
tries += 1
if ret:
amulet.raise_status(amulet.FAIL, ret)
|
[
"def",
"configure_rmq_ssl_on",
"(",
"self",
",",
"sentry_units",
",",
"deployment",
",",
"port",
"=",
"None",
",",
"max_wait",
"=",
"60",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Setting ssl charm config option: on'",
")",
"# Enable RMQ SSL",
"config",
"=",
"{",
"'ssl'",
":",
"'on'",
"}",
"if",
"port",
":",
"config",
"[",
"'ssl_port'",
"]",
"=",
"port",
"deployment",
".",
"d",
".",
"configure",
"(",
"'rabbitmq-server'",
",",
"config",
")",
"# Wait for unit status",
"self",
".",
"rmq_wait_for_cluster",
"(",
"deployment",
")",
"# Confirm",
"tries",
"=",
"0",
"ret",
"=",
"self",
".",
"validate_rmq_ssl_enabled_units",
"(",
"sentry_units",
",",
"port",
"=",
"port",
")",
"while",
"ret",
"and",
"tries",
"<",
"(",
"max_wait",
"/",
"4",
")",
":",
"time",
".",
"sleep",
"(",
"4",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Attempt {}: {}'",
".",
"format",
"(",
"tries",
",",
"ret",
")",
")",
"ret",
"=",
"self",
".",
"validate_rmq_ssl_enabled_units",
"(",
"sentry_units",
",",
"port",
"=",
"port",
")",
"tries",
"+=",
"1",
"if",
"ret",
":",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"ret",
")"
] |
Turn ssl charm config option on, with optional non-default
ssl port specification. Confirm that it is enabled on every
unit.
:param sentry_units: list of sentry units
:param deployment: amulet deployment object pointer
:param port: amqp port, use defaults if None
:param max_wait: maximum time to wait in seconds to confirm
:returns: None if successful. Raise on error.
|
[
"Turn",
"ssl",
"charm",
"config",
"option",
"on",
"with",
"optional",
"non",
"-",
"default",
"ssl",
"port",
"specification",
".",
"Confirm",
"that",
"it",
"is",
"enabled",
"on",
"every",
"unit",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1340-L1374
|
12,562
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.configure_rmq_ssl_off
|
def configure_rmq_ssl_off(self, sentry_units, deployment, max_wait=60):
"""Turn ssl charm config option off, confirm that it is disabled
on every unit.
:param sentry_units: list of sentry units
:param deployment: amulet deployment object pointer
:param max_wait: maximum time to wait in seconds to confirm
:returns: None if successful. Raise on error.
"""
self.log.debug('Setting ssl charm config option: off')
# Disable RMQ SSL
config = {'ssl': 'off'}
deployment.d.configure('rabbitmq-server', config)
# Wait for unit status
self.rmq_wait_for_cluster(deployment)
# Confirm
tries = 0
ret = self.validate_rmq_ssl_disabled_units(sentry_units)
while ret and tries < (max_wait / 4):
time.sleep(4)
self.log.debug('Attempt {}: {}'.format(tries, ret))
ret = self.validate_rmq_ssl_disabled_units(sentry_units)
tries += 1
if ret:
amulet.raise_status(amulet.FAIL, ret)
|
python
|
def configure_rmq_ssl_off(self, sentry_units, deployment, max_wait=60):
"""Turn ssl charm config option off, confirm that it is disabled
on every unit.
:param sentry_units: list of sentry units
:param deployment: amulet deployment object pointer
:param max_wait: maximum time to wait in seconds to confirm
:returns: None if successful. Raise on error.
"""
self.log.debug('Setting ssl charm config option: off')
# Disable RMQ SSL
config = {'ssl': 'off'}
deployment.d.configure('rabbitmq-server', config)
# Wait for unit status
self.rmq_wait_for_cluster(deployment)
# Confirm
tries = 0
ret = self.validate_rmq_ssl_disabled_units(sentry_units)
while ret and tries < (max_wait / 4):
time.sleep(4)
self.log.debug('Attempt {}: {}'.format(tries, ret))
ret = self.validate_rmq_ssl_disabled_units(sentry_units)
tries += 1
if ret:
amulet.raise_status(amulet.FAIL, ret)
|
[
"def",
"configure_rmq_ssl_off",
"(",
"self",
",",
"sentry_units",
",",
"deployment",
",",
"max_wait",
"=",
"60",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Setting ssl charm config option: off'",
")",
"# Disable RMQ SSL",
"config",
"=",
"{",
"'ssl'",
":",
"'off'",
"}",
"deployment",
".",
"d",
".",
"configure",
"(",
"'rabbitmq-server'",
",",
"config",
")",
"# Wait for unit status",
"self",
".",
"rmq_wait_for_cluster",
"(",
"deployment",
")",
"# Confirm",
"tries",
"=",
"0",
"ret",
"=",
"self",
".",
"validate_rmq_ssl_disabled_units",
"(",
"sentry_units",
")",
"while",
"ret",
"and",
"tries",
"<",
"(",
"max_wait",
"/",
"4",
")",
":",
"time",
".",
"sleep",
"(",
"4",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Attempt {}: {}'",
".",
"format",
"(",
"tries",
",",
"ret",
")",
")",
"ret",
"=",
"self",
".",
"validate_rmq_ssl_disabled_units",
"(",
"sentry_units",
")",
"tries",
"+=",
"1",
"if",
"ret",
":",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"ret",
")"
] |
Turn ssl charm config option off, confirm that it is disabled
on every unit.
:param sentry_units: list of sentry units
:param deployment: amulet deployment object pointer
:param max_wait: maximum time to wait in seconds to confirm
:returns: None if successful. Raise on error.
|
[
"Turn",
"ssl",
"charm",
"config",
"option",
"off",
"confirm",
"that",
"it",
"is",
"disabled",
"on",
"every",
"unit",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1376-L1404
|
12,563
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.connect_amqp_by_unit
|
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
port=None, fatal=True,
username="testuser1", password="changeme"):
"""Establish and return a pika amqp connection to the rabbitmq service
running on a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:param fatal: boolean, default to True (raises on connect error)
:param username: amqp user name, default to testuser1
:param password: amqp user password
:returns: pika amqp connection pointer or None if failed and non-fatal
"""
host = sentry_unit.info['public-address']
unit_name = sentry_unit.info['unit_name']
# Default port logic if port is not specified
if ssl and not port:
port = 5671
elif not ssl and not port:
port = 5672
self.log.debug('Connecting to amqp on {}:{} ({}) as '
'{}...'.format(host, port, unit_name, username))
try:
credentials = pika.PlainCredentials(username, password)
parameters = pika.ConnectionParameters(host=host, port=port,
credentials=credentials,
ssl=ssl,
connection_attempts=3,
retry_delay=5,
socket_timeout=1)
connection = pika.BlockingConnection(parameters)
assert connection.is_open is True
assert connection.is_closing is False
self.log.debug('Connect OK')
return connection
except Exception as e:
msg = ('amqp connection failed to {}:{} as '
'{} ({})'.format(host, port, username, str(e)))
if fatal:
amulet.raise_status(amulet.FAIL, msg)
else:
self.log.warn(msg)
return None
|
python
|
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
port=None, fatal=True,
username="testuser1", password="changeme"):
"""Establish and return a pika amqp connection to the rabbitmq service
running on a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:param fatal: boolean, default to True (raises on connect error)
:param username: amqp user name, default to testuser1
:param password: amqp user password
:returns: pika amqp connection pointer or None if failed and non-fatal
"""
host = sentry_unit.info['public-address']
unit_name = sentry_unit.info['unit_name']
# Default port logic if port is not specified
if ssl and not port:
port = 5671
elif not ssl and not port:
port = 5672
self.log.debug('Connecting to amqp on {}:{} ({}) as '
'{}...'.format(host, port, unit_name, username))
try:
credentials = pika.PlainCredentials(username, password)
parameters = pika.ConnectionParameters(host=host, port=port,
credentials=credentials,
ssl=ssl,
connection_attempts=3,
retry_delay=5,
socket_timeout=1)
connection = pika.BlockingConnection(parameters)
assert connection.is_open is True
assert connection.is_closing is False
self.log.debug('Connect OK')
return connection
except Exception as e:
msg = ('amqp connection failed to {}:{} as '
'{} ({})'.format(host, port, username, str(e)))
if fatal:
amulet.raise_status(amulet.FAIL, msg)
else:
self.log.warn(msg)
return None
|
[
"def",
"connect_amqp_by_unit",
"(",
"self",
",",
"sentry_unit",
",",
"ssl",
"=",
"False",
",",
"port",
"=",
"None",
",",
"fatal",
"=",
"True",
",",
"username",
"=",
"\"testuser1\"",
",",
"password",
"=",
"\"changeme\"",
")",
":",
"host",
"=",
"sentry_unit",
".",
"info",
"[",
"'public-address'",
"]",
"unit_name",
"=",
"sentry_unit",
".",
"info",
"[",
"'unit_name'",
"]",
"# Default port logic if port is not specified",
"if",
"ssl",
"and",
"not",
"port",
":",
"port",
"=",
"5671",
"elif",
"not",
"ssl",
"and",
"not",
"port",
":",
"port",
"=",
"5672",
"self",
".",
"log",
".",
"debug",
"(",
"'Connecting to amqp on {}:{} ({}) as '",
"'{}...'",
".",
"format",
"(",
"host",
",",
"port",
",",
"unit_name",
",",
"username",
")",
")",
"try",
":",
"credentials",
"=",
"pika",
".",
"PlainCredentials",
"(",
"username",
",",
"password",
")",
"parameters",
"=",
"pika",
".",
"ConnectionParameters",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"credentials",
"=",
"credentials",
",",
"ssl",
"=",
"ssl",
",",
"connection_attempts",
"=",
"3",
",",
"retry_delay",
"=",
"5",
",",
"socket_timeout",
"=",
"1",
")",
"connection",
"=",
"pika",
".",
"BlockingConnection",
"(",
"parameters",
")",
"assert",
"connection",
".",
"is_open",
"is",
"True",
"assert",
"connection",
".",
"is_closing",
"is",
"False",
"self",
".",
"log",
".",
"debug",
"(",
"'Connect OK'",
")",
"return",
"connection",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"(",
"'amqp connection failed to {}:{} as '",
"'{} ({})'",
".",
"format",
"(",
"host",
",",
"port",
",",
"username",
",",
"str",
"(",
"e",
")",
")",
")",
"if",
"fatal",
":",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
")",
"else",
":",
"self",
".",
"log",
".",
"warn",
"(",
"msg",
")",
"return",
"None"
] |
Establish and return a pika amqp connection to the rabbitmq service
running on a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:param fatal: boolean, default to True (raises on connect error)
:param username: amqp user name, default to testuser1
:param password: amqp user password
:returns: pika amqp connection pointer or None if failed and non-fatal
|
[
"Establish",
"and",
"return",
"a",
"pika",
"amqp",
"connection",
"to",
"the",
"rabbitmq",
"service",
"running",
"on",
"a",
"rmq",
"juju",
"unit",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1406-L1452
|
12,564
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.publish_amqp_message_by_unit
|
def publish_amqp_message_by_unit(self, sentry_unit, message,
queue="test", ssl=False,
username="testuser1",
password="changeme",
port=None):
"""Publish an amqp message to a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param message: amqp message string
:param queue: message queue, default to test
:param username: amqp user name, default to testuser1
:param password: amqp user password
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:returns: None. Raises exception if publish failed.
"""
self.log.debug('Publishing message to {} queue:\n{}'.format(queue,
message))
connection = self.connect_amqp_by_unit(sentry_unit, ssl=ssl,
port=port,
username=username,
password=password)
# NOTE(beisner): extra debug here re: pika hang potential:
# https://github.com/pika/pika/issues/297
# https://groups.google.com/forum/#!topic/rabbitmq-users/Ja0iyfF0Szw
self.log.debug('Defining channel...')
channel = connection.channel()
self.log.debug('Declaring queue...')
channel.queue_declare(queue=queue, auto_delete=False, durable=True)
self.log.debug('Publishing message...')
channel.basic_publish(exchange='', routing_key=queue, body=message)
self.log.debug('Closing channel...')
channel.close()
self.log.debug('Closing connection...')
connection.close()
|
python
|
def publish_amqp_message_by_unit(self, sentry_unit, message,
queue="test", ssl=False,
username="testuser1",
password="changeme",
port=None):
"""Publish an amqp message to a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param message: amqp message string
:param queue: message queue, default to test
:param username: amqp user name, default to testuser1
:param password: amqp user password
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:returns: None. Raises exception if publish failed.
"""
self.log.debug('Publishing message to {} queue:\n{}'.format(queue,
message))
connection = self.connect_amqp_by_unit(sentry_unit, ssl=ssl,
port=port,
username=username,
password=password)
# NOTE(beisner): extra debug here re: pika hang potential:
# https://github.com/pika/pika/issues/297
# https://groups.google.com/forum/#!topic/rabbitmq-users/Ja0iyfF0Szw
self.log.debug('Defining channel...')
channel = connection.channel()
self.log.debug('Declaring queue...')
channel.queue_declare(queue=queue, auto_delete=False, durable=True)
self.log.debug('Publishing message...')
channel.basic_publish(exchange='', routing_key=queue, body=message)
self.log.debug('Closing channel...')
channel.close()
self.log.debug('Closing connection...')
connection.close()
|
[
"def",
"publish_amqp_message_by_unit",
"(",
"self",
",",
"sentry_unit",
",",
"message",
",",
"queue",
"=",
"\"test\"",
",",
"ssl",
"=",
"False",
",",
"username",
"=",
"\"testuser1\"",
",",
"password",
"=",
"\"changeme\"",
",",
"port",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Publishing message to {} queue:\\n{}'",
".",
"format",
"(",
"queue",
",",
"message",
")",
")",
"connection",
"=",
"self",
".",
"connect_amqp_by_unit",
"(",
"sentry_unit",
",",
"ssl",
"=",
"ssl",
",",
"port",
"=",
"port",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
")",
"# NOTE(beisner): extra debug here re: pika hang potential:",
"# https://github.com/pika/pika/issues/297",
"# https://groups.google.com/forum/#!topic/rabbitmq-users/Ja0iyfF0Szw",
"self",
".",
"log",
".",
"debug",
"(",
"'Defining channel...'",
")",
"channel",
"=",
"connection",
".",
"channel",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Declaring queue...'",
")",
"channel",
".",
"queue_declare",
"(",
"queue",
"=",
"queue",
",",
"auto_delete",
"=",
"False",
",",
"durable",
"=",
"True",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Publishing message...'",
")",
"channel",
".",
"basic_publish",
"(",
"exchange",
"=",
"''",
",",
"routing_key",
"=",
"queue",
",",
"body",
"=",
"message",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Closing channel...'",
")",
"channel",
".",
"close",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Closing connection...'",
")",
"connection",
".",
"close",
"(",
")"
] |
Publish an amqp message to a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param message: amqp message string
:param queue: message queue, default to test
:param username: amqp user name, default to testuser1
:param password: amqp user password
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:returns: None. Raises exception if publish failed.
|
[
"Publish",
"an",
"amqp",
"message",
"to",
"a",
"rmq",
"juju",
"unit",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1454-L1489
|
12,565
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.get_amqp_message_by_unit
|
def get_amqp_message_by_unit(self, sentry_unit, queue="test",
username="testuser1",
password="changeme",
ssl=False, port=None):
"""Get an amqp message from a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param queue: message queue, default to test
:param username: amqp user name, default to testuser1
:param password: amqp user password
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:returns: amqp message body as string. Raise if get fails.
"""
connection = self.connect_amqp_by_unit(sentry_unit, ssl=ssl,
port=port,
username=username,
password=password)
channel = connection.channel()
method_frame, _, body = channel.basic_get(queue)
if method_frame:
self.log.debug('Retreived message from {} queue:\n{}'.format(queue,
body))
channel.basic_ack(method_frame.delivery_tag)
channel.close()
connection.close()
return body
else:
msg = 'No message retrieved.'
amulet.raise_status(amulet.FAIL, msg)
|
python
|
def get_amqp_message_by_unit(self, sentry_unit, queue="test",
username="testuser1",
password="changeme",
ssl=False, port=None):
"""Get an amqp message from a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param queue: message queue, default to test
:param username: amqp user name, default to testuser1
:param password: amqp user password
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:returns: amqp message body as string. Raise if get fails.
"""
connection = self.connect_amqp_by_unit(sentry_unit, ssl=ssl,
port=port,
username=username,
password=password)
channel = connection.channel()
method_frame, _, body = channel.basic_get(queue)
if method_frame:
self.log.debug('Retreived message from {} queue:\n{}'.format(queue,
body))
channel.basic_ack(method_frame.delivery_tag)
channel.close()
connection.close()
return body
else:
msg = 'No message retrieved.'
amulet.raise_status(amulet.FAIL, msg)
|
[
"def",
"get_amqp_message_by_unit",
"(",
"self",
",",
"sentry_unit",
",",
"queue",
"=",
"\"test\"",
",",
"username",
"=",
"\"testuser1\"",
",",
"password",
"=",
"\"changeme\"",
",",
"ssl",
"=",
"False",
",",
"port",
"=",
"None",
")",
":",
"connection",
"=",
"self",
".",
"connect_amqp_by_unit",
"(",
"sentry_unit",
",",
"ssl",
"=",
"ssl",
",",
"port",
"=",
"port",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
")",
"channel",
"=",
"connection",
".",
"channel",
"(",
")",
"method_frame",
",",
"_",
",",
"body",
"=",
"channel",
".",
"basic_get",
"(",
"queue",
")",
"if",
"method_frame",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Retreived message from {} queue:\\n{}'",
".",
"format",
"(",
"queue",
",",
"body",
")",
")",
"channel",
".",
"basic_ack",
"(",
"method_frame",
".",
"delivery_tag",
")",
"channel",
".",
"close",
"(",
")",
"connection",
".",
"close",
"(",
")",
"return",
"body",
"else",
":",
"msg",
"=",
"'No message retrieved.'",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
")"
] |
Get an amqp message from a rmq juju unit.
:param sentry_unit: sentry unit pointer
:param queue: message queue, default to test
:param username: amqp user name, default to testuser1
:param password: amqp user password
:param ssl: boolean, default to False
:param port: amqp port, use defaults if None
:returns: amqp message body as string. Raise if get fails.
|
[
"Get",
"an",
"amqp",
"message",
"from",
"a",
"rmq",
"juju",
"unit",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1491-L1521
|
12,566
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/amulet/utils.py
|
OpenStackAmuletUtils.validate_memcache
|
def validate_memcache(self, sentry_unit, conf, os_release,
earliest_release=5, section='keystone_authtoken',
check_kvs=None):
"""Check Memcache is running and is configured to be used
Example call from Amulet test:
def test_110_memcache(self):
u.validate_memcache(self.neutron_api_sentry,
'/etc/neutron/neutron.conf',
self._get_openstack_release())
:param sentry_unit: sentry unit
:param conf: OpenStack config file to check memcache settings
:param os_release: Current OpenStack release int code
:param earliest_release: Earliest Openstack release to check int code
:param section: OpenStack config file section to check
:param check_kvs: Dict of settings to check in config file
:returns: None
"""
if os_release < earliest_release:
self.log.debug('Skipping memcache checks for deployment. {} <'
'mitaka'.format(os_release))
return
_kvs = check_kvs or {'memcached_servers': 'inet6:[::1]:11211'}
self.log.debug('Checking memcached is running')
ret = self.validate_services_by_name({sentry_unit: ['memcached']})
if ret:
amulet.raise_status(amulet.FAIL, msg='Memcache running check'
'failed {}'.format(ret))
else:
self.log.debug('OK')
self.log.debug('Checking memcache url is configured in {}'.format(
conf))
if self.validate_config_data(sentry_unit, conf, section, _kvs):
message = "Memcache config error in: {}".format(conf)
amulet.raise_status(amulet.FAIL, msg=message)
else:
self.log.debug('OK')
self.log.debug('Checking memcache configuration in '
'/etc/memcached.conf')
contents = self.file_contents_safe(sentry_unit, '/etc/memcached.conf',
fatal=True)
ubuntu_release, _ = self.run_cmd_unit(sentry_unit, 'lsb_release -cs')
if CompareHostReleases(ubuntu_release) <= 'trusty':
memcache_listen_addr = 'ip6-localhost'
else:
memcache_listen_addr = '::1'
expected = {
'-p': '11211',
'-l': memcache_listen_addr}
found = []
for key, value in expected.items():
for line in contents.split('\n'):
if line.startswith(key):
self.log.debug('Checking {} is set to {}'.format(
key,
value))
assert value == line.split()[-1]
self.log.debug(line.split()[-1])
found.append(key)
if sorted(found) == sorted(expected.keys()):
self.log.debug('OK')
else:
message = "Memcache config error in: /etc/memcached.conf"
amulet.raise_status(amulet.FAIL, msg=message)
|
python
|
def validate_memcache(self, sentry_unit, conf, os_release,
earliest_release=5, section='keystone_authtoken',
check_kvs=None):
"""Check Memcache is running and is configured to be used
Example call from Amulet test:
def test_110_memcache(self):
u.validate_memcache(self.neutron_api_sentry,
'/etc/neutron/neutron.conf',
self._get_openstack_release())
:param sentry_unit: sentry unit
:param conf: OpenStack config file to check memcache settings
:param os_release: Current OpenStack release int code
:param earliest_release: Earliest Openstack release to check int code
:param section: OpenStack config file section to check
:param check_kvs: Dict of settings to check in config file
:returns: None
"""
if os_release < earliest_release:
self.log.debug('Skipping memcache checks for deployment. {} <'
'mitaka'.format(os_release))
return
_kvs = check_kvs or {'memcached_servers': 'inet6:[::1]:11211'}
self.log.debug('Checking memcached is running')
ret = self.validate_services_by_name({sentry_unit: ['memcached']})
if ret:
amulet.raise_status(amulet.FAIL, msg='Memcache running check'
'failed {}'.format(ret))
else:
self.log.debug('OK')
self.log.debug('Checking memcache url is configured in {}'.format(
conf))
if self.validate_config_data(sentry_unit, conf, section, _kvs):
message = "Memcache config error in: {}".format(conf)
amulet.raise_status(amulet.FAIL, msg=message)
else:
self.log.debug('OK')
self.log.debug('Checking memcache configuration in '
'/etc/memcached.conf')
contents = self.file_contents_safe(sentry_unit, '/etc/memcached.conf',
fatal=True)
ubuntu_release, _ = self.run_cmd_unit(sentry_unit, 'lsb_release -cs')
if CompareHostReleases(ubuntu_release) <= 'trusty':
memcache_listen_addr = 'ip6-localhost'
else:
memcache_listen_addr = '::1'
expected = {
'-p': '11211',
'-l': memcache_listen_addr}
found = []
for key, value in expected.items():
for line in contents.split('\n'):
if line.startswith(key):
self.log.debug('Checking {} is set to {}'.format(
key,
value))
assert value == line.split()[-1]
self.log.debug(line.split()[-1])
found.append(key)
if sorted(found) == sorted(expected.keys()):
self.log.debug('OK')
else:
message = "Memcache config error in: /etc/memcached.conf"
amulet.raise_status(amulet.FAIL, msg=message)
|
[
"def",
"validate_memcache",
"(",
"self",
",",
"sentry_unit",
",",
"conf",
",",
"os_release",
",",
"earliest_release",
"=",
"5",
",",
"section",
"=",
"'keystone_authtoken'",
",",
"check_kvs",
"=",
"None",
")",
":",
"if",
"os_release",
"<",
"earliest_release",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Skipping memcache checks for deployment. {} <'",
"'mitaka'",
".",
"format",
"(",
"os_release",
")",
")",
"return",
"_kvs",
"=",
"check_kvs",
"or",
"{",
"'memcached_servers'",
":",
"'inet6:[::1]:11211'",
"}",
"self",
".",
"log",
".",
"debug",
"(",
"'Checking memcached is running'",
")",
"ret",
"=",
"self",
".",
"validate_services_by_name",
"(",
"{",
"sentry_unit",
":",
"[",
"'memcached'",
"]",
"}",
")",
"if",
"ret",
":",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"'Memcache running check'",
"'failed {}'",
".",
"format",
"(",
"ret",
")",
")",
"else",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'OK'",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Checking memcache url is configured in {}'",
".",
"format",
"(",
"conf",
")",
")",
"if",
"self",
".",
"validate_config_data",
"(",
"sentry_unit",
",",
"conf",
",",
"section",
",",
"_kvs",
")",
":",
"message",
"=",
"\"Memcache config error in: {}\"",
".",
"format",
"(",
"conf",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"message",
")",
"else",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'OK'",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Checking memcache configuration in '",
"'/etc/memcached.conf'",
")",
"contents",
"=",
"self",
".",
"file_contents_safe",
"(",
"sentry_unit",
",",
"'/etc/memcached.conf'",
",",
"fatal",
"=",
"True",
")",
"ubuntu_release",
",",
"_",
"=",
"self",
".",
"run_cmd_unit",
"(",
"sentry_unit",
",",
"'lsb_release -cs'",
")",
"if",
"CompareHostReleases",
"(",
"ubuntu_release",
")",
"<=",
"'trusty'",
":",
"memcache_listen_addr",
"=",
"'ip6-localhost'",
"else",
":",
"memcache_listen_addr",
"=",
"'::1'",
"expected",
"=",
"{",
"'-p'",
":",
"'11211'",
",",
"'-l'",
":",
"memcache_listen_addr",
"}",
"found",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"expected",
".",
"items",
"(",
")",
":",
"for",
"line",
"in",
"contents",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"key",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Checking {} is set to {}'",
".",
"format",
"(",
"key",
",",
"value",
")",
")",
"assert",
"value",
"==",
"line",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
"self",
".",
"log",
".",
"debug",
"(",
"line",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
")",
"found",
".",
"append",
"(",
"key",
")",
"if",
"sorted",
"(",
"found",
")",
"==",
"sorted",
"(",
"expected",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'OK'",
")",
"else",
":",
"message",
"=",
"\"Memcache config error in: /etc/memcached.conf\"",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"message",
")"
] |
Check Memcache is running and is configured to be used
Example call from Amulet test:
def test_110_memcache(self):
u.validate_memcache(self.neutron_api_sentry,
'/etc/neutron/neutron.conf',
self._get_openstack_release())
:param sentry_unit: sentry unit
:param conf: OpenStack config file to check memcache settings
:param os_release: Current OpenStack release int code
:param earliest_release: Earliest Openstack release to check int code
:param section: OpenStack config file section to check
:param check_kvs: Dict of settings to check in config file
:returns: None
|
[
"Check",
"Memcache",
"is",
"running",
"and",
"is",
"configured",
"to",
"be",
"used"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/utils.py#L1523-L1588
|
12,567
|
juju/charm-helpers
|
charmhelpers/coordinator.py
|
BaseCoordinator.acquire
|
def acquire(self, lock):
'''Acquire the named lock, non-blocking.
The lock may be granted immediately, or in a future hook.
Returns True if the lock has been granted. The lock will be
automatically released at the end of the hook in which it is
granted.
Do not mindlessly call this method, as it triggers a cascade of
hooks. For example, if you call acquire() every time in your
peers relation-changed hook you will end up with an infinite loop
of hooks. It should almost always be guarded by some condition.
'''
unit = hookenv.local_unit()
ts = self.requests[unit].get(lock)
if not ts:
# If there is no outstanding request on the peers relation,
# create one.
self.requests.setdefault(lock, {})
self.requests[unit][lock] = _timestamp()
self.msg('Requested {}'.format(lock))
# If the leader has granted the lock, yay.
if self.granted(lock):
self.msg('Acquired {}'.format(lock))
return True
# If the unit making the request also happens to be the
# leader, it must handle the request now. Even though the
# request has been stored on the peers relation, the peers
# relation-changed hook will not be triggered.
if hookenv.is_leader():
return self.grant(lock, unit)
return False
|
python
|
def acquire(self, lock):
'''Acquire the named lock, non-blocking.
The lock may be granted immediately, or in a future hook.
Returns True if the lock has been granted. The lock will be
automatically released at the end of the hook in which it is
granted.
Do not mindlessly call this method, as it triggers a cascade of
hooks. For example, if you call acquire() every time in your
peers relation-changed hook you will end up with an infinite loop
of hooks. It should almost always be guarded by some condition.
'''
unit = hookenv.local_unit()
ts = self.requests[unit].get(lock)
if not ts:
# If there is no outstanding request on the peers relation,
# create one.
self.requests.setdefault(lock, {})
self.requests[unit][lock] = _timestamp()
self.msg('Requested {}'.format(lock))
# If the leader has granted the lock, yay.
if self.granted(lock):
self.msg('Acquired {}'.format(lock))
return True
# If the unit making the request also happens to be the
# leader, it must handle the request now. Even though the
# request has been stored on the peers relation, the peers
# relation-changed hook will not be triggered.
if hookenv.is_leader():
return self.grant(lock, unit)
return False
|
[
"def",
"acquire",
"(",
"self",
",",
"lock",
")",
":",
"unit",
"=",
"hookenv",
".",
"local_unit",
"(",
")",
"ts",
"=",
"self",
".",
"requests",
"[",
"unit",
"]",
".",
"get",
"(",
"lock",
")",
"if",
"not",
"ts",
":",
"# If there is no outstanding request on the peers relation,",
"# create one.",
"self",
".",
"requests",
".",
"setdefault",
"(",
"lock",
",",
"{",
"}",
")",
"self",
".",
"requests",
"[",
"unit",
"]",
"[",
"lock",
"]",
"=",
"_timestamp",
"(",
")",
"self",
".",
"msg",
"(",
"'Requested {}'",
".",
"format",
"(",
"lock",
")",
")",
"# If the leader has granted the lock, yay.",
"if",
"self",
".",
"granted",
"(",
"lock",
")",
":",
"self",
".",
"msg",
"(",
"'Acquired {}'",
".",
"format",
"(",
"lock",
")",
")",
"return",
"True",
"# If the unit making the request also happens to be the",
"# leader, it must handle the request now. Even though the",
"# request has been stored on the peers relation, the peers",
"# relation-changed hook will not be triggered.",
"if",
"hookenv",
".",
"is_leader",
"(",
")",
":",
"return",
"self",
".",
"grant",
"(",
"lock",
",",
"unit",
")",
"return",
"False"
] |
Acquire the named lock, non-blocking.
The lock may be granted immediately, or in a future hook.
Returns True if the lock has been granted. The lock will be
automatically released at the end of the hook in which it is
granted.
Do not mindlessly call this method, as it triggers a cascade of
hooks. For example, if you call acquire() every time in your
peers relation-changed hook you will end up with an infinite loop
of hooks. It should almost always be guarded by some condition.
|
[
"Acquire",
"the",
"named",
"lock",
"non",
"-",
"blocking",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L301-L336
|
12,568
|
juju/charm-helpers
|
charmhelpers/coordinator.py
|
BaseCoordinator.granted
|
def granted(self, lock):
'''Return True if a previously requested lock has been granted'''
unit = hookenv.local_unit()
ts = self.requests[unit].get(lock)
if ts and self.grants.get(unit, {}).get(lock) == ts:
return True
return False
|
python
|
def granted(self, lock):
'''Return True if a previously requested lock has been granted'''
unit = hookenv.local_unit()
ts = self.requests[unit].get(lock)
if ts and self.grants.get(unit, {}).get(lock) == ts:
return True
return False
|
[
"def",
"granted",
"(",
"self",
",",
"lock",
")",
":",
"unit",
"=",
"hookenv",
".",
"local_unit",
"(",
")",
"ts",
"=",
"self",
".",
"requests",
"[",
"unit",
"]",
".",
"get",
"(",
"lock",
")",
"if",
"ts",
"and",
"self",
".",
"grants",
".",
"get",
"(",
"unit",
",",
"{",
"}",
")",
".",
"get",
"(",
"lock",
")",
"==",
"ts",
":",
"return",
"True",
"return",
"False"
] |
Return True if a previously requested lock has been granted
|
[
"Return",
"True",
"if",
"a",
"previously",
"requested",
"lock",
"has",
"been",
"granted"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L338-L344
|
12,569
|
juju/charm-helpers
|
charmhelpers/coordinator.py
|
BaseCoordinator.request_timestamp
|
def request_timestamp(self, lock):
'''Return the timestamp of our outstanding request for lock, or None.
Returns a datetime.datetime() UTC timestamp, with no tzinfo attribute.
'''
ts = self.requests[hookenv.local_unit()].get(lock, None)
if ts is not None:
return datetime.strptime(ts, _timestamp_format)
|
python
|
def request_timestamp(self, lock):
'''Return the timestamp of our outstanding request for lock, or None.
Returns a datetime.datetime() UTC timestamp, with no tzinfo attribute.
'''
ts = self.requests[hookenv.local_unit()].get(lock, None)
if ts is not None:
return datetime.strptime(ts, _timestamp_format)
|
[
"def",
"request_timestamp",
"(",
"self",
",",
"lock",
")",
":",
"ts",
"=",
"self",
".",
"requests",
"[",
"hookenv",
".",
"local_unit",
"(",
")",
"]",
".",
"get",
"(",
"lock",
",",
"None",
")",
"if",
"ts",
"is",
"not",
"None",
":",
"return",
"datetime",
".",
"strptime",
"(",
"ts",
",",
"_timestamp_format",
")"
] |
Return the timestamp of our outstanding request for lock, or None.
Returns a datetime.datetime() UTC timestamp, with no tzinfo attribute.
|
[
"Return",
"the",
"timestamp",
"of",
"our",
"outstanding",
"request",
"for",
"lock",
"or",
"None",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L350-L357
|
12,570
|
juju/charm-helpers
|
charmhelpers/coordinator.py
|
BaseCoordinator.grant
|
def grant(self, lock, unit):
'''Maybe grant the lock to a unit.
The decision to grant the lock or not is made for $lock
by a corresponding method grant_$lock, which you may define
in a subclass. If no such method is defined, the default_grant
method is used. See Serial.default_grant() for details.
'''
if not hookenv.is_leader():
return False # Not the leader, so we cannot grant.
# Set of units already granted the lock.
granted = set()
for u in self.grants:
if lock in self.grants[u]:
granted.add(u)
if unit in granted:
return True # Already granted.
# Ordered list of units waiting for the lock.
reqs = set()
for u in self.requests:
if u in granted:
continue # In the granted set. Not wanted in the req list.
for _lock, ts in self.requests[u].items():
if _lock == lock:
reqs.add((ts, u))
queue = [t[1] for t in sorted(reqs)]
if unit not in queue:
return False # Unit has not requested the lock.
# Locate custom logic, or fallback to the default.
grant_func = getattr(self, 'grant_{}'.format(lock), self.default_grant)
if grant_func(lock, unit, granted, queue):
# Grant the lock.
self.msg('Leader grants {} to {}'.format(lock, unit))
self.grants.setdefault(unit, {})[lock] = self.requests[unit][lock]
return True
return False
|
python
|
def grant(self, lock, unit):
'''Maybe grant the lock to a unit.
The decision to grant the lock or not is made for $lock
by a corresponding method grant_$lock, which you may define
in a subclass. If no such method is defined, the default_grant
method is used. See Serial.default_grant() for details.
'''
if not hookenv.is_leader():
return False # Not the leader, so we cannot grant.
# Set of units already granted the lock.
granted = set()
for u in self.grants:
if lock in self.grants[u]:
granted.add(u)
if unit in granted:
return True # Already granted.
# Ordered list of units waiting for the lock.
reqs = set()
for u in self.requests:
if u in granted:
continue # In the granted set. Not wanted in the req list.
for _lock, ts in self.requests[u].items():
if _lock == lock:
reqs.add((ts, u))
queue = [t[1] for t in sorted(reqs)]
if unit not in queue:
return False # Unit has not requested the lock.
# Locate custom logic, or fallback to the default.
grant_func = getattr(self, 'grant_{}'.format(lock), self.default_grant)
if grant_func(lock, unit, granted, queue):
# Grant the lock.
self.msg('Leader grants {} to {}'.format(lock, unit))
self.grants.setdefault(unit, {})[lock] = self.requests[unit][lock]
return True
return False
|
[
"def",
"grant",
"(",
"self",
",",
"lock",
",",
"unit",
")",
":",
"if",
"not",
"hookenv",
".",
"is_leader",
"(",
")",
":",
"return",
"False",
"# Not the leader, so we cannot grant.",
"# Set of units already granted the lock.",
"granted",
"=",
"set",
"(",
")",
"for",
"u",
"in",
"self",
".",
"grants",
":",
"if",
"lock",
"in",
"self",
".",
"grants",
"[",
"u",
"]",
":",
"granted",
".",
"add",
"(",
"u",
")",
"if",
"unit",
"in",
"granted",
":",
"return",
"True",
"# Already granted.",
"# Ordered list of units waiting for the lock.",
"reqs",
"=",
"set",
"(",
")",
"for",
"u",
"in",
"self",
".",
"requests",
":",
"if",
"u",
"in",
"granted",
":",
"continue",
"# In the granted set. Not wanted in the req list.",
"for",
"_lock",
",",
"ts",
"in",
"self",
".",
"requests",
"[",
"u",
"]",
".",
"items",
"(",
")",
":",
"if",
"_lock",
"==",
"lock",
":",
"reqs",
".",
"add",
"(",
"(",
"ts",
",",
"u",
")",
")",
"queue",
"=",
"[",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
"sorted",
"(",
"reqs",
")",
"]",
"if",
"unit",
"not",
"in",
"queue",
":",
"return",
"False",
"# Unit has not requested the lock.",
"# Locate custom logic, or fallback to the default.",
"grant_func",
"=",
"getattr",
"(",
"self",
",",
"'grant_{}'",
".",
"format",
"(",
"lock",
")",
",",
"self",
".",
"default_grant",
")",
"if",
"grant_func",
"(",
"lock",
",",
"unit",
",",
"granted",
",",
"queue",
")",
":",
"# Grant the lock.",
"self",
".",
"msg",
"(",
"'Leader grants {} to {}'",
".",
"format",
"(",
"lock",
",",
"unit",
")",
")",
"self",
".",
"grants",
".",
"setdefault",
"(",
"unit",
",",
"{",
"}",
")",
"[",
"lock",
"]",
"=",
"self",
".",
"requests",
"[",
"unit",
"]",
"[",
"lock",
"]",
"return",
"True",
"return",
"False"
] |
Maybe grant the lock to a unit.
The decision to grant the lock or not is made for $lock
by a corresponding method grant_$lock, which you may define
in a subclass. If no such method is defined, the default_grant
method is used. See Serial.default_grant() for details.
|
[
"Maybe",
"grant",
"the",
"lock",
"to",
"a",
"unit",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L387-L427
|
12,571
|
juju/charm-helpers
|
charmhelpers/coordinator.py
|
BaseCoordinator.released
|
def released(self, unit, lock, timestamp):
'''Called on the leader when it has released a lock.
By default, does nothing but log messages. Override if you
need to perform additional housekeeping when a lock is released,
for example recording timestamps.
'''
interval = _utcnow() - timestamp
self.msg('Leader released {} from {}, held {}'.format(lock, unit,
interval))
|
python
|
def released(self, unit, lock, timestamp):
'''Called on the leader when it has released a lock.
By default, does nothing but log messages. Override if you
need to perform additional housekeeping when a lock is released,
for example recording timestamps.
'''
interval = _utcnow() - timestamp
self.msg('Leader released {} from {}, held {}'.format(lock, unit,
interval))
|
[
"def",
"released",
"(",
"self",
",",
"unit",
",",
"lock",
",",
"timestamp",
")",
":",
"interval",
"=",
"_utcnow",
"(",
")",
"-",
"timestamp",
"self",
".",
"msg",
"(",
"'Leader released {} from {}, held {}'",
".",
"format",
"(",
"lock",
",",
"unit",
",",
"interval",
")",
")"
] |
Called on the leader when it has released a lock.
By default, does nothing but log messages. Override if you
need to perform additional housekeeping when a lock is released,
for example recording timestamps.
|
[
"Called",
"on",
"the",
"leader",
"when",
"it",
"has",
"released",
"a",
"lock",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L429-L438
|
12,572
|
juju/charm-helpers
|
charmhelpers/coordinator.py
|
BaseCoordinator.require
|
def require(self, lock, guard_func, *guard_args, **guard_kw):
"""Decorate a function to be run only when a lock is acquired.
The lock is requested if the guard function returns True.
The decorated function is called if the lock has been granted.
"""
def decorator(f):
@wraps(f)
def wrapper(*args, **kw):
if self.granted(lock):
self.msg('Granted {}'.format(lock))
return f(*args, **kw)
if guard_func(*guard_args, **guard_kw) and self.acquire(lock):
return f(*args, **kw)
return None
return wrapper
return decorator
|
python
|
def require(self, lock, guard_func, *guard_args, **guard_kw):
"""Decorate a function to be run only when a lock is acquired.
The lock is requested if the guard function returns True.
The decorated function is called if the lock has been granted.
"""
def decorator(f):
@wraps(f)
def wrapper(*args, **kw):
if self.granted(lock):
self.msg('Granted {}'.format(lock))
return f(*args, **kw)
if guard_func(*guard_args, **guard_kw) and self.acquire(lock):
return f(*args, **kw)
return None
return wrapper
return decorator
|
[
"def",
"require",
"(",
"self",
",",
"lock",
",",
"guard_func",
",",
"*",
"guard_args",
",",
"*",
"*",
"guard_kw",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"granted",
"(",
"lock",
")",
":",
"self",
".",
"msg",
"(",
"'Granted {}'",
".",
"format",
"(",
"lock",
")",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"if",
"guard_func",
"(",
"*",
"guard_args",
",",
"*",
"*",
"guard_kw",
")",
"and",
"self",
".",
"acquire",
"(",
"lock",
")",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"None",
"return",
"wrapper",
"return",
"decorator"
] |
Decorate a function to be run only when a lock is acquired.
The lock is requested if the guard function returns True.
The decorated function is called if the lock has been granted.
|
[
"Decorate",
"a",
"function",
"to",
"be",
"run",
"only",
"when",
"a",
"lock",
"is",
"acquired",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L440-L457
|
12,573
|
juju/charm-helpers
|
charmhelpers/coordinator.py
|
BaseCoordinator.msg
|
def msg(self, msg):
'''Emit a message. Override to customize log spam.'''
hookenv.log('coordinator.{} {}'.format(self._name(), msg),
level=hookenv.INFO)
|
python
|
def msg(self, msg):
'''Emit a message. Override to customize log spam.'''
hookenv.log('coordinator.{} {}'.format(self._name(), msg),
level=hookenv.INFO)
|
[
"def",
"msg",
"(",
"self",
",",
"msg",
")",
":",
"hookenv",
".",
"log",
"(",
"'coordinator.{} {}'",
".",
"format",
"(",
"self",
".",
"_name",
"(",
")",
",",
"msg",
")",
",",
"level",
"=",
"hookenv",
".",
"INFO",
")"
] |
Emit a message. Override to customize log spam.
|
[
"Emit",
"a",
"message",
".",
"Override",
"to",
"customize",
"log",
"spam",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/coordinator.py#L459-L462
|
12,574
|
juju/charm-helpers
|
charmhelpers/__init__.py
|
deprecate
|
def deprecate(warning, date=None, log=None):
"""Add a deprecation warning the first time the function is used.
The date, which is a string in semi-ISO8660 format indicate the year-month
that the function is officially going to be removed.
usage:
@deprecate('use core/fetch/add_source() instead', '2017-04')
def contributed_add_source_thing(...):
...
And it then prints to the log ONCE that the function is deprecated.
The reason for passing the logging function (log) is so that hookenv.log
can be used for a charm if needed.
:param warning: String to indicat where it has moved ot.
:param date: optional sting, in YYYY-MM format to indicate when the
function will definitely (probably) be removed.
:param log: The log function to call to log. If not, logs to stdout
"""
def wrap(f):
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
try:
module = inspect.getmodule(f)
file = inspect.getsourcefile(f)
lines = inspect.getsourcelines(f)
f_name = "{}-{}-{}..{}-{}".format(
module.__name__, file, lines[0], lines[-1], f.__name__)
except (IOError, TypeError):
# assume it was local, so just use the name of the function
f_name = f.__name__
if f_name not in __deprecated_functions:
__deprecated_functions[f_name] = True
s = "DEPRECATION WARNING: Function {} is being removed".format(
f.__name__)
if date:
s = "{} on/around {}".format(s, date)
if warning:
s = "{} : {}".format(s, warning)
if log:
log(s)
else:
print(s)
return f(*args, **kwargs)
return wrapped_f
return wrap
|
python
|
def deprecate(warning, date=None, log=None):
"""Add a deprecation warning the first time the function is used.
The date, which is a string in semi-ISO8660 format indicate the year-month
that the function is officially going to be removed.
usage:
@deprecate('use core/fetch/add_source() instead', '2017-04')
def contributed_add_source_thing(...):
...
And it then prints to the log ONCE that the function is deprecated.
The reason for passing the logging function (log) is so that hookenv.log
can be used for a charm if needed.
:param warning: String to indicat where it has moved ot.
:param date: optional sting, in YYYY-MM format to indicate when the
function will definitely (probably) be removed.
:param log: The log function to call to log. If not, logs to stdout
"""
def wrap(f):
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
try:
module = inspect.getmodule(f)
file = inspect.getsourcefile(f)
lines = inspect.getsourcelines(f)
f_name = "{}-{}-{}..{}-{}".format(
module.__name__, file, lines[0], lines[-1], f.__name__)
except (IOError, TypeError):
# assume it was local, so just use the name of the function
f_name = f.__name__
if f_name not in __deprecated_functions:
__deprecated_functions[f_name] = True
s = "DEPRECATION WARNING: Function {} is being removed".format(
f.__name__)
if date:
s = "{} on/around {}".format(s, date)
if warning:
s = "{} : {}".format(s, warning)
if log:
log(s)
else:
print(s)
return f(*args, **kwargs)
return wrapped_f
return wrap
|
[
"def",
"deprecate",
"(",
"warning",
",",
"date",
"=",
"None",
",",
"log",
"=",
"None",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"f",
")",
"file",
"=",
"inspect",
".",
"getsourcefile",
"(",
"f",
")",
"lines",
"=",
"inspect",
".",
"getsourcelines",
"(",
"f",
")",
"f_name",
"=",
"\"{}-{}-{}..{}-{}\"",
".",
"format",
"(",
"module",
".",
"__name__",
",",
"file",
",",
"lines",
"[",
"0",
"]",
",",
"lines",
"[",
"-",
"1",
"]",
",",
"f",
".",
"__name__",
")",
"except",
"(",
"IOError",
",",
"TypeError",
")",
":",
"# assume it was local, so just use the name of the function",
"f_name",
"=",
"f",
".",
"__name__",
"if",
"f_name",
"not",
"in",
"__deprecated_functions",
":",
"__deprecated_functions",
"[",
"f_name",
"]",
"=",
"True",
"s",
"=",
"\"DEPRECATION WARNING: Function {} is being removed\"",
".",
"format",
"(",
"f",
".",
"__name__",
")",
"if",
"date",
":",
"s",
"=",
"\"{} on/around {}\"",
".",
"format",
"(",
"s",
",",
"date",
")",
"if",
"warning",
":",
"s",
"=",
"\"{} : {}\"",
".",
"format",
"(",
"s",
",",
"warning",
")",
"if",
"log",
":",
"log",
"(",
"s",
")",
"else",
":",
"print",
"(",
"s",
")",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapped_f",
"return",
"wrap"
] |
Add a deprecation warning the first time the function is used.
The date, which is a string in semi-ISO8660 format indicate the year-month
that the function is officially going to be removed.
usage:
@deprecate('use core/fetch/add_source() instead', '2017-04')
def contributed_add_source_thing(...):
...
And it then prints to the log ONCE that the function is deprecated.
The reason for passing the logging function (log) is so that hookenv.log
can be used for a charm if needed.
:param warning: String to indicat where it has moved ot.
:param date: optional sting, in YYYY-MM format to indicate when the
function will definitely (probably) be removed.
:param log: The log function to call to log. If not, logs to stdout
|
[
"Add",
"a",
"deprecation",
"warning",
"the",
"first",
"time",
"the",
"function",
"is",
"used",
".",
"The",
"date",
"which",
"is",
"a",
"string",
"in",
"semi",
"-",
"ISO8660",
"format",
"indicate",
"the",
"year",
"-",
"month",
"that",
"the",
"function",
"is",
"officially",
"going",
"to",
"be",
"removed",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/__init__.py#L50-L97
|
12,575
|
juju/charm-helpers
|
charmhelpers/fetch/archiveurl.py
|
ArchiveUrlFetchHandler.download
|
def download(self, source, dest):
"""
Download an archive file.
:param str source: URL pointing to an archive file.
:param str dest: Local path location to download archive file to.
"""
# propagate all exceptions
# URLError, OSError, etc
proto, netloc, path, params, query, fragment = urlparse(source)
if proto in ('http', 'https'):
auth, barehost = splituser(netloc)
if auth is not None:
source = urlunparse((proto, barehost, path, params, query, fragment))
username, password = splitpasswd(auth)
passman = HTTPPasswordMgrWithDefaultRealm()
# Realm is set to None in add_password to force the username and password
# to be used whatever the realm
passman.add_password(None, source, username, password)
authhandler = HTTPBasicAuthHandler(passman)
opener = build_opener(authhandler)
install_opener(opener)
response = urlopen(source)
try:
with open(dest, 'wb') as dest_file:
dest_file.write(response.read())
except Exception as e:
if os.path.isfile(dest):
os.unlink(dest)
raise e
|
python
|
def download(self, source, dest):
"""
Download an archive file.
:param str source: URL pointing to an archive file.
:param str dest: Local path location to download archive file to.
"""
# propagate all exceptions
# URLError, OSError, etc
proto, netloc, path, params, query, fragment = urlparse(source)
if proto in ('http', 'https'):
auth, barehost = splituser(netloc)
if auth is not None:
source = urlunparse((proto, barehost, path, params, query, fragment))
username, password = splitpasswd(auth)
passman = HTTPPasswordMgrWithDefaultRealm()
# Realm is set to None in add_password to force the username and password
# to be used whatever the realm
passman.add_password(None, source, username, password)
authhandler = HTTPBasicAuthHandler(passman)
opener = build_opener(authhandler)
install_opener(opener)
response = urlopen(source)
try:
with open(dest, 'wb') as dest_file:
dest_file.write(response.read())
except Exception as e:
if os.path.isfile(dest):
os.unlink(dest)
raise e
|
[
"def",
"download",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"# propagate all exceptions",
"# URLError, OSError, etc",
"proto",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"urlparse",
"(",
"source",
")",
"if",
"proto",
"in",
"(",
"'http'",
",",
"'https'",
")",
":",
"auth",
",",
"barehost",
"=",
"splituser",
"(",
"netloc",
")",
"if",
"auth",
"is",
"not",
"None",
":",
"source",
"=",
"urlunparse",
"(",
"(",
"proto",
",",
"barehost",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
")",
")",
"username",
",",
"password",
"=",
"splitpasswd",
"(",
"auth",
")",
"passman",
"=",
"HTTPPasswordMgrWithDefaultRealm",
"(",
")",
"# Realm is set to None in add_password to force the username and password",
"# to be used whatever the realm",
"passman",
".",
"add_password",
"(",
"None",
",",
"source",
",",
"username",
",",
"password",
")",
"authhandler",
"=",
"HTTPBasicAuthHandler",
"(",
"passman",
")",
"opener",
"=",
"build_opener",
"(",
"authhandler",
")",
"install_opener",
"(",
"opener",
")",
"response",
"=",
"urlopen",
"(",
"source",
")",
"try",
":",
"with",
"open",
"(",
"dest",
",",
"'wb'",
")",
"as",
"dest_file",
":",
"dest_file",
".",
"write",
"(",
"response",
".",
"read",
"(",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"dest",
")",
":",
"os",
".",
"unlink",
"(",
"dest",
")",
"raise",
"e"
] |
Download an archive file.
:param str source: URL pointing to an archive file.
:param str dest: Local path location to download archive file to.
|
[
"Download",
"an",
"archive",
"file",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/archiveurl.py#L85-L114
|
12,576
|
juju/charm-helpers
|
charmhelpers/fetch/archiveurl.py
|
ArchiveUrlFetchHandler.install
|
def install(self, source, dest=None, checksum=None, hash_type='sha1'):
"""
Download and install an archive file, with optional checksum validation.
The checksum can also be given on the `source` URL's fragment.
For example::
handler.install('http://example.com/file.tgz#sha1=deadbeef')
:param str source: URL pointing to an archive file.
:param str dest: Local destination path to install to. If not given,
installs to `$CHARM_DIR/archives/archive_file_name`.
:param str checksum: If given, validate the archive file after download.
:param str hash_type: Algorithm used to generate `checksum`.
Can be any hash alrgorithm supported by :mod:`hashlib`,
such as md5, sha1, sha256, sha512, etc.
"""
url_parts = self.parse_url(source)
dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched')
if not os.path.exists(dest_dir):
mkdir(dest_dir, perms=0o755)
dld_file = os.path.join(dest_dir, os.path.basename(url_parts.path))
try:
self.download(source, dld_file)
except URLError as e:
raise UnhandledSource(e.reason)
except OSError as e:
raise UnhandledSource(e.strerror)
options = parse_qs(url_parts.fragment)
for key, value in options.items():
if not six.PY3:
algorithms = hashlib.algorithms
else:
algorithms = hashlib.algorithms_available
if key in algorithms:
if len(value) != 1:
raise TypeError(
"Expected 1 hash value, not %d" % len(value))
expected = value[0]
check_hash(dld_file, expected, key)
if checksum:
check_hash(dld_file, checksum, hash_type)
return extract(dld_file, dest)
|
python
|
def install(self, source, dest=None, checksum=None, hash_type='sha1'):
"""
Download and install an archive file, with optional checksum validation.
The checksum can also be given on the `source` URL's fragment.
For example::
handler.install('http://example.com/file.tgz#sha1=deadbeef')
:param str source: URL pointing to an archive file.
:param str dest: Local destination path to install to. If not given,
installs to `$CHARM_DIR/archives/archive_file_name`.
:param str checksum: If given, validate the archive file after download.
:param str hash_type: Algorithm used to generate `checksum`.
Can be any hash alrgorithm supported by :mod:`hashlib`,
such as md5, sha1, sha256, sha512, etc.
"""
url_parts = self.parse_url(source)
dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched')
if not os.path.exists(dest_dir):
mkdir(dest_dir, perms=0o755)
dld_file = os.path.join(dest_dir, os.path.basename(url_parts.path))
try:
self.download(source, dld_file)
except URLError as e:
raise UnhandledSource(e.reason)
except OSError as e:
raise UnhandledSource(e.strerror)
options = parse_qs(url_parts.fragment)
for key, value in options.items():
if not six.PY3:
algorithms = hashlib.algorithms
else:
algorithms = hashlib.algorithms_available
if key in algorithms:
if len(value) != 1:
raise TypeError(
"Expected 1 hash value, not %d" % len(value))
expected = value[0]
check_hash(dld_file, expected, key)
if checksum:
check_hash(dld_file, checksum, hash_type)
return extract(dld_file, dest)
|
[
"def",
"install",
"(",
"self",
",",
"source",
",",
"dest",
"=",
"None",
",",
"checksum",
"=",
"None",
",",
"hash_type",
"=",
"'sha1'",
")",
":",
"url_parts",
"=",
"self",
".",
"parse_url",
"(",
"source",
")",
"dest_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'CHARM_DIR'",
")",
",",
"'fetched'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest_dir",
")",
":",
"mkdir",
"(",
"dest_dir",
",",
"perms",
"=",
"0o755",
")",
"dld_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest_dir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"url_parts",
".",
"path",
")",
")",
"try",
":",
"self",
".",
"download",
"(",
"source",
",",
"dld_file",
")",
"except",
"URLError",
"as",
"e",
":",
"raise",
"UnhandledSource",
"(",
"e",
".",
"reason",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"UnhandledSource",
"(",
"e",
".",
"strerror",
")",
"options",
"=",
"parse_qs",
"(",
"url_parts",
".",
"fragment",
")",
"for",
"key",
",",
"value",
"in",
"options",
".",
"items",
"(",
")",
":",
"if",
"not",
"six",
".",
"PY3",
":",
"algorithms",
"=",
"hashlib",
".",
"algorithms",
"else",
":",
"algorithms",
"=",
"hashlib",
".",
"algorithms_available",
"if",
"key",
"in",
"algorithms",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"\"Expected 1 hash value, not %d\"",
"%",
"len",
"(",
"value",
")",
")",
"expected",
"=",
"value",
"[",
"0",
"]",
"check_hash",
"(",
"dld_file",
",",
"expected",
",",
"key",
")",
"if",
"checksum",
":",
"check_hash",
"(",
"dld_file",
",",
"checksum",
",",
"hash_type",
")",
"return",
"extract",
"(",
"dld_file",
",",
"dest",
")"
] |
Download and install an archive file, with optional checksum validation.
The checksum can also be given on the `source` URL's fragment.
For example::
handler.install('http://example.com/file.tgz#sha1=deadbeef')
:param str source: URL pointing to an archive file.
:param str dest: Local destination path to install to. If not given,
installs to `$CHARM_DIR/archives/archive_file_name`.
:param str checksum: If given, validate the archive file after download.
:param str hash_type: Algorithm used to generate `checksum`.
Can be any hash alrgorithm supported by :mod:`hashlib`,
such as md5, sha1, sha256, sha512, etc.
|
[
"Download",
"and",
"install",
"an",
"archive",
"file",
"with",
"optional",
"checksum",
"validation",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/archiveurl.py#L122-L165
|
12,577
|
juju/charm-helpers
|
charmhelpers/fetch/python/debug.py
|
set_trace
|
def set_trace(addr=DEFAULT_ADDR, port=DEFAULT_PORT):
"""
Set a trace point using the remote debugger
"""
atexit.register(close_port, port)
try:
log("Starting a remote python debugger session on %s:%s" % (addr,
port))
open_port(port)
debugger = Rpdb(addr=addr, port=port)
debugger.set_trace(sys._getframe().f_back)
except Exception:
_error("Cannot start a remote debug session on %s:%s" % (addr,
port))
|
python
|
def set_trace(addr=DEFAULT_ADDR, port=DEFAULT_PORT):
"""
Set a trace point using the remote debugger
"""
atexit.register(close_port, port)
try:
log("Starting a remote python debugger session on %s:%s" % (addr,
port))
open_port(port)
debugger = Rpdb(addr=addr, port=port)
debugger.set_trace(sys._getframe().f_back)
except Exception:
_error("Cannot start a remote debug session on %s:%s" % (addr,
port))
|
[
"def",
"set_trace",
"(",
"addr",
"=",
"DEFAULT_ADDR",
",",
"port",
"=",
"DEFAULT_PORT",
")",
":",
"atexit",
".",
"register",
"(",
"close_port",
",",
"port",
")",
"try",
":",
"log",
"(",
"\"Starting a remote python debugger session on %s:%s\"",
"%",
"(",
"addr",
",",
"port",
")",
")",
"open_port",
"(",
"port",
")",
"debugger",
"=",
"Rpdb",
"(",
"addr",
"=",
"addr",
",",
"port",
"=",
"port",
")",
"debugger",
".",
"set_trace",
"(",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_back",
")",
"except",
"Exception",
":",
"_error",
"(",
"\"Cannot start a remote debug session on %s:%s\"",
"%",
"(",
"addr",
",",
"port",
")",
")"
] |
Set a trace point using the remote debugger
|
[
"Set",
"a",
"trace",
"point",
"using",
"the",
"remote",
"debugger"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/debug.py#L41-L54
|
12,578
|
juju/charm-helpers
|
charmhelpers/contrib/mellanox/infiniband.py
|
device_info
|
def device_info(device):
"""Returns a DeviceInfo object with the current device settings"""
status = subprocess.check_output([
'ibstat', device, '-s']).splitlines()
regexes = {
"CA type: (.*)": "device_type",
"Number of ports: (.*)": "num_ports",
"Firmware version: (.*)": "fw_ver",
"Hardware version: (.*)": "hw_ver",
"Node GUID: (.*)": "node_guid",
"System image GUID: (.*)": "sys_guid",
}
device = DeviceInfo()
for line in status:
for expression, key in regexes.items():
matches = re.search(expression, line)
if matches:
setattr(device, key, matches.group(1))
return device
|
python
|
def device_info(device):
"""Returns a DeviceInfo object with the current device settings"""
status = subprocess.check_output([
'ibstat', device, '-s']).splitlines()
regexes = {
"CA type: (.*)": "device_type",
"Number of ports: (.*)": "num_ports",
"Firmware version: (.*)": "fw_ver",
"Hardware version: (.*)": "hw_ver",
"Node GUID: (.*)": "node_guid",
"System image GUID: (.*)": "sys_guid",
}
device = DeviceInfo()
for line in status:
for expression, key in regexes.items():
matches = re.search(expression, line)
if matches:
setattr(device, key, matches.group(1))
return device
|
[
"def",
"device_info",
"(",
"device",
")",
":",
"status",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ibstat'",
",",
"device",
",",
"'-s'",
"]",
")",
".",
"splitlines",
"(",
")",
"regexes",
"=",
"{",
"\"CA type: (.*)\"",
":",
"\"device_type\"",
",",
"\"Number of ports: (.*)\"",
":",
"\"num_ports\"",
",",
"\"Firmware version: (.*)\"",
":",
"\"fw_ver\"",
",",
"\"Hardware version: (.*)\"",
":",
"\"hw_ver\"",
",",
"\"Node GUID: (.*)\"",
":",
"\"node_guid\"",
",",
"\"System image GUID: (.*)\"",
":",
"\"sys_guid\"",
",",
"}",
"device",
"=",
"DeviceInfo",
"(",
")",
"for",
"line",
"in",
"status",
":",
"for",
"expression",
",",
"key",
"in",
"regexes",
".",
"items",
"(",
")",
":",
"matches",
"=",
"re",
".",
"search",
"(",
"expression",
",",
"line",
")",
"if",
"matches",
":",
"setattr",
"(",
"device",
",",
"key",
",",
"matches",
".",
"group",
"(",
"1",
")",
")",
"return",
"device"
] |
Returns a DeviceInfo object with the current device settings
|
[
"Returns",
"a",
"DeviceInfo",
"object",
"with",
"the",
"current",
"device",
"settings"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/mellanox/infiniband.py#L111-L134
|
12,579
|
juju/charm-helpers
|
charmhelpers/contrib/mellanox/infiniband.py
|
ipoib_interfaces
|
def ipoib_interfaces():
"""Return a list of IPOIB capable ethernet interfaces"""
interfaces = []
for interface in network_interfaces():
try:
driver = re.search('^driver: (.+)$', subprocess.check_output([
'ethtool', '-i',
interface]), re.M).group(1)
if driver in IPOIB_DRIVERS:
interfaces.append(interface)
except Exception:
log("Skipping interface %s" % interface, level=INFO)
continue
return interfaces
|
python
|
def ipoib_interfaces():
"""Return a list of IPOIB capable ethernet interfaces"""
interfaces = []
for interface in network_interfaces():
try:
driver = re.search('^driver: (.+)$', subprocess.check_output([
'ethtool', '-i',
interface]), re.M).group(1)
if driver in IPOIB_DRIVERS:
interfaces.append(interface)
except Exception:
log("Skipping interface %s" % interface, level=INFO)
continue
return interfaces
|
[
"def",
"ipoib_interfaces",
"(",
")",
":",
"interfaces",
"=",
"[",
"]",
"for",
"interface",
"in",
"network_interfaces",
"(",
")",
":",
"try",
":",
"driver",
"=",
"re",
".",
"search",
"(",
"'^driver: (.+)$'",
",",
"subprocess",
".",
"check_output",
"(",
"[",
"'ethtool'",
",",
"'-i'",
",",
"interface",
"]",
")",
",",
"re",
".",
"M",
")",
".",
"group",
"(",
"1",
")",
"if",
"driver",
"in",
"IPOIB_DRIVERS",
":",
"interfaces",
".",
"append",
"(",
"interface",
")",
"except",
"Exception",
":",
"log",
"(",
"\"Skipping interface %s\"",
"%",
"interface",
",",
"level",
"=",
"INFO",
")",
"continue",
"return",
"interfaces"
] |
Return a list of IPOIB capable ethernet interfaces
|
[
"Return",
"a",
"list",
"of",
"IPOIB",
"capable",
"ethernet",
"interfaces"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/mellanox/infiniband.py#L137-L153
|
12,580
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/host/checks/login.py
|
get_audits
|
def get_audits():
"""Get OS hardening login.defs audits.
:returns: dictionary of audits
"""
audits = [TemplatedFile('/etc/login.defs', LoginContext(),
template_dir=TEMPLATES_DIR,
user='root', group='root', mode=0o0444)]
return audits
|
python
|
def get_audits():
"""Get OS hardening login.defs audits.
:returns: dictionary of audits
"""
audits = [TemplatedFile('/etc/login.defs', LoginContext(),
template_dir=TEMPLATES_DIR,
user='root', group='root', mode=0o0444)]
return audits
|
[
"def",
"get_audits",
"(",
")",
":",
"audits",
"=",
"[",
"TemplatedFile",
"(",
"'/etc/login.defs'",
",",
"LoginContext",
"(",
")",
",",
"template_dir",
"=",
"TEMPLATES_DIR",
",",
"user",
"=",
"'root'",
",",
"group",
"=",
"'root'",
",",
"mode",
"=",
"0o0444",
")",
"]",
"return",
"audits"
] |
Get OS hardening login.defs audits.
:returns: dictionary of audits
|
[
"Get",
"OS",
"hardening",
"login",
".",
"defs",
"audits",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/login.py#L22-L30
|
12,581
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/utils.py
|
_get_defaults
|
def _get_defaults(modules):
"""Load the default config for the provided modules.
:param modules: stack modules config defaults to lookup.
:returns: modules default config dictionary.
"""
default = os.path.join(os.path.dirname(__file__),
'defaults/%s.yaml' % (modules))
return yaml.safe_load(open(default))
|
python
|
def _get_defaults(modules):
"""Load the default config for the provided modules.
:param modules: stack modules config defaults to lookup.
:returns: modules default config dictionary.
"""
default = os.path.join(os.path.dirname(__file__),
'defaults/%s.yaml' % (modules))
return yaml.safe_load(open(default))
|
[
"def",
"_get_defaults",
"(",
"modules",
")",
":",
"default",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'defaults/%s.yaml'",
"%",
"(",
"modules",
")",
")",
"return",
"yaml",
".",
"safe_load",
"(",
"open",
"(",
"default",
")",
")"
] |
Load the default config for the provided modules.
:param modules: stack modules config defaults to lookup.
:returns: modules default config dictionary.
|
[
"Load",
"the",
"default",
"config",
"for",
"the",
"provided",
"modules",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L37-L45
|
12,582
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/utils.py
|
_get_schema
|
def _get_schema(modules):
"""Load the config schema for the provided modules.
NOTE: this schema is intended to have 1-1 relationship with they keys in
the default config and is used a means to verify valid overrides provided
by the user.
:param modules: stack modules config schema to lookup.
:returns: modules default schema dictionary.
"""
schema = os.path.join(os.path.dirname(__file__),
'defaults/%s.yaml.schema' % (modules))
return yaml.safe_load(open(schema))
|
python
|
def _get_schema(modules):
"""Load the config schema for the provided modules.
NOTE: this schema is intended to have 1-1 relationship with they keys in
the default config and is used a means to verify valid overrides provided
by the user.
:param modules: stack modules config schema to lookup.
:returns: modules default schema dictionary.
"""
schema = os.path.join(os.path.dirname(__file__),
'defaults/%s.yaml.schema' % (modules))
return yaml.safe_load(open(schema))
|
[
"def",
"_get_schema",
"(",
"modules",
")",
":",
"schema",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'defaults/%s.yaml.schema'",
"%",
"(",
"modules",
")",
")",
"return",
"yaml",
".",
"safe_load",
"(",
"open",
"(",
"schema",
")",
")"
] |
Load the config schema for the provided modules.
NOTE: this schema is intended to have 1-1 relationship with they keys in
the default config and is used a means to verify valid overrides provided
by the user.
:param modules: stack modules config schema to lookup.
:returns: modules default schema dictionary.
|
[
"Load",
"the",
"config",
"schema",
"for",
"the",
"provided",
"modules",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L48-L60
|
12,583
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/utils.py
|
_get_user_provided_overrides
|
def _get_user_provided_overrides(modules):
"""Load user-provided config overrides.
:param modules: stack modules to lookup in user overrides yaml file.
:returns: overrides dictionary.
"""
overrides = os.path.join(os.environ['JUJU_CHARM_DIR'],
'hardening.yaml')
if os.path.exists(overrides):
log("Found user-provided config overrides file '%s'" %
(overrides), level=DEBUG)
settings = yaml.safe_load(open(overrides))
if settings and settings.get(modules):
log("Applying '%s' overrides" % (modules), level=DEBUG)
return settings.get(modules)
log("No overrides found for '%s'" % (modules), level=DEBUG)
else:
log("No hardening config overrides file '%s' found in charm "
"root dir" % (overrides), level=DEBUG)
return {}
|
python
|
def _get_user_provided_overrides(modules):
"""Load user-provided config overrides.
:param modules: stack modules to lookup in user overrides yaml file.
:returns: overrides dictionary.
"""
overrides = os.path.join(os.environ['JUJU_CHARM_DIR'],
'hardening.yaml')
if os.path.exists(overrides):
log("Found user-provided config overrides file '%s'" %
(overrides), level=DEBUG)
settings = yaml.safe_load(open(overrides))
if settings and settings.get(modules):
log("Applying '%s' overrides" % (modules), level=DEBUG)
return settings.get(modules)
log("No overrides found for '%s'" % (modules), level=DEBUG)
else:
log("No hardening config overrides file '%s' found in charm "
"root dir" % (overrides), level=DEBUG)
return {}
|
[
"def",
"_get_user_provided_overrides",
"(",
"modules",
")",
":",
"overrides",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"'JUJU_CHARM_DIR'",
"]",
",",
"'hardening.yaml'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"overrides",
")",
":",
"log",
"(",
"\"Found user-provided config overrides file '%s'\"",
"%",
"(",
"overrides",
")",
",",
"level",
"=",
"DEBUG",
")",
"settings",
"=",
"yaml",
".",
"safe_load",
"(",
"open",
"(",
"overrides",
")",
")",
"if",
"settings",
"and",
"settings",
".",
"get",
"(",
"modules",
")",
":",
"log",
"(",
"\"Applying '%s' overrides\"",
"%",
"(",
"modules",
")",
",",
"level",
"=",
"DEBUG",
")",
"return",
"settings",
".",
"get",
"(",
"modules",
")",
"log",
"(",
"\"No overrides found for '%s'\"",
"%",
"(",
"modules",
")",
",",
"level",
"=",
"DEBUG",
")",
"else",
":",
"log",
"(",
"\"No hardening config overrides file '%s' found in charm \"",
"\"root dir\"",
"%",
"(",
"overrides",
")",
",",
"level",
"=",
"DEBUG",
")",
"return",
"{",
"}"
] |
Load user-provided config overrides.
:param modules: stack modules to lookup in user overrides yaml file.
:returns: overrides dictionary.
|
[
"Load",
"user",
"-",
"provided",
"config",
"overrides",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L63-L84
|
12,584
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/utils.py
|
_apply_overrides
|
def _apply_overrides(settings, overrides, schema):
"""Get overrides config overlayed onto modules defaults.
:param modules: require stack modules config.
:returns: dictionary of modules config with user overrides applied.
"""
if overrides:
for k, v in six.iteritems(overrides):
if k in schema:
if schema[k] is None:
settings[k] = v
elif type(schema[k]) is dict:
settings[k] = _apply_overrides(settings[k], overrides[k],
schema[k])
else:
raise Exception("Unexpected type found in schema '%s'" %
type(schema[k]), level=ERROR)
else:
log("Unknown override key '%s' - ignoring" % (k), level=INFO)
return settings
|
python
|
def _apply_overrides(settings, overrides, schema):
"""Get overrides config overlayed onto modules defaults.
:param modules: require stack modules config.
:returns: dictionary of modules config with user overrides applied.
"""
if overrides:
for k, v in six.iteritems(overrides):
if k in schema:
if schema[k] is None:
settings[k] = v
elif type(schema[k]) is dict:
settings[k] = _apply_overrides(settings[k], overrides[k],
schema[k])
else:
raise Exception("Unexpected type found in schema '%s'" %
type(schema[k]), level=ERROR)
else:
log("Unknown override key '%s' - ignoring" % (k), level=INFO)
return settings
|
[
"def",
"_apply_overrides",
"(",
"settings",
",",
"overrides",
",",
"schema",
")",
":",
"if",
"overrides",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"overrides",
")",
":",
"if",
"k",
"in",
"schema",
":",
"if",
"schema",
"[",
"k",
"]",
"is",
"None",
":",
"settings",
"[",
"k",
"]",
"=",
"v",
"elif",
"type",
"(",
"schema",
"[",
"k",
"]",
")",
"is",
"dict",
":",
"settings",
"[",
"k",
"]",
"=",
"_apply_overrides",
"(",
"settings",
"[",
"k",
"]",
",",
"overrides",
"[",
"k",
"]",
",",
"schema",
"[",
"k",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Unexpected type found in schema '%s'\"",
"%",
"type",
"(",
"schema",
"[",
"k",
"]",
")",
",",
"level",
"=",
"ERROR",
")",
"else",
":",
"log",
"(",
"\"Unknown override key '%s' - ignoring\"",
"%",
"(",
"k",
")",
",",
"level",
"=",
"INFO",
")",
"return",
"settings"
] |
Get overrides config overlayed onto modules defaults.
:param modules: require stack modules config.
:returns: dictionary of modules config with user overrides applied.
|
[
"Get",
"overrides",
"config",
"overlayed",
"onto",
"modules",
"defaults",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L87-L107
|
12,585
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/utils.py
|
ensure_permissions
|
def ensure_permissions(path, user, group, permissions, maxdepth=-1):
"""Ensure permissions for path.
If path is a file, apply to file and return. If path is a directory,
apply recursively (if required) to directory contents and return.
:param user: user name
:param group: group name
:param permissions: octal permissions
:param maxdepth: maximum recursion depth. A negative maxdepth allows
infinite recursion and maxdepth=0 means no recursion.
:returns: None
"""
if not os.path.exists(path):
log("File '%s' does not exist - cannot set permissions" % (path),
level=WARNING)
return
_user = pwd.getpwnam(user)
os.chown(path, _user.pw_uid, grp.getgrnam(group).gr_gid)
os.chmod(path, permissions)
if maxdepth == 0:
log("Max recursion depth reached - skipping further recursion",
level=DEBUG)
return
elif maxdepth > 0:
maxdepth -= 1
if os.path.isdir(path):
contents = glob.glob("%s/*" % (path))
for c in contents:
ensure_permissions(c, user=user, group=group,
permissions=permissions, maxdepth=maxdepth)
|
python
|
def ensure_permissions(path, user, group, permissions, maxdepth=-1):
"""Ensure permissions for path.
If path is a file, apply to file and return. If path is a directory,
apply recursively (if required) to directory contents and return.
:param user: user name
:param group: group name
:param permissions: octal permissions
:param maxdepth: maximum recursion depth. A negative maxdepth allows
infinite recursion and maxdepth=0 means no recursion.
:returns: None
"""
if not os.path.exists(path):
log("File '%s' does not exist - cannot set permissions" % (path),
level=WARNING)
return
_user = pwd.getpwnam(user)
os.chown(path, _user.pw_uid, grp.getgrnam(group).gr_gid)
os.chmod(path, permissions)
if maxdepth == 0:
log("Max recursion depth reached - skipping further recursion",
level=DEBUG)
return
elif maxdepth > 0:
maxdepth -= 1
if os.path.isdir(path):
contents = glob.glob("%s/*" % (path))
for c in contents:
ensure_permissions(c, user=user, group=group,
permissions=permissions, maxdepth=maxdepth)
|
[
"def",
"ensure_permissions",
"(",
"path",
",",
"user",
",",
"group",
",",
"permissions",
",",
"maxdepth",
"=",
"-",
"1",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"log",
"(",
"\"File '%s' does not exist - cannot set permissions\"",
"%",
"(",
"path",
")",
",",
"level",
"=",
"WARNING",
")",
"return",
"_user",
"=",
"pwd",
".",
"getpwnam",
"(",
"user",
")",
"os",
".",
"chown",
"(",
"path",
",",
"_user",
".",
"pw_uid",
",",
"grp",
".",
"getgrnam",
"(",
"group",
")",
".",
"gr_gid",
")",
"os",
".",
"chmod",
"(",
"path",
",",
"permissions",
")",
"if",
"maxdepth",
"==",
"0",
":",
"log",
"(",
"\"Max recursion depth reached - skipping further recursion\"",
",",
"level",
"=",
"DEBUG",
")",
"return",
"elif",
"maxdepth",
">",
"0",
":",
"maxdepth",
"-=",
"1",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"contents",
"=",
"glob",
".",
"glob",
"(",
"\"%s/*\"",
"%",
"(",
"path",
")",
")",
"for",
"c",
"in",
"contents",
":",
"ensure_permissions",
"(",
"c",
",",
"user",
"=",
"user",
",",
"group",
"=",
"group",
",",
"permissions",
"=",
"permissions",
",",
"maxdepth",
"=",
"maxdepth",
")"
] |
Ensure permissions for path.
If path is a file, apply to file and return. If path is a directory,
apply recursively (if required) to directory contents and return.
:param user: user name
:param group: group name
:param permissions: octal permissions
:param maxdepth: maximum recursion depth. A negative maxdepth allows
infinite recursion and maxdepth=0 means no recursion.
:returns: None
|
[
"Ensure",
"permissions",
"for",
"path",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/utils.py#L122-L155
|
12,586
|
juju/charm-helpers
|
charmhelpers/core/sysctl.py
|
create
|
def create(sysctl_dict, sysctl_file, ignore=False):
"""Creates a sysctl.conf file from a YAML associative array
:param sysctl_dict: a dict or YAML-formatted string of sysctl
options eg "{ 'kernel.max_pid': 1337 }"
:type sysctl_dict: str
:param sysctl_file: path to the sysctl file to be saved
:type sysctl_file: str or unicode
:param ignore: If True, ignore "unknown variable" errors.
:type ignore: bool
:returns: None
"""
if type(sysctl_dict) is not dict:
try:
sysctl_dict_parsed = yaml.safe_load(sysctl_dict)
except yaml.YAMLError:
log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict),
level=ERROR)
return
else:
sysctl_dict_parsed = sysctl_dict
with open(sysctl_file, "w") as fd:
for key, value in sysctl_dict_parsed.items():
fd.write("{}={}\n".format(key, value))
log("Updating sysctl_file: {} values: {}".format(sysctl_file,
sysctl_dict_parsed),
level=DEBUG)
call = ["sysctl", "-p", sysctl_file]
if ignore:
call.append("-e")
check_call(call)
|
python
|
def create(sysctl_dict, sysctl_file, ignore=False):
"""Creates a sysctl.conf file from a YAML associative array
:param sysctl_dict: a dict or YAML-formatted string of sysctl
options eg "{ 'kernel.max_pid': 1337 }"
:type sysctl_dict: str
:param sysctl_file: path to the sysctl file to be saved
:type sysctl_file: str or unicode
:param ignore: If True, ignore "unknown variable" errors.
:type ignore: bool
:returns: None
"""
if type(sysctl_dict) is not dict:
try:
sysctl_dict_parsed = yaml.safe_load(sysctl_dict)
except yaml.YAMLError:
log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict),
level=ERROR)
return
else:
sysctl_dict_parsed = sysctl_dict
with open(sysctl_file, "w") as fd:
for key, value in sysctl_dict_parsed.items():
fd.write("{}={}\n".format(key, value))
log("Updating sysctl_file: {} values: {}".format(sysctl_file,
sysctl_dict_parsed),
level=DEBUG)
call = ["sysctl", "-p", sysctl_file]
if ignore:
call.append("-e")
check_call(call)
|
[
"def",
"create",
"(",
"sysctl_dict",
",",
"sysctl_file",
",",
"ignore",
"=",
"False",
")",
":",
"if",
"type",
"(",
"sysctl_dict",
")",
"is",
"not",
"dict",
":",
"try",
":",
"sysctl_dict_parsed",
"=",
"yaml",
".",
"safe_load",
"(",
"sysctl_dict",
")",
"except",
"yaml",
".",
"YAMLError",
":",
"log",
"(",
"\"Error parsing YAML sysctl_dict: {}\"",
".",
"format",
"(",
"sysctl_dict",
")",
",",
"level",
"=",
"ERROR",
")",
"return",
"else",
":",
"sysctl_dict_parsed",
"=",
"sysctl_dict",
"with",
"open",
"(",
"sysctl_file",
",",
"\"w\"",
")",
"as",
"fd",
":",
"for",
"key",
",",
"value",
"in",
"sysctl_dict_parsed",
".",
"items",
"(",
")",
":",
"fd",
".",
"write",
"(",
"\"{}={}\\n\"",
".",
"format",
"(",
"key",
",",
"value",
")",
")",
"log",
"(",
"\"Updating sysctl_file: {} values: {}\"",
".",
"format",
"(",
"sysctl_file",
",",
"sysctl_dict_parsed",
")",
",",
"level",
"=",
"DEBUG",
")",
"call",
"=",
"[",
"\"sysctl\"",
",",
"\"-p\"",
",",
"sysctl_file",
"]",
"if",
"ignore",
":",
"call",
".",
"append",
"(",
"\"-e\"",
")",
"check_call",
"(",
"call",
")"
] |
Creates a sysctl.conf file from a YAML associative array
:param sysctl_dict: a dict or YAML-formatted string of sysctl
options eg "{ 'kernel.max_pid': 1337 }"
:type sysctl_dict: str
:param sysctl_file: path to the sysctl file to be saved
:type sysctl_file: str or unicode
:param ignore: If True, ignore "unknown variable" errors.
:type ignore: bool
:returns: None
|
[
"Creates",
"a",
"sysctl",
".",
"conf",
"file",
"from",
"a",
"YAML",
"associative",
"array"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/sysctl.py#L31-L65
|
12,587
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/ip.py
|
canonical_url
|
def canonical_url(configs, endpoint_type=PUBLIC):
"""Returns the correct HTTP URL to this host given the state of HTTPS
configuration, hacluster and charm configuration.
:param configs: OSTemplateRenderer config templating object to inspect
for a complete https context.
:param endpoint_type: str endpoint type to resolve.
:param returns: str base URL for services on the current service unit.
"""
scheme = _get_scheme(configs)
address = resolve_address(endpoint_type)
if is_ipv6(address):
address = "[{}]".format(address)
return '%s://%s' % (scheme, address)
|
python
|
def canonical_url(configs, endpoint_type=PUBLIC):
"""Returns the correct HTTP URL to this host given the state of HTTPS
configuration, hacluster and charm configuration.
:param configs: OSTemplateRenderer config templating object to inspect
for a complete https context.
:param endpoint_type: str endpoint type to resolve.
:param returns: str base URL for services on the current service unit.
"""
scheme = _get_scheme(configs)
address = resolve_address(endpoint_type)
if is_ipv6(address):
address = "[{}]".format(address)
return '%s://%s' % (scheme, address)
|
[
"def",
"canonical_url",
"(",
"configs",
",",
"endpoint_type",
"=",
"PUBLIC",
")",
":",
"scheme",
"=",
"_get_scheme",
"(",
"configs",
")",
"address",
"=",
"resolve_address",
"(",
"endpoint_type",
")",
"if",
"is_ipv6",
"(",
"address",
")",
":",
"address",
"=",
"\"[{}]\"",
".",
"format",
"(",
"address",
")",
"return",
"'%s://%s'",
"%",
"(",
"scheme",
",",
"address",
")"
] |
Returns the correct HTTP URL to this host given the state of HTTPS
configuration, hacluster and charm configuration.
:param configs: OSTemplateRenderer config templating object to inspect
for a complete https context.
:param endpoint_type: str endpoint type to resolve.
:param returns: str base URL for services on the current service unit.
|
[
"Returns",
"the",
"correct",
"HTTP",
"URL",
"to",
"this",
"host",
"given",
"the",
"state",
"of",
"HTTPS",
"configuration",
"hacluster",
"and",
"charm",
"configuration",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ip.py#L64-L79
|
12,588
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/ip.py
|
_get_address_override
|
def _get_address_override(endpoint_type=PUBLIC):
"""Returns any address overrides that the user has defined based on the
endpoint type.
Note: this function allows for the service name to be inserted into the
address if the user specifies {service_name}.somehost.org.
:param endpoint_type: the type of endpoint to retrieve the override
value for.
:returns: any endpoint address or hostname that the user has overridden
or None if an override is not present.
"""
override_key = ADDRESS_MAP[endpoint_type]['override']
addr_override = config(override_key)
if not addr_override:
return None
else:
return addr_override.format(service_name=service_name())
|
python
|
def _get_address_override(endpoint_type=PUBLIC):
"""Returns any address overrides that the user has defined based on the
endpoint type.
Note: this function allows for the service name to be inserted into the
address if the user specifies {service_name}.somehost.org.
:param endpoint_type: the type of endpoint to retrieve the override
value for.
:returns: any endpoint address or hostname that the user has overridden
or None if an override is not present.
"""
override_key = ADDRESS_MAP[endpoint_type]['override']
addr_override = config(override_key)
if not addr_override:
return None
else:
return addr_override.format(service_name=service_name())
|
[
"def",
"_get_address_override",
"(",
"endpoint_type",
"=",
"PUBLIC",
")",
":",
"override_key",
"=",
"ADDRESS_MAP",
"[",
"endpoint_type",
"]",
"[",
"'override'",
"]",
"addr_override",
"=",
"config",
"(",
"override_key",
")",
"if",
"not",
"addr_override",
":",
"return",
"None",
"else",
":",
"return",
"addr_override",
".",
"format",
"(",
"service_name",
"=",
"service_name",
"(",
")",
")"
] |
Returns any address overrides that the user has defined based on the
endpoint type.
Note: this function allows for the service name to be inserted into the
address if the user specifies {service_name}.somehost.org.
:param endpoint_type: the type of endpoint to retrieve the override
value for.
:returns: any endpoint address or hostname that the user has overridden
or None if an override is not present.
|
[
"Returns",
"any",
"address",
"overrides",
"that",
"the",
"user",
"has",
"defined",
"based",
"on",
"the",
"endpoint",
"type",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ip.py#L97-L114
|
12,589
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/ip.py
|
resolve_address
|
def resolve_address(endpoint_type=PUBLIC, override=True):
"""Return unit address depending on net config.
If unit is clustered with vip(s) and has net splits defined, return vip on
correct network. If clustered with no nets defined, return primary vip.
If not clustered, return unit address ensuring address is on configured net
split if one is configured, or a Juju 2.0 extra-binding has been used.
:param endpoint_type: Network endpoing type
:param override: Accept hostname overrides or not
"""
resolved_address = None
if override:
resolved_address = _get_address_override(endpoint_type)
if resolved_address:
return resolved_address
vips = config('vip')
if vips:
vips = vips.split()
net_type = ADDRESS_MAP[endpoint_type]['config']
net_addr = config(net_type)
net_fallback = ADDRESS_MAP[endpoint_type]['fallback']
binding = ADDRESS_MAP[endpoint_type]['binding']
clustered = is_clustered()
if clustered and vips:
if net_addr:
for vip in vips:
if is_address_in_network(net_addr, vip):
resolved_address = vip
break
else:
# NOTE: endeavour to check vips against network space
# bindings
try:
bound_cidr = resolve_network_cidr(
network_get_primary_address(binding)
)
for vip in vips:
if is_address_in_network(bound_cidr, vip):
resolved_address = vip
break
except (NotImplementedError, NoNetworkBinding):
# If no net-splits configured and no support for extra
# bindings/network spaces so we expect a single vip
resolved_address = vips[0]
else:
if config('prefer-ipv6'):
fallback_addr = get_ipv6_addr(exc_list=vips)[0]
else:
fallback_addr = unit_get(net_fallback)
if net_addr:
resolved_address = get_address_in_network(net_addr, fallback_addr)
else:
# NOTE: only try to use extra bindings if legacy network
# configuration is not in use
try:
resolved_address = network_get_primary_address(binding)
except (NotImplementedError, NoNetworkBinding):
resolved_address = fallback_addr
if resolved_address is None:
raise ValueError("Unable to resolve a suitable IP address based on "
"charm state and configuration. (net_type=%s, "
"clustered=%s)" % (net_type, clustered))
return resolved_address
|
python
|
def resolve_address(endpoint_type=PUBLIC, override=True):
"""Return unit address depending on net config.
If unit is clustered with vip(s) and has net splits defined, return vip on
correct network. If clustered with no nets defined, return primary vip.
If not clustered, return unit address ensuring address is on configured net
split if one is configured, or a Juju 2.0 extra-binding has been used.
:param endpoint_type: Network endpoing type
:param override: Accept hostname overrides or not
"""
resolved_address = None
if override:
resolved_address = _get_address_override(endpoint_type)
if resolved_address:
return resolved_address
vips = config('vip')
if vips:
vips = vips.split()
net_type = ADDRESS_MAP[endpoint_type]['config']
net_addr = config(net_type)
net_fallback = ADDRESS_MAP[endpoint_type]['fallback']
binding = ADDRESS_MAP[endpoint_type]['binding']
clustered = is_clustered()
if clustered and vips:
if net_addr:
for vip in vips:
if is_address_in_network(net_addr, vip):
resolved_address = vip
break
else:
# NOTE: endeavour to check vips against network space
# bindings
try:
bound_cidr = resolve_network_cidr(
network_get_primary_address(binding)
)
for vip in vips:
if is_address_in_network(bound_cidr, vip):
resolved_address = vip
break
except (NotImplementedError, NoNetworkBinding):
# If no net-splits configured and no support for extra
# bindings/network spaces so we expect a single vip
resolved_address = vips[0]
else:
if config('prefer-ipv6'):
fallback_addr = get_ipv6_addr(exc_list=vips)[0]
else:
fallback_addr = unit_get(net_fallback)
if net_addr:
resolved_address = get_address_in_network(net_addr, fallback_addr)
else:
# NOTE: only try to use extra bindings if legacy network
# configuration is not in use
try:
resolved_address = network_get_primary_address(binding)
except (NotImplementedError, NoNetworkBinding):
resolved_address = fallback_addr
if resolved_address is None:
raise ValueError("Unable to resolve a suitable IP address based on "
"charm state and configuration. (net_type=%s, "
"clustered=%s)" % (net_type, clustered))
return resolved_address
|
[
"def",
"resolve_address",
"(",
"endpoint_type",
"=",
"PUBLIC",
",",
"override",
"=",
"True",
")",
":",
"resolved_address",
"=",
"None",
"if",
"override",
":",
"resolved_address",
"=",
"_get_address_override",
"(",
"endpoint_type",
")",
"if",
"resolved_address",
":",
"return",
"resolved_address",
"vips",
"=",
"config",
"(",
"'vip'",
")",
"if",
"vips",
":",
"vips",
"=",
"vips",
".",
"split",
"(",
")",
"net_type",
"=",
"ADDRESS_MAP",
"[",
"endpoint_type",
"]",
"[",
"'config'",
"]",
"net_addr",
"=",
"config",
"(",
"net_type",
")",
"net_fallback",
"=",
"ADDRESS_MAP",
"[",
"endpoint_type",
"]",
"[",
"'fallback'",
"]",
"binding",
"=",
"ADDRESS_MAP",
"[",
"endpoint_type",
"]",
"[",
"'binding'",
"]",
"clustered",
"=",
"is_clustered",
"(",
")",
"if",
"clustered",
"and",
"vips",
":",
"if",
"net_addr",
":",
"for",
"vip",
"in",
"vips",
":",
"if",
"is_address_in_network",
"(",
"net_addr",
",",
"vip",
")",
":",
"resolved_address",
"=",
"vip",
"break",
"else",
":",
"# NOTE: endeavour to check vips against network space",
"# bindings",
"try",
":",
"bound_cidr",
"=",
"resolve_network_cidr",
"(",
"network_get_primary_address",
"(",
"binding",
")",
")",
"for",
"vip",
"in",
"vips",
":",
"if",
"is_address_in_network",
"(",
"bound_cidr",
",",
"vip",
")",
":",
"resolved_address",
"=",
"vip",
"break",
"except",
"(",
"NotImplementedError",
",",
"NoNetworkBinding",
")",
":",
"# If no net-splits configured and no support for extra",
"# bindings/network spaces so we expect a single vip",
"resolved_address",
"=",
"vips",
"[",
"0",
"]",
"else",
":",
"if",
"config",
"(",
"'prefer-ipv6'",
")",
":",
"fallback_addr",
"=",
"get_ipv6_addr",
"(",
"exc_list",
"=",
"vips",
")",
"[",
"0",
"]",
"else",
":",
"fallback_addr",
"=",
"unit_get",
"(",
"net_fallback",
")",
"if",
"net_addr",
":",
"resolved_address",
"=",
"get_address_in_network",
"(",
"net_addr",
",",
"fallback_addr",
")",
"else",
":",
"# NOTE: only try to use extra bindings if legacy network",
"# configuration is not in use",
"try",
":",
"resolved_address",
"=",
"network_get_primary_address",
"(",
"binding",
")",
"except",
"(",
"NotImplementedError",
",",
"NoNetworkBinding",
")",
":",
"resolved_address",
"=",
"fallback_addr",
"if",
"resolved_address",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Unable to resolve a suitable IP address based on \"",
"\"charm state and configuration. (net_type=%s, \"",
"\"clustered=%s)\"",
"%",
"(",
"net_type",
",",
"clustered",
")",
")",
"return",
"resolved_address"
] |
Return unit address depending on net config.
If unit is clustered with vip(s) and has net splits defined, return vip on
correct network. If clustered with no nets defined, return primary vip.
If not clustered, return unit address ensuring address is on configured net
split if one is configured, or a Juju 2.0 extra-binding has been used.
:param endpoint_type: Network endpoing type
:param override: Accept hostname overrides or not
|
[
"Return",
"unit",
"address",
"depending",
"on",
"net",
"config",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ip.py#L117-L187
|
12,590
|
juju/charm-helpers
|
charmhelpers/core/hugepage.py
|
hugepage_support
|
def hugepage_support(user, group='hugetlb', nr_hugepages=256,
max_map_count=65536, mnt_point='/run/hugepages/kvm',
pagesize='2MB', mount=True, set_shmmax=False):
"""Enable hugepages on system.
Args:
user (str) -- Username to allow access to hugepages to
group (str) -- Group name to own hugepages
nr_hugepages (int) -- Number of pages to reserve
max_map_count (int) -- Number of Virtual Memory Areas a process can own
mnt_point (str) -- Directory to mount hugepages on
pagesize (str) -- Size of hugepages
mount (bool) -- Whether to Mount hugepages
"""
group_info = add_group(group)
gid = group_info.gr_gid
add_user_to_group(user, group)
if max_map_count < 2 * nr_hugepages:
max_map_count = 2 * nr_hugepages
sysctl_settings = {
'vm.nr_hugepages': nr_hugepages,
'vm.max_map_count': max_map_count,
'vm.hugetlb_shm_group': gid,
}
if set_shmmax:
shmmax_current = int(check_output(['sysctl', '-n', 'kernel.shmmax']))
shmmax_minsize = bytes_from_string(pagesize) * nr_hugepages
if shmmax_minsize > shmmax_current:
sysctl_settings['kernel.shmmax'] = shmmax_minsize
sysctl.create(yaml.dump(sysctl_settings), '/etc/sysctl.d/10-hugepage.conf')
mkdir(mnt_point, owner='root', group='root', perms=0o755, force=False)
lfstab = fstab.Fstab()
fstab_entry = lfstab.get_entry_by_attr('mountpoint', mnt_point)
if fstab_entry:
lfstab.remove_entry(fstab_entry)
entry = lfstab.Entry('nodev', mnt_point, 'hugetlbfs',
'mode=1770,gid={},pagesize={}'.format(gid, pagesize), 0, 0)
lfstab.add_entry(entry)
if mount:
fstab_mount(mnt_point)
|
python
|
def hugepage_support(user, group='hugetlb', nr_hugepages=256,
max_map_count=65536, mnt_point='/run/hugepages/kvm',
pagesize='2MB', mount=True, set_shmmax=False):
"""Enable hugepages on system.
Args:
user (str) -- Username to allow access to hugepages to
group (str) -- Group name to own hugepages
nr_hugepages (int) -- Number of pages to reserve
max_map_count (int) -- Number of Virtual Memory Areas a process can own
mnt_point (str) -- Directory to mount hugepages on
pagesize (str) -- Size of hugepages
mount (bool) -- Whether to Mount hugepages
"""
group_info = add_group(group)
gid = group_info.gr_gid
add_user_to_group(user, group)
if max_map_count < 2 * nr_hugepages:
max_map_count = 2 * nr_hugepages
sysctl_settings = {
'vm.nr_hugepages': nr_hugepages,
'vm.max_map_count': max_map_count,
'vm.hugetlb_shm_group': gid,
}
if set_shmmax:
shmmax_current = int(check_output(['sysctl', '-n', 'kernel.shmmax']))
shmmax_minsize = bytes_from_string(pagesize) * nr_hugepages
if shmmax_minsize > shmmax_current:
sysctl_settings['kernel.shmmax'] = shmmax_minsize
sysctl.create(yaml.dump(sysctl_settings), '/etc/sysctl.d/10-hugepage.conf')
mkdir(mnt_point, owner='root', group='root', perms=0o755, force=False)
lfstab = fstab.Fstab()
fstab_entry = lfstab.get_entry_by_attr('mountpoint', mnt_point)
if fstab_entry:
lfstab.remove_entry(fstab_entry)
entry = lfstab.Entry('nodev', mnt_point, 'hugetlbfs',
'mode=1770,gid={},pagesize={}'.format(gid, pagesize), 0, 0)
lfstab.add_entry(entry)
if mount:
fstab_mount(mnt_point)
|
[
"def",
"hugepage_support",
"(",
"user",
",",
"group",
"=",
"'hugetlb'",
",",
"nr_hugepages",
"=",
"256",
",",
"max_map_count",
"=",
"65536",
",",
"mnt_point",
"=",
"'/run/hugepages/kvm'",
",",
"pagesize",
"=",
"'2MB'",
",",
"mount",
"=",
"True",
",",
"set_shmmax",
"=",
"False",
")",
":",
"group_info",
"=",
"add_group",
"(",
"group",
")",
"gid",
"=",
"group_info",
".",
"gr_gid",
"add_user_to_group",
"(",
"user",
",",
"group",
")",
"if",
"max_map_count",
"<",
"2",
"*",
"nr_hugepages",
":",
"max_map_count",
"=",
"2",
"*",
"nr_hugepages",
"sysctl_settings",
"=",
"{",
"'vm.nr_hugepages'",
":",
"nr_hugepages",
",",
"'vm.max_map_count'",
":",
"max_map_count",
",",
"'vm.hugetlb_shm_group'",
":",
"gid",
",",
"}",
"if",
"set_shmmax",
":",
"shmmax_current",
"=",
"int",
"(",
"check_output",
"(",
"[",
"'sysctl'",
",",
"'-n'",
",",
"'kernel.shmmax'",
"]",
")",
")",
"shmmax_minsize",
"=",
"bytes_from_string",
"(",
"pagesize",
")",
"*",
"nr_hugepages",
"if",
"shmmax_minsize",
">",
"shmmax_current",
":",
"sysctl_settings",
"[",
"'kernel.shmmax'",
"]",
"=",
"shmmax_minsize",
"sysctl",
".",
"create",
"(",
"yaml",
".",
"dump",
"(",
"sysctl_settings",
")",
",",
"'/etc/sysctl.d/10-hugepage.conf'",
")",
"mkdir",
"(",
"mnt_point",
",",
"owner",
"=",
"'root'",
",",
"group",
"=",
"'root'",
",",
"perms",
"=",
"0o755",
",",
"force",
"=",
"False",
")",
"lfstab",
"=",
"fstab",
".",
"Fstab",
"(",
")",
"fstab_entry",
"=",
"lfstab",
".",
"get_entry_by_attr",
"(",
"'mountpoint'",
",",
"mnt_point",
")",
"if",
"fstab_entry",
":",
"lfstab",
".",
"remove_entry",
"(",
"fstab_entry",
")",
"entry",
"=",
"lfstab",
".",
"Entry",
"(",
"'nodev'",
",",
"mnt_point",
",",
"'hugetlbfs'",
",",
"'mode=1770,gid={},pagesize={}'",
".",
"format",
"(",
"gid",
",",
"pagesize",
")",
",",
"0",
",",
"0",
")",
"lfstab",
".",
"add_entry",
"(",
"entry",
")",
"if",
"mount",
":",
"fstab_mount",
"(",
"mnt_point",
")"
] |
Enable hugepages on system.
Args:
user (str) -- Username to allow access to hugepages to
group (str) -- Group name to own hugepages
nr_hugepages (int) -- Number of pages to reserve
max_map_count (int) -- Number of Virtual Memory Areas a process can own
mnt_point (str) -- Directory to mount hugepages on
pagesize (str) -- Size of hugepages
mount (bool) -- Whether to Mount hugepages
|
[
"Enable",
"hugepages",
"on",
"system",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hugepage.py#L30-L69
|
12,591
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/audits/apache.py
|
DisabledModuleAudit.ensure_compliance
|
def ensure_compliance(self):
"""Ensures that the modules are not loaded."""
if not self.modules:
return
try:
loaded_modules = self._get_loaded_modules()
non_compliant_modules = []
for module in self.modules:
if module in loaded_modules:
log("Module '%s' is enabled but should not be." %
(module), level=INFO)
non_compliant_modules.append(module)
if len(non_compliant_modules) == 0:
return
for module in non_compliant_modules:
self._disable_module(module)
self._restart_apache()
except subprocess.CalledProcessError as e:
log('Error occurred auditing apache module compliance. '
'This may have been already reported. '
'Output is: %s' % e.output, level=ERROR)
|
python
|
def ensure_compliance(self):
"""Ensures that the modules are not loaded."""
if not self.modules:
return
try:
loaded_modules = self._get_loaded_modules()
non_compliant_modules = []
for module in self.modules:
if module in loaded_modules:
log("Module '%s' is enabled but should not be." %
(module), level=INFO)
non_compliant_modules.append(module)
if len(non_compliant_modules) == 0:
return
for module in non_compliant_modules:
self._disable_module(module)
self._restart_apache()
except subprocess.CalledProcessError as e:
log('Error occurred auditing apache module compliance. '
'This may have been already reported. '
'Output is: %s' % e.output, level=ERROR)
|
[
"def",
"ensure_compliance",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"modules",
":",
"return",
"try",
":",
"loaded_modules",
"=",
"self",
".",
"_get_loaded_modules",
"(",
")",
"non_compliant_modules",
"=",
"[",
"]",
"for",
"module",
"in",
"self",
".",
"modules",
":",
"if",
"module",
"in",
"loaded_modules",
":",
"log",
"(",
"\"Module '%s' is enabled but should not be.\"",
"%",
"(",
"module",
")",
",",
"level",
"=",
"INFO",
")",
"non_compliant_modules",
".",
"append",
"(",
"module",
")",
"if",
"len",
"(",
"non_compliant_modules",
")",
"==",
"0",
":",
"return",
"for",
"module",
"in",
"non_compliant_modules",
":",
"self",
".",
"_disable_module",
"(",
"module",
")",
"self",
".",
"_restart_apache",
"(",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"log",
"(",
"'Error occurred auditing apache module compliance. '",
"'This may have been already reported. '",
"'Output is: %s'",
"%",
"e",
".",
"output",
",",
"level",
"=",
"ERROR",
")"
] |
Ensures that the modules are not loaded.
|
[
"Ensures",
"that",
"the",
"modules",
"are",
"not",
"loaded",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/apache.py#L43-L66
|
12,592
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/audits/apache.py
|
DisabledModuleAudit._get_loaded_modules
|
def _get_loaded_modules():
"""Returns the modules which are enabled in Apache."""
output = subprocess.check_output(['apache2ctl', '-M'])
if six.PY3:
output = output.decode('utf-8')
modules = []
for line in output.splitlines():
# Each line of the enabled module output looks like:
# module_name (static|shared)
# Plus a header line at the top of the output which is stripped
# out by the regex.
matcher = re.search(r'^ (\S*)_module (\S*)', line)
if matcher:
modules.append(matcher.group(1))
return modules
|
python
|
def _get_loaded_modules():
"""Returns the modules which are enabled in Apache."""
output = subprocess.check_output(['apache2ctl', '-M'])
if six.PY3:
output = output.decode('utf-8')
modules = []
for line in output.splitlines():
# Each line of the enabled module output looks like:
# module_name (static|shared)
# Plus a header line at the top of the output which is stripped
# out by the regex.
matcher = re.search(r'^ (\S*)_module (\S*)', line)
if matcher:
modules.append(matcher.group(1))
return modules
|
[
"def",
"_get_loaded_modules",
"(",
")",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'apache2ctl'",
",",
"'-M'",
"]",
")",
"if",
"six",
".",
"PY3",
":",
"output",
"=",
"output",
".",
"decode",
"(",
"'utf-8'",
")",
"modules",
"=",
"[",
"]",
"for",
"line",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"# Each line of the enabled module output looks like:",
"# module_name (static|shared)",
"# Plus a header line at the top of the output which is stripped",
"# out by the regex.",
"matcher",
"=",
"re",
".",
"search",
"(",
"r'^ (\\S*)_module (\\S*)'",
",",
"line",
")",
"if",
"matcher",
":",
"modules",
".",
"append",
"(",
"matcher",
".",
"group",
"(",
"1",
")",
")",
"return",
"modules"
] |
Returns the modules which are enabled in Apache.
|
[
"Returns",
"the",
"modules",
"which",
"are",
"enabled",
"in",
"Apache",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/apache.py#L69-L83
|
12,593
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/audits/apache.py
|
DisabledModuleAudit._disable_module
|
def _disable_module(module):
"""Disables the specified module in Apache."""
try:
subprocess.check_call(['a2dismod', module])
except subprocess.CalledProcessError as e:
# Note: catch error here to allow the attempt of disabling
# multiple modules in one go rather than failing after the
# first module fails.
log('Error occurred disabling module %s. '
'Output is: %s' % (module, e.output), level=ERROR)
|
python
|
def _disable_module(module):
"""Disables the specified module in Apache."""
try:
subprocess.check_call(['a2dismod', module])
except subprocess.CalledProcessError as e:
# Note: catch error here to allow the attempt of disabling
# multiple modules in one go rather than failing after the
# first module fails.
log('Error occurred disabling module %s. '
'Output is: %s' % (module, e.output), level=ERROR)
|
[
"def",
"_disable_module",
"(",
"module",
")",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'a2dismod'",
",",
"module",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"# Note: catch error here to allow the attempt of disabling",
"# multiple modules in one go rather than failing after the",
"# first module fails.",
"log",
"(",
"'Error occurred disabling module %s. '",
"'Output is: %s'",
"%",
"(",
"module",
",",
"e",
".",
"output",
")",
",",
"level",
"=",
"ERROR",
")"
] |
Disables the specified module in Apache.
|
[
"Disables",
"the",
"specified",
"module",
"in",
"Apache",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/apache.py#L86-L95
|
12,594
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/templating.py
|
get_template_path
|
def get_template_path(template_dir, path):
"""Returns the template file which would be used to render the path.
The path to the template file is returned.
:param template_dir: the directory the templates are located in
:param path: the file path to be written to.
:returns: path to the template file
"""
return os.path.join(template_dir, os.path.basename(path))
|
python
|
def get_template_path(template_dir, path):
"""Returns the template file which would be used to render the path.
The path to the template file is returned.
:param template_dir: the directory the templates are located in
:param path: the file path to be written to.
:returns: path to the template file
"""
return os.path.join(template_dir, os.path.basename(path))
|
[
"def",
"get_template_path",
"(",
"template_dir",
",",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"template_dir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")"
] |
Returns the template file which would be used to render the path.
The path to the template file is returned.
:param template_dir: the directory the templates are located in
:param path: the file path to be written to.
:returns: path to the template file
|
[
"Returns",
"the",
"template",
"file",
"which",
"would",
"be",
"used",
"to",
"render",
"the",
"path",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/templating.py#L44-L52
|
12,595
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/templating.py
|
render_and_write
|
def render_and_write(template_dir, path, context):
"""Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
"""
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
rendered_content = template.render(context)
if not rendered_content:
log("Render returned None - skipping '%s'" % path,
level=WARNING)
return
write(path, rendered_content.encode('utf-8').strip())
log('Wrote template %s' % path, level=DEBUG)
|
python
|
def render_and_write(template_dir, path, context):
"""Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
"""
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
rendered_content = template.render(context)
if not rendered_content:
log("Render returned None - skipping '%s'" % path,
level=WARNING)
return
write(path, rendered_content.encode('utf-8').strip())
log('Wrote template %s' % path, level=DEBUG)
|
[
"def",
"render_and_write",
"(",
"template_dir",
",",
"path",
",",
"context",
")",
":",
"env",
"=",
"Environment",
"(",
"loader",
"=",
"FileSystemLoader",
"(",
"template_dir",
")",
")",
"template_file",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"template",
"=",
"env",
".",
"get_template",
"(",
"template_file",
")",
"log",
"(",
"'Rendering from template: %s'",
"%",
"template",
".",
"name",
",",
"level",
"=",
"DEBUG",
")",
"rendered_content",
"=",
"template",
".",
"render",
"(",
"context",
")",
"if",
"not",
"rendered_content",
":",
"log",
"(",
"\"Render returned None - skipping '%s'\"",
"%",
"path",
",",
"level",
"=",
"WARNING",
")",
"return",
"write",
"(",
"path",
",",
"rendered_content",
".",
"encode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")",
")",
"log",
"(",
"'Wrote template %s'",
"%",
"path",
",",
"level",
"=",
"DEBUG",
")"
] |
Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
|
[
"Renders",
"the",
"specified",
"template",
"into",
"the",
"file",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/templating.py#L55-L73
|
12,596
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/host/checks/apt.py
|
get_audits
|
def get_audits():
"""Get OS hardening apt audits.
:returns: dictionary of audits
"""
audits = [AptConfig([{'key': 'APT::Get::AllowUnauthenticated',
'expected': 'false'}])]
settings = get_settings('os')
clean_packages = settings['security']['packages_clean']
if clean_packages:
security_packages = settings['security']['packages_list']
if security_packages:
audits.append(RestrictedPackages(security_packages))
return audits
|
python
|
def get_audits():
"""Get OS hardening apt audits.
:returns: dictionary of audits
"""
audits = [AptConfig([{'key': 'APT::Get::AllowUnauthenticated',
'expected': 'false'}])]
settings = get_settings('os')
clean_packages = settings['security']['packages_clean']
if clean_packages:
security_packages = settings['security']['packages_list']
if security_packages:
audits.append(RestrictedPackages(security_packages))
return audits
|
[
"def",
"get_audits",
"(",
")",
":",
"audits",
"=",
"[",
"AptConfig",
"(",
"[",
"{",
"'key'",
":",
"'APT::Get::AllowUnauthenticated'",
",",
"'expected'",
":",
"'false'",
"}",
"]",
")",
"]",
"settings",
"=",
"get_settings",
"(",
"'os'",
")",
"clean_packages",
"=",
"settings",
"[",
"'security'",
"]",
"[",
"'packages_clean'",
"]",
"if",
"clean_packages",
":",
"security_packages",
"=",
"settings",
"[",
"'security'",
"]",
"[",
"'packages_list'",
"]",
"if",
"security_packages",
":",
"audits",
".",
"append",
"(",
"RestrictedPackages",
"(",
"security_packages",
")",
")",
"return",
"audits"
] |
Get OS hardening apt audits.
:returns: dictionary of audits
|
[
"Get",
"OS",
"hardening",
"apt",
"audits",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/apt.py#L22-L37
|
12,597
|
juju/charm-helpers
|
charmhelpers/contrib/hardening/host/checks/pam.py
|
get_audits
|
def get_audits():
"""Get OS hardening PAM authentication audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
if settings['auth']['pam_passwdqc_enable']:
audits.append(PasswdqcPAM('/etc/passwdqc.conf'))
if settings['auth']['retries']:
audits.append(Tally2PAM('/usr/share/pam-configs/tally2'))
else:
audits.append(DeletedFile('/usr/share/pam-configs/tally2'))
return audits
|
python
|
def get_audits():
"""Get OS hardening PAM authentication audits.
:returns: dictionary of audits
"""
audits = []
settings = utils.get_settings('os')
if settings['auth']['pam_passwdqc_enable']:
audits.append(PasswdqcPAM('/etc/passwdqc.conf'))
if settings['auth']['retries']:
audits.append(Tally2PAM('/usr/share/pam-configs/tally2'))
else:
audits.append(DeletedFile('/usr/share/pam-configs/tally2'))
return audits
|
[
"def",
"get_audits",
"(",
")",
":",
"audits",
"=",
"[",
"]",
"settings",
"=",
"utils",
".",
"get_settings",
"(",
"'os'",
")",
"if",
"settings",
"[",
"'auth'",
"]",
"[",
"'pam_passwdqc_enable'",
"]",
":",
"audits",
".",
"append",
"(",
"PasswdqcPAM",
"(",
"'/etc/passwdqc.conf'",
")",
")",
"if",
"settings",
"[",
"'auth'",
"]",
"[",
"'retries'",
"]",
":",
"audits",
".",
"append",
"(",
"Tally2PAM",
"(",
"'/usr/share/pam-configs/tally2'",
")",
")",
"else",
":",
"audits",
".",
"append",
"(",
"DeletedFile",
"(",
"'/usr/share/pam-configs/tally2'",
")",
")",
"return",
"audits"
] |
Get OS hardening PAM authentication audits.
:returns: dictionary of audits
|
[
"Get",
"OS",
"hardening",
"PAM",
"authentication",
"audits",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/pam.py#L38-L55
|
12,598
|
juju/charm-helpers
|
charmhelpers/contrib/ansible/__init__.py
|
install_ansible_support
|
def install_ansible_support(from_ppa=True, ppa_location='ppa:rquillo/ansible'):
"""Installs the ansible package.
By default it is installed from the `PPA`_ linked from
the ansible `website`_ or from a ppa specified by a charm config..
.. _PPA: https://launchpad.net/~rquillo/+archive/ansible
.. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu
If from_ppa is empty, you must ensure that the package is available
from a configured repository.
"""
if from_ppa:
charmhelpers.fetch.add_source(ppa_location)
charmhelpers.fetch.apt_update(fatal=True)
charmhelpers.fetch.apt_install('ansible')
with open(ansible_hosts_path, 'w+') as hosts_file:
hosts_file.write('localhost ansible_connection=local ansible_remote_tmp=/root/.ansible/tmp')
|
python
|
def install_ansible_support(from_ppa=True, ppa_location='ppa:rquillo/ansible'):
"""Installs the ansible package.
By default it is installed from the `PPA`_ linked from
the ansible `website`_ or from a ppa specified by a charm config..
.. _PPA: https://launchpad.net/~rquillo/+archive/ansible
.. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu
If from_ppa is empty, you must ensure that the package is available
from a configured repository.
"""
if from_ppa:
charmhelpers.fetch.add_source(ppa_location)
charmhelpers.fetch.apt_update(fatal=True)
charmhelpers.fetch.apt_install('ansible')
with open(ansible_hosts_path, 'w+') as hosts_file:
hosts_file.write('localhost ansible_connection=local ansible_remote_tmp=/root/.ansible/tmp')
|
[
"def",
"install_ansible_support",
"(",
"from_ppa",
"=",
"True",
",",
"ppa_location",
"=",
"'ppa:rquillo/ansible'",
")",
":",
"if",
"from_ppa",
":",
"charmhelpers",
".",
"fetch",
".",
"add_source",
"(",
"ppa_location",
")",
"charmhelpers",
".",
"fetch",
".",
"apt_update",
"(",
"fatal",
"=",
"True",
")",
"charmhelpers",
".",
"fetch",
".",
"apt_install",
"(",
"'ansible'",
")",
"with",
"open",
"(",
"ansible_hosts_path",
",",
"'w+'",
")",
"as",
"hosts_file",
":",
"hosts_file",
".",
"write",
"(",
"'localhost ansible_connection=local ansible_remote_tmp=/root/.ansible/tmp'",
")"
] |
Installs the ansible package.
By default it is installed from the `PPA`_ linked from
the ansible `website`_ or from a ppa specified by a charm config..
.. _PPA: https://launchpad.net/~rquillo/+archive/ansible
.. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-apt-ubuntu
If from_ppa is empty, you must ensure that the package is available
from a configured repository.
|
[
"Installs",
"the",
"ansible",
"package",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ansible/__init__.py#L120-L137
|
12,599
|
juju/charm-helpers
|
charmhelpers/contrib/ansible/__init__.py
|
AnsibleHooks.execute
|
def execute(self, args):
"""Execute the hook followed by the playbook using the hook as tag."""
hook_name = os.path.basename(args[0])
extra_vars = None
if hook_name in self._actions:
extra_vars = self._actions[hook_name](args[1:])
else:
super(AnsibleHooks, self).execute(args)
charmhelpers.contrib.ansible.apply_playbook(
self.playbook_path, tags=[hook_name], extra_vars=extra_vars)
|
python
|
def execute(self, args):
"""Execute the hook followed by the playbook using the hook as tag."""
hook_name = os.path.basename(args[0])
extra_vars = None
if hook_name in self._actions:
extra_vars = self._actions[hook_name](args[1:])
else:
super(AnsibleHooks, self).execute(args)
charmhelpers.contrib.ansible.apply_playbook(
self.playbook_path, tags=[hook_name], extra_vars=extra_vars)
|
[
"def",
"execute",
"(",
"self",
",",
"args",
")",
":",
"hook_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"args",
"[",
"0",
"]",
")",
"extra_vars",
"=",
"None",
"if",
"hook_name",
"in",
"self",
".",
"_actions",
":",
"extra_vars",
"=",
"self",
".",
"_actions",
"[",
"hook_name",
"]",
"(",
"args",
"[",
"1",
":",
"]",
")",
"else",
":",
"super",
"(",
"AnsibleHooks",
",",
"self",
")",
".",
"execute",
"(",
"args",
")",
"charmhelpers",
".",
"contrib",
".",
"ansible",
".",
"apply_playbook",
"(",
"self",
".",
"playbook_path",
",",
"tags",
"=",
"[",
"hook_name",
"]",
",",
"extra_vars",
"=",
"extra_vars",
")"
] |
Execute the hook followed by the playbook using the hook as tag.
|
[
"Execute",
"the",
"hook",
"followed",
"by",
"the",
"playbook",
"using",
"the",
"hook",
"as",
"tag",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ansible/__init__.py#L219-L229
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.