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,800
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
_check_listening_on_ports_list
def _check_listening_on_ports_list(ports): """Check that the ports list given are being listened to Returns a list of ports being listened to and a list of the booleans. @param ports: LIST or port numbers. @returns [(port_num, boolean), ...], [boolean] """ ports_open = [port_has_listener('0.0.0.0', p) for p in ports] return zip(ports, ports_open), ports_open
python
def _check_listening_on_ports_list(ports): """Check that the ports list given are being listened to Returns a list of ports being listened to and a list of the booleans. @param ports: LIST or port numbers. @returns [(port_num, boolean), ...], [boolean] """ ports_open = [port_has_listener('0.0.0.0', p) for p in ports] return zip(ports, ports_open), ports_open
[ "def", "_check_listening_on_ports_list", "(", "ports", ")", ":", "ports_open", "=", "[", "port_has_listener", "(", "'0.0.0.0'", ",", "p", ")", "for", "p", "in", "ports", "]", "return", "zip", "(", "ports", ",", "ports_open", ")", ",", "ports_open" ]
Check that the ports list given are being listened to Returns a list of ports being listened to and a list of the booleans. @param ports: LIST or port numbers. @returns [(port_num, boolean), ...], [boolean]
[ "Check", "that", "the", "ports", "list", "given", "are", "being", "listened", "to" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1118-L1128
12,801
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
workload_state_compare
def workload_state_compare(current_workload_state, workload_state): """ Return highest priority of two states""" hierarchy = {'unknown': -1, 'active': 0, 'maintenance': 1, 'waiting': 2, 'blocked': 3, } if hierarchy.get(workload_state) is None: workload_state = 'unknown' if hierarchy.get(current_workload_state) is None: current_workload_state = 'unknown' # Set workload_state based on hierarchy of statuses if hierarchy.get(current_workload_state) > hierarchy.get(workload_state): return current_workload_state else: return workload_state
python
def workload_state_compare(current_workload_state, workload_state): """ Return highest priority of two states""" hierarchy = {'unknown': -1, 'active': 0, 'maintenance': 1, 'waiting': 2, 'blocked': 3, } if hierarchy.get(workload_state) is None: workload_state = 'unknown' if hierarchy.get(current_workload_state) is None: current_workload_state = 'unknown' # Set workload_state based on hierarchy of statuses if hierarchy.get(current_workload_state) > hierarchy.get(workload_state): return current_workload_state else: return workload_state
[ "def", "workload_state_compare", "(", "current_workload_state", ",", "workload_state", ")", ":", "hierarchy", "=", "{", "'unknown'", ":", "-", "1", ",", "'active'", ":", "0", ",", "'maintenance'", ":", "1", ",", "'waiting'", ":", "2", ",", "'blocked'", ":", "3", ",", "}", "if", "hierarchy", ".", "get", "(", "workload_state", ")", "is", "None", ":", "workload_state", "=", "'unknown'", "if", "hierarchy", ".", "get", "(", "current_workload_state", ")", "is", "None", ":", "current_workload_state", "=", "'unknown'", "# Set workload_state based on hierarchy of statuses", "if", "hierarchy", ".", "get", "(", "current_workload_state", ")", ">", "hierarchy", ".", "get", "(", "workload_state", ")", ":", "return", "current_workload_state", "else", ":", "return", "workload_state" ]
Return highest priority of two states
[ "Return", "highest", "priority", "of", "two", "states" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1142-L1160
12,802
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
incomplete_relation_data
def incomplete_relation_data(configs, required_interfaces): """Check complete contexts against required_interfaces Return dictionary of incomplete relation data. configs is an OSConfigRenderer object with configs registered required_interfaces is a dictionary of required general interfaces with dictionary values of possible specific interfaces. Example: required_interfaces = {'database': ['shared-db', 'pgsql-db']} The interface is said to be satisfied if anyone of the interfaces in the list has a complete context. Return dictionary of incomplete or missing required contexts with relation status of interfaces and any missing data points. Example: {'message': {'amqp': {'missing_data': ['rabbitmq_password'], 'related': True}, 'zeromq-configuration': {'related': False}}, 'identity': {'identity-service': {'related': False}}, 'database': {'pgsql-db': {'related': False}, 'shared-db': {'related': True}}} """ complete_ctxts = configs.complete_contexts() incomplete_relations = [ svc_type for svc_type, interfaces in required_interfaces.items() if not set(interfaces).intersection(complete_ctxts)] return { i: configs.get_incomplete_context_data(required_interfaces[i]) for i in incomplete_relations}
python
def incomplete_relation_data(configs, required_interfaces): """Check complete contexts against required_interfaces Return dictionary of incomplete relation data. configs is an OSConfigRenderer object with configs registered required_interfaces is a dictionary of required general interfaces with dictionary values of possible specific interfaces. Example: required_interfaces = {'database': ['shared-db', 'pgsql-db']} The interface is said to be satisfied if anyone of the interfaces in the list has a complete context. Return dictionary of incomplete or missing required contexts with relation status of interfaces and any missing data points. Example: {'message': {'amqp': {'missing_data': ['rabbitmq_password'], 'related': True}, 'zeromq-configuration': {'related': False}}, 'identity': {'identity-service': {'related': False}}, 'database': {'pgsql-db': {'related': False}, 'shared-db': {'related': True}}} """ complete_ctxts = configs.complete_contexts() incomplete_relations = [ svc_type for svc_type, interfaces in required_interfaces.items() if not set(interfaces).intersection(complete_ctxts)] return { i: configs.get_incomplete_context_data(required_interfaces[i]) for i in incomplete_relations}
[ "def", "incomplete_relation_data", "(", "configs", ",", "required_interfaces", ")", ":", "complete_ctxts", "=", "configs", ".", "complete_contexts", "(", ")", "incomplete_relations", "=", "[", "svc_type", "for", "svc_type", ",", "interfaces", "in", "required_interfaces", ".", "items", "(", ")", "if", "not", "set", "(", "interfaces", ")", ".", "intersection", "(", "complete_ctxts", ")", "]", "return", "{", "i", ":", "configs", ".", "get_incomplete_context_data", "(", "required_interfaces", "[", "i", "]", ")", "for", "i", "in", "incomplete_relations", "}" ]
Check complete contexts against required_interfaces Return dictionary of incomplete relation data. configs is an OSConfigRenderer object with configs registered required_interfaces is a dictionary of required general interfaces with dictionary values of possible specific interfaces. Example: required_interfaces = {'database': ['shared-db', 'pgsql-db']} The interface is said to be satisfied if anyone of the interfaces in the list has a complete context. Return dictionary of incomplete or missing required contexts with relation status of interfaces and any missing data points. Example: {'message': {'amqp': {'missing_data': ['rabbitmq_password'], 'related': True}, 'zeromq-configuration': {'related': False}}, 'identity': {'identity-service': {'related': False}}, 'database': {'pgsql-db': {'related': False}, 'shared-db': {'related': True}}}
[ "Check", "complete", "contexts", "against", "required_interfaces", "Return", "dictionary", "of", "incomplete", "relation", "data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1163-L1195
12,803
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
do_action_openstack_upgrade
def do_action_openstack_upgrade(package, upgrade_callback, configs): """Perform action-managed OpenStack upgrade. Upgrades packages to the configured openstack-origin version and sets the corresponding action status as a result. If the charm was installed from source we cannot upgrade it. For backwards compatibility a config flag (action-managed-upgrade) must be set for this code to run, otherwise a full service level upgrade will fire on config-changed. @param package: package name for determining if upgrade available @param upgrade_callback: function callback to charm's upgrade function @param configs: templating object derived from OSConfigRenderer class @return: True if upgrade successful; False if upgrade failed or skipped """ ret = False if openstack_upgrade_available(package): if config('action-managed-upgrade'): juju_log('Upgrading OpenStack release') try: upgrade_callback(configs=configs) action_set({'outcome': 'success, upgrade completed.'}) ret = True except Exception: action_set({'outcome': 'upgrade failed, see traceback.'}) action_set({'traceback': traceback.format_exc()}) action_fail('do_openstack_upgrade resulted in an ' 'unexpected error') else: action_set({'outcome': 'action-managed-upgrade config is ' 'False, skipped upgrade.'}) else: action_set({'outcome': 'no upgrade available.'}) return ret
python
def do_action_openstack_upgrade(package, upgrade_callback, configs): """Perform action-managed OpenStack upgrade. Upgrades packages to the configured openstack-origin version and sets the corresponding action status as a result. If the charm was installed from source we cannot upgrade it. For backwards compatibility a config flag (action-managed-upgrade) must be set for this code to run, otherwise a full service level upgrade will fire on config-changed. @param package: package name for determining if upgrade available @param upgrade_callback: function callback to charm's upgrade function @param configs: templating object derived from OSConfigRenderer class @return: True if upgrade successful; False if upgrade failed or skipped """ ret = False if openstack_upgrade_available(package): if config('action-managed-upgrade'): juju_log('Upgrading OpenStack release') try: upgrade_callback(configs=configs) action_set({'outcome': 'success, upgrade completed.'}) ret = True except Exception: action_set({'outcome': 'upgrade failed, see traceback.'}) action_set({'traceback': traceback.format_exc()}) action_fail('do_openstack_upgrade resulted in an ' 'unexpected error') else: action_set({'outcome': 'action-managed-upgrade config is ' 'False, skipped upgrade.'}) else: action_set({'outcome': 'no upgrade available.'}) return ret
[ "def", "do_action_openstack_upgrade", "(", "package", ",", "upgrade_callback", ",", "configs", ")", ":", "ret", "=", "False", "if", "openstack_upgrade_available", "(", "package", ")", ":", "if", "config", "(", "'action-managed-upgrade'", ")", ":", "juju_log", "(", "'Upgrading OpenStack release'", ")", "try", ":", "upgrade_callback", "(", "configs", "=", "configs", ")", "action_set", "(", "{", "'outcome'", ":", "'success, upgrade completed.'", "}", ")", "ret", "=", "True", "except", "Exception", ":", "action_set", "(", "{", "'outcome'", ":", "'upgrade failed, see traceback.'", "}", ")", "action_set", "(", "{", "'traceback'", ":", "traceback", ".", "format_exc", "(", ")", "}", ")", "action_fail", "(", "'do_openstack_upgrade resulted in an '", "'unexpected error'", ")", "else", ":", "action_set", "(", "{", "'outcome'", ":", "'action-managed-upgrade config is '", "'False, skipped upgrade.'", "}", ")", "else", ":", "action_set", "(", "{", "'outcome'", ":", "'no upgrade available.'", "}", ")", "return", "ret" ]
Perform action-managed OpenStack upgrade. Upgrades packages to the configured openstack-origin version and sets the corresponding action status as a result. If the charm was installed from source we cannot upgrade it. For backwards compatibility a config flag (action-managed-upgrade) must be set for this code to run, otherwise a full service level upgrade will fire on config-changed. @param package: package name for determining if upgrade available @param upgrade_callback: function callback to charm's upgrade function @param configs: templating object derived from OSConfigRenderer class @return: True if upgrade successful; False if upgrade failed or skipped
[ "Perform", "action", "-", "managed", "OpenStack", "upgrade", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1198-L1236
12,804
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
manage_payload_services
def manage_payload_services(action, services=None, charm_func=None): """Run an action against all services. An optional charm_func() can be called. It should raise an Exception to indicate that the function failed. If it was succesfull it should return None or an optional message. The signature for charm_func is: charm_func() -> message: str charm_func() is executed after any services are stopped, if supplied. The services object can either be: - None : no services were passed (an empty dict is returned) - a list of strings - A dictionary (optionally OrderedDict) {service_name: {'service': ..}} - An array of [{'service': service_name, ...}, ...] :param action: Action to run: pause, resume, start or stop. :type action: str :param services: See above :type services: See above :param charm_func: function to run for custom charm pausing. :type charm_func: f() :returns: Status boolean and list of messages :rtype: (bool, []) :raises: RuntimeError """ actions = { 'pause': service_pause, 'resume': service_resume, 'start': service_start, 'stop': service_stop} action = action.lower() if action not in actions.keys(): raise RuntimeError( "action: {} must be one of: {}".format(action, ', '.join(actions.keys()))) services = _extract_services_list_helper(services) messages = [] success = True if services: for service in services.keys(): rc = actions[action](service) if not rc: success = False messages.append("{} didn't {} cleanly.".format(service, action)) if charm_func: try: message = charm_func() if message: messages.append(message) except Exception as e: success = False messages.append(str(e)) return success, messages
python
def manage_payload_services(action, services=None, charm_func=None): """Run an action against all services. An optional charm_func() can be called. It should raise an Exception to indicate that the function failed. If it was succesfull it should return None or an optional message. The signature for charm_func is: charm_func() -> message: str charm_func() is executed after any services are stopped, if supplied. The services object can either be: - None : no services were passed (an empty dict is returned) - a list of strings - A dictionary (optionally OrderedDict) {service_name: {'service': ..}} - An array of [{'service': service_name, ...}, ...] :param action: Action to run: pause, resume, start or stop. :type action: str :param services: See above :type services: See above :param charm_func: function to run for custom charm pausing. :type charm_func: f() :returns: Status boolean and list of messages :rtype: (bool, []) :raises: RuntimeError """ actions = { 'pause': service_pause, 'resume': service_resume, 'start': service_start, 'stop': service_stop} action = action.lower() if action not in actions.keys(): raise RuntimeError( "action: {} must be one of: {}".format(action, ', '.join(actions.keys()))) services = _extract_services_list_helper(services) messages = [] success = True if services: for service in services.keys(): rc = actions[action](service) if not rc: success = False messages.append("{} didn't {} cleanly.".format(service, action)) if charm_func: try: message = charm_func() if message: messages.append(message) except Exception as e: success = False messages.append(str(e)) return success, messages
[ "def", "manage_payload_services", "(", "action", ",", "services", "=", "None", ",", "charm_func", "=", "None", ")", ":", "actions", "=", "{", "'pause'", ":", "service_pause", ",", "'resume'", ":", "service_resume", ",", "'start'", ":", "service_start", ",", "'stop'", ":", "service_stop", "}", "action", "=", "action", ".", "lower", "(", ")", "if", "action", "not", "in", "actions", ".", "keys", "(", ")", ":", "raise", "RuntimeError", "(", "\"action: {} must be one of: {}\"", ".", "format", "(", "action", ",", "', '", ".", "join", "(", "actions", ".", "keys", "(", ")", ")", ")", ")", "services", "=", "_extract_services_list_helper", "(", "services", ")", "messages", "=", "[", "]", "success", "=", "True", "if", "services", ":", "for", "service", "in", "services", ".", "keys", "(", ")", ":", "rc", "=", "actions", "[", "action", "]", "(", "service", ")", "if", "not", "rc", ":", "success", "=", "False", "messages", ".", "append", "(", "\"{} didn't {} cleanly.\"", ".", "format", "(", "service", ",", "action", ")", ")", "if", "charm_func", ":", "try", ":", "message", "=", "charm_func", "(", ")", "if", "message", ":", "messages", ".", "append", "(", "message", ")", "except", "Exception", "as", "e", ":", "success", "=", "False", "messages", ".", "append", "(", "str", "(", "e", ")", ")", "return", "success", ",", "messages" ]
Run an action against all services. An optional charm_func() can be called. It should raise an Exception to indicate that the function failed. If it was succesfull it should return None or an optional message. The signature for charm_func is: charm_func() -> message: str charm_func() is executed after any services are stopped, if supplied. The services object can either be: - None : no services were passed (an empty dict is returned) - a list of strings - A dictionary (optionally OrderedDict) {service_name: {'service': ..}} - An array of [{'service': service_name, ...}, ...] :param action: Action to run: pause, resume, start or stop. :type action: str :param services: See above :type services: See above :param charm_func: function to run for custom charm pausing. :type charm_func: f() :returns: Status boolean and list of messages :rtype: (bool, []) :raises: RuntimeError
[ "Run", "an", "action", "against", "all", "services", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1334-L1390
12,805
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
pausable_restart_on_change
def pausable_restart_on_change(restart_map, stopstart=False, restart_functions=None): """A restart_on_change decorator that checks to see if the unit is paused. If it is paused then the decorated function doesn't fire. This is provided as a helper, as the @restart_on_change(...) decorator is in core.host, yet the openstack specific helpers are in this file (contrib.openstack.utils). Thus, this needs to be an optional feature for openstack charms (or charms that wish to use the openstack pause/resume type features). It is used as follows: from contrib.openstack.utils import ( pausable_restart_on_change as restart_on_change) @restart_on_change(restart_map, stopstart=<boolean>) def some_hook(...): pass see core.utils.restart_on_change() for more details. Note restart_map can be a callable, in which case, restart_map is only evaluated at runtime. This means that it is lazy and the underlying function won't be called if the decorated function is never called. Note, retains backwards compatibility for passing a non-callable dictionary. @param f: the function to decorate @param restart_map: (optionally callable, which then returns the restart_map) the restart map {conf_file: [services]} @param stopstart: DEFAULT false; whether to stop, start or just restart @returns decorator to use a restart_on_change with pausability """ def wrap(f): # py27 compatible nonlocal variable. When py3 only, replace with # nonlocal keyword __restart_map_cache = {'cache': None} @functools.wraps(f) def wrapped_f(*args, **kwargs): if is_unit_paused_set(): return f(*args, **kwargs) if __restart_map_cache['cache'] is None: __restart_map_cache['cache'] = restart_map() \ if callable(restart_map) else restart_map # otherwise, normal restart_on_change functionality return restart_on_change_helper( (lambda: f(*args, **kwargs)), __restart_map_cache['cache'], stopstart, restart_functions) return wrapped_f return wrap
python
def pausable_restart_on_change(restart_map, stopstart=False, restart_functions=None): """A restart_on_change decorator that checks to see if the unit is paused. If it is paused then the decorated function doesn't fire. This is provided as a helper, as the @restart_on_change(...) decorator is in core.host, yet the openstack specific helpers are in this file (contrib.openstack.utils). Thus, this needs to be an optional feature for openstack charms (or charms that wish to use the openstack pause/resume type features). It is used as follows: from contrib.openstack.utils import ( pausable_restart_on_change as restart_on_change) @restart_on_change(restart_map, stopstart=<boolean>) def some_hook(...): pass see core.utils.restart_on_change() for more details. Note restart_map can be a callable, in which case, restart_map is only evaluated at runtime. This means that it is lazy and the underlying function won't be called if the decorated function is never called. Note, retains backwards compatibility for passing a non-callable dictionary. @param f: the function to decorate @param restart_map: (optionally callable, which then returns the restart_map) the restart map {conf_file: [services]} @param stopstart: DEFAULT false; whether to stop, start or just restart @returns decorator to use a restart_on_change with pausability """ def wrap(f): # py27 compatible nonlocal variable. When py3 only, replace with # nonlocal keyword __restart_map_cache = {'cache': None} @functools.wraps(f) def wrapped_f(*args, **kwargs): if is_unit_paused_set(): return f(*args, **kwargs) if __restart_map_cache['cache'] is None: __restart_map_cache['cache'] = restart_map() \ if callable(restart_map) else restart_map # otherwise, normal restart_on_change functionality return restart_on_change_helper( (lambda: f(*args, **kwargs)), __restart_map_cache['cache'], stopstart, restart_functions) return wrapped_f return wrap
[ "def", "pausable_restart_on_change", "(", "restart_map", ",", "stopstart", "=", "False", ",", "restart_functions", "=", "None", ")", ":", "def", "wrap", "(", "f", ")", ":", "# py27 compatible nonlocal variable. When py3 only, replace with", "# nonlocal keyword", "__restart_map_cache", "=", "{", "'cache'", ":", "None", "}", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapped_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "is_unit_paused_set", "(", ")", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "__restart_map_cache", "[", "'cache'", "]", "is", "None", ":", "__restart_map_cache", "[", "'cache'", "]", "=", "restart_map", "(", ")", "if", "callable", "(", "restart_map", ")", "else", "restart_map", "# otherwise, normal restart_on_change functionality", "return", "restart_on_change_helper", "(", "(", "lambda", ":", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", ",", "__restart_map_cache", "[", "'cache'", "]", ",", "stopstart", ",", "restart_functions", ")", "return", "wrapped_f", "return", "wrap" ]
A restart_on_change decorator that checks to see if the unit is paused. If it is paused then the decorated function doesn't fire. This is provided as a helper, as the @restart_on_change(...) decorator is in core.host, yet the openstack specific helpers are in this file (contrib.openstack.utils). Thus, this needs to be an optional feature for openstack charms (or charms that wish to use the openstack pause/resume type features). It is used as follows: from contrib.openstack.utils import ( pausable_restart_on_change as restart_on_change) @restart_on_change(restart_map, stopstart=<boolean>) def some_hook(...): pass see core.utils.restart_on_change() for more details. Note restart_map can be a callable, in which case, restart_map is only evaluated at runtime. This means that it is lazy and the underlying function won't be called if the decorated function is never called. Note, retains backwards compatibility for passing a non-callable dictionary. @param f: the function to decorate @param restart_map: (optionally callable, which then returns the restart_map) the restart map {conf_file: [services]} @param stopstart: DEFAULT false; whether to stop, start or just restart @returns decorator to use a restart_on_change with pausability
[ "A", "restart_on_change", "decorator", "that", "checks", "to", "see", "if", "the", "unit", "is", "paused", ".", "If", "it", "is", "paused", "then", "the", "decorated", "function", "doesn", "t", "fire", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1498-L1548
12,806
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
ordered
def ordered(orderme): """Converts the provided dictionary into a collections.OrderedDict. The items in the returned OrderedDict will be inserted based on the natural sort order of the keys. Nested dictionaries will also be sorted in order to ensure fully predictable ordering. :param orderme: the dict to order :return: collections.OrderedDict :raises: ValueError: if `orderme` isn't a dict instance. """ if not isinstance(orderme, dict): raise ValueError('argument must be a dict type') result = OrderedDict() for k, v in sorted(six.iteritems(orderme), key=lambda x: x[0]): if isinstance(v, dict): result[k] = ordered(v) else: result[k] = v return result
python
def ordered(orderme): """Converts the provided dictionary into a collections.OrderedDict. The items in the returned OrderedDict will be inserted based on the natural sort order of the keys. Nested dictionaries will also be sorted in order to ensure fully predictable ordering. :param orderme: the dict to order :return: collections.OrderedDict :raises: ValueError: if `orderme` isn't a dict instance. """ if not isinstance(orderme, dict): raise ValueError('argument must be a dict type') result = OrderedDict() for k, v in sorted(six.iteritems(orderme), key=lambda x: x[0]): if isinstance(v, dict): result[k] = ordered(v) else: result[k] = v return result
[ "def", "ordered", "(", "orderme", ")", ":", "if", "not", "isinstance", "(", "orderme", ",", "dict", ")", ":", "raise", "ValueError", "(", "'argument must be a dict type'", ")", "result", "=", "OrderedDict", "(", ")", "for", "k", ",", "v", "in", "sorted", "(", "six", ".", "iteritems", "(", "orderme", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "result", "[", "k", "]", "=", "ordered", "(", "v", ")", "else", ":", "result", "[", "k", "]", "=", "v", "return", "result" ]
Converts the provided dictionary into a collections.OrderedDict. The items in the returned OrderedDict will be inserted based on the natural sort order of the keys. Nested dictionaries will also be sorted in order to ensure fully predictable ordering. :param orderme: the dict to order :return: collections.OrderedDict :raises: ValueError: if `orderme` isn't a dict instance.
[ "Converts", "the", "provided", "dictionary", "into", "a", "collections", ".", "OrderedDict", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1551-L1572
12,807
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
config_flags_parser
def config_flags_parser(config_flags): """Parses config flags string into dict. This parsing method supports a few different formats for the config flag values to be parsed: 1. A string in the simple format of key=value pairs, with the possibility of specifying multiple key value pairs within the same string. For example, a string in the format of 'key1=value1, key2=value2' will return a dict of: {'key1': 'value1', 'key2': 'value2'}. 2. A string in the above format, but supporting a comma-delimited list of values for the same key. For example, a string in the format of 'key1=value1, key2=value3,value4,value5' will return a dict of: {'key1': 'value1', 'key2': 'value2,value3,value4'} 3. A string containing a colon character (:) prior to an equal character (=) will be treated as yaml and parsed as such. This can be used to specify more complex key value pairs. For example, a string in the format of 'key1: subkey1=value1, subkey2=value2' will return a dict of: {'key1', 'subkey1=value1, subkey2=value2'} The provided config_flags string may be a list of comma-separated values which themselves may be comma-separated list of values. """ # If we find a colon before an equals sign then treat it as yaml. # Note: limit it to finding the colon first since this indicates assignment # for inline yaml. colon = config_flags.find(':') equals = config_flags.find('=') if colon > 0: if colon < equals or equals < 0: return ordered(yaml.safe_load(config_flags)) if config_flags.find('==') >= 0: juju_log("config_flags is not in expected format (key=value)", level=ERROR) raise OSContextError # strip the following from each value. post_strippers = ' ,' # we strip any leading/trailing '=' or ' ' from the string then # split on '='. split = config_flags.strip(' =').split('=') limit = len(split) flags = OrderedDict() for i in range(0, limit - 1): current = split[i] next = split[i + 1] vindex = next.rfind(',') if (i == limit - 2) or (vindex < 0): value = next else: value = next[:vindex] if i == 0: key = current else: # if this not the first entry, expect an embedded key. index = current.rfind(',') if index < 0: juju_log("Invalid config value(s) at index %s" % (i), level=ERROR) raise OSContextError key = current[index + 1:] # Add to collection. flags[key.strip(post_strippers)] = value.rstrip(post_strippers) return flags
python
def config_flags_parser(config_flags): """Parses config flags string into dict. This parsing method supports a few different formats for the config flag values to be parsed: 1. A string in the simple format of key=value pairs, with the possibility of specifying multiple key value pairs within the same string. For example, a string in the format of 'key1=value1, key2=value2' will return a dict of: {'key1': 'value1', 'key2': 'value2'}. 2. A string in the above format, but supporting a comma-delimited list of values for the same key. For example, a string in the format of 'key1=value1, key2=value3,value4,value5' will return a dict of: {'key1': 'value1', 'key2': 'value2,value3,value4'} 3. A string containing a colon character (:) prior to an equal character (=) will be treated as yaml and parsed as such. This can be used to specify more complex key value pairs. For example, a string in the format of 'key1: subkey1=value1, subkey2=value2' will return a dict of: {'key1', 'subkey1=value1, subkey2=value2'} The provided config_flags string may be a list of comma-separated values which themselves may be comma-separated list of values. """ # If we find a colon before an equals sign then treat it as yaml. # Note: limit it to finding the colon first since this indicates assignment # for inline yaml. colon = config_flags.find(':') equals = config_flags.find('=') if colon > 0: if colon < equals or equals < 0: return ordered(yaml.safe_load(config_flags)) if config_flags.find('==') >= 0: juju_log("config_flags is not in expected format (key=value)", level=ERROR) raise OSContextError # strip the following from each value. post_strippers = ' ,' # we strip any leading/trailing '=' or ' ' from the string then # split on '='. split = config_flags.strip(' =').split('=') limit = len(split) flags = OrderedDict() for i in range(0, limit - 1): current = split[i] next = split[i + 1] vindex = next.rfind(',') if (i == limit - 2) or (vindex < 0): value = next else: value = next[:vindex] if i == 0: key = current else: # if this not the first entry, expect an embedded key. index = current.rfind(',') if index < 0: juju_log("Invalid config value(s) at index %s" % (i), level=ERROR) raise OSContextError key = current[index + 1:] # Add to collection. flags[key.strip(post_strippers)] = value.rstrip(post_strippers) return flags
[ "def", "config_flags_parser", "(", "config_flags", ")", ":", "# If we find a colon before an equals sign then treat it as yaml.", "# Note: limit it to finding the colon first since this indicates assignment", "# for inline yaml.", "colon", "=", "config_flags", ".", "find", "(", "':'", ")", "equals", "=", "config_flags", ".", "find", "(", "'='", ")", "if", "colon", ">", "0", ":", "if", "colon", "<", "equals", "or", "equals", "<", "0", ":", "return", "ordered", "(", "yaml", ".", "safe_load", "(", "config_flags", ")", ")", "if", "config_flags", ".", "find", "(", "'=='", ")", ">=", "0", ":", "juju_log", "(", "\"config_flags is not in expected format (key=value)\"", ",", "level", "=", "ERROR", ")", "raise", "OSContextError", "# strip the following from each value.", "post_strippers", "=", "' ,'", "# we strip any leading/trailing '=' or ' ' from the string then", "# split on '='.", "split", "=", "config_flags", ".", "strip", "(", "' ='", ")", ".", "split", "(", "'='", ")", "limit", "=", "len", "(", "split", ")", "flags", "=", "OrderedDict", "(", ")", "for", "i", "in", "range", "(", "0", ",", "limit", "-", "1", ")", ":", "current", "=", "split", "[", "i", "]", "next", "=", "split", "[", "i", "+", "1", "]", "vindex", "=", "next", ".", "rfind", "(", "','", ")", "if", "(", "i", "==", "limit", "-", "2", ")", "or", "(", "vindex", "<", "0", ")", ":", "value", "=", "next", "else", ":", "value", "=", "next", "[", ":", "vindex", "]", "if", "i", "==", "0", ":", "key", "=", "current", "else", ":", "# if this not the first entry, expect an embedded key.", "index", "=", "current", ".", "rfind", "(", "','", ")", "if", "index", "<", "0", ":", "juju_log", "(", "\"Invalid config value(s) at index %s\"", "%", "(", "i", ")", ",", "level", "=", "ERROR", ")", "raise", "OSContextError", "key", "=", "current", "[", "index", "+", "1", ":", "]", "# Add to collection.", "flags", "[", "key", ".", "strip", "(", "post_strippers", ")", "]", "=", "value", ".", "rstrip", "(", "post_strippers", ")", "return", "flags" ]
Parses config flags string into dict. This parsing method supports a few different formats for the config flag values to be parsed: 1. A string in the simple format of key=value pairs, with the possibility of specifying multiple key value pairs within the same string. For example, a string in the format of 'key1=value1, key2=value2' will return a dict of: {'key1': 'value1', 'key2': 'value2'}. 2. A string in the above format, but supporting a comma-delimited list of values for the same key. For example, a string in the format of 'key1=value1, key2=value3,value4,value5' will return a dict of: {'key1': 'value1', 'key2': 'value2,value3,value4'} 3. A string containing a colon character (:) prior to an equal character (=) will be treated as yaml and parsed as such. This can be used to specify more complex key value pairs. For example, a string in the format of 'key1: subkey1=value1, subkey2=value2' will return a dict of: {'key1', 'subkey1=value1, subkey2=value2'} The provided config_flags string may be a list of comma-separated values which themselves may be comma-separated list of values.
[ "Parses", "config", "flags", "string", "into", "dict", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1575-L1649
12,808
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
os_application_version_set
def os_application_version_set(package): '''Set version of application for Juju 2.0 and later''' application_version = get_upstream_version(package) # NOTE(jamespage) if not able to figure out package version, fallback to # openstack codename version detection. if not application_version: application_version_set(os_release(package)) else: application_version_set(application_version)
python
def os_application_version_set(package): '''Set version of application for Juju 2.0 and later''' application_version = get_upstream_version(package) # NOTE(jamespage) if not able to figure out package version, fallback to # openstack codename version detection. if not application_version: application_version_set(os_release(package)) else: application_version_set(application_version)
[ "def", "os_application_version_set", "(", "package", ")", ":", "application_version", "=", "get_upstream_version", "(", "package", ")", "# NOTE(jamespage) if not able to figure out package version, fallback to", "# openstack codename version detection.", "if", "not", "application_version", ":", "application_version_set", "(", "os_release", "(", "package", ")", ")", "else", ":", "application_version_set", "(", "application_version", ")" ]
Set version of application for Juju 2.0 and later
[ "Set", "version", "of", "application", "for", "Juju", "2", ".", "0", "and", "later" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1652-L1660
12,809
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
enable_memcache
def enable_memcache(source=None, release=None, package=None): """Determine if memcache should be enabled on the local unit @param release: release of OpenStack currently deployed @param package: package to derive OpenStack version deployed @returns boolean Whether memcache should be enabled """ _release = None if release: _release = release else: _release = os_release(package, base='icehouse') if not _release: _release = get_os_codename_install_source(source) return CompareOpenStackReleases(_release) >= 'mitaka'
python
def enable_memcache(source=None, release=None, package=None): """Determine if memcache should be enabled on the local unit @param release: release of OpenStack currently deployed @param package: package to derive OpenStack version deployed @returns boolean Whether memcache should be enabled """ _release = None if release: _release = release else: _release = os_release(package, base='icehouse') if not _release: _release = get_os_codename_install_source(source) return CompareOpenStackReleases(_release) >= 'mitaka'
[ "def", "enable_memcache", "(", "source", "=", "None", ",", "release", "=", "None", ",", "package", "=", "None", ")", ":", "_release", "=", "None", "if", "release", ":", "_release", "=", "release", "else", ":", "_release", "=", "os_release", "(", "package", ",", "base", "=", "'icehouse'", ")", "if", "not", "_release", ":", "_release", "=", "get_os_codename_install_source", "(", "source", ")", "return", "CompareOpenStackReleases", "(", "_release", ")", ">=", "'mitaka'" ]
Determine if memcache should be enabled on the local unit @param release: release of OpenStack currently deployed @param package: package to derive OpenStack version deployed @returns boolean Whether memcache should be enabled
[ "Determine", "if", "memcache", "should", "be", "enabled", "on", "the", "local", "unit" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1663-L1678
12,810
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
token_cache_pkgs
def token_cache_pkgs(source=None, release=None): """Determine additional packages needed for token caching @param source: source string for charm @param release: release of OpenStack currently deployed @returns List of package to enable token caching """ packages = [] if enable_memcache(source=source, release=release): packages.extend(['memcached', 'python-memcache']) return packages
python
def token_cache_pkgs(source=None, release=None): """Determine additional packages needed for token caching @param source: source string for charm @param release: release of OpenStack currently deployed @returns List of package to enable token caching """ packages = [] if enable_memcache(source=source, release=release): packages.extend(['memcached', 'python-memcache']) return packages
[ "def", "token_cache_pkgs", "(", "source", "=", "None", ",", "release", "=", "None", ")", ":", "packages", "=", "[", "]", "if", "enable_memcache", "(", "source", "=", "source", ",", "release", "=", "release", ")", ":", "packages", ".", "extend", "(", "[", "'memcached'", ",", "'python-memcache'", "]", ")", "return", "packages" ]
Determine additional packages needed for token caching @param source: source string for charm @param release: release of OpenStack currently deployed @returns List of package to enable token caching
[ "Determine", "additional", "packages", "needed", "for", "token", "caching" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1681-L1691
12,811
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
snap_install_requested
def snap_install_requested(): """ Determine if installing from snaps If openstack-origin is of the form snap:track/channel[/branch] and channel is in SNAPS_CHANNELS return True. """ origin = config('openstack-origin') or "" if not origin.startswith('snap:'): return False _src = origin[5:] if '/' in _src: channel = _src.split('/')[1] else: # Handle snap:track with no channel channel = 'stable' return valid_snap_channel(channel)
python
def snap_install_requested(): """ Determine if installing from snaps If openstack-origin is of the form snap:track/channel[/branch] and channel is in SNAPS_CHANNELS return True. """ origin = config('openstack-origin') or "" if not origin.startswith('snap:'): return False _src = origin[5:] if '/' in _src: channel = _src.split('/')[1] else: # Handle snap:track with no channel channel = 'stable' return valid_snap_channel(channel)
[ "def", "snap_install_requested", "(", ")", ":", "origin", "=", "config", "(", "'openstack-origin'", ")", "or", "\"\"", "if", "not", "origin", ".", "startswith", "(", "'snap:'", ")", ":", "return", "False", "_src", "=", "origin", "[", "5", ":", "]", "if", "'/'", "in", "_src", ":", "channel", "=", "_src", ".", "split", "(", "'/'", ")", "[", "1", "]", "else", ":", "# Handle snap:track with no channel", "channel", "=", "'stable'", "return", "valid_snap_channel", "(", "channel", ")" ]
Determine if installing from snaps If openstack-origin is of the form snap:track/channel[/branch] and channel is in SNAPS_CHANNELS return True.
[ "Determine", "if", "installing", "from", "snaps" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1718-L1734
12,812
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
get_snaps_install_info_from_origin
def get_snaps_install_info_from_origin(snaps, src, mode='classic'): """Generate a dictionary of snap install information from origin @param snaps: List of snaps @param src: String of openstack-origin or source of the form snap:track/channel @param mode: String classic, devmode or jailmode @returns: Dictionary of snaps with channels and modes """ if not src.startswith('snap:'): juju_log("Snap source is not a snap origin", 'WARN') return {} _src = src[5:] channel = '--channel={}'.format(_src) return {snap: {'channel': channel, 'mode': mode} for snap in snaps}
python
def get_snaps_install_info_from_origin(snaps, src, mode='classic'): """Generate a dictionary of snap install information from origin @param snaps: List of snaps @param src: String of openstack-origin or source of the form snap:track/channel @param mode: String classic, devmode or jailmode @returns: Dictionary of snaps with channels and modes """ if not src.startswith('snap:'): juju_log("Snap source is not a snap origin", 'WARN') return {} _src = src[5:] channel = '--channel={}'.format(_src) return {snap: {'channel': channel, 'mode': mode} for snap in snaps}
[ "def", "get_snaps_install_info_from_origin", "(", "snaps", ",", "src", ",", "mode", "=", "'classic'", ")", ":", "if", "not", "src", ".", "startswith", "(", "'snap:'", ")", ":", "juju_log", "(", "\"Snap source is not a snap origin\"", ",", "'WARN'", ")", "return", "{", "}", "_src", "=", "src", "[", "5", ":", "]", "channel", "=", "'--channel={}'", ".", "format", "(", "_src", ")", "return", "{", "snap", ":", "{", "'channel'", ":", "channel", ",", "'mode'", ":", "mode", "}", "for", "snap", "in", "snaps", "}" ]
Generate a dictionary of snap install information from origin @param snaps: List of snaps @param src: String of openstack-origin or source of the form snap:track/channel @param mode: String classic, devmode or jailmode @returns: Dictionary of snaps with channels and modes
[ "Generate", "a", "dictionary", "of", "snap", "install", "information", "from", "origin" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1737-L1755
12,813
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
install_os_snaps
def install_os_snaps(snaps, refresh=False): """Install OpenStack snaps from channel and with mode @param snaps: Dictionary of snaps with channels and modes of the form: {'snap_name': {'channel': 'snap_channel', 'mode': 'snap_mode'}} Where channel is a snapstore channel and mode is --classic, --devmode or --jailmode. @param post_snap_install: Callback function to run after snaps have been installed """ def _ensure_flag(flag): if flag.startswith('--'): return flag return '--{}'.format(flag) if refresh: for snap in snaps.keys(): snap_refresh(snap, _ensure_flag(snaps[snap]['channel']), _ensure_flag(snaps[snap]['mode'])) else: for snap in snaps.keys(): snap_install(snap, _ensure_flag(snaps[snap]['channel']), _ensure_flag(snaps[snap]['mode']))
python
def install_os_snaps(snaps, refresh=False): """Install OpenStack snaps from channel and with mode @param snaps: Dictionary of snaps with channels and modes of the form: {'snap_name': {'channel': 'snap_channel', 'mode': 'snap_mode'}} Where channel is a snapstore channel and mode is --classic, --devmode or --jailmode. @param post_snap_install: Callback function to run after snaps have been installed """ def _ensure_flag(flag): if flag.startswith('--'): return flag return '--{}'.format(flag) if refresh: for snap in snaps.keys(): snap_refresh(snap, _ensure_flag(snaps[snap]['channel']), _ensure_flag(snaps[snap]['mode'])) else: for snap in snaps.keys(): snap_install(snap, _ensure_flag(snaps[snap]['channel']), _ensure_flag(snaps[snap]['mode']))
[ "def", "install_os_snaps", "(", "snaps", ",", "refresh", "=", "False", ")", ":", "def", "_ensure_flag", "(", "flag", ")", ":", "if", "flag", ".", "startswith", "(", "'--'", ")", ":", "return", "flag", "return", "'--{}'", ".", "format", "(", "flag", ")", "if", "refresh", ":", "for", "snap", "in", "snaps", ".", "keys", "(", ")", ":", "snap_refresh", "(", "snap", ",", "_ensure_flag", "(", "snaps", "[", "snap", "]", "[", "'channel'", "]", ")", ",", "_ensure_flag", "(", "snaps", "[", "snap", "]", "[", "'mode'", "]", ")", ")", "else", ":", "for", "snap", "in", "snaps", ".", "keys", "(", ")", ":", "snap_install", "(", "snap", ",", "_ensure_flag", "(", "snaps", "[", "snap", "]", "[", "'channel'", "]", ")", ",", "_ensure_flag", "(", "snaps", "[", "snap", "]", "[", "'mode'", "]", ")", ")" ]
Install OpenStack snaps from channel and with mode @param snaps: Dictionary of snaps with channels and modes of the form: {'snap_name': {'channel': 'snap_channel', 'mode': 'snap_mode'}} Where channel is a snapstore channel and mode is --classic, --devmode or --jailmode. @param post_snap_install: Callback function to run after snaps have been installed
[ "Install", "OpenStack", "snaps", "from", "channel", "and", "with", "mode" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1758-L1784
12,814
juju/charm-helpers
charmhelpers/contrib/openstack/utils.py
series_upgrade_complete
def series_upgrade_complete(resume_unit_helper=None, configs=None): """ Run common series upgrade complete tasks. :param resume_unit_helper: function: Function to resume unit :param configs: OSConfigRenderer object: Configurations :returns None: """ clear_unit_paused() clear_unit_upgrading() if configs: configs.write_all() if resume_unit_helper: resume_unit_helper(configs)
python
def series_upgrade_complete(resume_unit_helper=None, configs=None): """ Run common series upgrade complete tasks. :param resume_unit_helper: function: Function to resume unit :param configs: OSConfigRenderer object: Configurations :returns None: """ clear_unit_paused() clear_unit_upgrading() if configs: configs.write_all() if resume_unit_helper: resume_unit_helper(configs)
[ "def", "series_upgrade_complete", "(", "resume_unit_helper", "=", "None", ",", "configs", "=", "None", ")", ":", "clear_unit_paused", "(", ")", "clear_unit_upgrading", "(", ")", "if", "configs", ":", "configs", ".", "write_all", "(", ")", "if", "resume_unit_helper", ":", "resume_unit_helper", "(", "configs", ")" ]
Run common series upgrade complete tasks. :param resume_unit_helper: function: Function to resume unit :param configs: OSConfigRenderer object: Configurations :returns None:
[ "Run", "common", "series", "upgrade", "complete", "tasks", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L1831-L1843
12,815
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
get_certificate_request
def get_certificate_request(json_encode=True): """Generate a certificatee requests based on the network confioguration """ req = CertRequest(json_encode=json_encode) req.add_hostname_cn() # Add os-hostname entries for net_type in [INTERNAL, ADMIN, PUBLIC]: net_config = config(ADDRESS_MAP[net_type]['override']) try: net_addr = resolve_address(endpoint_type=net_type) ip = network_get_primary_address( ADDRESS_MAP[net_type]['binding']) addresses = [net_addr, ip] vip = get_vip_in_network(resolve_network_cidr(ip)) if vip: addresses.append(vip) if net_config: req.add_entry( net_type, net_config, addresses) else: # There is network address with no corresponding hostname. # Add the ip to the hostname cert to allow for this. req.add_hostname_cn_ip(addresses) except NoNetworkBinding: log("Skipping request for certificate for ip in {} space, no " "local address found".format(net_type), WARNING) return req.get_request()
python
def get_certificate_request(json_encode=True): """Generate a certificatee requests based on the network confioguration """ req = CertRequest(json_encode=json_encode) req.add_hostname_cn() # Add os-hostname entries for net_type in [INTERNAL, ADMIN, PUBLIC]: net_config = config(ADDRESS_MAP[net_type]['override']) try: net_addr = resolve_address(endpoint_type=net_type) ip = network_get_primary_address( ADDRESS_MAP[net_type]['binding']) addresses = [net_addr, ip] vip = get_vip_in_network(resolve_network_cidr(ip)) if vip: addresses.append(vip) if net_config: req.add_entry( net_type, net_config, addresses) else: # There is network address with no corresponding hostname. # Add the ip to the hostname cert to allow for this. req.add_hostname_cn_ip(addresses) except NoNetworkBinding: log("Skipping request for certificate for ip in {} space, no " "local address found".format(net_type), WARNING) return req.get_request()
[ "def", "get_certificate_request", "(", "json_encode", "=", "True", ")", ":", "req", "=", "CertRequest", "(", "json_encode", "=", "json_encode", ")", "req", ".", "add_hostname_cn", "(", ")", "# Add os-hostname entries", "for", "net_type", "in", "[", "INTERNAL", ",", "ADMIN", ",", "PUBLIC", "]", ":", "net_config", "=", "config", "(", "ADDRESS_MAP", "[", "net_type", "]", "[", "'override'", "]", ")", "try", ":", "net_addr", "=", "resolve_address", "(", "endpoint_type", "=", "net_type", ")", "ip", "=", "network_get_primary_address", "(", "ADDRESS_MAP", "[", "net_type", "]", "[", "'binding'", "]", ")", "addresses", "=", "[", "net_addr", ",", "ip", "]", "vip", "=", "get_vip_in_network", "(", "resolve_network_cidr", "(", "ip", ")", ")", "if", "vip", ":", "addresses", ".", "append", "(", "vip", ")", "if", "net_config", ":", "req", ".", "add_entry", "(", "net_type", ",", "net_config", ",", "addresses", ")", "else", ":", "# There is network address with no corresponding hostname.", "# Add the ip to the hostname cert to allow for this.", "req", ".", "add_hostname_cn_ip", "(", "addresses", ")", "except", "NoNetworkBinding", ":", "log", "(", "\"Skipping request for certificate for ip in {} space, no \"", "\"local address found\"", ".", "format", "(", "net_type", ")", ",", "WARNING", ")", "return", "req", ".", "get_request", "(", ")" ]
Generate a certificatee requests based on the network confioguration
[ "Generate", "a", "certificatee", "requests", "based", "on", "the", "network", "confioguration" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L114-L143
12,816
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
create_ip_cert_links
def create_ip_cert_links(ssl_dir, custom_hostname_link=None): """Create symlinks for SAN records :param ssl_dir: str Directory to create symlinks in :param custom_hostname_link: str Additional link to be created """ hostname = get_hostname(unit_get('private-address')) hostname_cert = os.path.join( ssl_dir, 'cert_{}'.format(hostname)) hostname_key = os.path.join( ssl_dir, 'key_{}'.format(hostname)) # Add links to hostname cert, used if os-hostname vars not set for net_type in [INTERNAL, ADMIN, PUBLIC]: try: addr = resolve_address(endpoint_type=net_type) cert = os.path.join(ssl_dir, 'cert_{}'.format(addr)) key = os.path.join(ssl_dir, 'key_{}'.format(addr)) if os.path.isfile(hostname_cert) and not os.path.isfile(cert): os.symlink(hostname_cert, cert) os.symlink(hostname_key, key) except NoNetworkBinding: log("Skipping creating cert symlink for ip in {} space, no " "local address found".format(net_type), WARNING) if custom_hostname_link: custom_cert = os.path.join( ssl_dir, 'cert_{}'.format(custom_hostname_link)) custom_key = os.path.join( ssl_dir, 'key_{}'.format(custom_hostname_link)) if os.path.isfile(hostname_cert) and not os.path.isfile(custom_cert): os.symlink(hostname_cert, custom_cert) os.symlink(hostname_key, custom_key)
python
def create_ip_cert_links(ssl_dir, custom_hostname_link=None): """Create symlinks for SAN records :param ssl_dir: str Directory to create symlinks in :param custom_hostname_link: str Additional link to be created """ hostname = get_hostname(unit_get('private-address')) hostname_cert = os.path.join( ssl_dir, 'cert_{}'.format(hostname)) hostname_key = os.path.join( ssl_dir, 'key_{}'.format(hostname)) # Add links to hostname cert, used if os-hostname vars not set for net_type in [INTERNAL, ADMIN, PUBLIC]: try: addr = resolve_address(endpoint_type=net_type) cert = os.path.join(ssl_dir, 'cert_{}'.format(addr)) key = os.path.join(ssl_dir, 'key_{}'.format(addr)) if os.path.isfile(hostname_cert) and not os.path.isfile(cert): os.symlink(hostname_cert, cert) os.symlink(hostname_key, key) except NoNetworkBinding: log("Skipping creating cert symlink for ip in {} space, no " "local address found".format(net_type), WARNING) if custom_hostname_link: custom_cert = os.path.join( ssl_dir, 'cert_{}'.format(custom_hostname_link)) custom_key = os.path.join( ssl_dir, 'key_{}'.format(custom_hostname_link)) if os.path.isfile(hostname_cert) and not os.path.isfile(custom_cert): os.symlink(hostname_cert, custom_cert) os.symlink(hostname_key, custom_key)
[ "def", "create_ip_cert_links", "(", "ssl_dir", ",", "custom_hostname_link", "=", "None", ")", ":", "hostname", "=", "get_hostname", "(", "unit_get", "(", "'private-address'", ")", ")", "hostname_cert", "=", "os", ".", "path", ".", "join", "(", "ssl_dir", ",", "'cert_{}'", ".", "format", "(", "hostname", ")", ")", "hostname_key", "=", "os", ".", "path", ".", "join", "(", "ssl_dir", ",", "'key_{}'", ".", "format", "(", "hostname", ")", ")", "# Add links to hostname cert, used if os-hostname vars not set", "for", "net_type", "in", "[", "INTERNAL", ",", "ADMIN", ",", "PUBLIC", "]", ":", "try", ":", "addr", "=", "resolve_address", "(", "endpoint_type", "=", "net_type", ")", "cert", "=", "os", ".", "path", ".", "join", "(", "ssl_dir", ",", "'cert_{}'", ".", "format", "(", "addr", ")", ")", "key", "=", "os", ".", "path", ".", "join", "(", "ssl_dir", ",", "'key_{}'", ".", "format", "(", "addr", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "hostname_cert", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "cert", ")", ":", "os", ".", "symlink", "(", "hostname_cert", ",", "cert", ")", "os", ".", "symlink", "(", "hostname_key", ",", "key", ")", "except", "NoNetworkBinding", ":", "log", "(", "\"Skipping creating cert symlink for ip in {} space, no \"", "\"local address found\"", ".", "format", "(", "net_type", ")", ",", "WARNING", ")", "if", "custom_hostname_link", ":", "custom_cert", "=", "os", ".", "path", ".", "join", "(", "ssl_dir", ",", "'cert_{}'", ".", "format", "(", "custom_hostname_link", ")", ")", "custom_key", "=", "os", ".", "path", ".", "join", "(", "ssl_dir", ",", "'key_{}'", ".", "format", "(", "custom_hostname_link", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "hostname_cert", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "custom_cert", ")", ":", "os", ".", "symlink", "(", "hostname_cert", ",", "custom_cert", ")", "os", ".", "symlink", "(", "hostname_key", ",", "custom_key", ")" ]
Create symlinks for SAN records :param ssl_dir: str Directory to create symlinks in :param custom_hostname_link: str Additional link to be created
[ "Create", "symlinks", "for", "SAN", "records" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L146-L180
12,817
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
install_certs
def install_certs(ssl_dir, certs, chain=None, user='root', group='root'): """Install the certs passed into the ssl dir and append the chain if provided. :param ssl_dir: str Directory to create symlinks in :param certs: {} {'cn': {'cert': 'CERT', 'key': 'KEY'}} :param chain: str Chain to be appended to certs :param user: (Optional) Owner of certificate files. Defaults to 'root' :type user: str :param group: (Optional) Group of certificate files. Defaults to 'root' :type group: str """ for cn, bundle in certs.items(): cert_filename = 'cert_{}'.format(cn) key_filename = 'key_{}'.format(cn) cert_data = bundle['cert'] if chain: # Append chain file so that clients that trust the root CA will # trust certs signed by an intermediate in the chain cert_data = cert_data + os.linesep + chain write_file( path=os.path.join(ssl_dir, cert_filename), owner=user, group=group, content=cert_data, perms=0o640) write_file( path=os.path.join(ssl_dir, key_filename), owner=user, group=group, content=bundle['key'], perms=0o640)
python
def install_certs(ssl_dir, certs, chain=None, user='root', group='root'): """Install the certs passed into the ssl dir and append the chain if provided. :param ssl_dir: str Directory to create symlinks in :param certs: {} {'cn': {'cert': 'CERT', 'key': 'KEY'}} :param chain: str Chain to be appended to certs :param user: (Optional) Owner of certificate files. Defaults to 'root' :type user: str :param group: (Optional) Group of certificate files. Defaults to 'root' :type group: str """ for cn, bundle in certs.items(): cert_filename = 'cert_{}'.format(cn) key_filename = 'key_{}'.format(cn) cert_data = bundle['cert'] if chain: # Append chain file so that clients that trust the root CA will # trust certs signed by an intermediate in the chain cert_data = cert_data + os.linesep + chain write_file( path=os.path.join(ssl_dir, cert_filename), owner=user, group=group, content=cert_data, perms=0o640) write_file( path=os.path.join(ssl_dir, key_filename), owner=user, group=group, content=bundle['key'], perms=0o640)
[ "def", "install_certs", "(", "ssl_dir", ",", "certs", ",", "chain", "=", "None", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ")", ":", "for", "cn", ",", "bundle", "in", "certs", ".", "items", "(", ")", ":", "cert_filename", "=", "'cert_{}'", ".", "format", "(", "cn", ")", "key_filename", "=", "'key_{}'", ".", "format", "(", "cn", ")", "cert_data", "=", "bundle", "[", "'cert'", "]", "if", "chain", ":", "# Append chain file so that clients that trust the root CA will", "# trust certs signed by an intermediate in the chain", "cert_data", "=", "cert_data", "+", "os", ".", "linesep", "+", "chain", "write_file", "(", "path", "=", "os", ".", "path", ".", "join", "(", "ssl_dir", ",", "cert_filename", ")", ",", "owner", "=", "user", ",", "group", "=", "group", ",", "content", "=", "cert_data", ",", "perms", "=", "0o640", ")", "write_file", "(", "path", "=", "os", ".", "path", ".", "join", "(", "ssl_dir", ",", "key_filename", ")", ",", "owner", "=", "user", ",", "group", "=", "group", ",", "content", "=", "bundle", "[", "'key'", "]", ",", "perms", "=", "0o640", ")" ]
Install the certs passed into the ssl dir and append the chain if provided. :param ssl_dir: str Directory to create symlinks in :param certs: {} {'cn': {'cert': 'CERT', 'key': 'KEY'}} :param chain: str Chain to be appended to certs :param user: (Optional) Owner of certificate files. Defaults to 'root' :type user: str :param group: (Optional) Group of certificate files. Defaults to 'root' :type group: str
[ "Install", "the", "certs", "passed", "into", "the", "ssl", "dir", "and", "append", "the", "chain", "if", "provided", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L183-L208
12,818
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
process_certificates
def process_certificates(service_name, relation_id, unit, custom_hostname_link=None, user='root', group='root'): """Process the certificates supplied down the relation :param service_name: str Name of service the certifcates are for. :param relation_id: str Relation id providing the certs :param unit: str Unit providing the certs :param custom_hostname_link: str Name of custom link to create :param user: (Optional) Owner of certificate files. Defaults to 'root' :type user: str :param group: (Optional) Group of certificate files. Defaults to 'root' :type group: str :returns: True if certificates processed for local unit or False :rtype: bool """ data = relation_get(rid=relation_id, unit=unit) ssl_dir = os.path.join('/etc/apache2/ssl/', service_name) mkdir(path=ssl_dir) name = local_unit().replace('/', '_') certs = data.get('{}.processed_requests'.format(name)) chain = data.get('chain') ca = data.get('ca') if certs: certs = json.loads(certs) install_ca_cert(ca.encode()) install_certs(ssl_dir, certs, chain, user=user, group=group) create_ip_cert_links( ssl_dir, custom_hostname_link=custom_hostname_link) return True return False
python
def process_certificates(service_name, relation_id, unit, custom_hostname_link=None, user='root', group='root'): """Process the certificates supplied down the relation :param service_name: str Name of service the certifcates are for. :param relation_id: str Relation id providing the certs :param unit: str Unit providing the certs :param custom_hostname_link: str Name of custom link to create :param user: (Optional) Owner of certificate files. Defaults to 'root' :type user: str :param group: (Optional) Group of certificate files. Defaults to 'root' :type group: str :returns: True if certificates processed for local unit or False :rtype: bool """ data = relation_get(rid=relation_id, unit=unit) ssl_dir = os.path.join('/etc/apache2/ssl/', service_name) mkdir(path=ssl_dir) name = local_unit().replace('/', '_') certs = data.get('{}.processed_requests'.format(name)) chain = data.get('chain') ca = data.get('ca') if certs: certs = json.loads(certs) install_ca_cert(ca.encode()) install_certs(ssl_dir, certs, chain, user=user, group=group) create_ip_cert_links( ssl_dir, custom_hostname_link=custom_hostname_link) return True return False
[ "def", "process_certificates", "(", "service_name", ",", "relation_id", ",", "unit", ",", "custom_hostname_link", "=", "None", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ")", ":", "data", "=", "relation_get", "(", "rid", "=", "relation_id", ",", "unit", "=", "unit", ")", "ssl_dir", "=", "os", ".", "path", ".", "join", "(", "'/etc/apache2/ssl/'", ",", "service_name", ")", "mkdir", "(", "path", "=", "ssl_dir", ")", "name", "=", "local_unit", "(", ")", ".", "replace", "(", "'/'", ",", "'_'", ")", "certs", "=", "data", ".", "get", "(", "'{}.processed_requests'", ".", "format", "(", "name", ")", ")", "chain", "=", "data", ".", "get", "(", "'chain'", ")", "ca", "=", "data", ".", "get", "(", "'ca'", ")", "if", "certs", ":", "certs", "=", "json", ".", "loads", "(", "certs", ")", "install_ca_cert", "(", "ca", ".", "encode", "(", ")", ")", "install_certs", "(", "ssl_dir", ",", "certs", ",", "chain", ",", "user", "=", "user", ",", "group", "=", "group", ")", "create_ip_cert_links", "(", "ssl_dir", ",", "custom_hostname_link", "=", "custom_hostname_link", ")", "return", "True", "return", "False" ]
Process the certificates supplied down the relation :param service_name: str Name of service the certifcates are for. :param relation_id: str Relation id providing the certs :param unit: str Unit providing the certs :param custom_hostname_link: str Name of custom link to create :param user: (Optional) Owner of certificate files. Defaults to 'root' :type user: str :param group: (Optional) Group of certificate files. Defaults to 'root' :type group: str :returns: True if certificates processed for local unit or False :rtype: bool
[ "Process", "the", "certificates", "supplied", "down", "the", "relation" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L211-L241
12,819
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
get_requests_for_local_unit
def get_requests_for_local_unit(relation_name=None): """Extract any certificates data targeted at this unit down relation_name. :param relation_name: str Name of relation to check for data. :returns: List of bundles of certificates. :rtype: List of dicts """ local_name = local_unit().replace('/', '_') raw_certs_key = '{}.processed_requests'.format(local_name) relation_name = relation_name or 'certificates' bundles = [] for rid in relation_ids(relation_name): for unit in related_units(rid): data = relation_get(rid=rid, unit=unit) if data.get(raw_certs_key): bundles.append({ 'ca': data['ca'], 'chain': data.get('chain'), 'certs': json.loads(data[raw_certs_key])}) return bundles
python
def get_requests_for_local_unit(relation_name=None): """Extract any certificates data targeted at this unit down relation_name. :param relation_name: str Name of relation to check for data. :returns: List of bundles of certificates. :rtype: List of dicts """ local_name = local_unit().replace('/', '_') raw_certs_key = '{}.processed_requests'.format(local_name) relation_name = relation_name or 'certificates' bundles = [] for rid in relation_ids(relation_name): for unit in related_units(rid): data = relation_get(rid=rid, unit=unit) if data.get(raw_certs_key): bundles.append({ 'ca': data['ca'], 'chain': data.get('chain'), 'certs': json.loads(data[raw_certs_key])}) return bundles
[ "def", "get_requests_for_local_unit", "(", "relation_name", "=", "None", ")", ":", "local_name", "=", "local_unit", "(", ")", ".", "replace", "(", "'/'", ",", "'_'", ")", "raw_certs_key", "=", "'{}.processed_requests'", ".", "format", "(", "local_name", ")", "relation_name", "=", "relation_name", "or", "'certificates'", "bundles", "=", "[", "]", "for", "rid", "in", "relation_ids", "(", "relation_name", ")", ":", "for", "unit", "in", "related_units", "(", "rid", ")", ":", "data", "=", "relation_get", "(", "rid", "=", "rid", ",", "unit", "=", "unit", ")", "if", "data", ".", "get", "(", "raw_certs_key", ")", ":", "bundles", ".", "append", "(", "{", "'ca'", ":", "data", "[", "'ca'", "]", ",", "'chain'", ":", "data", ".", "get", "(", "'chain'", ")", ",", "'certs'", ":", "json", ".", "loads", "(", "data", "[", "raw_certs_key", "]", ")", "}", ")", "return", "bundles" ]
Extract any certificates data targeted at this unit down relation_name. :param relation_name: str Name of relation to check for data. :returns: List of bundles of certificates. :rtype: List of dicts
[ "Extract", "any", "certificates", "data", "targeted", "at", "this", "unit", "down", "relation_name", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L244-L263
12,820
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
get_bundle_for_cn
def get_bundle_for_cn(cn, relation_name=None): """Extract certificates for the given cn. :param cn: str Canonical Name on certificate. :param relation_name: str Relation to check for certificates down. :returns: Dictionary of certificate data, :rtype: dict. """ entries = get_requests_for_local_unit(relation_name) cert_bundle = {} for entry in entries: for _cn, bundle in entry['certs'].items(): if _cn == cn: cert_bundle = { 'cert': bundle['cert'], 'key': bundle['key'], 'chain': entry['chain'], 'ca': entry['ca']} break if cert_bundle: break return cert_bundle
python
def get_bundle_for_cn(cn, relation_name=None): """Extract certificates for the given cn. :param cn: str Canonical Name on certificate. :param relation_name: str Relation to check for certificates down. :returns: Dictionary of certificate data, :rtype: dict. """ entries = get_requests_for_local_unit(relation_name) cert_bundle = {} for entry in entries: for _cn, bundle in entry['certs'].items(): if _cn == cn: cert_bundle = { 'cert': bundle['cert'], 'key': bundle['key'], 'chain': entry['chain'], 'ca': entry['ca']} break if cert_bundle: break return cert_bundle
[ "def", "get_bundle_for_cn", "(", "cn", ",", "relation_name", "=", "None", ")", ":", "entries", "=", "get_requests_for_local_unit", "(", "relation_name", ")", "cert_bundle", "=", "{", "}", "for", "entry", "in", "entries", ":", "for", "_cn", ",", "bundle", "in", "entry", "[", "'certs'", "]", ".", "items", "(", ")", ":", "if", "_cn", "==", "cn", ":", "cert_bundle", "=", "{", "'cert'", ":", "bundle", "[", "'cert'", "]", ",", "'key'", ":", "bundle", "[", "'key'", "]", ",", "'chain'", ":", "entry", "[", "'chain'", "]", ",", "'ca'", ":", "entry", "[", "'ca'", "]", "}", "break", "if", "cert_bundle", ":", "break", "return", "cert_bundle" ]
Extract certificates for the given cn. :param cn: str Canonical Name on certificate. :param relation_name: str Relation to check for certificates down. :returns: Dictionary of certificate data, :rtype: dict.
[ "Extract", "certificates", "for", "the", "given", "cn", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L266-L287
12,821
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
CertRequest.add_entry
def add_entry(self, net_type, cn, addresses): """Add a request to the batch :param net_type: str netwrok space name request is for :param cn: str Canonical Name for certificate :param addresses: [] List of addresses to be used as SANs """ self.entries.append({ 'cn': cn, 'addresses': addresses})
python
def add_entry(self, net_type, cn, addresses): """Add a request to the batch :param net_type: str netwrok space name request is for :param cn: str Canonical Name for certificate :param addresses: [] List of addresses to be used as SANs """ self.entries.append({ 'cn': cn, 'addresses': addresses})
[ "def", "add_entry", "(", "self", ",", "net_type", ",", "cn", ",", "addresses", ")", ":", "self", ".", "entries", ".", "append", "(", "{", "'cn'", ":", "cn", ",", "'addresses'", ":", "addresses", "}", ")" ]
Add a request to the batch :param net_type: str netwrok space name request is for :param cn: str Canonical Name for certificate :param addresses: [] List of addresses to be used as SANs
[ "Add", "a", "request", "to", "the", "batch" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L64-L73
12,822
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
CertRequest.add_hostname_cn
def add_hostname_cn(self): """Add a request for the hostname of the machine""" ip = unit_get('private-address') addresses = [ip] # If a vip is being used without os-hostname config or # network spaces then we need to ensure the local units # cert has the approriate vip in the SAN list vip = get_vip_in_network(resolve_network_cidr(ip)) if vip: addresses.append(vip) self.hostname_entry = { 'cn': get_hostname(ip), 'addresses': addresses}
python
def add_hostname_cn(self): """Add a request for the hostname of the machine""" ip = unit_get('private-address') addresses = [ip] # If a vip is being used without os-hostname config or # network spaces then we need to ensure the local units # cert has the approriate vip in the SAN list vip = get_vip_in_network(resolve_network_cidr(ip)) if vip: addresses.append(vip) self.hostname_entry = { 'cn': get_hostname(ip), 'addresses': addresses}
[ "def", "add_hostname_cn", "(", "self", ")", ":", "ip", "=", "unit_get", "(", "'private-address'", ")", "addresses", "=", "[", "ip", "]", "# If a vip is being used without os-hostname config or", "# network spaces then we need to ensure the local units", "# cert has the approriate vip in the SAN list", "vip", "=", "get_vip_in_network", "(", "resolve_network_cidr", "(", "ip", ")", ")", "if", "vip", ":", "addresses", ".", "append", "(", "vip", ")", "self", ".", "hostname_entry", "=", "{", "'cn'", ":", "get_hostname", "(", "ip", ")", ",", "'addresses'", ":", "addresses", "}" ]
Add a request for the hostname of the machine
[ "Add", "a", "request", "for", "the", "hostname", "of", "the", "machine" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L75-L87
12,823
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
CertRequest.add_hostname_cn_ip
def add_hostname_cn_ip(self, addresses): """Add an address to the SAN list for the hostname request :param addr: [] List of address to be added """ for addr in addresses: if addr not in self.hostname_entry['addresses']: self.hostname_entry['addresses'].append(addr)
python
def add_hostname_cn_ip(self, addresses): """Add an address to the SAN list for the hostname request :param addr: [] List of address to be added """ for addr in addresses: if addr not in self.hostname_entry['addresses']: self.hostname_entry['addresses'].append(addr)
[ "def", "add_hostname_cn_ip", "(", "self", ",", "addresses", ")", ":", "for", "addr", "in", "addresses", ":", "if", "addr", "not", "in", "self", ".", "hostname_entry", "[", "'addresses'", "]", ":", "self", ".", "hostname_entry", "[", "'addresses'", "]", ".", "append", "(", "addr", ")" ]
Add an address to the SAN list for the hostname request :param addr: [] List of address to be added
[ "Add", "an", "address", "to", "the", "SAN", "list", "for", "the", "hostname", "request" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L89-L96
12,824
juju/charm-helpers
charmhelpers/contrib/openstack/cert_utils.py
CertRequest.get_request
def get_request(self): """Generate request from the batched up entries """ if self.hostname_entry: self.entries.append(self.hostname_entry) request = {} for entry in self.entries: sans = sorted(list(set(entry['addresses']))) request[entry['cn']] = {'sans': sans} if self.json_encode: return {'cert_requests': json.dumps(request, sort_keys=True)} else: return {'cert_requests': request}
python
def get_request(self): """Generate request from the batched up entries """ if self.hostname_entry: self.entries.append(self.hostname_entry) request = {} for entry in self.entries: sans = sorted(list(set(entry['addresses']))) request[entry['cn']] = {'sans': sans} if self.json_encode: return {'cert_requests': json.dumps(request, sort_keys=True)} else: return {'cert_requests': request}
[ "def", "get_request", "(", "self", ")", ":", "if", "self", ".", "hostname_entry", ":", "self", ".", "entries", ".", "append", "(", "self", ".", "hostname_entry", ")", "request", "=", "{", "}", "for", "entry", "in", "self", ".", "entries", ":", "sans", "=", "sorted", "(", "list", "(", "set", "(", "entry", "[", "'addresses'", "]", ")", ")", ")", "request", "[", "entry", "[", "'cn'", "]", "]", "=", "{", "'sans'", ":", "sans", "}", "if", "self", ".", "json_encode", ":", "return", "{", "'cert_requests'", ":", "json", ".", "dumps", "(", "request", ",", "sort_keys", "=", "True", ")", "}", "else", ":", "return", "{", "'cert_requests'", ":", "request", "}" ]
Generate request from the batched up entries
[ "Generate", "request", "from", "the", "batched", "up", "entries" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/cert_utils.py#L98-L111
12,825
juju/charm-helpers
charmhelpers/contrib/hardening/host/checks/sysctl.py
get_audits
def get_audits(): """Get OS hardening sysctl audits. :returns: dictionary of audits """ audits = [] settings = utils.get_settings('os') # Apply the sysctl settings which are configured to be applied. audits.append(SysctlConf()) # Make sure that only root has access to the sysctl.conf file, and # that it is read-only. audits.append(FilePermissionAudit('/etc/sysctl.conf', user='root', group='root', mode=0o0440)) # If module loading is not enabled, then ensure that the modules # file has the appropriate permissions and rebuild the initramfs if not settings['security']['kernel_enable_module_loading']: audits.append(ModulesTemplate()) return audits
python
def get_audits(): """Get OS hardening sysctl audits. :returns: dictionary of audits """ audits = [] settings = utils.get_settings('os') # Apply the sysctl settings which are configured to be applied. audits.append(SysctlConf()) # Make sure that only root has access to the sysctl.conf file, and # that it is read-only. audits.append(FilePermissionAudit('/etc/sysctl.conf', user='root', group='root', mode=0o0440)) # If module loading is not enabled, then ensure that the modules # file has the appropriate permissions and rebuild the initramfs if not settings['security']['kernel_enable_module_loading']: audits.append(ModulesTemplate()) return audits
[ "def", "get_audits", "(", ")", ":", "audits", "=", "[", "]", "settings", "=", "utils", ".", "get_settings", "(", "'os'", ")", "# Apply the sysctl settings which are configured to be applied.", "audits", ".", "append", "(", "SysctlConf", "(", ")", ")", "# Make sure that only root has access to the sysctl.conf file, and", "# that it is read-only.", "audits", ".", "append", "(", "FilePermissionAudit", "(", "'/etc/sysctl.conf'", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ",", "mode", "=", "0o0440", ")", ")", "# If module loading is not enabled, then ensure that the modules", "# file has the appropriate permissions and rebuild the initramfs", "if", "not", "settings", "[", "'security'", "]", "[", "'kernel_enable_module_loading'", "]", ":", "audits", ".", "append", "(", "ModulesTemplate", "(", ")", ")", "return", "audits" ]
Get OS hardening sysctl audits. :returns: dictionary of audits
[ "Get", "OS", "hardening", "sysctl", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/sysctl.py#L77-L97
12,826
juju/charm-helpers
charmhelpers/contrib/openstack/audits/openstack_security_guide.py
_stat
def _stat(file): """ Get the Ownership information from a file. :param file: The path to a file to stat :type file: str :returns: owner, group, and mode of the specified file :rtype: Ownership :raises subprocess.CalledProcessError: If the underlying stat fails """ out = subprocess.check_output( ['stat', '-c', '%U %G %a', file]).decode('utf-8') return Ownership(*out.strip().split(' '))
python
def _stat(file): """ Get the Ownership information from a file. :param file: The path to a file to stat :type file: str :returns: owner, group, and mode of the specified file :rtype: Ownership :raises subprocess.CalledProcessError: If the underlying stat fails """ out = subprocess.check_output( ['stat', '-c', '%U %G %a', file]).decode('utf-8') return Ownership(*out.strip().split(' '))
[ "def", "_stat", "(", "file", ")", ":", "out", "=", "subprocess", ".", "check_output", "(", "[", "'stat'", ",", "'-c'", ",", "'%U %G %a'", ",", "file", "]", ")", ".", "decode", "(", "'utf-8'", ")", "return", "Ownership", "(", "*", "out", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", ")" ]
Get the Ownership information from a file. :param file: The path to a file to stat :type file: str :returns: owner, group, and mode of the specified file :rtype: Ownership :raises subprocess.CalledProcessError: If the underlying stat fails
[ "Get", "the", "Ownership", "information", "from", "a", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L104-L116
12,827
juju/charm-helpers
charmhelpers/contrib/openstack/audits/openstack_security_guide.py
_config_ini
def _config_ini(path): """ Parse an ini file :param path: The path to a file to parse :type file: str :returns: Configuration contained in path :rtype: Dict """ conf = configparser.ConfigParser() conf.read(path) return dict(conf)
python
def _config_ini(path): """ Parse an ini file :param path: The path to a file to parse :type file: str :returns: Configuration contained in path :rtype: Dict """ conf = configparser.ConfigParser() conf.read(path) return dict(conf)
[ "def", "_config_ini", "(", "path", ")", ":", "conf", "=", "configparser", ".", "ConfigParser", "(", ")", "conf", ".", "read", "(", "path", ")", "return", "dict", "(", "conf", ")" ]
Parse an ini file :param path: The path to a file to parse :type file: str :returns: Configuration contained in path :rtype: Dict
[ "Parse", "an", "ini", "file" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L120-L131
12,828
juju/charm-helpers
charmhelpers/contrib/openstack/audits/openstack_security_guide.py
_validate_file_mode
def _validate_file_mode(mode, file_name, optional=False): """ Validate that a specified file has the specified permissions. :param mode: file mode that is desires :type owner: str :param file_name: Path to the file to verify :type file_name: str :param optional: Is this file optional, ie: Should this test fail when it's missing :type optional: bool """ try: ownership = _stat(file_name) except subprocess.CalledProcessError as e: print("Error reading file: {}".format(e)) if not optional: assert False, "Specified file does not exist: {}".format(file_name) assert mode == ownership.mode, \ "{} has an incorrect mode: {} should be {}".format( file_name, ownership.mode, mode) print("Validate mode of {}: PASS".format(file_name))
python
def _validate_file_mode(mode, file_name, optional=False): """ Validate that a specified file has the specified permissions. :param mode: file mode that is desires :type owner: str :param file_name: Path to the file to verify :type file_name: str :param optional: Is this file optional, ie: Should this test fail when it's missing :type optional: bool """ try: ownership = _stat(file_name) except subprocess.CalledProcessError as e: print("Error reading file: {}".format(e)) if not optional: assert False, "Specified file does not exist: {}".format(file_name) assert mode == ownership.mode, \ "{} has an incorrect mode: {} should be {}".format( file_name, ownership.mode, mode) print("Validate mode of {}: PASS".format(file_name))
[ "def", "_validate_file_mode", "(", "mode", ",", "file_name", ",", "optional", "=", "False", ")", ":", "try", ":", "ownership", "=", "_stat", "(", "file_name", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "print", "(", "\"Error reading file: {}\"", ".", "format", "(", "e", ")", ")", "if", "not", "optional", ":", "assert", "False", ",", "\"Specified file does not exist: {}\"", ".", "format", "(", "file_name", ")", "assert", "mode", "==", "ownership", ".", "mode", ",", "\"{} has an incorrect mode: {} should be {}\"", ".", "format", "(", "file_name", ",", "ownership", ".", "mode", ",", "mode", ")", "print", "(", "\"Validate mode of {}: PASS\"", ".", "format", "(", "file_name", ")", ")" ]
Validate that a specified file has the specified permissions. :param mode: file mode that is desires :type owner: str :param file_name: Path to the file to verify :type file_name: str :param optional: Is this file optional, ie: Should this test fail when it's missing :type optional: bool
[ "Validate", "that", "a", "specified", "file", "has", "the", "specified", "permissions", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L163-L184
12,829
juju/charm-helpers
charmhelpers/contrib/openstack/audits/openstack_security_guide.py
_config_section
def _config_section(config, section): """Read the configuration file and return a section.""" path = os.path.join(config.get('config_path'), config.get('config_file')) conf = _config_ini(path) return conf.get(section)
python
def _config_section(config, section): """Read the configuration file and return a section.""" path = os.path.join(config.get('config_path'), config.get('config_file')) conf = _config_ini(path) return conf.get(section)
[ "def", "_config_section", "(", "config", ",", "section", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "config", ".", "get", "(", "'config_path'", ")", ",", "config", ".", "get", "(", "'config_file'", ")", ")", "conf", "=", "_config_ini", "(", "path", ")", "return", "conf", ".", "get", "(", "section", ")" ]
Read the configuration file and return a section.
[ "Read", "the", "configuration", "file", "and", "return", "a", "section", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L188-L192
12,830
juju/charm-helpers
charmhelpers/contrib/openstack/audits/openstack_security_guide.py
validate_file_permissions
def validate_file_permissions(config): """Verify that permissions on configuration files are secure enough.""" files = config.get('files', {}) for file_name, options in files.items(): for key in options.keys(): if key not in ["owner", "group", "mode"]: raise RuntimeError( "Invalid ownership configuration: {}".format(key)) mode = options.get('mode', config.get('permissions', '600')) optional = options.get('optional', config.get('optional', 'False')) if '*' in file_name: for file in glob.glob(file_name): if file not in files.keys(): if os.path.isfile(file): _validate_file_mode(mode, file, optional) else: if os.path.isfile(file_name): _validate_file_mode(mode, file_name, optional)
python
def validate_file_permissions(config): """Verify that permissions on configuration files are secure enough.""" files = config.get('files', {}) for file_name, options in files.items(): for key in options.keys(): if key not in ["owner", "group", "mode"]: raise RuntimeError( "Invalid ownership configuration: {}".format(key)) mode = options.get('mode', config.get('permissions', '600')) optional = options.get('optional', config.get('optional', 'False')) if '*' in file_name: for file in glob.glob(file_name): if file not in files.keys(): if os.path.isfile(file): _validate_file_mode(mode, file, optional) else: if os.path.isfile(file_name): _validate_file_mode(mode, file_name, optional)
[ "def", "validate_file_permissions", "(", "config", ")", ":", "files", "=", "config", ".", "get", "(", "'files'", ",", "{", "}", ")", "for", "file_name", ",", "options", "in", "files", ".", "items", "(", ")", ":", "for", "key", "in", "options", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "[", "\"owner\"", ",", "\"group\"", ",", "\"mode\"", "]", ":", "raise", "RuntimeError", "(", "\"Invalid ownership configuration: {}\"", ".", "format", "(", "key", ")", ")", "mode", "=", "options", ".", "get", "(", "'mode'", ",", "config", ".", "get", "(", "'permissions'", ",", "'600'", ")", ")", "optional", "=", "options", ".", "get", "(", "'optional'", ",", "config", ".", "get", "(", "'optional'", ",", "'False'", ")", ")", "if", "'*'", "in", "file_name", ":", "for", "file", "in", "glob", ".", "glob", "(", "file_name", ")", ":", "if", "file", "not", "in", "files", ".", "keys", "(", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "file", ")", ":", "_validate_file_mode", "(", "mode", ",", "file", ",", "optional", ")", "else", ":", "if", "os", ".", "path", ".", "isfile", "(", "file_name", ")", ":", "_validate_file_mode", "(", "mode", ",", "file_name", ",", "optional", ")" ]
Verify that permissions on configuration files are secure enough.
[ "Verify", "that", "permissions", "on", "configuration", "files", "are", "secure", "enough", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L220-L237
12,831
juju/charm-helpers
charmhelpers/contrib/openstack/audits/openstack_security_guide.py
validate_uses_tls_for_keystone
def validate_uses_tls_for_keystone(audit_options): """Verify that TLS is used to communicate with Keystone.""" section = _config_section(audit_options, 'keystone_authtoken') assert section is not None, "Missing section 'keystone_authtoken'" assert not section.get('insecure') and \ "https://" in section.get("auth_uri"), \ "TLS is not used for Keystone"
python
def validate_uses_tls_for_keystone(audit_options): """Verify that TLS is used to communicate with Keystone.""" section = _config_section(audit_options, 'keystone_authtoken') assert section is not None, "Missing section 'keystone_authtoken'" assert not section.get('insecure') and \ "https://" in section.get("auth_uri"), \ "TLS is not used for Keystone"
[ "def", "validate_uses_tls_for_keystone", "(", "audit_options", ")", ":", "section", "=", "_config_section", "(", "audit_options", ",", "'keystone_authtoken'", ")", "assert", "section", "is", "not", "None", ",", "\"Missing section 'keystone_authtoken'\"", "assert", "not", "section", ".", "get", "(", "'insecure'", ")", "and", "\"https://\"", "in", "section", ".", "get", "(", "\"auth_uri\"", ")", ",", "\"TLS is not used for Keystone\"" ]
Verify that TLS is used to communicate with Keystone.
[ "Verify", "that", "TLS", "is", "used", "to", "communicate", "with", "Keystone", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L250-L256
12,832
juju/charm-helpers
charmhelpers/contrib/openstack/audits/openstack_security_guide.py
validate_uses_tls_for_glance
def validate_uses_tls_for_glance(audit_options): """Verify that TLS is used to communicate with Glance.""" section = _config_section(audit_options, 'glance') assert section is not None, "Missing section 'glance'" assert not section.get('insecure') and \ "https://" in section.get("api_servers"), \ "TLS is not used for Glance"
python
def validate_uses_tls_for_glance(audit_options): """Verify that TLS is used to communicate with Glance.""" section = _config_section(audit_options, 'glance') assert section is not None, "Missing section 'glance'" assert not section.get('insecure') and \ "https://" in section.get("api_servers"), \ "TLS is not used for Glance"
[ "def", "validate_uses_tls_for_glance", "(", "audit_options", ")", ":", "section", "=", "_config_section", "(", "audit_options", ",", "'glance'", ")", "assert", "section", "is", "not", "None", ",", "\"Missing section 'glance'\"", "assert", "not", "section", ".", "get", "(", "'insecure'", ")", "and", "\"https://\"", "in", "section", ".", "get", "(", "\"api_servers\"", ")", ",", "\"TLS is not used for Glance\"" ]
Verify that TLS is used to communicate with Glance.
[ "Verify", "that", "TLS", "is", "used", "to", "communicate", "with", "Glance", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/openstack_security_guide.py#L260-L266
12,833
juju/charm-helpers
charmhelpers/core/services/helpers.py
RelationContext.is_ready
def is_ready(self): """ Returns True if all of the `required_keys` are available from any units. """ ready = len(self.get(self.name, [])) > 0 if not ready: hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG) return ready
python
def is_ready(self): """ Returns True if all of the `required_keys` are available from any units. """ ready = len(self.get(self.name, [])) > 0 if not ready: hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG) return ready
[ "def", "is_ready", "(", "self", ")", ":", "ready", "=", "len", "(", "self", ".", "get", "(", "self", ".", "name", ",", "[", "]", ")", ")", ">", "0", "if", "not", "ready", ":", "hookenv", ".", "log", "(", "'Incomplete relation: {}'", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", ",", "hookenv", ".", "DEBUG", ")", "return", "ready" ]
Returns True if all of the `required_keys` are available from any units.
[ "Returns", "True", "if", "all", "of", "the", "required_keys", "are", "available", "from", "any", "units", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/helpers.py#L70-L77
12,834
juju/charm-helpers
charmhelpers/core/services/helpers.py
RelationContext._is_ready
def _is_ready(self, unit_data): """ Helper method that tests a set of relation data and returns True if all of the `required_keys` are present. """ return set(unit_data.keys()).issuperset(set(self.required_keys))
python
def _is_ready(self, unit_data): """ Helper method that tests a set of relation data and returns True if all of the `required_keys` are present. """ return set(unit_data.keys()).issuperset(set(self.required_keys))
[ "def", "_is_ready", "(", "self", ",", "unit_data", ")", ":", "return", "set", "(", "unit_data", ".", "keys", "(", ")", ")", ".", "issuperset", "(", "set", "(", "self", ".", "required_keys", ")", ")" ]
Helper method that tests a set of relation data and returns True if all of the `required_keys` are present.
[ "Helper", "method", "that", "tests", "a", "set", "of", "relation", "data", "and", "returns", "True", "if", "all", "of", "the", "required_keys", "are", "present", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/helpers.py#L79-L84
12,835
juju/charm-helpers
charmhelpers/core/services/base.py
service_restart
def service_restart(service_name): """ Wrapper around host.service_restart to prevent spurious "unknown service" messages in the logs. """ if host.service_available(service_name): if host.service_running(service_name): host.service_restart(service_name) else: host.service_start(service_name)
python
def service_restart(service_name): """ Wrapper around host.service_restart to prevent spurious "unknown service" messages in the logs. """ if host.service_available(service_name): if host.service_running(service_name): host.service_restart(service_name) else: host.service_start(service_name)
[ "def", "service_restart", "(", "service_name", ")", ":", "if", "host", ".", "service_available", "(", "service_name", ")", ":", "if", "host", ".", "service_running", "(", "service_name", ")", ":", "host", ".", "service_restart", "(", "service_name", ")", "else", ":", "host", ".", "service_start", "(", "service_name", ")" ]
Wrapper around host.service_restart to prevent spurious "unknown service" messages in the logs.
[ "Wrapper", "around", "host", ".", "service_restart", "to", "prevent", "spurious", "unknown", "service", "messages", "in", "the", "logs", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L349-L358
12,836
juju/charm-helpers
charmhelpers/core/services/base.py
ServiceManager.manage
def manage(self): """ Handle the current hook by doing The Right Thing with the registered services. """ hookenv._run_atstart() try: hook_name = hookenv.hook_name() if hook_name == 'stop': self.stop_services() else: self.reconfigure_services() self.provide_data() except SystemExit as x: if x.code is None or x.code == 0: hookenv._run_atexit() hookenv._run_atexit()
python
def manage(self): """ Handle the current hook by doing The Right Thing with the registered services. """ hookenv._run_atstart() try: hook_name = hookenv.hook_name() if hook_name == 'stop': self.stop_services() else: self.reconfigure_services() self.provide_data() except SystemExit as x: if x.code is None or x.code == 0: hookenv._run_atexit() hookenv._run_atexit()
[ "def", "manage", "(", "self", ")", ":", "hookenv", ".", "_run_atstart", "(", ")", "try", ":", "hook_name", "=", "hookenv", ".", "hook_name", "(", ")", "if", "hook_name", "==", "'stop'", ":", "self", ".", "stop_services", "(", ")", "else", ":", "self", ".", "reconfigure_services", "(", ")", "self", ".", "provide_data", "(", ")", "except", "SystemExit", "as", "x", ":", "if", "x", ".", "code", "is", "None", "or", "x", ".", "code", "==", "0", ":", "hookenv", ".", "_run_atexit", "(", ")", "hookenv", ".", "_run_atexit", "(", ")" ]
Handle the current hook by doing The Right Thing with the registered services.
[ "Handle", "the", "current", "hook", "by", "doing", "The", "Right", "Thing", "with", "the", "registered", "services", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L125-L140
12,837
juju/charm-helpers
charmhelpers/core/services/base.py
ServiceManager.provide_data
def provide_data(self): """ Set the relation data for each provider in the ``provided_data`` list. A provider must have a `name` attribute, which indicates which relation to set data on, and a `provide_data()` method, which returns a dict of data to set. The `provide_data()` method can optionally accept two parameters: * ``remote_service`` The name of the remote service that the data will be provided to. The `provide_data()` method will be called once for each connected service (not unit). This allows the method to tailor its data to the given service. * ``service_ready`` Whether or not the service definition had all of its requirements met, and thus the ``data_ready`` callbacks run. Note that the ``provided_data`` methods are now called **after** the ``data_ready`` callbacks are run. This gives the ``data_ready`` callbacks a chance to generate any data necessary for the providing to the remote services. """ for service_name, service in self.services.items(): service_ready = self.is_ready(service_name) for provider in service.get('provided_data', []): for relid in hookenv.relation_ids(provider.name): units = hookenv.related_units(relid) if not units: continue remote_service = units[0].split('/')[0] argspec = getargspec(provider.provide_data) if len(argspec.args) > 1: data = provider.provide_data(remote_service, service_ready) else: data = provider.provide_data() if data: hookenv.relation_set(relid, data)
python
def provide_data(self): """ Set the relation data for each provider in the ``provided_data`` list. A provider must have a `name` attribute, which indicates which relation to set data on, and a `provide_data()` method, which returns a dict of data to set. The `provide_data()` method can optionally accept two parameters: * ``remote_service`` The name of the remote service that the data will be provided to. The `provide_data()` method will be called once for each connected service (not unit). This allows the method to tailor its data to the given service. * ``service_ready`` Whether or not the service definition had all of its requirements met, and thus the ``data_ready`` callbacks run. Note that the ``provided_data`` methods are now called **after** the ``data_ready`` callbacks are run. This gives the ``data_ready`` callbacks a chance to generate any data necessary for the providing to the remote services. """ for service_name, service in self.services.items(): service_ready = self.is_ready(service_name) for provider in service.get('provided_data', []): for relid in hookenv.relation_ids(provider.name): units = hookenv.related_units(relid) if not units: continue remote_service = units[0].split('/')[0] argspec = getargspec(provider.provide_data) if len(argspec.args) > 1: data = provider.provide_data(remote_service, service_ready) else: data = provider.provide_data() if data: hookenv.relation_set(relid, data)
[ "def", "provide_data", "(", "self", ")", ":", "for", "service_name", ",", "service", "in", "self", ".", "services", ".", "items", "(", ")", ":", "service_ready", "=", "self", ".", "is_ready", "(", "service_name", ")", "for", "provider", "in", "service", ".", "get", "(", "'provided_data'", ",", "[", "]", ")", ":", "for", "relid", "in", "hookenv", ".", "relation_ids", "(", "provider", ".", "name", ")", ":", "units", "=", "hookenv", ".", "related_units", "(", "relid", ")", "if", "not", "units", ":", "continue", "remote_service", "=", "units", "[", "0", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", "argspec", "=", "getargspec", "(", "provider", ".", "provide_data", ")", "if", "len", "(", "argspec", ".", "args", ")", ">", "1", ":", "data", "=", "provider", ".", "provide_data", "(", "remote_service", ",", "service_ready", ")", "else", ":", "data", "=", "provider", ".", "provide_data", "(", ")", "if", "data", ":", "hookenv", ".", "relation_set", "(", "relid", ",", "data", ")" ]
Set the relation data for each provider in the ``provided_data`` list. A provider must have a `name` attribute, which indicates which relation to set data on, and a `provide_data()` method, which returns a dict of data to set. The `provide_data()` method can optionally accept two parameters: * ``remote_service`` The name of the remote service that the data will be provided to. The `provide_data()` method will be called once for each connected service (not unit). This allows the method to tailor its data to the given service. * ``service_ready`` Whether or not the service definition had all of its requirements met, and thus the ``data_ready`` callbacks run. Note that the ``provided_data`` methods are now called **after** the ``data_ready`` callbacks are run. This gives the ``data_ready`` callbacks a chance to generate any data necessary for the providing to the remote services.
[ "Set", "the", "relation", "data", "for", "each", "provider", "in", "the", "provided_data", "list", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L142-L178
12,838
juju/charm-helpers
charmhelpers/core/services/base.py
ServiceManager.reconfigure_services
def reconfigure_services(self, *service_names): """ Update all files for one or more registered services, and, if ready, optionally restart them. If no service names are given, reconfigures all registered services. """ for service_name in service_names or self.services.keys(): if self.is_ready(service_name): self.fire_event('data_ready', service_name) self.fire_event('start', service_name, default=[ service_restart, manage_ports]) self.save_ready(service_name) else: if self.was_ready(service_name): self.fire_event('data_lost', service_name) self.fire_event('stop', service_name, default=[ manage_ports, service_stop]) self.save_lost(service_name)
python
def reconfigure_services(self, *service_names): """ Update all files for one or more registered services, and, if ready, optionally restart them. If no service names are given, reconfigures all registered services. """ for service_name in service_names or self.services.keys(): if self.is_ready(service_name): self.fire_event('data_ready', service_name) self.fire_event('start', service_name, default=[ service_restart, manage_ports]) self.save_ready(service_name) else: if self.was_ready(service_name): self.fire_event('data_lost', service_name) self.fire_event('stop', service_name, default=[ manage_ports, service_stop]) self.save_lost(service_name)
[ "def", "reconfigure_services", "(", "self", ",", "*", "service_names", ")", ":", "for", "service_name", "in", "service_names", "or", "self", ".", "services", ".", "keys", "(", ")", ":", "if", "self", ".", "is_ready", "(", "service_name", ")", ":", "self", ".", "fire_event", "(", "'data_ready'", ",", "service_name", ")", "self", ".", "fire_event", "(", "'start'", ",", "service_name", ",", "default", "=", "[", "service_restart", ",", "manage_ports", "]", ")", "self", ".", "save_ready", "(", "service_name", ")", "else", ":", "if", "self", ".", "was_ready", "(", "service_name", ")", ":", "self", ".", "fire_event", "(", "'data_lost'", ",", "service_name", ")", "self", ".", "fire_event", "(", "'stop'", ",", "service_name", ",", "default", "=", "[", "manage_ports", ",", "service_stop", "]", ")", "self", ".", "save_lost", "(", "service_name", ")" ]
Update all files for one or more registered services, and, if ready, optionally restart them. If no service names are given, reconfigures all registered services.
[ "Update", "all", "files", "for", "one", "or", "more", "registered", "services", "and", "if", "ready", "optionally", "restart", "them", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L180-L200
12,839
juju/charm-helpers
charmhelpers/core/services/base.py
ServiceManager.stop_services
def stop_services(self, *service_names): """ Stop one or more registered services, by name. If no service names are given, stops all registered services. """ for service_name in service_names or self.services.keys(): self.fire_event('stop', service_name, default=[ manage_ports, service_stop])
python
def stop_services(self, *service_names): """ Stop one or more registered services, by name. If no service names are given, stops all registered services. """ for service_name in service_names or self.services.keys(): self.fire_event('stop', service_name, default=[ manage_ports, service_stop])
[ "def", "stop_services", "(", "self", ",", "*", "service_names", ")", ":", "for", "service_name", "in", "service_names", "or", "self", ".", "services", ".", "keys", "(", ")", ":", "self", ".", "fire_event", "(", "'stop'", ",", "service_name", ",", "default", "=", "[", "manage_ports", ",", "service_stop", "]", ")" ]
Stop one or more registered services, by name. If no service names are given, stops all registered services.
[ "Stop", "one", "or", "more", "registered", "services", "by", "name", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L202-L211
12,840
juju/charm-helpers
charmhelpers/core/services/base.py
ServiceManager.get_service
def get_service(self, service_name): """ Given the name of a registered service, return its service definition. """ service = self.services.get(service_name) if not service: raise KeyError('Service not registered: %s' % service_name) return service
python
def get_service(self, service_name): """ Given the name of a registered service, return its service definition. """ service = self.services.get(service_name) if not service: raise KeyError('Service not registered: %s' % service_name) return service
[ "def", "get_service", "(", "self", ",", "service_name", ")", ":", "service", "=", "self", ".", "services", ".", "get", "(", "service_name", ")", "if", "not", "service", ":", "raise", "KeyError", "(", "'Service not registered: %s'", "%", "service_name", ")", "return", "service" ]
Given the name of a registered service, return its service definition.
[ "Given", "the", "name", "of", "a", "registered", "service", "return", "its", "service", "definition", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L213-L220
12,841
juju/charm-helpers
charmhelpers/core/services/base.py
ServiceManager.fire_event
def fire_event(self, event_name, service_name, default=None): """ Fire a data_ready, data_lost, start, or stop event on a given service. """ service = self.get_service(service_name) callbacks = service.get(event_name, default) if not callbacks: return if not isinstance(callbacks, Iterable): callbacks = [callbacks] for callback in callbacks: if isinstance(callback, ManagerCallback): callback(self, service_name, event_name) else: callback(service_name)
python
def fire_event(self, event_name, service_name, default=None): """ Fire a data_ready, data_lost, start, or stop event on a given service. """ service = self.get_service(service_name) callbacks = service.get(event_name, default) if not callbacks: return if not isinstance(callbacks, Iterable): callbacks = [callbacks] for callback in callbacks: if isinstance(callback, ManagerCallback): callback(self, service_name, event_name) else: callback(service_name)
[ "def", "fire_event", "(", "self", ",", "event_name", ",", "service_name", ",", "default", "=", "None", ")", ":", "service", "=", "self", ".", "get_service", "(", "service_name", ")", "callbacks", "=", "service", ".", "get", "(", "event_name", ",", "default", ")", "if", "not", "callbacks", ":", "return", "if", "not", "isinstance", "(", "callbacks", ",", "Iterable", ")", ":", "callbacks", "=", "[", "callbacks", "]", "for", "callback", "in", "callbacks", ":", "if", "isinstance", "(", "callback", ",", "ManagerCallback", ")", ":", "callback", "(", "self", ",", "service_name", ",", "event_name", ")", "else", ":", "callback", "(", "service_name", ")" ]
Fire a data_ready, data_lost, start, or stop event on a given service.
[ "Fire", "a", "data_ready", "data_lost", "start", "or", "stop", "event", "on", "a", "given", "service", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L222-L236
12,842
juju/charm-helpers
charmhelpers/core/services/base.py
ServiceManager.is_ready
def is_ready(self, service_name): """ Determine if a registered service is ready, by checking its 'required_data'. A 'required_data' item can be any mapping type, and is considered ready if `bool(item)` evaluates as True. """ service = self.get_service(service_name) reqs = service.get('required_data', []) return all(bool(req) for req in reqs)
python
def is_ready(self, service_name): """ Determine if a registered service is ready, by checking its 'required_data'. A 'required_data' item can be any mapping type, and is considered ready if `bool(item)` evaluates as True. """ service = self.get_service(service_name) reqs = service.get('required_data', []) return all(bool(req) for req in reqs)
[ "def", "is_ready", "(", "self", ",", "service_name", ")", ":", "service", "=", "self", ".", "get_service", "(", "service_name", ")", "reqs", "=", "service", ".", "get", "(", "'required_data'", ",", "[", "]", ")", "return", "all", "(", "bool", "(", "req", ")", "for", "req", "in", "reqs", ")" ]
Determine if a registered service is ready, by checking its 'required_data'. A 'required_data' item can be any mapping type, and is considered ready if `bool(item)` evaluates as True.
[ "Determine", "if", "a", "registered", "service", "is", "ready", "by", "checking", "its", "required_data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L238-L247
12,843
juju/charm-helpers
charmhelpers/core/services/base.py
ServiceManager.save_ready
def save_ready(self, service_name): """ Save an indicator that the given service is now data_ready. """ self._load_ready_file() self._ready.add(service_name) self._save_ready_file()
python
def save_ready(self, service_name): """ Save an indicator that the given service is now data_ready. """ self._load_ready_file() self._ready.add(service_name) self._save_ready_file()
[ "def", "save_ready", "(", "self", ",", "service_name", ")", ":", "self", ".", "_load_ready_file", "(", ")", "self", ".", "_ready", ".", "add", "(", "service_name", ")", "self", ".", "_save_ready_file", "(", ")" ]
Save an indicator that the given service is now data_ready.
[ "Save", "an", "indicator", "that", "the", "given", "service", "is", "now", "data_ready", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L264-L270
12,844
juju/charm-helpers
charmhelpers/core/services/base.py
ServiceManager.save_lost
def save_lost(self, service_name): """ Save an indicator that the given service is no longer data_ready. """ self._load_ready_file() self._ready.discard(service_name) self._save_ready_file()
python
def save_lost(self, service_name): """ Save an indicator that the given service is no longer data_ready. """ self._load_ready_file() self._ready.discard(service_name) self._save_ready_file()
[ "def", "save_lost", "(", "self", ",", "service_name", ")", ":", "self", ".", "_load_ready_file", "(", ")", "self", ".", "_ready", ".", "discard", "(", "service_name", ")", "self", ".", "_save_ready_file", "(", ")" ]
Save an indicator that the given service is no longer data_ready.
[ "Save", "an", "indicator", "that", "the", "given", "service", "is", "no", "longer", "data_ready", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/services/base.py#L272-L278
12,845
juju/charm-helpers
charmhelpers/contrib/network/ufw.py
is_enabled
def is_enabled(): """ Check if `ufw` is enabled :returns: True if ufw is enabled """ output = subprocess.check_output(['ufw', 'status'], universal_newlines=True, env={'LANG': 'en_US', 'PATH': os.environ['PATH']}) m = re.findall(r'^Status: active\n', output, re.M) return len(m) >= 1
python
def is_enabled(): """ Check if `ufw` is enabled :returns: True if ufw is enabled """ output = subprocess.check_output(['ufw', 'status'], universal_newlines=True, env={'LANG': 'en_US', 'PATH': os.environ['PATH']}) m = re.findall(r'^Status: active\n', output, re.M) return len(m) >= 1
[ "def", "is_enabled", "(", ")", ":", "output", "=", "subprocess", ".", "check_output", "(", "[", "'ufw'", ",", "'status'", "]", ",", "universal_newlines", "=", "True", ",", "env", "=", "{", "'LANG'", ":", "'en_US'", ",", "'PATH'", ":", "os", ".", "environ", "[", "'PATH'", "]", "}", ")", "m", "=", "re", ".", "findall", "(", "r'^Status: active\\n'", ",", "output", ",", "re", ".", "M", ")", "return", "len", "(", "m", ")", ">=", "1" ]
Check if `ufw` is enabled :returns: True if ufw is enabled
[ "Check", "if", "ufw", "is", "enabled" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L56-L69
12,846
juju/charm-helpers
charmhelpers/contrib/network/ufw.py
is_ipv6_ok
def is_ipv6_ok(soft_fail=False): """ Check if IPv6 support is present and ip6tables functional :param soft_fail: If set to True and IPv6 support is broken, then reports that the host doesn't have IPv6 support, otherwise a UFWIPv6Error exception is raised. :returns: True if IPv6 is working, False otherwise """ # do we have IPv6 in the machine? if os.path.isdir('/proc/sys/net/ipv6'): # is ip6tables kernel module loaded? if not is_module_loaded('ip6_tables'): # ip6tables support isn't complete, let's try to load it try: modprobe('ip6_tables') # great, we can load the module return True except subprocess.CalledProcessError as ex: hookenv.log("Couldn't load ip6_tables module: %s" % ex.output, level="WARN") # we are in a world where ip6tables isn't working if soft_fail: # so we inform that the machine doesn't have IPv6 return False else: raise UFWIPv6Error("IPv6 firewall support broken") else: # the module is present :) return True else: # the system doesn't have IPv6 return False
python
def is_ipv6_ok(soft_fail=False): """ Check if IPv6 support is present and ip6tables functional :param soft_fail: If set to True and IPv6 support is broken, then reports that the host doesn't have IPv6 support, otherwise a UFWIPv6Error exception is raised. :returns: True if IPv6 is working, False otherwise """ # do we have IPv6 in the machine? if os.path.isdir('/proc/sys/net/ipv6'): # is ip6tables kernel module loaded? if not is_module_loaded('ip6_tables'): # ip6tables support isn't complete, let's try to load it try: modprobe('ip6_tables') # great, we can load the module return True except subprocess.CalledProcessError as ex: hookenv.log("Couldn't load ip6_tables module: %s" % ex.output, level="WARN") # we are in a world where ip6tables isn't working if soft_fail: # so we inform that the machine doesn't have IPv6 return False else: raise UFWIPv6Error("IPv6 firewall support broken") else: # the module is present :) return True else: # the system doesn't have IPv6 return False
[ "def", "is_ipv6_ok", "(", "soft_fail", "=", "False", ")", ":", "# do we have IPv6 in the machine?", "if", "os", ".", "path", ".", "isdir", "(", "'/proc/sys/net/ipv6'", ")", ":", "# is ip6tables kernel module loaded?", "if", "not", "is_module_loaded", "(", "'ip6_tables'", ")", ":", "# ip6tables support isn't complete, let's try to load it", "try", ":", "modprobe", "(", "'ip6_tables'", ")", "# great, we can load the module", "return", "True", "except", "subprocess", ".", "CalledProcessError", "as", "ex", ":", "hookenv", ".", "log", "(", "\"Couldn't load ip6_tables module: %s\"", "%", "ex", ".", "output", ",", "level", "=", "\"WARN\"", ")", "# we are in a world where ip6tables isn't working", "if", "soft_fail", ":", "# so we inform that the machine doesn't have IPv6", "return", "False", "else", ":", "raise", "UFWIPv6Error", "(", "\"IPv6 firewall support broken\"", ")", "else", ":", "# the module is present :)", "return", "True", "else", ":", "# the system doesn't have IPv6", "return", "False" ]
Check if IPv6 support is present and ip6tables functional :param soft_fail: If set to True and IPv6 support is broken, then reports that the host doesn't have IPv6 support, otherwise a UFWIPv6Error exception is raised. :returns: True if IPv6 is working, False otherwise
[ "Check", "if", "IPv6", "support", "is", "present", "and", "ip6tables", "functional" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L72-L106
12,847
juju/charm-helpers
charmhelpers/contrib/network/ufw.py
default_policy
def default_policy(policy='deny', direction='incoming'): """ Changes the default policy for traffic `direction` :param policy: allow, deny or reject :param direction: traffic direction, possible values: incoming, outgoing, routed """ if policy not in ['allow', 'deny', 'reject']: raise UFWError(('Unknown policy %s, valid values: ' 'allow, deny, reject') % policy) if direction not in ['incoming', 'outgoing', 'routed']: raise UFWError(('Unknown direction %s, valid values: ' 'incoming, outgoing, routed') % direction) output = subprocess.check_output(['ufw', 'default', policy, direction], universal_newlines=True, env={'LANG': 'en_US', 'PATH': os.environ['PATH']}) hookenv.log(output, level='DEBUG') m = re.findall("^Default %s policy changed to '%s'\n" % (direction, policy), output, re.M) if len(m) == 0: hookenv.log("ufw couldn't change the default policy to %s for %s" % (policy, direction), level='WARN') return False else: hookenv.log("ufw default policy for %s changed to %s" % (direction, policy), level='INFO') return True
python
def default_policy(policy='deny', direction='incoming'): """ Changes the default policy for traffic `direction` :param policy: allow, deny or reject :param direction: traffic direction, possible values: incoming, outgoing, routed """ if policy not in ['allow', 'deny', 'reject']: raise UFWError(('Unknown policy %s, valid values: ' 'allow, deny, reject') % policy) if direction not in ['incoming', 'outgoing', 'routed']: raise UFWError(('Unknown direction %s, valid values: ' 'incoming, outgoing, routed') % direction) output = subprocess.check_output(['ufw', 'default', policy, direction], universal_newlines=True, env={'LANG': 'en_US', 'PATH': os.environ['PATH']}) hookenv.log(output, level='DEBUG') m = re.findall("^Default %s policy changed to '%s'\n" % (direction, policy), output, re.M) if len(m) == 0: hookenv.log("ufw couldn't change the default policy to %s for %s" % (policy, direction), level='WARN') return False else: hookenv.log("ufw default policy for %s changed to %s" % (direction, policy), level='INFO') return True
[ "def", "default_policy", "(", "policy", "=", "'deny'", ",", "direction", "=", "'incoming'", ")", ":", "if", "policy", "not", "in", "[", "'allow'", ",", "'deny'", ",", "'reject'", "]", ":", "raise", "UFWError", "(", "(", "'Unknown policy %s, valid values: '", "'allow, deny, reject'", ")", "%", "policy", ")", "if", "direction", "not", "in", "[", "'incoming'", ",", "'outgoing'", ",", "'routed'", "]", ":", "raise", "UFWError", "(", "(", "'Unknown direction %s, valid values: '", "'incoming, outgoing, routed'", ")", "%", "direction", ")", "output", "=", "subprocess", ".", "check_output", "(", "[", "'ufw'", ",", "'default'", ",", "policy", ",", "direction", "]", ",", "universal_newlines", "=", "True", ",", "env", "=", "{", "'LANG'", ":", "'en_US'", ",", "'PATH'", ":", "os", ".", "environ", "[", "'PATH'", "]", "}", ")", "hookenv", ".", "log", "(", "output", ",", "level", "=", "'DEBUG'", ")", "m", "=", "re", ".", "findall", "(", "\"^Default %s policy changed to '%s'\\n\"", "%", "(", "direction", ",", "policy", ")", ",", "output", ",", "re", ".", "M", ")", "if", "len", "(", "m", ")", "==", "0", ":", "hookenv", ".", "log", "(", "\"ufw couldn't change the default policy to %s for %s\"", "%", "(", "policy", ",", "direction", ")", ",", "level", "=", "'WARN'", ")", "return", "False", "else", ":", "hookenv", ".", "log", "(", "\"ufw default policy for %s changed to %s\"", "%", "(", "direction", ",", "policy", ")", ",", "level", "=", "'INFO'", ")", "return", "True" ]
Changes the default policy for traffic `direction` :param policy: allow, deny or reject :param direction: traffic direction, possible values: incoming, outgoing, routed
[ "Changes", "the", "default", "policy", "for", "traffic", "direction" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L203-L235
12,848
juju/charm-helpers
charmhelpers/contrib/network/ufw.py
revoke_access
def revoke_access(src, dst='any', port=None, proto=None): """ Revoke access to an address or subnet :param src: address (e.g. 192.168.1.234) or subnet (e.g. 192.168.1.0/24). :param dst: destiny of the connection, if the machine has multiple IPs and connections to only one of those have to accepted this is the field has to be set. :param port: destiny port :param proto: protocol (tcp or udp) """ return modify_access(src, dst=dst, port=port, proto=proto, action='delete')
python
def revoke_access(src, dst='any', port=None, proto=None): """ Revoke access to an address or subnet :param src: address (e.g. 192.168.1.234) or subnet (e.g. 192.168.1.0/24). :param dst: destiny of the connection, if the machine has multiple IPs and connections to only one of those have to accepted this is the field has to be set. :param port: destiny port :param proto: protocol (tcp or udp) """ return modify_access(src, dst=dst, port=port, proto=proto, action='delete')
[ "def", "revoke_access", "(", "src", ",", "dst", "=", "'any'", ",", "port", "=", "None", ",", "proto", "=", "None", ")", ":", "return", "modify_access", "(", "src", ",", "dst", "=", "dst", ",", "port", "=", "port", ",", "proto", "=", "proto", ",", "action", "=", "'delete'", ")" ]
Revoke access to an address or subnet :param src: address (e.g. 192.168.1.234) or subnet (e.g. 192.168.1.0/24). :param dst: destiny of the connection, if the machine has multiple IPs and connections to only one of those have to accepted this is the field has to be set. :param port: destiny port :param proto: protocol (tcp or udp)
[ "Revoke", "access", "to", "an", "address", "or", "subnet" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ufw.py#L308-L320
12,849
juju/charm-helpers
charmhelpers/core/kernel.py
rmmod
def rmmod(module, force=False): """Remove a module from the linux kernel""" cmd = ['rmmod'] if force: cmd.append('-f') cmd.append(module) log('Removing kernel module %s' % module, level=INFO) return subprocess.check_call(cmd)
python
def rmmod(module, force=False): """Remove a module from the linux kernel""" cmd = ['rmmod'] if force: cmd.append('-f') cmd.append(module) log('Removing kernel module %s' % module, level=INFO) return subprocess.check_call(cmd)
[ "def", "rmmod", "(", "module", ",", "force", "=", "False", ")", ":", "cmd", "=", "[", "'rmmod'", "]", "if", "force", ":", "cmd", ".", "append", "(", "'-f'", ")", "cmd", ".", "append", "(", "module", ")", "log", "(", "'Removing kernel module %s'", "%", "module", ",", "level", "=", "INFO", ")", "return", "subprocess", ".", "check_call", "(", "cmd", ")" ]
Remove a module from the linux kernel
[ "Remove", "a", "module", "from", "the", "linux", "kernel" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/kernel.py#L53-L60
12,850
juju/charm-helpers
charmhelpers/core/kernel.py
is_module_loaded
def is_module_loaded(module): """Checks if a kernel module is already loaded""" matches = re.findall('^%s[ ]+' % module, lsmod(), re.M) return len(matches) > 0
python
def is_module_loaded(module): """Checks if a kernel module is already loaded""" matches = re.findall('^%s[ ]+' % module, lsmod(), re.M) return len(matches) > 0
[ "def", "is_module_loaded", "(", "module", ")", ":", "matches", "=", "re", ".", "findall", "(", "'^%s[ ]+'", "%", "module", ",", "lsmod", "(", ")", ",", "re", ".", "M", ")", "return", "len", "(", "matches", ")", ">", "0" ]
Checks if a kernel module is already loaded
[ "Checks", "if", "a", "kernel", "module", "is", "already", "loaded" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/kernel.py#L69-L72
12,851
juju/charm-helpers
charmhelpers/contrib/charmsupport/volumes.py
get_config
def get_config(): '''Gather and sanity-check volume configuration data''' volume_config = {} config = hookenv.config() errors = False if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'): volume_config['ephemeral'] = True else: volume_config['ephemeral'] = False try: volume_map = yaml.safe_load(config.get('volume-map', '{}')) except yaml.YAMLError as e: hookenv.log("Error parsing YAML volume-map: {}".format(e), hookenv.ERROR) errors = True if volume_map is None: # probably an empty string volume_map = {} elif not isinstance(volume_map, dict): hookenv.log("Volume-map should be a dictionary, not {}".format( type(volume_map))) errors = True volume_config['device'] = volume_map.get(os.environ['JUJU_UNIT_NAME']) if volume_config['device'] and volume_config['ephemeral']: # asked for ephemeral storage but also defined a volume ID hookenv.log('A volume is defined for this unit, but ephemeral ' 'storage was requested', hookenv.ERROR) errors = True elif not volume_config['device'] and not volume_config['ephemeral']: # asked for permanent storage but did not define volume ID hookenv.log('Ephemeral storage was requested, but there is no volume ' 'defined for this unit.', hookenv.ERROR) errors = True unit_mount_name = hookenv.local_unit().replace('/', '-') volume_config['mountpoint'] = os.path.join(MOUNT_BASE, unit_mount_name) if errors: return None return volume_config
python
def get_config(): '''Gather and sanity-check volume configuration data''' volume_config = {} config = hookenv.config() errors = False if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'): volume_config['ephemeral'] = True else: volume_config['ephemeral'] = False try: volume_map = yaml.safe_load(config.get('volume-map', '{}')) except yaml.YAMLError as e: hookenv.log("Error parsing YAML volume-map: {}".format(e), hookenv.ERROR) errors = True if volume_map is None: # probably an empty string volume_map = {} elif not isinstance(volume_map, dict): hookenv.log("Volume-map should be a dictionary, not {}".format( type(volume_map))) errors = True volume_config['device'] = volume_map.get(os.environ['JUJU_UNIT_NAME']) if volume_config['device'] and volume_config['ephemeral']: # asked for ephemeral storage but also defined a volume ID hookenv.log('A volume is defined for this unit, but ephemeral ' 'storage was requested', hookenv.ERROR) errors = True elif not volume_config['device'] and not volume_config['ephemeral']: # asked for permanent storage but did not define volume ID hookenv.log('Ephemeral storage was requested, but there is no volume ' 'defined for this unit.', hookenv.ERROR) errors = True unit_mount_name = hookenv.local_unit().replace('/', '-') volume_config['mountpoint'] = os.path.join(MOUNT_BASE, unit_mount_name) if errors: return None return volume_config
[ "def", "get_config", "(", ")", ":", "volume_config", "=", "{", "}", "config", "=", "hookenv", ".", "config", "(", ")", "errors", "=", "False", "if", "config", ".", "get", "(", "'volume-ephemeral'", ")", "in", "(", "True", ",", "'True'", ",", "'true'", ",", "'Yes'", ",", "'yes'", ")", ":", "volume_config", "[", "'ephemeral'", "]", "=", "True", "else", ":", "volume_config", "[", "'ephemeral'", "]", "=", "False", "try", ":", "volume_map", "=", "yaml", ".", "safe_load", "(", "config", ".", "get", "(", "'volume-map'", ",", "'{}'", ")", ")", "except", "yaml", ".", "YAMLError", "as", "e", ":", "hookenv", ".", "log", "(", "\"Error parsing YAML volume-map: {}\"", ".", "format", "(", "e", ")", ",", "hookenv", ".", "ERROR", ")", "errors", "=", "True", "if", "volume_map", "is", "None", ":", "# probably an empty string", "volume_map", "=", "{", "}", "elif", "not", "isinstance", "(", "volume_map", ",", "dict", ")", ":", "hookenv", ".", "log", "(", "\"Volume-map should be a dictionary, not {}\"", ".", "format", "(", "type", "(", "volume_map", ")", ")", ")", "errors", "=", "True", "volume_config", "[", "'device'", "]", "=", "volume_map", ".", "get", "(", "os", ".", "environ", "[", "'JUJU_UNIT_NAME'", "]", ")", "if", "volume_config", "[", "'device'", "]", "and", "volume_config", "[", "'ephemeral'", "]", ":", "# asked for ephemeral storage but also defined a volume ID", "hookenv", ".", "log", "(", "'A volume is defined for this unit, but ephemeral '", "'storage was requested'", ",", "hookenv", ".", "ERROR", ")", "errors", "=", "True", "elif", "not", "volume_config", "[", "'device'", "]", "and", "not", "volume_config", "[", "'ephemeral'", "]", ":", "# asked for permanent storage but did not define volume ID", "hookenv", ".", "log", "(", "'Ephemeral storage was requested, but there is no volume '", "'defined for this unit.'", ",", "hookenv", ".", "ERROR", ")", "errors", "=", "True", "unit_mount_name", "=", "hookenv", ".", "local_unit", "(", ")", ".", "replace", "(", "'/'", ",", "'-'", ")", "volume_config", "[", "'mountpoint'", "]", "=", "os", ".", "path", ".", "join", "(", "MOUNT_BASE", ",", "unit_mount_name", ")", "if", "errors", ":", "return", "None", "return", "volume_config" ]
Gather and sanity-check volume configuration data
[ "Gather", "and", "sanity", "-", "check", "volume", "configuration", "data" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmsupport/volumes.py#L73-L116
12,852
juju/charm-helpers
charmhelpers/contrib/hardening/host/checks/limits.py
get_audits
def get_audits(): """Get OS hardening security limits audits. :returns: dictionary of audits """ audits = [] settings = utils.get_settings('os') # Ensure that the /etc/security/limits.d directory is only writable # by the root user, but others can execute and read. audits.append(DirectoryPermissionAudit('/etc/security/limits.d', user='root', group='root', mode=0o755)) # If core dumps are not enabled, then don't allow core dumps to be # created as they may contain sensitive information. if not settings['security']['kernel_enable_core_dump']: audits.append(TemplatedFile('/etc/security/limits.d/10.hardcore.conf', SecurityLimitsContext(), template_dir=TEMPLATES_DIR, user='root', group='root', mode=0o0440)) return audits
python
def get_audits(): """Get OS hardening security limits audits. :returns: dictionary of audits """ audits = [] settings = utils.get_settings('os') # Ensure that the /etc/security/limits.d directory is only writable # by the root user, but others can execute and read. audits.append(DirectoryPermissionAudit('/etc/security/limits.d', user='root', group='root', mode=0o755)) # If core dumps are not enabled, then don't allow core dumps to be # created as they may contain sensitive information. if not settings['security']['kernel_enable_core_dump']: audits.append(TemplatedFile('/etc/security/limits.d/10.hardcore.conf', SecurityLimitsContext(), template_dir=TEMPLATES_DIR, user='root', group='root', mode=0o0440)) return audits
[ "def", "get_audits", "(", ")", ":", "audits", "=", "[", "]", "settings", "=", "utils", ".", "get_settings", "(", "'os'", ")", "# Ensure that the /etc/security/limits.d directory is only writable", "# by the root user, but others can execute and read.", "audits", ".", "append", "(", "DirectoryPermissionAudit", "(", "'/etc/security/limits.d'", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ",", "mode", "=", "0o755", ")", ")", "# If core dumps are not enabled, then don't allow core dumps to be", "# created as they may contain sensitive information.", "if", "not", "settings", "[", "'security'", "]", "[", "'kernel_enable_core_dump'", "]", ":", "audits", ".", "append", "(", "TemplatedFile", "(", "'/etc/security/limits.d/10.hardcore.conf'", ",", "SecurityLimitsContext", "(", ")", ",", "template_dir", "=", "TEMPLATES_DIR", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ",", "mode", "=", "0o0440", ")", ")", "return", "audits" ]
Get OS hardening security limits audits. :returns: dictionary of audits
[ "Get", "OS", "hardening", "security", "limits", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/limits.py#L23-L44
12,853
juju/charm-helpers
charmhelpers/contrib/hardening/audits/__init__.py
BaseAudit._take_action
def _take_action(self): """Determines whether to perform the action or not. Checks whether or not an action should be taken. This is determined by the truthy value for the unless parameter. If unless is a callback method, it will be invoked with no parameters in order to determine whether or not the action should be taken. Otherwise, the truthy value of the unless attribute will determine if the action should be performed. """ # Do the action if there isn't an unless override. if self.unless is None: return True # Invoke the callback if there is one. if hasattr(self.unless, '__call__'): return not self.unless() return not self.unless
python
def _take_action(self): """Determines whether to perform the action or not. Checks whether or not an action should be taken. This is determined by the truthy value for the unless parameter. If unless is a callback method, it will be invoked with no parameters in order to determine whether or not the action should be taken. Otherwise, the truthy value of the unless attribute will determine if the action should be performed. """ # Do the action if there isn't an unless override. if self.unless is None: return True # Invoke the callback if there is one. if hasattr(self.unless, '__call__'): return not self.unless() return not self.unless
[ "def", "_take_action", "(", "self", ")", ":", "# Do the action if there isn't an unless override.", "if", "self", ".", "unless", "is", "None", ":", "return", "True", "# Invoke the callback if there is one.", "if", "hasattr", "(", "self", ".", "unless", ",", "'__call__'", ")", ":", "return", "not", "self", ".", "unless", "(", ")", "return", "not", "self", ".", "unless" ]
Determines whether to perform the action or not. Checks whether or not an action should be taken. This is determined by the truthy value for the unless parameter. If unless is a callback method, it will be invoked with no parameters in order to determine whether or not the action should be taken. Otherwise, the truthy value of the unless attribute will determine if the action should be performed.
[ "Determines", "whether", "to", "perform", "the", "action", "or", "not", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/__init__.py#L36-L54
12,854
juju/charm-helpers
charmhelpers/contrib/openstack/alternatives.py
install_alternative
def install_alternative(name, target, source, priority=50): ''' Install alternative configuration ''' if (os.path.exists(target) and not os.path.islink(target)): # Move existing file/directory away before installing shutil.move(target, '{}.bak'.format(target)) cmd = [ 'update-alternatives', '--force', '--install', target, name, source, str(priority) ] subprocess.check_call(cmd)
python
def install_alternative(name, target, source, priority=50): ''' Install alternative configuration ''' if (os.path.exists(target) and not os.path.islink(target)): # Move existing file/directory away before installing shutil.move(target, '{}.bak'.format(target)) cmd = [ 'update-alternatives', '--force', '--install', target, name, source, str(priority) ] subprocess.check_call(cmd)
[ "def", "install_alternative", "(", "name", ",", "target", ",", "source", ",", "priority", "=", "50", ")", ":", "if", "(", "os", ".", "path", ".", "exists", "(", "target", ")", "and", "not", "os", ".", "path", ".", "islink", "(", "target", ")", ")", ":", "# Move existing file/directory away before installing", "shutil", ".", "move", "(", "target", ",", "'{}.bak'", ".", "format", "(", "target", ")", ")", "cmd", "=", "[", "'update-alternatives'", ",", "'--force'", ",", "'--install'", ",", "target", ",", "name", ",", "source", ",", "str", "(", "priority", ")", "]", "subprocess", ".", "check_call", "(", "cmd", ")" ]
Install alternative configuration
[ "Install", "alternative", "configuration" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/alternatives.py#L22-L31
12,855
juju/charm-helpers
charmhelpers/contrib/openstack/context.py
ensure_packages
def ensure_packages(packages): """Install but do not upgrade required plugin packages.""" required = filter_installed_packages(packages) if required: apt_install(required, fatal=True)
python
def ensure_packages(packages): """Install but do not upgrade required plugin packages.""" required = filter_installed_packages(packages) if required: apt_install(required, fatal=True)
[ "def", "ensure_packages", "(", "packages", ")", ":", "required", "=", "filter_installed_packages", "(", "packages", ")", "if", "required", ":", "apt_install", "(", "required", ",", "fatal", "=", "True", ")" ]
Install but do not upgrade required plugin packages.
[ "Install", "but", "do", "not", "upgrade", "required", "plugin", "packages", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L123-L127
12,856
juju/charm-helpers
charmhelpers/contrib/openstack/context.py
_calculate_workers
def _calculate_workers(): ''' Determine the number of worker processes based on the CPU count of the unit containing the application. Workers will be limited to MAX_DEFAULT_WORKERS in container environments where no worker-multipler configuration option been set. @returns int: number of worker processes to use ''' multiplier = config('worker-multiplier') or DEFAULT_MULTIPLIER count = int(_num_cpus() * multiplier) if multiplier > 0 and count == 0: count = 1 if config('worker-multiplier') is None and is_container(): # NOTE(jamespage): Limit unconfigured worker-multiplier # to MAX_DEFAULT_WORKERS to avoid insane # worker configuration in LXD containers # on large servers # Reference: https://pad.lv/1665270 count = min(count, MAX_DEFAULT_WORKERS) return count
python
def _calculate_workers(): ''' Determine the number of worker processes based on the CPU count of the unit containing the application. Workers will be limited to MAX_DEFAULT_WORKERS in container environments where no worker-multipler configuration option been set. @returns int: number of worker processes to use ''' multiplier = config('worker-multiplier') or DEFAULT_MULTIPLIER count = int(_num_cpus() * multiplier) if multiplier > 0 and count == 0: count = 1 if config('worker-multiplier') is None and is_container(): # NOTE(jamespage): Limit unconfigured worker-multiplier # to MAX_DEFAULT_WORKERS to avoid insane # worker configuration in LXD containers # on large servers # Reference: https://pad.lv/1665270 count = min(count, MAX_DEFAULT_WORKERS) return count
[ "def", "_calculate_workers", "(", ")", ":", "multiplier", "=", "config", "(", "'worker-multiplier'", ")", "or", "DEFAULT_MULTIPLIER", "count", "=", "int", "(", "_num_cpus", "(", ")", "*", "multiplier", ")", "if", "multiplier", ">", "0", "and", "count", "==", "0", ":", "count", "=", "1", "if", "config", "(", "'worker-multiplier'", ")", "is", "None", "and", "is_container", "(", ")", ":", "# NOTE(jamespage): Limit unconfigured worker-multiplier", "# to MAX_DEFAULT_WORKERS to avoid insane", "# worker configuration in LXD containers", "# on large servers", "# Reference: https://pad.lv/1665270", "count", "=", "min", "(", "count", ",", "MAX_DEFAULT_WORKERS", ")", "return", "count" ]
Determine the number of worker processes based on the CPU count of the unit containing the application. Workers will be limited to MAX_DEFAULT_WORKERS in container environments where no worker-multipler configuration option been set. @returns int: number of worker processes to use
[ "Determine", "the", "number", "of", "worker", "processes", "based", "on", "the", "CPU", "count", "of", "the", "unit", "containing", "the", "application", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1355-L1379
12,857
juju/charm-helpers
charmhelpers/contrib/openstack/context.py
OSContextGenerator.get_related
def get_related(self): """Check if any of the context interfaces have relation ids. Set self.related and return True if one of the interfaces has relation ids. """ # Fresh start self.related = False try: for interface in self.interfaces: if relation_ids(interface): self.related = True return self.related except AttributeError as e: log("{} {}" "".format(self, e), 'INFO') return self.related
python
def get_related(self): """Check if any of the context interfaces have relation ids. Set self.related and return True if one of the interfaces has relation ids. """ # Fresh start self.related = False try: for interface in self.interfaces: if relation_ids(interface): self.related = True return self.related except AttributeError as e: log("{} {}" "".format(self, e), 'INFO') return self.related
[ "def", "get_related", "(", "self", ")", ":", "# Fresh start", "self", ".", "related", "=", "False", "try", ":", "for", "interface", "in", "self", ".", "interfaces", ":", "if", "relation_ids", "(", "interface", ")", ":", "self", ".", "related", "=", "True", "return", "self", ".", "related", "except", "AttributeError", "as", "e", ":", "log", "(", "\"{} {}\"", "\"\"", ".", "format", "(", "self", ",", "e", ")", ",", "'INFO'", ")", "return", "self", ".", "related" ]
Check if any of the context interfaces have relation ids. Set self.related and return True if one of the interfaces has relation ids.
[ "Check", "if", "any", "of", "the", "context", "interfaces", "have", "relation", "ids", ".", "Set", "self", ".", "related", "and", "return", "True", "if", "one", "of", "the", "interfaces", "has", "relation", "ids", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L174-L189
12,858
juju/charm-helpers
charmhelpers/contrib/openstack/context.py
ApacheSSLContext.canonical_names
def canonical_names(self): """Figure out which canonical names clients will access this service. """ cns = [] for r_id in relation_ids('identity-service'): for unit in related_units(r_id): rdata = relation_get(rid=r_id, unit=unit) for k in rdata: if k.startswith('ssl_key_'): cns.append(k.lstrip('ssl_key_')) return sorted(list(set(cns)))
python
def canonical_names(self): """Figure out which canonical names clients will access this service. """ cns = [] for r_id in relation_ids('identity-service'): for unit in related_units(r_id): rdata = relation_get(rid=r_id, unit=unit) for k in rdata: if k.startswith('ssl_key_'): cns.append(k.lstrip('ssl_key_')) return sorted(list(set(cns)))
[ "def", "canonical_names", "(", "self", ")", ":", "cns", "=", "[", "]", "for", "r_id", "in", "relation_ids", "(", "'identity-service'", ")", ":", "for", "unit", "in", "related_units", "(", "r_id", ")", ":", "rdata", "=", "relation_get", "(", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "for", "k", "in", "rdata", ":", "if", "k", ".", "startswith", "(", "'ssl_key_'", ")", ":", "cns", ".", "append", "(", "k", ".", "lstrip", "(", "'ssl_key_'", ")", ")", "return", "sorted", "(", "list", "(", "set", "(", "cns", ")", ")", ")" ]
Figure out which canonical names clients will access this service.
[ "Figure", "out", "which", "canonical", "names", "clients", "will", "access", "this", "service", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L835-L846
12,859
juju/charm-helpers
charmhelpers/contrib/openstack/context.py
VolumeAPIContext._determine_ctxt
def _determine_ctxt(self): """Determines the Volume API endpoint information. Determines the appropriate version of the API that should be used as well as the catalog_info string that would be supplied. Returns a dict containing the volume_api_version and the volume_catalog_info. """ rel = os_release(self.pkg, base='icehouse') version = '2' if CompareOpenStackReleases(rel) >= 'pike': version = '3' service_type = 'volumev{version}'.format(version=version) service_name = 'cinderv{version}'.format(version=version) endpoint_type = 'publicURL' if config('use-internal-endpoints'): endpoint_type = 'internalURL' catalog_info = '{type}:{name}:{endpoint}'.format( type=service_type, name=service_name, endpoint=endpoint_type) return { 'volume_api_version': version, 'volume_catalog_info': catalog_info, }
python
def _determine_ctxt(self): """Determines the Volume API endpoint information. Determines the appropriate version of the API that should be used as well as the catalog_info string that would be supplied. Returns a dict containing the volume_api_version and the volume_catalog_info. """ rel = os_release(self.pkg, base='icehouse') version = '2' if CompareOpenStackReleases(rel) >= 'pike': version = '3' service_type = 'volumev{version}'.format(version=version) service_name = 'cinderv{version}'.format(version=version) endpoint_type = 'publicURL' if config('use-internal-endpoints'): endpoint_type = 'internalURL' catalog_info = '{type}:{name}:{endpoint}'.format( type=service_type, name=service_name, endpoint=endpoint_type) return { 'volume_api_version': version, 'volume_catalog_info': catalog_info, }
[ "def", "_determine_ctxt", "(", "self", ")", ":", "rel", "=", "os_release", "(", "self", ".", "pkg", ",", "base", "=", "'icehouse'", ")", "version", "=", "'2'", "if", "CompareOpenStackReleases", "(", "rel", ")", ">=", "'pike'", ":", "version", "=", "'3'", "service_type", "=", "'volumev{version}'", ".", "format", "(", "version", "=", "version", ")", "service_name", "=", "'cinderv{version}'", ".", "format", "(", "version", "=", "version", ")", "endpoint_type", "=", "'publicURL'", "if", "config", "(", "'use-internal-endpoints'", ")", ":", "endpoint_type", "=", "'internalURL'", "catalog_info", "=", "'{type}:{name}:{endpoint}'", ".", "format", "(", "type", "=", "service_type", ",", "name", "=", "service_name", ",", "endpoint", "=", "endpoint_type", ")", "return", "{", "'volume_api_version'", ":", "version", ",", "'volume_catalog_info'", ":", "catalog_info", ",", "}" ]
Determines the Volume API endpoint information. Determines the appropriate version of the API that should be used as well as the catalog_info string that would be supplied. Returns a dict containing the volume_api_version and the volume_catalog_info.
[ "Determines", "the", "Volume", "API", "endpoint", "information", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1736-L1759
12,860
juju/charm-helpers
charmhelpers/contrib/openstack/context.py
AppArmorContext._determine_ctxt
def _determine_ctxt(self): """ Validate aa-profile-mode settings is disable, enforce, or complain. :return ctxt: Dictionary of the apparmor profile or None """ if config('aa-profile-mode') in ['disable', 'enforce', 'complain']: ctxt = {'aa_profile_mode': config('aa-profile-mode'), 'ubuntu_release': lsb_release()['DISTRIB_RELEASE']} if self.aa_profile: ctxt['aa_profile'] = self.aa_profile else: ctxt = None return ctxt
python
def _determine_ctxt(self): """ Validate aa-profile-mode settings is disable, enforce, or complain. :return ctxt: Dictionary of the apparmor profile or None """ if config('aa-profile-mode') in ['disable', 'enforce', 'complain']: ctxt = {'aa_profile_mode': config('aa-profile-mode'), 'ubuntu_release': lsb_release()['DISTRIB_RELEASE']} if self.aa_profile: ctxt['aa_profile'] = self.aa_profile else: ctxt = None return ctxt
[ "def", "_determine_ctxt", "(", "self", ")", ":", "if", "config", "(", "'aa-profile-mode'", ")", "in", "[", "'disable'", ",", "'enforce'", ",", "'complain'", "]", ":", "ctxt", "=", "{", "'aa_profile_mode'", ":", "config", "(", "'aa-profile-mode'", ")", ",", "'ubuntu_release'", ":", "lsb_release", "(", ")", "[", "'DISTRIB_RELEASE'", "]", "}", "if", "self", ".", "aa_profile", ":", "ctxt", "[", "'aa_profile'", "]", "=", "self", ".", "aa_profile", "else", ":", "ctxt", "=", "None", "return", "ctxt" ]
Validate aa-profile-mode settings is disable, enforce, or complain. :return ctxt: Dictionary of the apparmor profile or None
[ "Validate", "aa", "-", "profile", "-", "mode", "settings", "is", "disable", "enforce", "or", "complain", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1780-L1793
12,861
juju/charm-helpers
charmhelpers/contrib/openstack/context.py
AppArmorContext.manually_disable_aa_profile
def manually_disable_aa_profile(self): """ Manually disable an apparmor profile. If aa-profile-mode is set to disabled (default) this is required as the template has been written but apparmor is yet unaware of the profile and aa-disable aa-profile fails. Without this the profile would kick into enforce mode on the next service restart. """ profile_path = '/etc/apparmor.d' disable_path = '/etc/apparmor.d/disable' if not os.path.lexists(os.path.join(disable_path, self.aa_profile)): os.symlink(os.path.join(profile_path, self.aa_profile), os.path.join(disable_path, self.aa_profile))
python
def manually_disable_aa_profile(self): """ Manually disable an apparmor profile. If aa-profile-mode is set to disabled (default) this is required as the template has been written but apparmor is yet unaware of the profile and aa-disable aa-profile fails. Without this the profile would kick into enforce mode on the next service restart. """ profile_path = '/etc/apparmor.d' disable_path = '/etc/apparmor.d/disable' if not os.path.lexists(os.path.join(disable_path, self.aa_profile)): os.symlink(os.path.join(profile_path, self.aa_profile), os.path.join(disable_path, self.aa_profile))
[ "def", "manually_disable_aa_profile", "(", "self", ")", ":", "profile_path", "=", "'/etc/apparmor.d'", "disable_path", "=", "'/etc/apparmor.d/disable'", "if", "not", "os", ".", "path", ".", "lexists", "(", "os", ".", "path", ".", "join", "(", "disable_path", ",", "self", ".", "aa_profile", ")", ")", ":", "os", ".", "symlink", "(", "os", ".", "path", ".", "join", "(", "profile_path", ",", "self", ".", "aa_profile", ")", ",", "os", ".", "path", ".", "join", "(", "disable_path", ",", "self", ".", "aa_profile", ")", ")" ]
Manually disable an apparmor profile. If aa-profile-mode is set to disabled (default) this is required as the template has been written but apparmor is yet unaware of the profile and aa-disable aa-profile fails. Without this the profile would kick into enforce mode on the next service restart.
[ "Manually", "disable", "an", "apparmor", "profile", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1805-L1819
12,862
juju/charm-helpers
charmhelpers/contrib/openstack/context.py
AppArmorContext.setup_aa_profile
def setup_aa_profile(self): """ Setup an apparmor profile. The ctxt dictionary will contain the apparmor profile mode and the apparmor profile name. Makes calls out to aa-disable, aa-complain, or aa-enforce to setup the apparmor profile. """ self() if not self.ctxt: log("Not enabling apparmor Profile") return self.install_aa_utils() cmd = ['aa-{}'.format(self.ctxt['aa_profile_mode'])] cmd.append(self.ctxt['aa_profile']) log("Setting up the apparmor profile for {} in {} mode." "".format(self.ctxt['aa_profile'], self.ctxt['aa_profile_mode'])) try: check_call(cmd) except CalledProcessError as e: # If aa-profile-mode is set to disabled (default) manual # disabling is required as the template has been written but # apparmor is yet unaware of the profile and aa-disable aa-profile # fails. If aa-disable learns to read profile files first this can # be removed. if self.ctxt['aa_profile_mode'] == 'disable': log("Manually disabling the apparmor profile for {}." "".format(self.ctxt['aa_profile'])) self.manually_disable_aa_profile() return status_set('blocked', "Apparmor profile {} failed to be set to {}." "".format(self.ctxt['aa_profile'], self.ctxt['aa_profile_mode'])) raise e
python
def setup_aa_profile(self): """ Setup an apparmor profile. The ctxt dictionary will contain the apparmor profile mode and the apparmor profile name. Makes calls out to aa-disable, aa-complain, or aa-enforce to setup the apparmor profile. """ self() if not self.ctxt: log("Not enabling apparmor Profile") return self.install_aa_utils() cmd = ['aa-{}'.format(self.ctxt['aa_profile_mode'])] cmd.append(self.ctxt['aa_profile']) log("Setting up the apparmor profile for {} in {} mode." "".format(self.ctxt['aa_profile'], self.ctxt['aa_profile_mode'])) try: check_call(cmd) except CalledProcessError as e: # If aa-profile-mode is set to disabled (default) manual # disabling is required as the template has been written but # apparmor is yet unaware of the profile and aa-disable aa-profile # fails. If aa-disable learns to read profile files first this can # be removed. if self.ctxt['aa_profile_mode'] == 'disable': log("Manually disabling the apparmor profile for {}." "".format(self.ctxt['aa_profile'])) self.manually_disable_aa_profile() return status_set('blocked', "Apparmor profile {} failed to be set to {}." "".format(self.ctxt['aa_profile'], self.ctxt['aa_profile_mode'])) raise e
[ "def", "setup_aa_profile", "(", "self", ")", ":", "self", "(", ")", "if", "not", "self", ".", "ctxt", ":", "log", "(", "\"Not enabling apparmor Profile\"", ")", "return", "self", ".", "install_aa_utils", "(", ")", "cmd", "=", "[", "'aa-{}'", ".", "format", "(", "self", ".", "ctxt", "[", "'aa_profile_mode'", "]", ")", "]", "cmd", ".", "append", "(", "self", ".", "ctxt", "[", "'aa_profile'", "]", ")", "log", "(", "\"Setting up the apparmor profile for {} in {} mode.\"", "\"\"", ".", "format", "(", "self", ".", "ctxt", "[", "'aa_profile'", "]", ",", "self", ".", "ctxt", "[", "'aa_profile_mode'", "]", ")", ")", "try", ":", "check_call", "(", "cmd", ")", "except", "CalledProcessError", "as", "e", ":", "# If aa-profile-mode is set to disabled (default) manual", "# disabling is required as the template has been written but", "# apparmor is yet unaware of the profile and aa-disable aa-profile", "# fails. If aa-disable learns to read profile files first this can", "# be removed.", "if", "self", ".", "ctxt", "[", "'aa_profile_mode'", "]", "==", "'disable'", ":", "log", "(", "\"Manually disabling the apparmor profile for {}.\"", "\"\"", ".", "format", "(", "self", ".", "ctxt", "[", "'aa_profile'", "]", ")", ")", "self", ".", "manually_disable_aa_profile", "(", ")", "return", "status_set", "(", "'blocked'", ",", "\"Apparmor profile {} failed to be set to {}.\"", "\"\"", ".", "format", "(", "self", ".", "ctxt", "[", "'aa_profile'", "]", ",", "self", ".", "ctxt", "[", "'aa_profile_mode'", "]", ")", ")", "raise", "e" ]
Setup an apparmor profile. The ctxt dictionary will contain the apparmor profile mode and the apparmor profile name. Makes calls out to aa-disable, aa-complain, or aa-enforce to setup the apparmor profile.
[ "Setup", "an", "apparmor", "profile", ".", "The", "ctxt", "dictionary", "will", "contain", "the", "apparmor", "profile", "mode", "and", "the", "apparmor", "profile", "name", ".", "Makes", "calls", "out", "to", "aa", "-", "disable", "aa", "-", "complain", "or", "aa", "-", "enforce", "to", "setup", "the", "apparmor", "profile", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/context.py#L1821-L1854
12,863
juju/charm-helpers
charmhelpers/payload/execd.py
execd_module_paths
def execd_module_paths(execd_dir=None): """Generate a list of full paths to modules within execd_dir.""" if not execd_dir: execd_dir = default_execd_dir() if not os.path.exists(execd_dir): return for subpath in os.listdir(execd_dir): module = os.path.join(execd_dir, subpath) if os.path.isdir(module): yield module
python
def execd_module_paths(execd_dir=None): """Generate a list of full paths to modules within execd_dir.""" if not execd_dir: execd_dir = default_execd_dir() if not os.path.exists(execd_dir): return for subpath in os.listdir(execd_dir): module = os.path.join(execd_dir, subpath) if os.path.isdir(module): yield module
[ "def", "execd_module_paths", "(", "execd_dir", "=", "None", ")", ":", "if", "not", "execd_dir", ":", "execd_dir", "=", "default_execd_dir", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "execd_dir", ")", ":", "return", "for", "subpath", "in", "os", ".", "listdir", "(", "execd_dir", ")", ":", "module", "=", "os", ".", "path", ".", "join", "(", "execd_dir", ",", "subpath", ")", "if", "os", ".", "path", ".", "isdir", "(", "module", ")", ":", "yield", "module" ]
Generate a list of full paths to modules within execd_dir.
[ "Generate", "a", "list", "of", "full", "paths", "to", "modules", "within", "execd_dir", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/execd.py#L27-L38
12,864
juju/charm-helpers
charmhelpers/payload/execd.py
execd_submodule_paths
def execd_submodule_paths(command, execd_dir=None): """Generate a list of full paths to the specified command within exec_dir. """ for module_path in execd_module_paths(execd_dir): path = os.path.join(module_path, command) if os.access(path, os.X_OK) and os.path.isfile(path): yield path
python
def execd_submodule_paths(command, execd_dir=None): """Generate a list of full paths to the specified command within exec_dir. """ for module_path in execd_module_paths(execd_dir): path = os.path.join(module_path, command) if os.access(path, os.X_OK) and os.path.isfile(path): yield path
[ "def", "execd_submodule_paths", "(", "command", ",", "execd_dir", "=", "None", ")", ":", "for", "module_path", "in", "execd_module_paths", "(", "execd_dir", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "module_path", ",", "command", ")", "if", "os", ".", "access", "(", "path", ",", "os", ".", "X_OK", ")", "and", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "yield", "path" ]
Generate a list of full paths to the specified command within exec_dir.
[ "Generate", "a", "list", "of", "full", "paths", "to", "the", "specified", "command", "within", "exec_dir", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/execd.py#L41-L47
12,865
juju/charm-helpers
charmhelpers/payload/execd.py
execd_run
def execd_run(command, execd_dir=None, die_on_error=True, stderr=subprocess.STDOUT): """Run command for each module within execd_dir which defines it.""" for submodule_path in execd_submodule_paths(command, execd_dir): try: subprocess.check_output(submodule_path, stderr=stderr, universal_newlines=True) except subprocess.CalledProcessError as e: hookenv.log("Error ({}) running {}. Output: {}".format( e.returncode, e.cmd, e.output)) if die_on_error: sys.exit(e.returncode)
python
def execd_run(command, execd_dir=None, die_on_error=True, stderr=subprocess.STDOUT): """Run command for each module within execd_dir which defines it.""" for submodule_path in execd_submodule_paths(command, execd_dir): try: subprocess.check_output(submodule_path, stderr=stderr, universal_newlines=True) except subprocess.CalledProcessError as e: hookenv.log("Error ({}) running {}. Output: {}".format( e.returncode, e.cmd, e.output)) if die_on_error: sys.exit(e.returncode)
[ "def", "execd_run", "(", "command", ",", "execd_dir", "=", "None", ",", "die_on_error", "=", "True", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ":", "for", "submodule_path", "in", "execd_submodule_paths", "(", "command", ",", "execd_dir", ")", ":", "try", ":", "subprocess", ".", "check_output", "(", "submodule_path", ",", "stderr", "=", "stderr", ",", "universal_newlines", "=", "True", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "hookenv", ".", "log", "(", "\"Error ({}) running {}. Output: {}\"", ".", "format", "(", "e", ".", "returncode", ",", "e", ".", "cmd", ",", "e", ".", "output", ")", ")", "if", "die_on_error", ":", "sys", ".", "exit", "(", "e", ".", "returncode", ")" ]
Run command for each module within execd_dir which defines it.
[ "Run", "command", "for", "each", "module", "within", "execd_dir", "which", "defines", "it", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/execd.py#L50-L60
12,866
juju/charm-helpers
charmhelpers/core/unitdata.py
Storage.getrange
def getrange(self, key_prefix, strip=False): """ Get a range of keys starting with a common prefix as a mapping of keys to values. :param str key_prefix: Common prefix among all keys :param bool strip: Optionally strip the common prefix from the key names in the returned dict :return dict: A (possibly empty) dict of key-value mappings """ self.cursor.execute("select key, data from kv where key like ?", ['%s%%' % key_prefix]) result = self.cursor.fetchall() if not result: return {} if not strip: key_prefix = '' return dict([ (k[len(key_prefix):], json.loads(v)) for k, v in result])
python
def getrange(self, key_prefix, strip=False): """ Get a range of keys starting with a common prefix as a mapping of keys to values. :param str key_prefix: Common prefix among all keys :param bool strip: Optionally strip the common prefix from the key names in the returned dict :return dict: A (possibly empty) dict of key-value mappings """ self.cursor.execute("select key, data from kv where key like ?", ['%s%%' % key_prefix]) result = self.cursor.fetchall() if not result: return {} if not strip: key_prefix = '' return dict([ (k[len(key_prefix):], json.loads(v)) for k, v in result])
[ "def", "getrange", "(", "self", ",", "key_prefix", ",", "strip", "=", "False", ")", ":", "self", ".", "cursor", ".", "execute", "(", "\"select key, data from kv where key like ?\"", ",", "[", "'%s%%'", "%", "key_prefix", "]", ")", "result", "=", "self", ".", "cursor", ".", "fetchall", "(", ")", "if", "not", "result", ":", "return", "{", "}", "if", "not", "strip", ":", "key_prefix", "=", "''", "return", "dict", "(", "[", "(", "k", "[", "len", "(", "key_prefix", ")", ":", "]", ",", "json", ".", "loads", "(", "v", ")", ")", "for", "k", ",", "v", "in", "result", "]", ")" ]
Get a range of keys starting with a common prefix as a mapping of keys to values. :param str key_prefix: Common prefix among all keys :param bool strip: Optionally strip the common prefix from the key names in the returned dict :return dict: A (possibly empty) dict of key-value mappings
[ "Get", "a", "range", "of", "keys", "starting", "with", "a", "common", "prefix", "as", "a", "mapping", "of", "keys", "to", "values", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L208-L227
12,867
juju/charm-helpers
charmhelpers/core/unitdata.py
Storage.update
def update(self, mapping, prefix=""): """ Set the values of multiple keys at once. :param dict mapping: Mapping of keys to values :param str prefix: Optional prefix to apply to all keys in `mapping` before setting """ for k, v in mapping.items(): self.set("%s%s" % (prefix, k), v)
python
def update(self, mapping, prefix=""): """ Set the values of multiple keys at once. :param dict mapping: Mapping of keys to values :param str prefix: Optional prefix to apply to all keys in `mapping` before setting """ for k, v in mapping.items(): self.set("%s%s" % (prefix, k), v)
[ "def", "update", "(", "self", ",", "mapping", ",", "prefix", "=", "\"\"", ")", ":", "for", "k", ",", "v", "in", "mapping", ".", "items", "(", ")", ":", "self", ".", "set", "(", "\"%s%s\"", "%", "(", "prefix", ",", "k", ")", ",", "v", ")" ]
Set the values of multiple keys at once. :param dict mapping: Mapping of keys to values :param str prefix: Optional prefix to apply to all keys in `mapping` before setting
[ "Set", "the", "values", "of", "multiple", "keys", "at", "once", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L229-L238
12,868
juju/charm-helpers
charmhelpers/core/unitdata.py
Storage.unset
def unset(self, key): """ Remove a key from the database entirely. """ self.cursor.execute('delete from kv where key=?', [key]) if self.revision and self.cursor.rowcount: self.cursor.execute( 'insert into kv_revisions values (?, ?, ?)', [key, self.revision, json.dumps('DELETED')])
python
def unset(self, key): """ Remove a key from the database entirely. """ self.cursor.execute('delete from kv where key=?', [key]) if self.revision and self.cursor.rowcount: self.cursor.execute( 'insert into kv_revisions values (?, ?, ?)', [key, self.revision, json.dumps('DELETED')])
[ "def", "unset", "(", "self", ",", "key", ")", ":", "self", ".", "cursor", ".", "execute", "(", "'delete from kv where key=?'", ",", "[", "key", "]", ")", "if", "self", ".", "revision", "and", "self", ".", "cursor", ".", "rowcount", ":", "self", ".", "cursor", ".", "execute", "(", "'insert into kv_revisions values (?, ?, ?)'", ",", "[", "key", ",", "self", ".", "revision", ",", "json", ".", "dumps", "(", "'DELETED'", ")", "]", ")" ]
Remove a key from the database entirely.
[ "Remove", "a", "key", "from", "the", "database", "entirely", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L240-L248
12,869
juju/charm-helpers
charmhelpers/core/unitdata.py
Storage.unsetrange
def unsetrange(self, keys=None, prefix=""): """ Remove a range of keys starting with a common prefix, from the database entirely. :param list keys: List of keys to remove. :param str prefix: Optional prefix to apply to all keys in ``keys`` before removing. """ if keys is not None: keys = ['%s%s' % (prefix, key) for key in keys] self.cursor.execute('delete from kv where key in (%s)' % ','.join(['?'] * len(keys)), keys) if self.revision and self.cursor.rowcount: self.cursor.execute( 'insert into kv_revisions values %s' % ','.join(['(?, ?, ?)'] * len(keys)), list(itertools.chain.from_iterable((key, self.revision, json.dumps('DELETED')) for key in keys))) else: self.cursor.execute('delete from kv where key like ?', ['%s%%' % prefix]) if self.revision and self.cursor.rowcount: self.cursor.execute( 'insert into kv_revisions values (?, ?, ?)', ['%s%%' % prefix, self.revision, json.dumps('DELETED')])
python
def unsetrange(self, keys=None, prefix=""): """ Remove a range of keys starting with a common prefix, from the database entirely. :param list keys: List of keys to remove. :param str prefix: Optional prefix to apply to all keys in ``keys`` before removing. """ if keys is not None: keys = ['%s%s' % (prefix, key) for key in keys] self.cursor.execute('delete from kv where key in (%s)' % ','.join(['?'] * len(keys)), keys) if self.revision and self.cursor.rowcount: self.cursor.execute( 'insert into kv_revisions values %s' % ','.join(['(?, ?, ?)'] * len(keys)), list(itertools.chain.from_iterable((key, self.revision, json.dumps('DELETED')) for key in keys))) else: self.cursor.execute('delete from kv where key like ?', ['%s%%' % prefix]) if self.revision and self.cursor.rowcount: self.cursor.execute( 'insert into kv_revisions values (?, ?, ?)', ['%s%%' % prefix, self.revision, json.dumps('DELETED')])
[ "def", "unsetrange", "(", "self", ",", "keys", "=", "None", ",", "prefix", "=", "\"\"", ")", ":", "if", "keys", "is", "not", "None", ":", "keys", "=", "[", "'%s%s'", "%", "(", "prefix", ",", "key", ")", "for", "key", "in", "keys", "]", "self", ".", "cursor", ".", "execute", "(", "'delete from kv where key in (%s)'", "%", "','", ".", "join", "(", "[", "'?'", "]", "*", "len", "(", "keys", ")", ")", ",", "keys", ")", "if", "self", ".", "revision", "and", "self", ".", "cursor", ".", "rowcount", ":", "self", ".", "cursor", ".", "execute", "(", "'insert into kv_revisions values %s'", "%", "','", ".", "join", "(", "[", "'(?, ?, ?)'", "]", "*", "len", "(", "keys", ")", ")", ",", "list", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "(", "key", ",", "self", ".", "revision", ",", "json", ".", "dumps", "(", "'DELETED'", ")", ")", "for", "key", "in", "keys", ")", ")", ")", "else", ":", "self", ".", "cursor", ".", "execute", "(", "'delete from kv where key like ?'", ",", "[", "'%s%%'", "%", "prefix", "]", ")", "if", "self", ".", "revision", "and", "self", ".", "cursor", ".", "rowcount", ":", "self", ".", "cursor", ".", "execute", "(", "'insert into kv_revisions values (?, ?, ?)'", ",", "[", "'%s%%'", "%", "prefix", ",", "self", ".", "revision", ",", "json", ".", "dumps", "(", "'DELETED'", ")", "]", ")" ]
Remove a range of keys starting with a common prefix, from the database entirely. :param list keys: List of keys to remove. :param str prefix: Optional prefix to apply to all keys in ``keys`` before removing.
[ "Remove", "a", "range", "of", "keys", "starting", "with", "a", "common", "prefix", "from", "the", "database", "entirely", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L250-L272
12,870
juju/charm-helpers
charmhelpers/core/unitdata.py
Storage.delta
def delta(self, mapping, prefix): """ return a delta containing values that have changed. """ previous = self.getrange(prefix, strip=True) if not previous: pk = set() else: pk = set(previous.keys()) ck = set(mapping.keys()) delta = DeltaSet() # added for k in ck.difference(pk): delta[k] = Delta(None, mapping[k]) # removed for k in pk.difference(ck): delta[k] = Delta(previous[k], None) # changed for k in pk.intersection(ck): c = mapping[k] p = previous[k] if c != p: delta[k] = Delta(p, c) return delta
python
def delta(self, mapping, prefix): """ return a delta containing values that have changed. """ previous = self.getrange(prefix, strip=True) if not previous: pk = set() else: pk = set(previous.keys()) ck = set(mapping.keys()) delta = DeltaSet() # added for k in ck.difference(pk): delta[k] = Delta(None, mapping[k]) # removed for k in pk.difference(ck): delta[k] = Delta(previous[k], None) # changed for k in pk.intersection(ck): c = mapping[k] p = previous[k] if c != p: delta[k] = Delta(p, c) return delta
[ "def", "delta", "(", "self", ",", "mapping", ",", "prefix", ")", ":", "previous", "=", "self", ".", "getrange", "(", "prefix", ",", "strip", "=", "True", ")", "if", "not", "previous", ":", "pk", "=", "set", "(", ")", "else", ":", "pk", "=", "set", "(", "previous", ".", "keys", "(", ")", ")", "ck", "=", "set", "(", "mapping", ".", "keys", "(", ")", ")", "delta", "=", "DeltaSet", "(", ")", "# added", "for", "k", "in", "ck", ".", "difference", "(", "pk", ")", ":", "delta", "[", "k", "]", "=", "Delta", "(", "None", ",", "mapping", "[", "k", "]", ")", "# removed", "for", "k", "in", "pk", ".", "difference", "(", "ck", ")", ":", "delta", "[", "k", "]", "=", "Delta", "(", "previous", "[", "k", "]", ",", "None", ")", "# changed", "for", "k", "in", "pk", ".", "intersection", "(", "ck", ")", ":", "c", "=", "mapping", "[", "k", "]", "p", "=", "previous", "[", "k", "]", "if", "c", "!=", "p", ":", "delta", "[", "k", "]", "=", "Delta", "(", "p", ",", "c", ")", "return", "delta" ]
return a delta containing values that have changed.
[ "return", "a", "delta", "containing", "values", "that", "have", "changed", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L326-L353
12,871
juju/charm-helpers
charmhelpers/core/unitdata.py
Storage.hook_scope
def hook_scope(self, name=""): """Scope all future interactions to the current hook execution revision.""" assert not self.revision self.cursor.execute( 'insert into hooks (hook, date) values (?, ?)', (name or sys.argv[0], datetime.datetime.utcnow().isoformat())) self.revision = self.cursor.lastrowid try: yield self.revision self.revision = None except Exception: self.flush(False) self.revision = None raise else: self.flush()
python
def hook_scope(self, name=""): """Scope all future interactions to the current hook execution revision.""" assert not self.revision self.cursor.execute( 'insert into hooks (hook, date) values (?, ?)', (name or sys.argv[0], datetime.datetime.utcnow().isoformat())) self.revision = self.cursor.lastrowid try: yield self.revision self.revision = None except Exception: self.flush(False) self.revision = None raise else: self.flush()
[ "def", "hook_scope", "(", "self", ",", "name", "=", "\"\"", ")", ":", "assert", "not", "self", ".", "revision", "self", ".", "cursor", ".", "execute", "(", "'insert into hooks (hook, date) values (?, ?)'", ",", "(", "name", "or", "sys", ".", "argv", "[", "0", "]", ",", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", ")", ")", "self", ".", "revision", "=", "self", ".", "cursor", ".", "lastrowid", "try", ":", "yield", "self", ".", "revision", "self", ".", "revision", "=", "None", "except", "Exception", ":", "self", ".", "flush", "(", "False", ")", "self", ".", "revision", "=", "None", "raise", "else", ":", "self", ".", "flush", "(", ")" ]
Scope all future interactions to the current hook execution revision.
[ "Scope", "all", "future", "interactions", "to", "the", "current", "hook", "execution", "revision", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/unitdata.py#L356-L373
12,872
juju/charm-helpers
charmhelpers/contrib/network/ovs/__init__.py
add_bridge
def add_bridge(name, datapath_type=None): ''' Add the named bridge to openvswitch ''' log('Creating bridge {}'.format(name)) cmd = ["ovs-vsctl", "--", "--may-exist", "add-br", name] if datapath_type is not None: cmd += ['--', 'set', 'bridge', name, 'datapath_type={}'.format(datapath_type)] subprocess.check_call(cmd)
python
def add_bridge(name, datapath_type=None): ''' Add the named bridge to openvswitch ''' log('Creating bridge {}'.format(name)) cmd = ["ovs-vsctl", "--", "--may-exist", "add-br", name] if datapath_type is not None: cmd += ['--', 'set', 'bridge', name, 'datapath_type={}'.format(datapath_type)] subprocess.check_call(cmd)
[ "def", "add_bridge", "(", "name", ",", "datapath_type", "=", "None", ")", ":", "log", "(", "'Creating bridge {}'", ".", "format", "(", "name", ")", ")", "cmd", "=", "[", "\"ovs-vsctl\"", ",", "\"--\"", ",", "\"--may-exist\"", ",", "\"add-br\"", ",", "name", "]", "if", "datapath_type", "is", "not", "None", ":", "cmd", "+=", "[", "'--'", ",", "'set'", ",", "'bridge'", ",", "name", ",", "'datapath_type={}'", ".", "format", "(", "datapath_type", ")", "]", "subprocess", ".", "check_call", "(", "cmd", ")" ]
Add the named bridge to openvswitch
[ "Add", "the", "named", "bridge", "to", "openvswitch" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L46-L53
12,873
juju/charm-helpers
charmhelpers/contrib/network/ovs/__init__.py
add_bridge_port
def add_bridge_port(name, port, promisc=False): ''' Add a port to the named openvswitch bridge ''' log('Adding port {} to bridge {}'.format(port, name)) subprocess.check_call(["ovs-vsctl", "--", "--may-exist", "add-port", name, port]) subprocess.check_call(["ip", "link", "set", port, "up"]) if promisc: subprocess.check_call(["ip", "link", "set", port, "promisc", "on"]) else: subprocess.check_call(["ip", "link", "set", port, "promisc", "off"])
python
def add_bridge_port(name, port, promisc=False): ''' Add a port to the named openvswitch bridge ''' log('Adding port {} to bridge {}'.format(port, name)) subprocess.check_call(["ovs-vsctl", "--", "--may-exist", "add-port", name, port]) subprocess.check_call(["ip", "link", "set", port, "up"]) if promisc: subprocess.check_call(["ip", "link", "set", port, "promisc", "on"]) else: subprocess.check_call(["ip", "link", "set", port, "promisc", "off"])
[ "def", "add_bridge_port", "(", "name", ",", "port", ",", "promisc", "=", "False", ")", ":", "log", "(", "'Adding port {} to bridge {}'", ".", "format", "(", "port", ",", "name", ")", ")", "subprocess", ".", "check_call", "(", "[", "\"ovs-vsctl\"", ",", "\"--\"", ",", "\"--may-exist\"", ",", "\"add-port\"", ",", "name", ",", "port", "]", ")", "subprocess", ".", "check_call", "(", "[", "\"ip\"", ",", "\"link\"", ",", "\"set\"", ",", "port", ",", "\"up\"", "]", ")", "if", "promisc", ":", "subprocess", ".", "check_call", "(", "[", "\"ip\"", ",", "\"link\"", ",", "\"set\"", ",", "port", ",", "\"promisc\"", ",", "\"on\"", "]", ")", "else", ":", "subprocess", ".", "check_call", "(", "[", "\"ip\"", ",", "\"link\"", ",", "\"set\"", ",", "port", ",", "\"promisc\"", ",", "\"off\"", "]", ")" ]
Add a port to the named openvswitch bridge
[ "Add", "a", "port", "to", "the", "named", "openvswitch", "bridge" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L62-L71
12,874
juju/charm-helpers
charmhelpers/contrib/network/ovs/__init__.py
del_bridge_port
def del_bridge_port(name, port): ''' Delete a port from the named openvswitch bridge ''' log('Deleting port {} from bridge {}'.format(port, name)) subprocess.check_call(["ovs-vsctl", "--", "--if-exists", "del-port", name, port]) subprocess.check_call(["ip", "link", "set", port, "down"]) subprocess.check_call(["ip", "link", "set", port, "promisc", "off"])
python
def del_bridge_port(name, port): ''' Delete a port from the named openvswitch bridge ''' log('Deleting port {} from bridge {}'.format(port, name)) subprocess.check_call(["ovs-vsctl", "--", "--if-exists", "del-port", name, port]) subprocess.check_call(["ip", "link", "set", port, "down"]) subprocess.check_call(["ip", "link", "set", port, "promisc", "off"])
[ "def", "del_bridge_port", "(", "name", ",", "port", ")", ":", "log", "(", "'Deleting port {} from bridge {}'", ".", "format", "(", "port", ",", "name", ")", ")", "subprocess", ".", "check_call", "(", "[", "\"ovs-vsctl\"", ",", "\"--\"", ",", "\"--if-exists\"", ",", "\"del-port\"", ",", "name", ",", "port", "]", ")", "subprocess", ".", "check_call", "(", "[", "\"ip\"", ",", "\"link\"", ",", "\"set\"", ",", "port", ",", "\"down\"", "]", ")", "subprocess", ".", "check_call", "(", "[", "\"ip\"", ",", "\"link\"", ",", "\"set\"", ",", "port", ",", "\"promisc\"", ",", "\"off\"", "]", ")" ]
Delete a port from the named openvswitch bridge
[ "Delete", "a", "port", "from", "the", "named", "openvswitch", "bridge" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L74-L80
12,875
juju/charm-helpers
charmhelpers/contrib/network/ovs/__init__.py
get_certificate
def get_certificate(): ''' Read openvswitch certificate from disk ''' if os.path.exists(CERT_PATH): log('Reading ovs certificate from {}'.format(CERT_PATH)) with open(CERT_PATH, 'r') as cert: full_cert = cert.read() begin_marker = "-----BEGIN CERTIFICATE-----" end_marker = "-----END CERTIFICATE-----" begin_index = full_cert.find(begin_marker) end_index = full_cert.rfind(end_marker) if end_index == -1 or begin_index == -1: raise RuntimeError("Certificate does not contain valid begin" " and end markers.") full_cert = full_cert[begin_index:(end_index + len(end_marker))] return full_cert else: log('Certificate not found', level=WARNING) return None
python
def get_certificate(): ''' Read openvswitch certificate from disk ''' if os.path.exists(CERT_PATH): log('Reading ovs certificate from {}'.format(CERT_PATH)) with open(CERT_PATH, 'r') as cert: full_cert = cert.read() begin_marker = "-----BEGIN CERTIFICATE-----" end_marker = "-----END CERTIFICATE-----" begin_index = full_cert.find(begin_marker) end_index = full_cert.rfind(end_marker) if end_index == -1 or begin_index == -1: raise RuntimeError("Certificate does not contain valid begin" " and end markers.") full_cert = full_cert[begin_index:(end_index + len(end_marker))] return full_cert else: log('Certificate not found', level=WARNING) return None
[ "def", "get_certificate", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "CERT_PATH", ")", ":", "log", "(", "'Reading ovs certificate from {}'", ".", "format", "(", "CERT_PATH", ")", ")", "with", "open", "(", "CERT_PATH", ",", "'r'", ")", "as", "cert", ":", "full_cert", "=", "cert", ".", "read", "(", ")", "begin_marker", "=", "\"-----BEGIN CERTIFICATE-----\"", "end_marker", "=", "\"-----END CERTIFICATE-----\"", "begin_index", "=", "full_cert", ".", "find", "(", "begin_marker", ")", "end_index", "=", "full_cert", ".", "rfind", "(", "end_marker", ")", "if", "end_index", "==", "-", "1", "or", "begin_index", "==", "-", "1", ":", "raise", "RuntimeError", "(", "\"Certificate does not contain valid begin\"", "\" and end markers.\"", ")", "full_cert", "=", "full_cert", "[", "begin_index", ":", "(", "end_index", "+", "len", "(", "end_marker", ")", ")", "]", "return", "full_cert", "else", ":", "log", "(", "'Certificate not found'", ",", "level", "=", "WARNING", ")", "return", "None" ]
Read openvswitch certificate from disk
[ "Read", "openvswitch", "certificate", "from", "disk" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L180-L197
12,876
juju/charm-helpers
charmhelpers/contrib/network/ovs/__init__.py
check_for_eni_source
def check_for_eni_source(): ''' Juju removes the source line when setting up interfaces, replace if missing ''' with open('/etc/network/interfaces', 'r') as eni: for line in eni: if line == 'source /etc/network/interfaces.d/*': return with open('/etc/network/interfaces', 'a') as eni: eni.write('\nsource /etc/network/interfaces.d/*')
python
def check_for_eni_source(): ''' Juju removes the source line when setting up interfaces, replace if missing ''' with open('/etc/network/interfaces', 'r') as eni: for line in eni: if line == 'source /etc/network/interfaces.d/*': return with open('/etc/network/interfaces', 'a') as eni: eni.write('\nsource /etc/network/interfaces.d/*')
[ "def", "check_for_eni_source", "(", ")", ":", "with", "open", "(", "'/etc/network/interfaces'", ",", "'r'", ")", "as", "eni", ":", "for", "line", "in", "eni", ":", "if", "line", "==", "'source /etc/network/interfaces.d/*'", ":", "return", "with", "open", "(", "'/etc/network/interfaces'", ",", "'a'", ")", "as", "eni", ":", "eni", ".", "write", "(", "'\\nsource /etc/network/interfaces.d/*'", ")" ]
Juju removes the source line when setting up interfaces, replace if missing
[ "Juju", "removes", "the", "source", "line", "when", "setting", "up", "interfaces", "replace", "if", "missing" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ovs/__init__.py#L200-L209
12,877
juju/charm-helpers
charmhelpers/contrib/hardening/audits/apt.py
RestrictedPackages.delete_package
def delete_package(self, cache, pkg): """Deletes the package from the system. Deletes the package form the system, properly handling virtual packages. :param cache: the apt cache :param pkg: the package to remove """ if self.is_virtual_package(pkg): log("Package '%s' appears to be virtual - purging provides" % pkg.name, level=DEBUG) for _p in pkg.provides_list: self.delete_package(cache, _p[2].parent_pkg) elif not pkg.current_ver: log("Package '%s' not installed" % pkg.name, level=DEBUG) return else: log("Purging package '%s'" % pkg.name, level=DEBUG) apt_purge(pkg.name)
python
def delete_package(self, cache, pkg): """Deletes the package from the system. Deletes the package form the system, properly handling virtual packages. :param cache: the apt cache :param pkg: the package to remove """ if self.is_virtual_package(pkg): log("Package '%s' appears to be virtual - purging provides" % pkg.name, level=DEBUG) for _p in pkg.provides_list: self.delete_package(cache, _p[2].parent_pkg) elif not pkg.current_ver: log("Package '%s' not installed" % pkg.name, level=DEBUG) return else: log("Purging package '%s'" % pkg.name, level=DEBUG) apt_purge(pkg.name)
[ "def", "delete_package", "(", "self", ",", "cache", ",", "pkg", ")", ":", "if", "self", ".", "is_virtual_package", "(", "pkg", ")", ":", "log", "(", "\"Package '%s' appears to be virtual - purging provides\"", "%", "pkg", ".", "name", ",", "level", "=", "DEBUG", ")", "for", "_p", "in", "pkg", ".", "provides_list", ":", "self", ".", "delete_package", "(", "cache", ",", "_p", "[", "2", "]", ".", "parent_pkg", ")", "elif", "not", "pkg", ".", "current_ver", ":", "log", "(", "\"Package '%s' not installed\"", "%", "pkg", ".", "name", ",", "level", "=", "DEBUG", ")", "return", "else", ":", "log", "(", "\"Purging package '%s'\"", "%", "pkg", ".", "name", ",", "level", "=", "DEBUG", ")", "apt_purge", "(", "pkg", ".", "name", ")" ]
Deletes the package from the system. Deletes the package form the system, properly handling virtual packages. :param cache: the apt cache :param pkg: the package to remove
[ "Deletes", "the", "package", "from", "the", "system", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/apt.py#L81-L100
12,878
aschn/drf-tracking
rest_framework_tracking/base_mixins.py
BaseLoggingMixin._get_ip_address
def _get_ip_address(self, request): """Get the remote ip address the request was generated from. """ ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None) if ipaddr: # X_FORWARDED_FOR returns client1, proxy1, proxy2,... return ipaddr.split(",")[0].strip() return request.META.get("REMOTE_ADDR", "")
python
def _get_ip_address(self, request): """Get the remote ip address the request was generated from. """ ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None) if ipaddr: # X_FORWARDED_FOR returns client1, proxy1, proxy2,... return ipaddr.split(",")[0].strip() return request.META.get("REMOTE_ADDR", "")
[ "def", "_get_ip_address", "(", "self", ",", "request", ")", ":", "ipaddr", "=", "request", ".", "META", ".", "get", "(", "\"HTTP_X_FORWARDED_FOR\"", ",", "None", ")", "if", "ipaddr", ":", "# X_FORWARDED_FOR returns client1, proxy1, proxy2,...", "return", "ipaddr", ".", "split", "(", "\",\"", ")", "[", "0", "]", ".", "strip", "(", ")", "return", "request", ".", "META", ".", "get", "(", "\"REMOTE_ADDR\"", ",", "\"\"", ")" ]
Get the remote ip address the request was generated from.
[ "Get", "the", "remote", "ip", "address", "the", "request", "was", "generated", "from", "." ]
1910f413bd5166bbeaf694c7c0101f331af4f47d
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L100-L106
12,879
aschn/drf-tracking
rest_framework_tracking/base_mixins.py
BaseLoggingMixin._get_view_name
def _get_view_name(self, request): """Get view name.""" method = request.method.lower() try: attributes = getattr(self, method) view_name = type(attributes.__self__).__module__ + '.' + type(attributes.__self__).__name__ return view_name except AttributeError: return None
python
def _get_view_name(self, request): """Get view name.""" method = request.method.lower() try: attributes = getattr(self, method) view_name = type(attributes.__self__).__module__ + '.' + type(attributes.__self__).__name__ return view_name except AttributeError: return None
[ "def", "_get_view_name", "(", "self", ",", "request", ")", ":", "method", "=", "request", ".", "method", ".", "lower", "(", ")", "try", ":", "attributes", "=", "getattr", "(", "self", ",", "method", ")", "view_name", "=", "type", "(", "attributes", ".", "__self__", ")", ".", "__module__", "+", "'.'", "+", "type", "(", "attributes", ".", "__self__", ")", ".", "__name__", "return", "view_name", "except", "AttributeError", ":", "return", "None" ]
Get view name.
[ "Get", "view", "name", "." ]
1910f413bd5166bbeaf694c7c0101f331af4f47d
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L108-L116
12,880
aschn/drf-tracking
rest_framework_tracking/base_mixins.py
BaseLoggingMixin._get_view_method
def _get_view_method(self, request): """Get view method.""" if hasattr(self, 'action'): return self.action if self.action else None return request.method.lower()
python
def _get_view_method(self, request): """Get view method.""" if hasattr(self, 'action'): return self.action if self.action else None return request.method.lower()
[ "def", "_get_view_method", "(", "self", ",", "request", ")", ":", "if", "hasattr", "(", "self", ",", "'action'", ")", ":", "return", "self", ".", "action", "if", "self", ".", "action", "else", "None", "return", "request", ".", "method", ".", "lower", "(", ")" ]
Get view method.
[ "Get", "view", "method", "." ]
1910f413bd5166bbeaf694c7c0101f331af4f47d
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L118-L122
12,881
aschn/drf-tracking
rest_framework_tracking/base_mixins.py
BaseLoggingMixin._get_response_ms
def _get_response_ms(self): """ Get the duration of the request response cycle is milliseconds. In case of negative duration 0 is returned. """ response_timedelta = now() - self.log['requested_at'] response_ms = int(response_timedelta.total_seconds() * 1000) return max(response_ms, 0)
python
def _get_response_ms(self): """ Get the duration of the request response cycle is milliseconds. In case of negative duration 0 is returned. """ response_timedelta = now() - self.log['requested_at'] response_ms = int(response_timedelta.total_seconds() * 1000) return max(response_ms, 0)
[ "def", "_get_response_ms", "(", "self", ")", ":", "response_timedelta", "=", "now", "(", ")", "-", "self", ".", "log", "[", "'requested_at'", "]", "response_ms", "=", "int", "(", "response_timedelta", ".", "total_seconds", "(", ")", "*", "1000", ")", "return", "max", "(", "response_ms", ",", "0", ")" ]
Get the duration of the request response cycle is milliseconds. In case of negative duration 0 is returned.
[ "Get", "the", "duration", "of", "the", "request", "response", "cycle", "is", "milliseconds", ".", "In", "case", "of", "negative", "duration", "0", "is", "returned", "." ]
1910f413bd5166bbeaf694c7c0101f331af4f47d
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L131-L138
12,882
aschn/drf-tracking
rest_framework_tracking/base_mixins.py
BaseLoggingMixin.should_log
def should_log(self, request, response): """ Method that should return a value that evaluated to True if the request should be logged. By default, check if the request method is in logging_methods. """ return self.logging_methods == '__all__' or request.method in self.logging_methods
python
def should_log(self, request, response): """ Method that should return a value that evaluated to True if the request should be logged. By default, check if the request method is in logging_methods. """ return self.logging_methods == '__all__' or request.method in self.logging_methods
[ "def", "should_log", "(", "self", ",", "request", ",", "response", ")", ":", "return", "self", ".", "logging_methods", "==", "'__all__'", "or", "request", ".", "method", "in", "self", ".", "logging_methods" ]
Method that should return a value that evaluated to True if the request should be logged. By default, check if the request method is in logging_methods.
[ "Method", "that", "should", "return", "a", "value", "that", "evaluated", "to", "True", "if", "the", "request", "should", "be", "logged", ".", "By", "default", "check", "if", "the", "request", "method", "is", "in", "logging_methods", "." ]
1910f413bd5166bbeaf694c7c0101f331af4f47d
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L140-L145
12,883
Esri/ArcREST
src/arcresthelper/common.py
merge_dicts
def merge_dicts(dicts, op=operator.add): """Merge a list of dictionaries. Args: dicts (list): a list of dictionary objects op (operator): an operator item used to merge the dictionaries. Defaults to :py:func:`operator.add`. Returns: dict: the merged dictionary """ a = None for b in dicts: if a is None: a = b.copy() else: a = dict(a.items() + b.items() + [(k, op(a[k], b[k])) for k in set(b) & set(a)]) return a
python
def merge_dicts(dicts, op=operator.add): """Merge a list of dictionaries. Args: dicts (list): a list of dictionary objects op (operator): an operator item used to merge the dictionaries. Defaults to :py:func:`operator.add`. Returns: dict: the merged dictionary """ a = None for b in dicts: if a is None: a = b.copy() else: a = dict(a.items() + b.items() + [(k, op(a[k], b[k])) for k in set(b) & set(a)]) return a
[ "def", "merge_dicts", "(", "dicts", ",", "op", "=", "operator", ".", "add", ")", ":", "a", "=", "None", "for", "b", "in", "dicts", ":", "if", "a", "is", "None", ":", "a", "=", "b", ".", "copy", "(", ")", "else", ":", "a", "=", "dict", "(", "a", ".", "items", "(", ")", "+", "b", ".", "items", "(", ")", "+", "[", "(", "k", ",", "op", "(", "a", "[", "k", "]", ",", "b", "[", "k", "]", ")", ")", "for", "k", "in", "set", "(", "b", ")", "&", "set", "(", "a", ")", "]", ")", "return", "a" ]
Merge a list of dictionaries. Args: dicts (list): a list of dictionary objects op (operator): an operator item used to merge the dictionaries. Defaults to :py:func:`operator.add`. Returns: dict: the merged dictionary
[ "Merge", "a", "list", "of", "dictionaries", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L39-L57
12,884
Esri/ArcREST
src/arcresthelper/common.py
getLayerIndex
def getLayerIndex(url): """Extract the layer index from a url. Args: url (str): The url to parse. Returns: int: The layer index. Examples: >>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12" >>> arcresthelper.common.getLayerIndex(url) 12 """ urlInfo = None urlSplit = None inx = None try: urlInfo = urlparse.urlparse(url) urlSplit = str(urlInfo.path).split('/') inx = urlSplit[len(urlSplit)-1] if is_number(inx): return int(inx) except: return 0 finally: urlInfo = None urlSplit = None del urlInfo del urlSplit gc.collect()
python
def getLayerIndex(url): """Extract the layer index from a url. Args: url (str): The url to parse. Returns: int: The layer index. Examples: >>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12" >>> arcresthelper.common.getLayerIndex(url) 12 """ urlInfo = None urlSplit = None inx = None try: urlInfo = urlparse.urlparse(url) urlSplit = str(urlInfo.path).split('/') inx = urlSplit[len(urlSplit)-1] if is_number(inx): return int(inx) except: return 0 finally: urlInfo = None urlSplit = None del urlInfo del urlSplit gc.collect()
[ "def", "getLayerIndex", "(", "url", ")", ":", "urlInfo", "=", "None", "urlSplit", "=", "None", "inx", "=", "None", "try", ":", "urlInfo", "=", "urlparse", ".", "urlparse", "(", "url", ")", "urlSplit", "=", "str", "(", "urlInfo", ".", "path", ")", ".", "split", "(", "'/'", ")", "inx", "=", "urlSplit", "[", "len", "(", "urlSplit", ")", "-", "1", "]", "if", "is_number", "(", "inx", ")", ":", "return", "int", "(", "inx", ")", "except", ":", "return", "0", "finally", ":", "urlInfo", "=", "None", "urlSplit", "=", "None", "del", "urlInfo", "del", "urlSplit", "gc", ".", "collect", "(", ")" ]
Extract the layer index from a url. Args: url (str): The url to parse. Returns: int: The layer index. Examples: >>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12" >>> arcresthelper.common.getLayerIndex(url) 12
[ "Extract", "the", "layer", "index", "from", "a", "url", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L97-L132
12,885
Esri/ArcREST
src/arcresthelper/common.py
getLayerName
def getLayerName(url): """Extract the layer name from a url. Args: url (str): The url to parse. Returns: str: The layer name. Examples: >>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12" >>> arcresthelper.common.getLayerIndex(url) 'test' """ urlInfo = None urlSplit = None try: urlInfo = urlparse.urlparse(url) urlSplit = str(urlInfo.path).split('/') name = urlSplit[len(urlSplit)-3] return name except: return url finally: urlInfo = None urlSplit = None del urlInfo del urlSplit gc.collect()
python
def getLayerName(url): """Extract the layer name from a url. Args: url (str): The url to parse. Returns: str: The layer name. Examples: >>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12" >>> arcresthelper.common.getLayerIndex(url) 'test' """ urlInfo = None urlSplit = None try: urlInfo = urlparse.urlparse(url) urlSplit = str(urlInfo.path).split('/') name = urlSplit[len(urlSplit)-3] return name except: return url finally: urlInfo = None urlSplit = None del urlInfo del urlSplit gc.collect()
[ "def", "getLayerName", "(", "url", ")", ":", "urlInfo", "=", "None", "urlSplit", "=", "None", "try", ":", "urlInfo", "=", "urlparse", ".", "urlparse", "(", "url", ")", "urlSplit", "=", "str", "(", "urlInfo", ".", "path", ")", ".", "split", "(", "'/'", ")", "name", "=", "urlSplit", "[", "len", "(", "urlSplit", ")", "-", "3", "]", "return", "name", "except", ":", "return", "url", "finally", ":", "urlInfo", "=", "None", "urlSplit", "=", "None", "del", "urlInfo", "del", "urlSplit", "gc", ".", "collect", "(", ")" ]
Extract the layer name from a url. Args: url (str): The url to parse. Returns: str: The layer name. Examples: >>> url = "http://services.arcgis.com/<random>/arcgis/rest/services/test/FeatureServer/12" >>> arcresthelper.common.getLayerIndex(url) 'test'
[ "Extract", "the", "layer", "name", "from", "a", "url", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L134-L166
12,886
Esri/ArcREST
src/arcresthelper/common.py
random_string_generator
def random_string_generator(size=6, chars=string.ascii_uppercase): """Generates a random string from a set of characters. Args: size (int): The length of the resultant string. Defaults to 6. chars (str): The characters to be used by :py:func:`random.choice`. Defaults to :py:const:`string.ascii_uppercase`. Returns: str: The randomly generated string. Examples: >>> arcresthelper.common.random_string_generator() 'DCNYWU' >>> arcresthelper.common.random_string_generator(12, "arcREST") 'cESaTTEacTES' """ try: return ''.join(random.choice(chars) for _ in range(size)) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "random_string_generator", "line": line, "filename": filename, "synerror": synerror, } ) finally: pass
python
def random_string_generator(size=6, chars=string.ascii_uppercase): """Generates a random string from a set of characters. Args: size (int): The length of the resultant string. Defaults to 6. chars (str): The characters to be used by :py:func:`random.choice`. Defaults to :py:const:`string.ascii_uppercase`. Returns: str: The randomly generated string. Examples: >>> arcresthelper.common.random_string_generator() 'DCNYWU' >>> arcresthelper.common.random_string_generator(12, "arcREST") 'cESaTTEacTES' """ try: return ''.join(random.choice(chars) for _ in range(size)) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "random_string_generator", "line": line, "filename": filename, "synerror": synerror, } ) finally: pass
[ "def", "random_string_generator", "(", "size", "=", "6", ",", "chars", "=", "string", ".", "ascii_uppercase", ")", ":", "try", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "chars", ")", "for", "_", "in", "range", "(", "size", ")", ")", "except", ":", "line", ",", "filename", ",", "synerror", "=", "trace", "(", ")", "raise", "ArcRestHelperError", "(", "{", "\"function\"", ":", "\"random_string_generator\"", ",", "\"line\"", ":", "line", ",", "\"filename\"", ":", "filename", ",", "\"synerror\"", ":", "synerror", ",", "}", ")", "finally", ":", "pass" ]
Generates a random string from a set of characters. Args: size (int): The length of the resultant string. Defaults to 6. chars (str): The characters to be used by :py:func:`random.choice`. Defaults to :py:const:`string.ascii_uppercase`. Returns: str: The randomly generated string. Examples: >>> arcresthelper.common.random_string_generator() 'DCNYWU' >>> arcresthelper.common.random_string_generator(12, "arcREST") 'cESaTTEacTES'
[ "Generates", "a", "random", "string", "from", "a", "set", "of", "characters", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L204-L233
12,887
Esri/ArcREST
src/arcresthelper/common.py
random_int_generator
def random_int_generator(maxrange): """Generates a random integer from 0 to `maxrange`, inclusive. Args: maxrange (int): The upper range of integers to randomly choose. Returns: int: The randomly generated integer from :py:func:`random.randint`. Examples: >>> arcresthelper.common.random_int_generator(15) 9 """ try: return random.randint(0,maxrange) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "random_int_generator", "line": line, "filename": filename, "synerror": synerror, } ) finally: pass
python
def random_int_generator(maxrange): """Generates a random integer from 0 to `maxrange`, inclusive. Args: maxrange (int): The upper range of integers to randomly choose. Returns: int: The randomly generated integer from :py:func:`random.randint`. Examples: >>> arcresthelper.common.random_int_generator(15) 9 """ try: return random.randint(0,maxrange) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "random_int_generator", "line": line, "filename": filename, "synerror": synerror, } ) finally: pass
[ "def", "random_int_generator", "(", "maxrange", ")", ":", "try", ":", "return", "random", ".", "randint", "(", "0", ",", "maxrange", ")", "except", ":", "line", ",", "filename", ",", "synerror", "=", "trace", "(", ")", "raise", "ArcRestHelperError", "(", "{", "\"function\"", ":", "\"random_int_generator\"", ",", "\"line\"", ":", "line", ",", "\"filename\"", ":", "filename", ",", "\"synerror\"", ":", "synerror", ",", "}", ")", "finally", ":", "pass" ]
Generates a random integer from 0 to `maxrange`, inclusive. Args: maxrange (int): The upper range of integers to randomly choose. Returns: int: The randomly generated integer from :py:func:`random.randint`. Examples: >>> arcresthelper.common.random_int_generator(15) 9
[ "Generates", "a", "random", "integer", "from", "0", "to", "maxrange", "inclusive", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L235-L261
12,888
Esri/ArcREST
src/arcresthelper/common.py
local_time_to_online
def local_time_to_online(dt=None): """Converts datetime object to a UTC timestamp for AGOL. Args: dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`. Returns: float: A UTC timestamp as understood by AGOL (time in ms since Unix epoch * 1000) Examples: >>> arcresthelper.common.local_time_to_online() # PST 1457167261000.0 >>> dt = datetime.datetime(1993, 3, 5, 12, 35, 15) # PST >>> arcresthelper.common.local_time_to_online(dt) 731392515000.0 See Also: :py:func:`online_time_to_string` for converting a UTC timestamp """ is_dst = None utc_offset = None try: if dt is None: dt = datetime.datetime.now() is_dst = time.daylight > 0 and time.localtime().tm_isdst > 0 utc_offset = (time.altzone if is_dst else time.timezone) return (time.mktime(dt.timetuple()) * 1000) + (utc_offset * 1000) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "local_time_to_online", "line": line, "filename": filename, "synerror": synerror, } ) finally: is_dst = None utc_offset = None del is_dst del utc_offset
python
def local_time_to_online(dt=None): """Converts datetime object to a UTC timestamp for AGOL. Args: dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`. Returns: float: A UTC timestamp as understood by AGOL (time in ms since Unix epoch * 1000) Examples: >>> arcresthelper.common.local_time_to_online() # PST 1457167261000.0 >>> dt = datetime.datetime(1993, 3, 5, 12, 35, 15) # PST >>> arcresthelper.common.local_time_to_online(dt) 731392515000.0 See Also: :py:func:`online_time_to_string` for converting a UTC timestamp """ is_dst = None utc_offset = None try: if dt is None: dt = datetime.datetime.now() is_dst = time.daylight > 0 and time.localtime().tm_isdst > 0 utc_offset = (time.altzone if is_dst else time.timezone) return (time.mktime(dt.timetuple()) * 1000) + (utc_offset * 1000) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "local_time_to_online", "line": line, "filename": filename, "synerror": synerror, } ) finally: is_dst = None utc_offset = None del is_dst del utc_offset
[ "def", "local_time_to_online", "(", "dt", "=", "None", ")", ":", "is_dst", "=", "None", "utc_offset", "=", "None", "try", ":", "if", "dt", "is", "None", ":", "dt", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "is_dst", "=", "time", ".", "daylight", ">", "0", "and", "time", ".", "localtime", "(", ")", ".", "tm_isdst", ">", "0", "utc_offset", "=", "(", "time", ".", "altzone", "if", "is_dst", "else", "time", ".", "timezone", ")", "return", "(", "time", ".", "mktime", "(", "dt", ".", "timetuple", "(", ")", ")", "*", "1000", ")", "+", "(", "utc_offset", "*", "1000", ")", "except", ":", "line", ",", "filename", ",", "synerror", "=", "trace", "(", ")", "raise", "ArcRestHelperError", "(", "{", "\"function\"", ":", "\"local_time_to_online\"", ",", "\"line\"", ":", "line", ",", "\"filename\"", ":", "filename", ",", "\"synerror\"", ":", "synerror", ",", "}", ")", "finally", ":", "is_dst", "=", "None", "utc_offset", "=", "None", "del", "is_dst", "del", "utc_offset" ]
Converts datetime object to a UTC timestamp for AGOL. Args: dt (datetime): The :py:class:`datetime.datetime` object to convert. Defaults to ``None``, i.e., :py:func:`datetime.datetime.now`. Returns: float: A UTC timestamp as understood by AGOL (time in ms since Unix epoch * 1000) Examples: >>> arcresthelper.common.local_time_to_online() # PST 1457167261000.0 >>> dt = datetime.datetime(1993, 3, 5, 12, 35, 15) # PST >>> arcresthelper.common.local_time_to_online(dt) 731392515000.0 See Also: :py:func:`online_time_to_string` for converting a UTC timestamp
[ "Converts", "datetime", "object", "to", "a", "UTC", "timestamp", "for", "AGOL", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L263-L306
12,889
Esri/ArcREST
src/arcresthelper/common.py
is_number
def is_number(s): """Determines if the input is numeric Args: s: The value to check. Returns: bool: ``True`` if the input is numeric, ``False`` otherwise. """ try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False
python
def is_number(s): """Determines if the input is numeric Args: s: The value to check. Returns: bool: ``True`` if the input is numeric, ``False`` otherwise. """ try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False
[ "def", "is_number", "(", "s", ")", ":", "try", ":", "float", "(", "s", ")", "return", "True", "except", "ValueError", ":", "pass", "try", ":", "import", "unicodedata", "unicodedata", ".", "numeric", "(", "s", ")", "return", "True", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "return", "False" ]
Determines if the input is numeric Args: s: The value to check. Returns: bool: ``True`` if the input is numeric, ``False`` otherwise.
[ "Determines", "if", "the", "input", "is", "numeric" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L345-L367
12,890
Esri/ArcREST
src/arcresthelper/common.py
init_config_json
def init_config_json(config_file): """Deserializes a JSON configuration file. Args: config_file (str): The path to the JSON file. Returns: dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``. """ json_data = None try: if os.path.exists(config_file): #Load the config file with open(config_file) as json_file: json_data = json.load(json_file) return unicode_convert(json_data) else: return None except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "init_config_json", "line": line, "filename": filename, "synerror": synerror, } ) finally: json_data = None del json_data gc.collect()
python
def init_config_json(config_file): """Deserializes a JSON configuration file. Args: config_file (str): The path to the JSON file. Returns: dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``. """ json_data = None try: if os.path.exists(config_file): #Load the config file with open(config_file) as json_file: json_data = json.load(json_file) return unicode_convert(json_data) else: return None except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "init_config_json", "line": line, "filename": filename, "synerror": synerror, } ) finally: json_data = None del json_data gc.collect()
[ "def", "init_config_json", "(", "config_file", ")", ":", "json_data", "=", "None", "try", ":", "if", "os", ".", "path", ".", "exists", "(", "config_file", ")", ":", "#Load the config file", "with", "open", "(", "config_file", ")", "as", "json_file", ":", "json_data", "=", "json", ".", "load", "(", "json_file", ")", "return", "unicode_convert", "(", "json_data", ")", "else", ":", "return", "None", "except", ":", "line", ",", "filename", ",", "synerror", "=", "trace", "(", ")", "raise", "ArcRestHelperError", "(", "{", "\"function\"", ":", "\"init_config_json\"", ",", "\"line\"", ":", "line", ",", "\"filename\"", ":", "filename", ",", "\"synerror\"", ":", "synerror", ",", "}", ")", "finally", ":", "json_data", "=", "None", "del", "json_data", "gc", ".", "collect", "(", ")" ]
Deserializes a JSON configuration file. Args: config_file (str): The path to the JSON file. Returns: dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``.
[ "Deserializes", "a", "JSON", "configuration", "file", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L369-L402
12,891
Esri/ArcREST
src/arcresthelper/common.py
write_config_json
def write_config_json(config_file, data): """Serializes an object to disk. Args: config_file (str): The path on disk to save the file. data (object): The object to serialize. """ outfile = None try: with open(config_file, 'w') as outfile: json.dump(data, outfile) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "init_config_json", "line": line, "filename": filename, "synerror": synerror, } ) finally: outfile = None del outfile gc.collect()
python
def write_config_json(config_file, data): """Serializes an object to disk. Args: config_file (str): The path on disk to save the file. data (object): The object to serialize. """ outfile = None try: with open(config_file, 'w') as outfile: json.dump(data, outfile) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "init_config_json", "line": line, "filename": filename, "synerror": synerror, } ) finally: outfile = None del outfile gc.collect()
[ "def", "write_config_json", "(", "config_file", ",", "data", ")", ":", "outfile", "=", "None", "try", ":", "with", "open", "(", "config_file", ",", "'w'", ")", "as", "outfile", ":", "json", ".", "dump", "(", "data", ",", "outfile", ")", "except", ":", "line", ",", "filename", ",", "synerror", "=", "trace", "(", ")", "raise", "ArcRestHelperError", "(", "{", "\"function\"", ":", "\"init_config_json\"", ",", "\"line\"", ":", "line", ",", "\"filename\"", ":", "filename", ",", "\"synerror\"", ":", "synerror", ",", "}", ")", "finally", ":", "outfile", "=", "None", "del", "outfile", "gc", ".", "collect", "(", ")" ]
Serializes an object to disk. Args: config_file (str): The path on disk to save the file. data (object): The object to serialize.
[ "Serializes", "an", "object", "to", "disk", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L405-L431
12,892
Esri/ArcREST
src/arcresthelper/common.py
unicode_convert
def unicode_convert(obj): """Converts unicode objects to anscii. Args: obj (object): The object to convert. Returns: The object converted to anscii, if possible. For ``dict`` and ``list``, the object type is maintained. """ try: if isinstance(obj, dict): return {unicode_convert(key): unicode_convert(value) for key, value in obj.items()} elif isinstance(obj, list): return [unicode_convert(element) for element in obj] elif isinstance(obj, str): return obj elif isinstance(obj, six.text_type): return obj.encode('utf-8') elif isinstance(obj, six.integer_types): return obj else: return obj except: return obj
python
def unicode_convert(obj): """Converts unicode objects to anscii. Args: obj (object): The object to convert. Returns: The object converted to anscii, if possible. For ``dict`` and ``list``, the object type is maintained. """ try: if isinstance(obj, dict): return {unicode_convert(key): unicode_convert(value) for key, value in obj.items()} elif isinstance(obj, list): return [unicode_convert(element) for element in obj] elif isinstance(obj, str): return obj elif isinstance(obj, six.text_type): return obj.encode('utf-8') elif isinstance(obj, six.integer_types): return obj else: return obj except: return obj
[ "def", "unicode_convert", "(", "obj", ")", ":", "try", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "{", "unicode_convert", "(", "key", ")", ":", "unicode_convert", "(", "value", ")", "for", "key", ",", "value", "in", "obj", ".", "items", "(", ")", "}", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "[", "unicode_convert", "(", "element", ")", "for", "element", "in", "obj", "]", "elif", "isinstance", "(", "obj", ",", "str", ")", ":", "return", "obj", "elif", "isinstance", "(", "obj", ",", "six", ".", "text_type", ")", ":", "return", "obj", ".", "encode", "(", "'utf-8'", ")", "elif", "isinstance", "(", "obj", ",", "six", ".", "integer_types", ")", ":", "return", "obj", "else", ":", "return", "obj", "except", ":", "return", "obj" ]
Converts unicode objects to anscii. Args: obj (object): The object to convert. Returns: The object converted to anscii, if possible. For ``dict`` and ``list``, the object type is maintained.
[ "Converts", "unicode", "objects", "to", "anscii", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L434-L457
12,893
Esri/ArcREST
src/arcresthelper/common.py
find_replace
def find_replace(obj, find, replace): """ Searches an object and performs a find and replace. Args: obj (object): The object to iterate and find/replace. find (str): The string to search for. replace (str): The string to replace with. Returns: object: The object with replaced strings. """ try: if isinstance(obj, dict): return {find_replace(key,find,replace): find_replace(value,find,replace) for key, value in obj.items()} elif isinstance(obj, list): return [find_replace(element,find,replace) for element in obj] elif obj == find: return unicode_convert(replace) else: try: return unicode_convert(find_replace_string(obj, find, replace)) #obj = unicode_convert(json.loads(obj)) #return find_replace(obj,find,replace) except: return unicode_convert(obj) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "find_replace", "line": line, "filename": filename, "synerror": synerror, } ) finally: pass
python
def find_replace(obj, find, replace): """ Searches an object and performs a find and replace. Args: obj (object): The object to iterate and find/replace. find (str): The string to search for. replace (str): The string to replace with. Returns: object: The object with replaced strings. """ try: if isinstance(obj, dict): return {find_replace(key,find,replace): find_replace(value,find,replace) for key, value in obj.items()} elif isinstance(obj, list): return [find_replace(element,find,replace) for element in obj] elif obj == find: return unicode_convert(replace) else: try: return unicode_convert(find_replace_string(obj, find, replace)) #obj = unicode_convert(json.loads(obj)) #return find_replace(obj,find,replace) except: return unicode_convert(obj) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "find_replace", "line": line, "filename": filename, "synerror": synerror, } ) finally: pass
[ "def", "find_replace", "(", "obj", ",", "find", ",", "replace", ")", ":", "try", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "{", "find_replace", "(", "key", ",", "find", ",", "replace", ")", ":", "find_replace", "(", "value", ",", "find", ",", "replace", ")", "for", "key", ",", "value", "in", "obj", ".", "items", "(", ")", "}", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "[", "find_replace", "(", "element", ",", "find", ",", "replace", ")", "for", "element", "in", "obj", "]", "elif", "obj", "==", "find", ":", "return", "unicode_convert", "(", "replace", ")", "else", ":", "try", ":", "return", "unicode_convert", "(", "find_replace_string", "(", "obj", ",", "find", ",", "replace", ")", ")", "#obj = unicode_convert(json.loads(obj))", "#return find_replace(obj,find,replace)", "except", ":", "return", "unicode_convert", "(", "obj", ")", "except", ":", "line", ",", "filename", ",", "synerror", "=", "trace", "(", ")", "raise", "ArcRestHelperError", "(", "{", "\"function\"", ":", "\"find_replace\"", ",", "\"line\"", ":", "line", ",", "\"filename\"", ":", "filename", ",", "\"synerror\"", ":", "synerror", ",", "}", ")", "finally", ":", "pass" ]
Searches an object and performs a find and replace. Args: obj (object): The object to iterate and find/replace. find (str): The string to search for. replace (str): The string to replace with. Returns: object: The object with replaced strings.
[ "Searches", "an", "object", "and", "performs", "a", "find", "and", "replace", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcresthelper/common.py#L490-L525
12,894
Esri/ArcREST
src/arcrest/_abstract/abstract.py
BaseAGSServer._tostr
def _tostr(self,obj): """ converts a object to list, if object is a list, it creates a comma seperated string. """ if not obj: return '' if isinstance(obj, list): return ', '.join(map(self._tostr, obj)) return str(obj)
python
def _tostr(self,obj): """ converts a object to list, if object is a list, it creates a comma seperated string. """ if not obj: return '' if isinstance(obj, list): return ', '.join(map(self._tostr, obj)) return str(obj)
[ "def", "_tostr", "(", "self", ",", "obj", ")", ":", "if", "not", "obj", ":", "return", "''", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "', '", ".", "join", "(", "map", "(", "self", ".", "_tostr", ",", "obj", ")", ")", "return", "str", "(", "obj", ")" ]
converts a object to list, if object is a list, it creates a comma seperated string.
[ "converts", "a", "object", "to", "list", "if", "object", "is", "a", "list", "it", "creates", "a", "comma", "seperated", "string", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/_abstract/abstract.py#L151-L159
12,895
Esri/ArcREST
src/arcrest/_abstract/abstract.py
BaseAGOLClass._unzip_file
def _unzip_file(self, zip_file, out_folder): """ unzips a file to a given folder """ try: zf = zipfile.ZipFile(zip_file, 'r') zf.extractall(path=out_folder) zf.close() del zf return True except: return False
python
def _unzip_file(self, zip_file, out_folder): """ unzips a file to a given folder """ try: zf = zipfile.ZipFile(zip_file, 'r') zf.extractall(path=out_folder) zf.close() del zf return True except: return False
[ "def", "_unzip_file", "(", "self", ",", "zip_file", ",", "out_folder", ")", ":", "try", ":", "zf", "=", "zipfile", ".", "ZipFile", "(", "zip_file", ",", "'r'", ")", "zf", ".", "extractall", "(", "path", "=", "out_folder", ")", "zf", ".", "close", "(", ")", "del", "zf", "return", "True", "except", ":", "return", "False" ]
unzips a file to a given folder
[ "unzips", "a", "file", "to", "a", "given", "folder" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/_abstract/abstract.py#L235-L244
12,896
Esri/ArcREST
src/arcrest/_abstract/abstract.py
BaseAGOLClass._list_files
def _list_files(self, path): """lists files in a given directory""" files = [] for f in glob.glob(pathname=path): files.append(f) files.sort() return files
python
def _list_files(self, path): """lists files in a given directory""" files = [] for f in glob.glob(pathname=path): files.append(f) files.sort() return files
[ "def", "_list_files", "(", "self", ",", "path", ")", ":", "files", "=", "[", "]", "for", "f", "in", "glob", ".", "glob", "(", "pathname", "=", "path", ")", ":", "files", ".", "append", "(", "f", ")", "files", ".", "sort", "(", ")", "return", "files" ]
lists files in a given directory
[ "lists", "files", "in", "a", "given", "directory" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/_abstract/abstract.py#L252-L258
12,897
Esri/ArcREST
src/arcrest/_abstract/abstract.py
BaseAGOLClass._get_content_type
def _get_content_type(self, filename): """ gets the content type of a file """ mntype = mimetypes.guess_type(filename)[0] filename, fileExtension = os.path.splitext(filename) if mntype is None and\ fileExtension.lower() == ".csv": mntype = "text/csv" elif mntype is None and \ fileExtension.lower() == ".sd": mntype = "File/sd" elif mntype is None: #mntype = 'application/octet-stream' mntype= "File/%s" % fileExtension.replace('.', '') return mntype
python
def _get_content_type(self, filename): """ gets the content type of a file """ mntype = mimetypes.guess_type(filename)[0] filename, fileExtension = os.path.splitext(filename) if mntype is None and\ fileExtension.lower() == ".csv": mntype = "text/csv" elif mntype is None and \ fileExtension.lower() == ".sd": mntype = "File/sd" elif mntype is None: #mntype = 'application/octet-stream' mntype= "File/%s" % fileExtension.replace('.', '') return mntype
[ "def", "_get_content_type", "(", "self", ",", "filename", ")", ":", "mntype", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "filename", ",", "fileExtension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "mntype", "is", "None", "and", "fileExtension", ".", "lower", "(", ")", "==", "\".csv\"", ":", "mntype", "=", "\"text/csv\"", "elif", "mntype", "is", "None", "and", "fileExtension", ".", "lower", "(", ")", "==", "\".sd\"", ":", "mntype", "=", "\"File/sd\"", "elif", "mntype", "is", "None", ":", "#mntype = 'application/octet-stream'", "mntype", "=", "\"File/%s\"", "%", "fileExtension", ".", "replace", "(", "'.'", ",", "''", ")", "return", "mntype" ]
gets the content type of a file
[ "gets", "the", "content", "type", "of", "a", "file" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/_abstract/abstract.py#L260-L273
12,898
Esri/ArcREST
src/arcrest/common/symbology.py
SimpleMarkerSymbol.value
def value(self): """returns the object as dictionary""" if self._outline is None: return { "type" : "esriSMS", "style" : self._style, "color" : self._color.value, "size" : self._size, "angle" : self._angle, "xoffset" : self._xoffset, "yoffset" : self._yoffset } else: return { "type" : "esriSMS", "style" : self._style, "color" : self._color.value, "size" : self._size, "angle" : self._angle, "xoffset" : self._xoffset, "yoffset" : self._yoffset, "outline" : { "width" : self._outline['width'], "color" : self._color.value } }
python
def value(self): """returns the object as dictionary""" if self._outline is None: return { "type" : "esriSMS", "style" : self._style, "color" : self._color.value, "size" : self._size, "angle" : self._angle, "xoffset" : self._xoffset, "yoffset" : self._yoffset } else: return { "type" : "esriSMS", "style" : self._style, "color" : self._color.value, "size" : self._size, "angle" : self._angle, "xoffset" : self._xoffset, "yoffset" : self._yoffset, "outline" : { "width" : self._outline['width'], "color" : self._color.value } }
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "_outline", "is", "None", ":", "return", "{", "\"type\"", ":", "\"esriSMS\"", ",", "\"style\"", ":", "self", ".", "_style", ",", "\"color\"", ":", "self", ".", "_color", ".", "value", ",", "\"size\"", ":", "self", ".", "_size", ",", "\"angle\"", ":", "self", ".", "_angle", ",", "\"xoffset\"", ":", "self", ".", "_xoffset", ",", "\"yoffset\"", ":", "self", ".", "_yoffset", "}", "else", ":", "return", "{", "\"type\"", ":", "\"esriSMS\"", ",", "\"style\"", ":", "self", ".", "_style", ",", "\"color\"", ":", "self", ".", "_color", ".", "value", ",", "\"size\"", ":", "self", ".", "_size", ",", "\"angle\"", ":", "self", ".", "_angle", ",", "\"xoffset\"", ":", "self", ".", "_xoffset", ",", "\"yoffset\"", ":", "self", ".", "_yoffset", ",", "\"outline\"", ":", "{", "\"width\"", ":", "self", ".", "_outline", "[", "'width'", "]", ",", "\"color\"", ":", "self", ".", "_color", ".", "value", "}", "}" ]
returns the object as dictionary
[ "returns", "the", "object", "as", "dictionary" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/symbology.py#L157-L182
12,899
Esri/ArcREST
src/arcrest/manageportal/administration.py
_Federation.unfederate
def unfederate(self, serverId): """ This operation unfederates an ArcGIS Server from Portal for ArcGIS """ url = self._url + "/servers/{serverid}/unfederate".format( serverid=serverId) params = {"f" : "json"} return self._get(url=url, param_dict=params, proxy_port=self._proxy_port, proxy_url=self._proxy_ur)
python
def unfederate(self, serverId): """ This operation unfederates an ArcGIS Server from Portal for ArcGIS """ url = self._url + "/servers/{serverid}/unfederate".format( serverid=serverId) params = {"f" : "json"} return self._get(url=url, param_dict=params, proxy_port=self._proxy_port, proxy_url=self._proxy_ur)
[ "def", "unfederate", "(", "self", ",", "serverId", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/servers/{serverid}/unfederate\"", ".", "format", "(", "serverid", "=", "serverId", ")", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "return", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "proxy_url", "=", "self", ".", "_proxy_ur", ")" ]
This operation unfederates an ArcGIS Server from Portal for ArcGIS
[ "This", "operation", "unfederates", "an", "ArcGIS", "Server", "from", "Portal", "for", "ArcGIS" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageportal/administration.py#L72-L82