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,600
juju/charm-helpers
charmhelpers/contrib/ansible/__init__.py
AnsibleHooks.action
def action(self, *action_names): """Decorator, registering them as actions""" def action_wrapper(decorated): @functools.wraps(decorated) def wrapper(argv): kwargs = dict(arg.split('=') for arg in argv) try: return decorated(**kwargs) except TypeError as e: if decorated.__doc__: e.args += (decorated.__doc__,) raise self.register_action(decorated.__name__, wrapper) if '_' in decorated.__name__: self.register_action( decorated.__name__.replace('_', '-'), wrapper) return wrapper return action_wrapper
python
def action(self, *action_names): """Decorator, registering them as actions""" def action_wrapper(decorated): @functools.wraps(decorated) def wrapper(argv): kwargs = dict(arg.split('=') for arg in argv) try: return decorated(**kwargs) except TypeError as e: if decorated.__doc__: e.args += (decorated.__doc__,) raise self.register_action(decorated.__name__, wrapper) if '_' in decorated.__name__: self.register_action( decorated.__name__.replace('_', '-'), wrapper) return wrapper return action_wrapper
[ "def", "action", "(", "self", ",", "*", "action_names", ")", ":", "def", "action_wrapper", "(", "decorated", ")", ":", "@", "functools", ".", "wraps", "(", "decorated", ")", "def", "wrapper", "(", "argv", ")", ":", "kwargs", "=", "dict", "(", "arg", ".", "split", "(", "'='", ")", "for", "arg", "in", "argv", ")", "try", ":", "return", "decorated", "(", "*", "*", "kwargs", ")", "except", "TypeError", "as", "e", ":", "if", "decorated", ".", "__doc__", ":", "e", ".", "args", "+=", "(", "decorated", ".", "__doc__", ",", ")", "raise", "self", ".", "register_action", "(", "decorated", ".", "__name__", ",", "wrapper", ")", "if", "'_'", "in", "decorated", ".", "__name__", ":", "self", ".", "register_action", "(", "decorated", ".", "__name__", ".", "replace", "(", "'_'", ",", "'-'", ")", ",", "wrapper", ")", "return", "wrapper", "return", "action_wrapper" ]
Decorator, registering them as actions
[ "Decorator", "registering", "them", "as", "actions" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ansible/__init__.py#L231-L252
12,601
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment.get_logger
def get_logger(self, name="deployment-logger", level=logging.DEBUG): """Get a logger object that will log to stdout.""" log = logging logger = log.getLogger(name) fmt = log.Formatter("%(asctime)s %(funcName)s " "%(levelname)s: %(message)s") handler = log.StreamHandler(stream=sys.stdout) handler.setLevel(level) handler.setFormatter(fmt) logger.addHandler(handler) logger.setLevel(level) return logger
python
def get_logger(self, name="deployment-logger", level=logging.DEBUG): """Get a logger object that will log to stdout.""" log = logging logger = log.getLogger(name) fmt = log.Formatter("%(asctime)s %(funcName)s " "%(levelname)s: %(message)s") handler = log.StreamHandler(stream=sys.stdout) handler.setLevel(level) handler.setFormatter(fmt) logger.addHandler(handler) logger.setLevel(level) return logger
[ "def", "get_logger", "(", "self", ",", "name", "=", "\"deployment-logger\"", ",", "level", "=", "logging", ".", "DEBUG", ")", ":", "log", "=", "logging", "logger", "=", "log", ".", "getLogger", "(", "name", ")", "fmt", "=", "log", ".", "Formatter", "(", "\"%(asctime)s %(funcName)s \"", "\"%(levelname)s: %(message)s\"", ")", "handler", "=", "log", ".", "StreamHandler", "(", "stream", "=", "sys", ".", "stdout", ")", "handler", ".", "setLevel", "(", "level", ")", "handler", ".", "setFormatter", "(", "fmt", ")", "logger", ".", "addHandler", "(", "handler", ")", "logger", ".", "setLevel", "(", "level", ")", "return", "logger" ]
Get a logger object that will log to stdout.
[ "Get", "a", "logger", "object", "that", "will", "log", "to", "stdout", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L49-L63
12,602
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment._determine_branch_locations
def _determine_branch_locations(self, other_services): """Determine the branch locations for the other services. Determine if the local branch being tested is derived from its stable or next (dev) branch, and based on this, use the corresonding stable or next branches for the other_services.""" self.log.info('OpenStackAmuletDeployment: determine branch locations') # Charms outside the ~openstack-charmers base_charms = { 'mysql': ['trusty'], 'mongodb': ['trusty'], 'nrpe': ['trusty', 'xenial'], } for svc in other_services: # If a location has been explicitly set, use it if svc.get('location'): continue if svc['name'] in base_charms: # NOTE: not all charms have support for all series we # want/need to test against, so fix to most recent # that each base charm supports target_series = self.series if self.series not in base_charms[svc['name']]: target_series = base_charms[svc['name']][-1] svc['location'] = 'cs:{}/{}'.format(target_series, svc['name']) elif self.stable: svc['location'] = 'cs:{}/{}'.format(self.series, svc['name']) else: svc['location'] = 'cs:~openstack-charmers-next/{}/{}'.format( self.series, svc['name'] ) return other_services
python
def _determine_branch_locations(self, other_services): """Determine the branch locations for the other services. Determine if the local branch being tested is derived from its stable or next (dev) branch, and based on this, use the corresonding stable or next branches for the other_services.""" self.log.info('OpenStackAmuletDeployment: determine branch locations') # Charms outside the ~openstack-charmers base_charms = { 'mysql': ['trusty'], 'mongodb': ['trusty'], 'nrpe': ['trusty', 'xenial'], } for svc in other_services: # If a location has been explicitly set, use it if svc.get('location'): continue if svc['name'] in base_charms: # NOTE: not all charms have support for all series we # want/need to test against, so fix to most recent # that each base charm supports target_series = self.series if self.series not in base_charms[svc['name']]: target_series = base_charms[svc['name']][-1] svc['location'] = 'cs:{}/{}'.format(target_series, svc['name']) elif self.stable: svc['location'] = 'cs:{}/{}'.format(self.series, svc['name']) else: svc['location'] = 'cs:~openstack-charmers-next/{}/{}'.format( self.series, svc['name'] ) return other_services
[ "def", "_determine_branch_locations", "(", "self", ",", "other_services", ")", ":", "self", ".", "log", ".", "info", "(", "'OpenStackAmuletDeployment: determine branch locations'", ")", "# Charms outside the ~openstack-charmers", "base_charms", "=", "{", "'mysql'", ":", "[", "'trusty'", "]", ",", "'mongodb'", ":", "[", "'trusty'", "]", ",", "'nrpe'", ":", "[", "'trusty'", ",", "'xenial'", "]", ",", "}", "for", "svc", "in", "other_services", ":", "# If a location has been explicitly set, use it", "if", "svc", ".", "get", "(", "'location'", ")", ":", "continue", "if", "svc", "[", "'name'", "]", "in", "base_charms", ":", "# NOTE: not all charms have support for all series we", "# want/need to test against, so fix to most recent", "# that each base charm supports", "target_series", "=", "self", ".", "series", "if", "self", ".", "series", "not", "in", "base_charms", "[", "svc", "[", "'name'", "]", "]", ":", "target_series", "=", "base_charms", "[", "svc", "[", "'name'", "]", "]", "[", "-", "1", "]", "svc", "[", "'location'", "]", "=", "'cs:{}/{}'", ".", "format", "(", "target_series", ",", "svc", "[", "'name'", "]", ")", "elif", "self", ".", "stable", ":", "svc", "[", "'location'", "]", "=", "'cs:{}/{}'", ".", "format", "(", "self", ".", "series", ",", "svc", "[", "'name'", "]", ")", "else", ":", "svc", "[", "'location'", "]", "=", "'cs:~openstack-charmers-next/{}/{}'", ".", "format", "(", "self", ".", "series", ",", "svc", "[", "'name'", "]", ")", "return", "other_services" ]
Determine the branch locations for the other services. Determine if the local branch being tested is derived from its stable or next (dev) branch, and based on this, use the corresonding stable or next branches for the other_services.
[ "Determine", "the", "branch", "locations", "for", "the", "other", "services", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L65-L103
12,603
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment._auto_wait_for_status
def _auto_wait_for_status(self, message=None, exclude_services=None, include_only=None, timeout=None): """Wait for all units to have a specific extended status, except for any defined as excluded. Unless specified via message, any status containing any case of 'ready' will be considered a match. Examples of message usage: Wait for all unit status to CONTAIN any case of 'ready' or 'ok': message = re.compile('.*ready.*|.*ok.*', re.IGNORECASE) Wait for all units to reach this status (exact match): message = re.compile('^Unit is ready and clustered$') Wait for all units to reach any one of these (exact match): message = re.compile('Unit is ready|OK|Ready') Wait for at least one unit to reach this status (exact match): message = {'ready'} See Amulet's sentry.wait_for_messages() for message usage detail. https://github.com/juju/amulet/blob/master/amulet/sentry.py :param message: Expected status match :param exclude_services: List of juju service names to ignore, not to be used in conjuction with include_only. :param include_only: List of juju service names to exclusively check, not to be used in conjuction with exclude_services. :param timeout: Maximum time in seconds to wait for status match :returns: None. Raises if timeout is hit. """ if not timeout: timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 1800)) self.log.info('Waiting for extended status on units for {}s...' ''.format(timeout)) all_services = self.d.services.keys() if exclude_services and include_only: raise ValueError('exclude_services can not be used ' 'with include_only') if message: if isinstance(message, re._pattern_type): match = message.pattern else: match = message self.log.debug('Custom extended status wait match: ' '{}'.format(match)) else: self.log.debug('Default extended status wait match: contains ' 'READY (case-insensitive)') message = re.compile('.*ready.*', re.IGNORECASE) if exclude_services: self.log.debug('Excluding services from extended status match: ' '{}'.format(exclude_services)) else: exclude_services = [] if include_only: services = include_only else: services = list(set(all_services) - set(exclude_services)) self.log.debug('Waiting up to {}s for extended status on services: ' '{}'.format(timeout, services)) service_messages = {service: message for service in services} # Check for idleness self.d.sentry.wait(timeout=timeout) # Check for error states and bail early self.d.sentry.wait_for_status(self.d.juju_env, services, timeout=timeout) # Check for ready messages self.d.sentry.wait_for_messages(service_messages, timeout=timeout) self.log.info('OK')
python
def _auto_wait_for_status(self, message=None, exclude_services=None, include_only=None, timeout=None): """Wait for all units to have a specific extended status, except for any defined as excluded. Unless specified via message, any status containing any case of 'ready' will be considered a match. Examples of message usage: Wait for all unit status to CONTAIN any case of 'ready' or 'ok': message = re.compile('.*ready.*|.*ok.*', re.IGNORECASE) Wait for all units to reach this status (exact match): message = re.compile('^Unit is ready and clustered$') Wait for all units to reach any one of these (exact match): message = re.compile('Unit is ready|OK|Ready') Wait for at least one unit to reach this status (exact match): message = {'ready'} See Amulet's sentry.wait_for_messages() for message usage detail. https://github.com/juju/amulet/blob/master/amulet/sentry.py :param message: Expected status match :param exclude_services: List of juju service names to ignore, not to be used in conjuction with include_only. :param include_only: List of juju service names to exclusively check, not to be used in conjuction with exclude_services. :param timeout: Maximum time in seconds to wait for status match :returns: None. Raises if timeout is hit. """ if not timeout: timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 1800)) self.log.info('Waiting for extended status on units for {}s...' ''.format(timeout)) all_services = self.d.services.keys() if exclude_services and include_only: raise ValueError('exclude_services can not be used ' 'with include_only') if message: if isinstance(message, re._pattern_type): match = message.pattern else: match = message self.log.debug('Custom extended status wait match: ' '{}'.format(match)) else: self.log.debug('Default extended status wait match: contains ' 'READY (case-insensitive)') message = re.compile('.*ready.*', re.IGNORECASE) if exclude_services: self.log.debug('Excluding services from extended status match: ' '{}'.format(exclude_services)) else: exclude_services = [] if include_only: services = include_only else: services = list(set(all_services) - set(exclude_services)) self.log.debug('Waiting up to {}s for extended status on services: ' '{}'.format(timeout, services)) service_messages = {service: message for service in services} # Check for idleness self.d.sentry.wait(timeout=timeout) # Check for error states and bail early self.d.sentry.wait_for_status(self.d.juju_env, services, timeout=timeout) # Check for ready messages self.d.sentry.wait_for_messages(service_messages, timeout=timeout) self.log.info('OK')
[ "def", "_auto_wait_for_status", "(", "self", ",", "message", "=", "None", ",", "exclude_services", "=", "None", ",", "include_only", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "not", "timeout", ":", "timeout", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'AMULET_SETUP_TIMEOUT'", ",", "1800", ")", ")", "self", ".", "log", ".", "info", "(", "'Waiting for extended status on units for {}s...'", "''", ".", "format", "(", "timeout", ")", ")", "all_services", "=", "self", ".", "d", ".", "services", ".", "keys", "(", ")", "if", "exclude_services", "and", "include_only", ":", "raise", "ValueError", "(", "'exclude_services can not be used '", "'with include_only'", ")", "if", "message", ":", "if", "isinstance", "(", "message", ",", "re", ".", "_pattern_type", ")", ":", "match", "=", "message", ".", "pattern", "else", ":", "match", "=", "message", "self", ".", "log", ".", "debug", "(", "'Custom extended status wait match: '", "'{}'", ".", "format", "(", "match", ")", ")", "else", ":", "self", ".", "log", ".", "debug", "(", "'Default extended status wait match: contains '", "'READY (case-insensitive)'", ")", "message", "=", "re", ".", "compile", "(", "'.*ready.*'", ",", "re", ".", "IGNORECASE", ")", "if", "exclude_services", ":", "self", ".", "log", ".", "debug", "(", "'Excluding services from extended status match: '", "'{}'", ".", "format", "(", "exclude_services", ")", ")", "else", ":", "exclude_services", "=", "[", "]", "if", "include_only", ":", "services", "=", "include_only", "else", ":", "services", "=", "list", "(", "set", "(", "all_services", ")", "-", "set", "(", "exclude_services", ")", ")", "self", ".", "log", ".", "debug", "(", "'Waiting up to {}s for extended status on services: '", "'{}'", ".", "format", "(", "timeout", ",", "services", ")", ")", "service_messages", "=", "{", "service", ":", "message", "for", "service", "in", "services", "}", "# Check for idleness", "self", ".", "d", ".", "sentry", ".", "wait", "(", "timeout", "=", "timeout", ")", "# Check for error states and bail early", "self", ".", "d", ".", "sentry", ".", "wait_for_status", "(", "self", ".", "d", ".", "juju_env", ",", "services", ",", "timeout", "=", "timeout", ")", "# Check for ready messages", "self", ".", "d", ".", "sentry", ".", "wait_for_messages", "(", "service_messages", ",", "timeout", "=", "timeout", ")", "self", ".", "log", ".", "info", "(", "'OK'", ")" ]
Wait for all units to have a specific extended status, except for any defined as excluded. Unless specified via message, any status containing any case of 'ready' will be considered a match. Examples of message usage: Wait for all unit status to CONTAIN any case of 'ready' or 'ok': message = re.compile('.*ready.*|.*ok.*', re.IGNORECASE) Wait for all units to reach this status (exact match): message = re.compile('^Unit is ready and clustered$') Wait for all units to reach any one of these (exact match): message = re.compile('Unit is ready|OK|Ready') Wait for at least one unit to reach this status (exact match): message = {'ready'} See Amulet's sentry.wait_for_messages() for message usage detail. https://github.com/juju/amulet/blob/master/amulet/sentry.py :param message: Expected status match :param exclude_services: List of juju service names to ignore, not to be used in conjuction with include_only. :param include_only: List of juju service names to exclusively check, not to be used in conjuction with exclude_services. :param timeout: Maximum time in seconds to wait for status match :returns: None. Raises if timeout is hit.
[ "Wait", "for", "all", "units", "to", "have", "a", "specific", "extended", "status", "except", "for", "any", "defined", "as", "excluded", ".", "Unless", "specified", "via", "message", "any", "status", "containing", "any", "case", "of", "ready", "will", "be", "considered", "a", "match", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L192-L269
12,604
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment._get_openstack_release
def _get_openstack_release(self): """Get openstack release. Return an integer representing the enum value of the openstack release. """ # Must be ordered by OpenStack release (not by Ubuntu release): for i, os_pair in enumerate(OPENSTACK_RELEASES_PAIRS): setattr(self, os_pair, i) releases = { ('trusty', None): self.trusty_icehouse, ('trusty', 'cloud:trusty-kilo'): self.trusty_kilo, ('trusty', 'cloud:trusty-liberty'): self.trusty_liberty, ('trusty', 'cloud:trusty-mitaka'): self.trusty_mitaka, ('xenial', None): self.xenial_mitaka, ('xenial', 'cloud:xenial-newton'): self.xenial_newton, ('xenial', 'cloud:xenial-ocata'): self.xenial_ocata, ('xenial', 'cloud:xenial-pike'): self.xenial_pike, ('xenial', 'cloud:xenial-queens'): self.xenial_queens, ('yakkety', None): self.yakkety_newton, ('zesty', None): self.zesty_ocata, ('artful', None): self.artful_pike, ('bionic', None): self.bionic_queens, ('bionic', 'cloud:bionic-rocky'): self.bionic_rocky, ('bionic', 'cloud:bionic-stein'): self.bionic_stein, ('cosmic', None): self.cosmic_rocky, ('disco', None): self.disco_stein, } return releases[(self.series, self.openstack)]
python
def _get_openstack_release(self): """Get openstack release. Return an integer representing the enum value of the openstack release. """ # Must be ordered by OpenStack release (not by Ubuntu release): for i, os_pair in enumerate(OPENSTACK_RELEASES_PAIRS): setattr(self, os_pair, i) releases = { ('trusty', None): self.trusty_icehouse, ('trusty', 'cloud:trusty-kilo'): self.trusty_kilo, ('trusty', 'cloud:trusty-liberty'): self.trusty_liberty, ('trusty', 'cloud:trusty-mitaka'): self.trusty_mitaka, ('xenial', None): self.xenial_mitaka, ('xenial', 'cloud:xenial-newton'): self.xenial_newton, ('xenial', 'cloud:xenial-ocata'): self.xenial_ocata, ('xenial', 'cloud:xenial-pike'): self.xenial_pike, ('xenial', 'cloud:xenial-queens'): self.xenial_queens, ('yakkety', None): self.yakkety_newton, ('zesty', None): self.zesty_ocata, ('artful', None): self.artful_pike, ('bionic', None): self.bionic_queens, ('bionic', 'cloud:bionic-rocky'): self.bionic_rocky, ('bionic', 'cloud:bionic-stein'): self.bionic_stein, ('cosmic', None): self.cosmic_rocky, ('disco', None): self.disco_stein, } return releases[(self.series, self.openstack)]
[ "def", "_get_openstack_release", "(", "self", ")", ":", "# Must be ordered by OpenStack release (not by Ubuntu release):", "for", "i", ",", "os_pair", "in", "enumerate", "(", "OPENSTACK_RELEASES_PAIRS", ")", ":", "setattr", "(", "self", ",", "os_pair", ",", "i", ")", "releases", "=", "{", "(", "'trusty'", ",", "None", ")", ":", "self", ".", "trusty_icehouse", ",", "(", "'trusty'", ",", "'cloud:trusty-kilo'", ")", ":", "self", ".", "trusty_kilo", ",", "(", "'trusty'", ",", "'cloud:trusty-liberty'", ")", ":", "self", ".", "trusty_liberty", ",", "(", "'trusty'", ",", "'cloud:trusty-mitaka'", ")", ":", "self", ".", "trusty_mitaka", ",", "(", "'xenial'", ",", "None", ")", ":", "self", ".", "xenial_mitaka", ",", "(", "'xenial'", ",", "'cloud:xenial-newton'", ")", ":", "self", ".", "xenial_newton", ",", "(", "'xenial'", ",", "'cloud:xenial-ocata'", ")", ":", "self", ".", "xenial_ocata", ",", "(", "'xenial'", ",", "'cloud:xenial-pike'", ")", ":", "self", ".", "xenial_pike", ",", "(", "'xenial'", ",", "'cloud:xenial-queens'", ")", ":", "self", ".", "xenial_queens", ",", "(", "'yakkety'", ",", "None", ")", ":", "self", ".", "yakkety_newton", ",", "(", "'zesty'", ",", "None", ")", ":", "self", ".", "zesty_ocata", ",", "(", "'artful'", ",", "None", ")", ":", "self", ".", "artful_pike", ",", "(", "'bionic'", ",", "None", ")", ":", "self", ".", "bionic_queens", ",", "(", "'bionic'", ",", "'cloud:bionic-rocky'", ")", ":", "self", ".", "bionic_rocky", ",", "(", "'bionic'", ",", "'cloud:bionic-stein'", ")", ":", "self", ".", "bionic_stein", ",", "(", "'cosmic'", ",", "None", ")", ":", "self", ".", "cosmic_rocky", ",", "(", "'disco'", ",", "None", ")", ":", "self", ".", "disco_stein", ",", "}", "return", "releases", "[", "(", "self", ".", "series", ",", "self", ".", "openstack", ")", "]" ]
Get openstack release. Return an integer representing the enum value of the openstack release.
[ "Get", "openstack", "release", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L271-L300
12,605
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment._get_openstack_release_string
def _get_openstack_release_string(self): """Get openstack release string. Return a string representing the openstack release. """ releases = OrderedDict([ ('trusty', 'icehouse'), ('xenial', 'mitaka'), ('yakkety', 'newton'), ('zesty', 'ocata'), ('artful', 'pike'), ('bionic', 'queens'), ('cosmic', 'rocky'), ('disco', 'stein'), ]) if self.openstack: os_origin = self.openstack.split(':')[1] return os_origin.split('%s-' % self.series)[1].split('/')[0] else: return releases[self.series]
python
def _get_openstack_release_string(self): """Get openstack release string. Return a string representing the openstack release. """ releases = OrderedDict([ ('trusty', 'icehouse'), ('xenial', 'mitaka'), ('yakkety', 'newton'), ('zesty', 'ocata'), ('artful', 'pike'), ('bionic', 'queens'), ('cosmic', 'rocky'), ('disco', 'stein'), ]) if self.openstack: os_origin = self.openstack.split(':')[1] return os_origin.split('%s-' % self.series)[1].split('/')[0] else: return releases[self.series]
[ "def", "_get_openstack_release_string", "(", "self", ")", ":", "releases", "=", "OrderedDict", "(", "[", "(", "'trusty'", ",", "'icehouse'", ")", ",", "(", "'xenial'", ",", "'mitaka'", ")", ",", "(", "'yakkety'", ",", "'newton'", ")", ",", "(", "'zesty'", ",", "'ocata'", ")", ",", "(", "'artful'", ",", "'pike'", ")", ",", "(", "'bionic'", ",", "'queens'", ")", ",", "(", "'cosmic'", ",", "'rocky'", ")", ",", "(", "'disco'", ",", "'stein'", ")", ",", "]", ")", "if", "self", ".", "openstack", ":", "os_origin", "=", "self", ".", "openstack", ".", "split", "(", "':'", ")", "[", "1", "]", "return", "os_origin", ".", "split", "(", "'%s-'", "%", "self", ".", "series", ")", "[", "1", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", "else", ":", "return", "releases", "[", "self", ".", "series", "]" ]
Get openstack release string. Return a string representing the openstack release.
[ "Get", "openstack", "release", "string", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L302-L321
12,606
juju/charm-helpers
charmhelpers/contrib/openstack/amulet/deployment.py
OpenStackAmuletDeployment.get_ceph_expected_pools
def get_ceph_expected_pools(self, radosgw=False): """Return a list of expected ceph pools in a ceph + cinder + glance test scenario, based on OpenStack release and whether ceph radosgw is flagged as present or not.""" if self._get_openstack_release() == self.trusty_icehouse: # Icehouse pools = [ 'data', 'metadata', 'rbd', 'cinder-ceph', 'glance' ] elif (self.trusty_kilo <= self._get_openstack_release() <= self.zesty_ocata): # Kilo through Ocata pools = [ 'rbd', 'cinder-ceph', 'glance' ] else: # Pike and later pools = [ 'cinder-ceph', 'glance' ] if radosgw: pools.extend([ '.rgw.root', '.rgw.control', '.rgw', '.rgw.gc', '.users.uid' ]) return pools
python
def get_ceph_expected_pools(self, radosgw=False): """Return a list of expected ceph pools in a ceph + cinder + glance test scenario, based on OpenStack release and whether ceph radosgw is flagged as present or not.""" if self._get_openstack_release() == self.trusty_icehouse: # Icehouse pools = [ 'data', 'metadata', 'rbd', 'cinder-ceph', 'glance' ] elif (self.trusty_kilo <= self._get_openstack_release() <= self.zesty_ocata): # Kilo through Ocata pools = [ 'rbd', 'cinder-ceph', 'glance' ] else: # Pike and later pools = [ 'cinder-ceph', 'glance' ] if radosgw: pools.extend([ '.rgw.root', '.rgw.control', '.rgw', '.rgw.gc', '.users.uid' ]) return pools
[ "def", "get_ceph_expected_pools", "(", "self", ",", "radosgw", "=", "False", ")", ":", "if", "self", ".", "_get_openstack_release", "(", ")", "==", "self", ".", "trusty_icehouse", ":", "# Icehouse", "pools", "=", "[", "'data'", ",", "'metadata'", ",", "'rbd'", ",", "'cinder-ceph'", ",", "'glance'", "]", "elif", "(", "self", ".", "trusty_kilo", "<=", "self", ".", "_get_openstack_release", "(", ")", "<=", "self", ".", "zesty_ocata", ")", ":", "# Kilo through Ocata", "pools", "=", "[", "'rbd'", ",", "'cinder-ceph'", ",", "'glance'", "]", "else", ":", "# Pike and later", "pools", "=", "[", "'cinder-ceph'", ",", "'glance'", "]", "if", "radosgw", ":", "pools", ".", "extend", "(", "[", "'.rgw.root'", ",", "'.rgw.control'", ",", "'.rgw'", ",", "'.rgw.gc'", ",", "'.users.uid'", "]", ")", "return", "pools" ]
Return a list of expected ceph pools in a ceph + cinder + glance test scenario, based on OpenStack release and whether ceph radosgw is flagged as present or not.
[ "Return", "a", "list", "of", "expected", "ceph", "pools", "in", "a", "ceph", "+", "cinder", "+", "glance", "test", "scenario", "based", "on", "OpenStack", "release", "and", "whether", "ceph", "radosgw", "is", "flagged", "as", "present", "or", "not", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/amulet/deployment.py#L323-L361
12,607
juju/charm-helpers
charmhelpers/osplatform.py
get_platform
def get_platform(): """Return the current OS platform. For example: if current os platform is Ubuntu then a string "ubuntu" will be returned (which is the name of the module). This string is used to decide which platform module should be imported. """ # linux_distribution is deprecated and will be removed in Python 3.7 # Warings *not* disabled, as we certainly need to fix this. tuple_platform = platform.linux_distribution() current_platform = tuple_platform[0] if "Ubuntu" in current_platform: return "ubuntu" elif "CentOS" in current_platform: return "centos" elif "debian" in current_platform: # Stock Python does not detect Ubuntu and instead returns debian. # Or at least it does in some build environments like Travis CI return "ubuntu" else: raise RuntimeError("This module is not supported on {}." .format(current_platform))
python
def get_platform(): """Return the current OS platform. For example: if current os platform is Ubuntu then a string "ubuntu" will be returned (which is the name of the module). This string is used to decide which platform module should be imported. """ # linux_distribution is deprecated and will be removed in Python 3.7 # Warings *not* disabled, as we certainly need to fix this. tuple_platform = platform.linux_distribution() current_platform = tuple_platform[0] if "Ubuntu" in current_platform: return "ubuntu" elif "CentOS" in current_platform: return "centos" elif "debian" in current_platform: # Stock Python does not detect Ubuntu and instead returns debian. # Or at least it does in some build environments like Travis CI return "ubuntu" else: raise RuntimeError("This module is not supported on {}." .format(current_platform))
[ "def", "get_platform", "(", ")", ":", "# linux_distribution is deprecated and will be removed in Python 3.7", "# Warings *not* disabled, as we certainly need to fix this.", "tuple_platform", "=", "platform", ".", "linux_distribution", "(", ")", "current_platform", "=", "tuple_platform", "[", "0", "]", "if", "\"Ubuntu\"", "in", "current_platform", ":", "return", "\"ubuntu\"", "elif", "\"CentOS\"", "in", "current_platform", ":", "return", "\"centos\"", "elif", "\"debian\"", "in", "current_platform", ":", "# Stock Python does not detect Ubuntu and instead returns debian.", "# Or at least it does in some build environments like Travis CI", "return", "\"ubuntu\"", "else", ":", "raise", "RuntimeError", "(", "\"This module is not supported on {}.\"", ".", "format", "(", "current_platform", ")", ")" ]
Return the current OS platform. For example: if current os platform is Ubuntu then a string "ubuntu" will be returned (which is the name of the module). This string is used to decide which platform module should be imported.
[ "Return", "the", "current", "OS", "platform", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/osplatform.py#L4-L25
12,608
juju/charm-helpers
charmhelpers/fetch/python/version.py
current_version_string
def current_version_string(): """Current system python version as string major.minor.micro""" return "{0}.{1}.{2}".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
python
def current_version_string(): """Current system python version as string major.minor.micro""" return "{0}.{1}.{2}".format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
[ "def", "current_version_string", "(", ")", ":", "return", "\"{0}.{1}.{2}\"", ".", "format", "(", "sys", ".", "version_info", ".", "major", ",", "sys", ".", "version_info", ".", "minor", ",", "sys", ".", "version_info", ".", "micro", ")" ]
Current system python version as string major.minor.micro
[ "Current", "system", "python", "version", "as", "string", "major", ".", "minor", ".", "micro" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/version.py#L28-L32
12,609
juju/charm-helpers
charmhelpers/contrib/hardening/mysql/checks/config.py
get_audits
def get_audits(): """Get MySQL hardening config audits. :returns: dictionary of audits """ if subprocess.call(['which', 'mysql'], stdout=subprocess.PIPE) != 0: log("MySQL does not appear to be installed on this node - " "skipping mysql hardening", level=WARNING) return [] settings = utils.get_settings('mysql') hardening_settings = settings['hardening'] my_cnf = hardening_settings['mysql-conf'] audits = [ FilePermissionAudit(paths=[my_cnf], user='root', group='root', mode=0o0600), TemplatedFile(hardening_settings['hardening-conf'], MySQLConfContext(), TEMPLATES_DIR, mode=0o0750, user='mysql', group='root', service_actions=[{'service': 'mysql', 'actions': ['restart']}]), # MySQL and Percona charms do not allow configuration of the # data directory, so use the default. DirectoryPermissionAudit('/var/lib/mysql', user='mysql', group='mysql', recursive=False, mode=0o755), DirectoryPermissionAudit('/etc/mysql', user='root', group='root', recursive=False, mode=0o700), ] return audits
python
def get_audits(): """Get MySQL hardening config audits. :returns: dictionary of audits """ if subprocess.call(['which', 'mysql'], stdout=subprocess.PIPE) != 0: log("MySQL does not appear to be installed on this node - " "skipping mysql hardening", level=WARNING) return [] settings = utils.get_settings('mysql') hardening_settings = settings['hardening'] my_cnf = hardening_settings['mysql-conf'] audits = [ FilePermissionAudit(paths=[my_cnf], user='root', group='root', mode=0o0600), TemplatedFile(hardening_settings['hardening-conf'], MySQLConfContext(), TEMPLATES_DIR, mode=0o0750, user='mysql', group='root', service_actions=[{'service': 'mysql', 'actions': ['restart']}]), # MySQL and Percona charms do not allow configuration of the # data directory, so use the default. DirectoryPermissionAudit('/var/lib/mysql', user='mysql', group='mysql', recursive=False, mode=0o755), DirectoryPermissionAudit('/etc/mysql', user='root', group='root', recursive=False, mode=0o700), ] return audits
[ "def", "get_audits", "(", ")", ":", "if", "subprocess", ".", "call", "(", "[", "'which'", ",", "'mysql'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "!=", "0", ":", "log", "(", "\"MySQL does not appear to be installed on this node - \"", "\"skipping mysql hardening\"", ",", "level", "=", "WARNING", ")", "return", "[", "]", "settings", "=", "utils", ".", "get_settings", "(", "'mysql'", ")", "hardening_settings", "=", "settings", "[", "'hardening'", "]", "my_cnf", "=", "hardening_settings", "[", "'mysql-conf'", "]", "audits", "=", "[", "FilePermissionAudit", "(", "paths", "=", "[", "my_cnf", "]", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ",", "mode", "=", "0o0600", ")", ",", "TemplatedFile", "(", "hardening_settings", "[", "'hardening-conf'", "]", ",", "MySQLConfContext", "(", ")", ",", "TEMPLATES_DIR", ",", "mode", "=", "0o0750", ",", "user", "=", "'mysql'", ",", "group", "=", "'root'", ",", "service_actions", "=", "[", "{", "'service'", ":", "'mysql'", ",", "'actions'", ":", "[", "'restart'", "]", "}", "]", ")", ",", "# MySQL and Percona charms do not allow configuration of the", "# data directory, so use the default.", "DirectoryPermissionAudit", "(", "'/var/lib/mysql'", ",", "user", "=", "'mysql'", ",", "group", "=", "'mysql'", ",", "recursive", "=", "False", ",", "mode", "=", "0o755", ")", ",", "DirectoryPermissionAudit", "(", "'/etc/mysql'", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ",", "recursive", "=", "False", ",", "mode", "=", "0o700", ")", ",", "]", "return", "audits" ]
Get MySQL hardening config audits. :returns: dictionary of audits
[ "Get", "MySQL", "hardening", "config", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/mysql/checks/config.py#L31-L73
12,610
juju/charm-helpers
charmhelpers/core/host.py
service_reload
def service_reload(service_name, restart_on_failure=False, **kwargs): """Reload a system service, optionally falling back to restart if reload fails. The specified service name is managed via the system level init system. Some init systems (e.g. upstart) require that additional arguments be provided in order to directly control service instances whereas other init systems allow for addressing instances of a service directly by name (e.g. systemd). The kwargs allow for the additional parameters to be passed to underlying init systems for those systems which require/allow for them. For example, the ceph-osd upstart script requires the id parameter to be passed along in order to identify which running daemon should be reloaded. The follow- ing example restarts the ceph-osd service for instance id=4: service_reload('ceph-osd', id=4) :param service_name: the name of the service to reload :param restart_on_failure: boolean indicating whether to fallback to a restart if the reload fails. :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems not allowing additional parameters via the commandline (systemd). """ service_result = service('reload', service_name, **kwargs) if not service_result and restart_on_failure: service_result = service('restart', service_name, **kwargs) return service_result
python
def service_reload(service_name, restart_on_failure=False, **kwargs): """Reload a system service, optionally falling back to restart if reload fails. The specified service name is managed via the system level init system. Some init systems (e.g. upstart) require that additional arguments be provided in order to directly control service instances whereas other init systems allow for addressing instances of a service directly by name (e.g. systemd). The kwargs allow for the additional parameters to be passed to underlying init systems for those systems which require/allow for them. For example, the ceph-osd upstart script requires the id parameter to be passed along in order to identify which running daemon should be reloaded. The follow- ing example restarts the ceph-osd service for instance id=4: service_reload('ceph-osd', id=4) :param service_name: the name of the service to reload :param restart_on_failure: boolean indicating whether to fallback to a restart if the reload fails. :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems not allowing additional parameters via the commandline (systemd). """ service_result = service('reload', service_name, **kwargs) if not service_result and restart_on_failure: service_result = service('restart', service_name, **kwargs) return service_result
[ "def", "service_reload", "(", "service_name", ",", "restart_on_failure", "=", "False", ",", "*", "*", "kwargs", ")", ":", "service_result", "=", "service", "(", "'reload'", ",", "service_name", ",", "*", "*", "kwargs", ")", "if", "not", "service_result", "and", "restart_on_failure", ":", "service_result", "=", "service", "(", "'restart'", ",", "service_name", ",", "*", "*", "kwargs", ")", "return", "service_result" ]
Reload a system service, optionally falling back to restart if reload fails. The specified service name is managed via the system level init system. Some init systems (e.g. upstart) require that additional arguments be provided in order to directly control service instances whereas other init systems allow for addressing instances of a service directly by name (e.g. systemd). The kwargs allow for the additional parameters to be passed to underlying init systems for those systems which require/allow for them. For example, the ceph-osd upstart script requires the id parameter to be passed along in order to identify which running daemon should be reloaded. The follow- ing example restarts the ceph-osd service for instance id=4: service_reload('ceph-osd', id=4) :param service_name: the name of the service to reload :param restart_on_failure: boolean indicating whether to fallback to a restart if the reload fails. :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems not allowing additional parameters via the commandline (systemd).
[ "Reload", "a", "system", "service", "optionally", "falling", "back", "to", "restart", "if", "reload", "fails", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L143-L173
12,611
juju/charm-helpers
charmhelpers/core/host.py
service_pause
def service_pause(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): """Pause a system service. Stop it, and prevent it from starting again at boot. :param service_name: the name of the service to pause :param init_dir: path to the upstart init directory :param initd_dir: path to the sysv init directory :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems which do not support key=value arguments via the commandline. """ stopped = True if service_running(service_name, **kwargs): stopped = service_stop(service_name, **kwargs) upstart_file = os.path.join(init_dir, "{}.conf".format(service_name)) sysv_file = os.path.join(initd_dir, service_name) if init_is_systemd(): service('disable', service_name) service('mask', service_name) elif os.path.exists(upstart_file): override_path = os.path.join( init_dir, '{}.override'.format(service_name)) with open(override_path, 'w') as fh: fh.write("manual\n") elif os.path.exists(sysv_file): subprocess.check_call(["update-rc.d", service_name, "disable"]) else: raise ValueError( "Unable to detect {0} as SystemD, Upstart {1} or" " SysV {2}".format( service_name, upstart_file, sysv_file)) return stopped
python
def service_pause(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): """Pause a system service. Stop it, and prevent it from starting again at boot. :param service_name: the name of the service to pause :param init_dir: path to the upstart init directory :param initd_dir: path to the sysv init directory :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems which do not support key=value arguments via the commandline. """ stopped = True if service_running(service_name, **kwargs): stopped = service_stop(service_name, **kwargs) upstart_file = os.path.join(init_dir, "{}.conf".format(service_name)) sysv_file = os.path.join(initd_dir, service_name) if init_is_systemd(): service('disable', service_name) service('mask', service_name) elif os.path.exists(upstart_file): override_path = os.path.join( init_dir, '{}.override'.format(service_name)) with open(override_path, 'w') as fh: fh.write("manual\n") elif os.path.exists(sysv_file): subprocess.check_call(["update-rc.d", service_name, "disable"]) else: raise ValueError( "Unable to detect {0} as SystemD, Upstart {1} or" " SysV {2}".format( service_name, upstart_file, sysv_file)) return stopped
[ "def", "service_pause", "(", "service_name", ",", "init_dir", "=", "\"/etc/init\"", ",", "initd_dir", "=", "\"/etc/init.d\"", ",", "*", "*", "kwargs", ")", ":", "stopped", "=", "True", "if", "service_running", "(", "service_name", ",", "*", "*", "kwargs", ")", ":", "stopped", "=", "service_stop", "(", "service_name", ",", "*", "*", "kwargs", ")", "upstart_file", "=", "os", ".", "path", ".", "join", "(", "init_dir", ",", "\"{}.conf\"", ".", "format", "(", "service_name", ")", ")", "sysv_file", "=", "os", ".", "path", ".", "join", "(", "initd_dir", ",", "service_name", ")", "if", "init_is_systemd", "(", ")", ":", "service", "(", "'disable'", ",", "service_name", ")", "service", "(", "'mask'", ",", "service_name", ")", "elif", "os", ".", "path", ".", "exists", "(", "upstart_file", ")", ":", "override_path", "=", "os", ".", "path", ".", "join", "(", "init_dir", ",", "'{}.override'", ".", "format", "(", "service_name", ")", ")", "with", "open", "(", "override_path", ",", "'w'", ")", "as", "fh", ":", "fh", ".", "write", "(", "\"manual\\n\"", ")", "elif", "os", ".", "path", ".", "exists", "(", "sysv_file", ")", ":", "subprocess", ".", "check_call", "(", "[", "\"update-rc.d\"", ",", "service_name", ",", "\"disable\"", "]", ")", "else", ":", "raise", "ValueError", "(", "\"Unable to detect {0} as SystemD, Upstart {1} or\"", "\" SysV {2}\"", ".", "format", "(", "service_name", ",", "upstart_file", ",", "sysv_file", ")", ")", "return", "stopped" ]
Pause a system service. Stop it, and prevent it from starting again at boot. :param service_name: the name of the service to pause :param init_dir: path to the upstart init directory :param initd_dir: path to the sysv init directory :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for init systems which do not support key=value arguments via the commandline.
[ "Pause", "a", "system", "service", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L176-L211
12,612
juju/charm-helpers
charmhelpers/core/host.py
service_resume
def service_resume(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): """Resume a system service. Reenable starting again at boot. Start the service. :param service_name: the name of the service to resume :param init_dir: the path to the init dir :param initd dir: the path to the initd dir :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for systemd enabled systems. """ upstart_file = os.path.join(init_dir, "{}.conf".format(service_name)) sysv_file = os.path.join(initd_dir, service_name) if init_is_systemd(): service('unmask', service_name) service('enable', service_name) elif os.path.exists(upstart_file): override_path = os.path.join( init_dir, '{}.override'.format(service_name)) if os.path.exists(override_path): os.unlink(override_path) elif os.path.exists(sysv_file): subprocess.check_call(["update-rc.d", service_name, "enable"]) else: raise ValueError( "Unable to detect {0} as SystemD, Upstart {1} or" " SysV {2}".format( service_name, upstart_file, sysv_file)) started = service_running(service_name, **kwargs) if not started: started = service_start(service_name, **kwargs) return started
python
def service_resume(service_name, init_dir="/etc/init", initd_dir="/etc/init.d", **kwargs): """Resume a system service. Reenable starting again at boot. Start the service. :param service_name: the name of the service to resume :param init_dir: the path to the init dir :param initd dir: the path to the initd dir :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for systemd enabled systems. """ upstart_file = os.path.join(init_dir, "{}.conf".format(service_name)) sysv_file = os.path.join(initd_dir, service_name) if init_is_systemd(): service('unmask', service_name) service('enable', service_name) elif os.path.exists(upstart_file): override_path = os.path.join( init_dir, '{}.override'.format(service_name)) if os.path.exists(override_path): os.unlink(override_path) elif os.path.exists(sysv_file): subprocess.check_call(["update-rc.d", service_name, "enable"]) else: raise ValueError( "Unable to detect {0} as SystemD, Upstart {1} or" " SysV {2}".format( service_name, upstart_file, sysv_file)) started = service_running(service_name, **kwargs) if not started: started = service_start(service_name, **kwargs) return started
[ "def", "service_resume", "(", "service_name", ",", "init_dir", "=", "\"/etc/init\"", ",", "initd_dir", "=", "\"/etc/init.d\"", ",", "*", "*", "kwargs", ")", ":", "upstart_file", "=", "os", ".", "path", ".", "join", "(", "init_dir", ",", "\"{}.conf\"", ".", "format", "(", "service_name", ")", ")", "sysv_file", "=", "os", ".", "path", ".", "join", "(", "initd_dir", ",", "service_name", ")", "if", "init_is_systemd", "(", ")", ":", "service", "(", "'unmask'", ",", "service_name", ")", "service", "(", "'enable'", ",", "service_name", ")", "elif", "os", ".", "path", ".", "exists", "(", "upstart_file", ")", ":", "override_path", "=", "os", ".", "path", ".", "join", "(", "init_dir", ",", "'{}.override'", ".", "format", "(", "service_name", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "override_path", ")", ":", "os", ".", "unlink", "(", "override_path", ")", "elif", "os", ".", "path", ".", "exists", "(", "sysv_file", ")", ":", "subprocess", ".", "check_call", "(", "[", "\"update-rc.d\"", ",", "service_name", ",", "\"enable\"", "]", ")", "else", ":", "raise", "ValueError", "(", "\"Unable to detect {0} as SystemD, Upstart {1} or\"", "\" SysV {2}\"", ".", "format", "(", "service_name", ",", "upstart_file", ",", "sysv_file", ")", ")", "started", "=", "service_running", "(", "service_name", ",", "*", "*", "kwargs", ")", "if", "not", "started", ":", "started", "=", "service_start", "(", "service_name", ",", "*", "*", "kwargs", ")", "return", "started" ]
Resume a system service. Reenable starting again at boot. Start the service. :param service_name: the name of the service to resume :param init_dir: the path to the init dir :param initd dir: the path to the initd dir :param **kwargs: additional parameters to pass to the init system when managing services. These will be passed as key=value parameters to the init system's commandline. kwargs are ignored for systemd enabled systems.
[ "Resume", "a", "system", "service", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L214-L249
12,613
juju/charm-helpers
charmhelpers/core/host.py
service
def service(action, service_name, **kwargs): """Control a system service. :param action: the action to take on the service :param service_name: the name of the service to perform th action on :param **kwargs: additional params to be passed to the service command in the form of key=value. """ if init_is_systemd(): cmd = ['systemctl', action, service_name] else: cmd = ['service', service_name, action] for key, value in six.iteritems(kwargs): parameter = '%s=%s' % (key, value) cmd.append(parameter) return subprocess.call(cmd) == 0
python
def service(action, service_name, **kwargs): """Control a system service. :param action: the action to take on the service :param service_name: the name of the service to perform th action on :param **kwargs: additional params to be passed to the service command in the form of key=value. """ if init_is_systemd(): cmd = ['systemctl', action, service_name] else: cmd = ['service', service_name, action] for key, value in six.iteritems(kwargs): parameter = '%s=%s' % (key, value) cmd.append(parameter) return subprocess.call(cmd) == 0
[ "def", "service", "(", "action", ",", "service_name", ",", "*", "*", "kwargs", ")", ":", "if", "init_is_systemd", "(", ")", ":", "cmd", "=", "[", "'systemctl'", ",", "action", ",", "service_name", "]", "else", ":", "cmd", "=", "[", "'service'", ",", "service_name", ",", "action", "]", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "parameter", "=", "'%s=%s'", "%", "(", "key", ",", "value", ")", "cmd", ".", "append", "(", "parameter", ")", "return", "subprocess", ".", "call", "(", "cmd", ")", "==", "0" ]
Control a system service. :param action: the action to take on the service :param service_name: the name of the service to perform th action on :param **kwargs: additional params to be passed to the service command in the form of key=value.
[ "Control", "a", "system", "service", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L252-L267
12,614
juju/charm-helpers
charmhelpers/core/host.py
service_running
def service_running(service_name, **kwargs): """Determine whether a system service is running. :param service_name: the name of the service :param **kwargs: additional args to pass to the service command. This is used to pass additional key=value arguments to the service command line for managing specific instance units (e.g. service ceph-osd status id=2). The kwargs are ignored in systemd services. """ if init_is_systemd(): return service('is-active', service_name) else: if os.path.exists(_UPSTART_CONF.format(service_name)): try: cmd = ['status', service_name] for key, value in six.iteritems(kwargs): parameter = '%s=%s' % (key, value) cmd.append(parameter) output = subprocess.check_output( cmd, stderr=subprocess.STDOUT).decode('UTF-8') except subprocess.CalledProcessError: return False else: # This works for upstart scripts where the 'service' command # returns a consistent string to represent running # 'start/running' if ("start/running" in output or "is running" in output or "up and running" in output): return True elif os.path.exists(_INIT_D_CONF.format(service_name)): # Check System V scripts init script return codes return service('status', service_name) return False
python
def service_running(service_name, **kwargs): """Determine whether a system service is running. :param service_name: the name of the service :param **kwargs: additional args to pass to the service command. This is used to pass additional key=value arguments to the service command line for managing specific instance units (e.g. service ceph-osd status id=2). The kwargs are ignored in systemd services. """ if init_is_systemd(): return service('is-active', service_name) else: if os.path.exists(_UPSTART_CONF.format(service_name)): try: cmd = ['status', service_name] for key, value in six.iteritems(kwargs): parameter = '%s=%s' % (key, value) cmd.append(parameter) output = subprocess.check_output( cmd, stderr=subprocess.STDOUT).decode('UTF-8') except subprocess.CalledProcessError: return False else: # This works for upstart scripts where the 'service' command # returns a consistent string to represent running # 'start/running' if ("start/running" in output or "is running" in output or "up and running" in output): return True elif os.path.exists(_INIT_D_CONF.format(service_name)): # Check System V scripts init script return codes return service('status', service_name) return False
[ "def", "service_running", "(", "service_name", ",", "*", "*", "kwargs", ")", ":", "if", "init_is_systemd", "(", ")", ":", "return", "service", "(", "'is-active'", ",", "service_name", ")", "else", ":", "if", "os", ".", "path", ".", "exists", "(", "_UPSTART_CONF", ".", "format", "(", "service_name", ")", ")", ":", "try", ":", "cmd", "=", "[", "'status'", ",", "service_name", "]", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "parameter", "=", "'%s=%s'", "%", "(", "key", ",", "value", ")", "cmd", ".", "append", "(", "parameter", ")", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ".", "decode", "(", "'UTF-8'", ")", "except", "subprocess", ".", "CalledProcessError", ":", "return", "False", "else", ":", "# This works for upstart scripts where the 'service' command", "# returns a consistent string to represent running", "# 'start/running'", "if", "(", "\"start/running\"", "in", "output", "or", "\"is running\"", "in", "output", "or", "\"up and running\"", "in", "output", ")", ":", "return", "True", "elif", "os", ".", "path", ".", "exists", "(", "_INIT_D_CONF", ".", "format", "(", "service_name", ")", ")", ":", "# Check System V scripts init script return codes", "return", "service", "(", "'status'", ",", "service_name", ")", "return", "False" ]
Determine whether a system service is running. :param service_name: the name of the service :param **kwargs: additional args to pass to the service command. This is used to pass additional key=value arguments to the service command line for managing specific instance units (e.g. service ceph-osd status id=2). The kwargs are ignored in systemd services.
[ "Determine", "whether", "a", "system", "service", "is", "running", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L274-L308
12,615
juju/charm-helpers
charmhelpers/core/host.py
adduser
def adduser(username, password=None, shell='/bin/bash', system_user=False, primary_group=None, secondary_groups=None, uid=None, home_dir=None): """Add a user to the system. Will log but otherwise succeed if the user already exists. :param str username: Username to create :param str password: Password for user; if ``None``, create a system user :param str shell: The default shell for the user :param bool system_user: Whether to create a login or system user :param str primary_group: Primary group for user; defaults to username :param list secondary_groups: Optional list of additional groups :param int uid: UID for user being created :param str home_dir: Home directory for user :returns: The password database entry struct, as returned by `pwd.getpwnam` """ try: user_info = pwd.getpwnam(username) log('user {0} already exists!'.format(username)) if uid: user_info = pwd.getpwuid(int(uid)) log('user with uid {0} already exists!'.format(uid)) except KeyError: log('creating user {0}'.format(username)) cmd = ['useradd'] if uid: cmd.extend(['--uid', str(uid)]) if home_dir: cmd.extend(['--home', str(home_dir)]) if system_user or password is None: cmd.append('--system') else: cmd.extend([ '--create-home', '--shell', shell, '--password', password, ]) if not primary_group: try: grp.getgrnam(username) primary_group = username # avoid "group exists" error except KeyError: pass if primary_group: cmd.extend(['-g', primary_group]) if secondary_groups: cmd.extend(['-G', ','.join(secondary_groups)]) cmd.append(username) subprocess.check_call(cmd) user_info = pwd.getpwnam(username) return user_info
python
def adduser(username, password=None, shell='/bin/bash', system_user=False, primary_group=None, secondary_groups=None, uid=None, home_dir=None): """Add a user to the system. Will log but otherwise succeed if the user already exists. :param str username: Username to create :param str password: Password for user; if ``None``, create a system user :param str shell: The default shell for the user :param bool system_user: Whether to create a login or system user :param str primary_group: Primary group for user; defaults to username :param list secondary_groups: Optional list of additional groups :param int uid: UID for user being created :param str home_dir: Home directory for user :returns: The password database entry struct, as returned by `pwd.getpwnam` """ try: user_info = pwd.getpwnam(username) log('user {0} already exists!'.format(username)) if uid: user_info = pwd.getpwuid(int(uid)) log('user with uid {0} already exists!'.format(uid)) except KeyError: log('creating user {0}'.format(username)) cmd = ['useradd'] if uid: cmd.extend(['--uid', str(uid)]) if home_dir: cmd.extend(['--home', str(home_dir)]) if system_user or password is None: cmd.append('--system') else: cmd.extend([ '--create-home', '--shell', shell, '--password', password, ]) if not primary_group: try: grp.getgrnam(username) primary_group = username # avoid "group exists" error except KeyError: pass if primary_group: cmd.extend(['-g', primary_group]) if secondary_groups: cmd.extend(['-G', ','.join(secondary_groups)]) cmd.append(username) subprocess.check_call(cmd) user_info = pwd.getpwnam(username) return user_info
[ "def", "adduser", "(", "username", ",", "password", "=", "None", ",", "shell", "=", "'/bin/bash'", ",", "system_user", "=", "False", ",", "primary_group", "=", "None", ",", "secondary_groups", "=", "None", ",", "uid", "=", "None", ",", "home_dir", "=", "None", ")", ":", "try", ":", "user_info", "=", "pwd", ".", "getpwnam", "(", "username", ")", "log", "(", "'user {0} already exists!'", ".", "format", "(", "username", ")", ")", "if", "uid", ":", "user_info", "=", "pwd", ".", "getpwuid", "(", "int", "(", "uid", ")", ")", "log", "(", "'user with uid {0} already exists!'", ".", "format", "(", "uid", ")", ")", "except", "KeyError", ":", "log", "(", "'creating user {0}'", ".", "format", "(", "username", ")", ")", "cmd", "=", "[", "'useradd'", "]", "if", "uid", ":", "cmd", ".", "extend", "(", "[", "'--uid'", ",", "str", "(", "uid", ")", "]", ")", "if", "home_dir", ":", "cmd", ".", "extend", "(", "[", "'--home'", ",", "str", "(", "home_dir", ")", "]", ")", "if", "system_user", "or", "password", "is", "None", ":", "cmd", ".", "append", "(", "'--system'", ")", "else", ":", "cmd", ".", "extend", "(", "[", "'--create-home'", ",", "'--shell'", ",", "shell", ",", "'--password'", ",", "password", ",", "]", ")", "if", "not", "primary_group", ":", "try", ":", "grp", ".", "getgrnam", "(", "username", ")", "primary_group", "=", "username", "# avoid \"group exists\" error", "except", "KeyError", ":", "pass", "if", "primary_group", ":", "cmd", ".", "extend", "(", "[", "'-g'", ",", "primary_group", "]", ")", "if", "secondary_groups", ":", "cmd", ".", "extend", "(", "[", "'-G'", ",", "','", ".", "join", "(", "secondary_groups", ")", "]", ")", "cmd", ".", "append", "(", "username", ")", "subprocess", ".", "check_call", "(", "cmd", ")", "user_info", "=", "pwd", ".", "getpwnam", "(", "username", ")", "return", "user_info" ]
Add a user to the system. Will log but otherwise succeed if the user already exists. :param str username: Username to create :param str password: Password for user; if ``None``, create a system user :param str shell: The default shell for the user :param bool system_user: Whether to create a login or system user :param str primary_group: Primary group for user; defaults to username :param list secondary_groups: Optional list of additional groups :param int uid: UID for user being created :param str home_dir: Home directory for user :returns: The password database entry struct, as returned by `pwd.getpwnam`
[ "Add", "a", "user", "to", "the", "system", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L321-L373
12,616
juju/charm-helpers
charmhelpers/core/host.py
user_exists
def user_exists(username): """Check if a user exists""" try: pwd.getpwnam(username) user_exists = True except KeyError: user_exists = False return user_exists
python
def user_exists(username): """Check if a user exists""" try: pwd.getpwnam(username) user_exists = True except KeyError: user_exists = False return user_exists
[ "def", "user_exists", "(", "username", ")", ":", "try", ":", "pwd", ".", "getpwnam", "(", "username", ")", "user_exists", "=", "True", "except", "KeyError", ":", "user_exists", "=", "False", "return", "user_exists" ]
Check if a user exists
[ "Check", "if", "a", "user", "exists" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L376-L383
12,617
juju/charm-helpers
charmhelpers/core/host.py
uid_exists
def uid_exists(uid): """Check if a uid exists""" try: pwd.getpwuid(uid) uid_exists = True except KeyError: uid_exists = False return uid_exists
python
def uid_exists(uid): """Check if a uid exists""" try: pwd.getpwuid(uid) uid_exists = True except KeyError: uid_exists = False return uid_exists
[ "def", "uid_exists", "(", "uid", ")", ":", "try", ":", "pwd", ".", "getpwuid", "(", "uid", ")", "uid_exists", "=", "True", "except", "KeyError", ":", "uid_exists", "=", "False", "return", "uid_exists" ]
Check if a uid exists
[ "Check", "if", "a", "uid", "exists" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L386-L393
12,618
juju/charm-helpers
charmhelpers/core/host.py
group_exists
def group_exists(groupname): """Check if a group exists""" try: grp.getgrnam(groupname) group_exists = True except KeyError: group_exists = False return group_exists
python
def group_exists(groupname): """Check if a group exists""" try: grp.getgrnam(groupname) group_exists = True except KeyError: group_exists = False return group_exists
[ "def", "group_exists", "(", "groupname", ")", ":", "try", ":", "grp", ".", "getgrnam", "(", "groupname", ")", "group_exists", "=", "True", "except", "KeyError", ":", "group_exists", "=", "False", "return", "group_exists" ]
Check if a group exists
[ "Check", "if", "a", "group", "exists" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L396-L403
12,619
juju/charm-helpers
charmhelpers/core/host.py
gid_exists
def gid_exists(gid): """Check if a gid exists""" try: grp.getgrgid(gid) gid_exists = True except KeyError: gid_exists = False return gid_exists
python
def gid_exists(gid): """Check if a gid exists""" try: grp.getgrgid(gid) gid_exists = True except KeyError: gid_exists = False return gid_exists
[ "def", "gid_exists", "(", "gid", ")", ":", "try", ":", "grp", ".", "getgrgid", "(", "gid", ")", "gid_exists", "=", "True", "except", "KeyError", ":", "gid_exists", "=", "False", "return", "gid_exists" ]
Check if a gid exists
[ "Check", "if", "a", "gid", "exists" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L406-L413
12,620
juju/charm-helpers
charmhelpers/core/host.py
add_group
def add_group(group_name, system_group=False, gid=None): """Add a group to the system Will log but otherwise succeed if the group already exists. :param str group_name: group to create :param bool system_group: Create system group :param int gid: GID for user being created :returns: The password database entry struct, as returned by `grp.getgrnam` """ try: group_info = grp.getgrnam(group_name) log('group {0} already exists!'.format(group_name)) if gid: group_info = grp.getgrgid(gid) log('group with gid {0} already exists!'.format(gid)) except KeyError: log('creating group {0}'.format(group_name)) add_new_group(group_name, system_group, gid) group_info = grp.getgrnam(group_name) return group_info
python
def add_group(group_name, system_group=False, gid=None): """Add a group to the system Will log but otherwise succeed if the group already exists. :param str group_name: group to create :param bool system_group: Create system group :param int gid: GID for user being created :returns: The password database entry struct, as returned by `grp.getgrnam` """ try: group_info = grp.getgrnam(group_name) log('group {0} already exists!'.format(group_name)) if gid: group_info = grp.getgrgid(gid) log('group with gid {0} already exists!'.format(gid)) except KeyError: log('creating group {0}'.format(group_name)) add_new_group(group_name, system_group, gid) group_info = grp.getgrnam(group_name) return group_info
[ "def", "add_group", "(", "group_name", ",", "system_group", "=", "False", ",", "gid", "=", "None", ")", ":", "try", ":", "group_info", "=", "grp", ".", "getgrnam", "(", "group_name", ")", "log", "(", "'group {0} already exists!'", ".", "format", "(", "group_name", ")", ")", "if", "gid", ":", "group_info", "=", "grp", ".", "getgrgid", "(", "gid", ")", "log", "(", "'group with gid {0} already exists!'", ".", "format", "(", "gid", ")", ")", "except", "KeyError", ":", "log", "(", "'creating group {0}'", ".", "format", "(", "group_name", ")", ")", "add_new_group", "(", "group_name", ",", "system_group", ",", "gid", ")", "group_info", "=", "grp", ".", "getgrnam", "(", "group_name", ")", "return", "group_info" ]
Add a group to the system Will log but otherwise succeed if the group already exists. :param str group_name: group to create :param bool system_group: Create system group :param int gid: GID for user being created :returns: The password database entry struct, as returned by `grp.getgrnam`
[ "Add", "a", "group", "to", "the", "system" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L416-L437
12,621
juju/charm-helpers
charmhelpers/core/host.py
chage
def chage(username, lastday=None, expiredate=None, inactive=None, mindays=None, maxdays=None, root=None, warndays=None): """Change user password expiry information :param str username: User to update :param str lastday: Set when password was changed in YYYY-MM-DD format :param str expiredate: Set when user's account will no longer be accessible in YYYY-MM-DD format. -1 will remove an account expiration date. :param str inactive: Set the number of days of inactivity after a password has expired before the account is locked. -1 will remove an account's inactivity. :param str mindays: Set the minimum number of days between password changes to MIN_DAYS. 0 indicates the password can be changed anytime. :param str maxdays: Set the maximum number of days during which a password is valid. -1 as MAX_DAYS will remove checking maxdays :param str root: Apply changes in the CHROOT_DIR directory :param str warndays: Set the number of days of warning before a password change is required :raises subprocess.CalledProcessError: if call to chage fails """ cmd = ['chage'] if root: cmd.extend(['--root', root]) if lastday: cmd.extend(['--lastday', lastday]) if expiredate: cmd.extend(['--expiredate', expiredate]) if inactive: cmd.extend(['--inactive', inactive]) if mindays: cmd.extend(['--mindays', mindays]) if maxdays: cmd.extend(['--maxdays', maxdays]) if warndays: cmd.extend(['--warndays', warndays]) cmd.append(username) subprocess.check_call(cmd)
python
def chage(username, lastday=None, expiredate=None, inactive=None, mindays=None, maxdays=None, root=None, warndays=None): """Change user password expiry information :param str username: User to update :param str lastday: Set when password was changed in YYYY-MM-DD format :param str expiredate: Set when user's account will no longer be accessible in YYYY-MM-DD format. -1 will remove an account expiration date. :param str inactive: Set the number of days of inactivity after a password has expired before the account is locked. -1 will remove an account's inactivity. :param str mindays: Set the minimum number of days between password changes to MIN_DAYS. 0 indicates the password can be changed anytime. :param str maxdays: Set the maximum number of days during which a password is valid. -1 as MAX_DAYS will remove checking maxdays :param str root: Apply changes in the CHROOT_DIR directory :param str warndays: Set the number of days of warning before a password change is required :raises subprocess.CalledProcessError: if call to chage fails """ cmd = ['chage'] if root: cmd.extend(['--root', root]) if lastday: cmd.extend(['--lastday', lastday]) if expiredate: cmd.extend(['--expiredate', expiredate]) if inactive: cmd.extend(['--inactive', inactive]) if mindays: cmd.extend(['--mindays', mindays]) if maxdays: cmd.extend(['--maxdays', maxdays]) if warndays: cmd.extend(['--warndays', warndays]) cmd.append(username) subprocess.check_call(cmd)
[ "def", "chage", "(", "username", ",", "lastday", "=", "None", ",", "expiredate", "=", "None", ",", "inactive", "=", "None", ",", "mindays", "=", "None", ",", "maxdays", "=", "None", ",", "root", "=", "None", ",", "warndays", "=", "None", ")", ":", "cmd", "=", "[", "'chage'", "]", "if", "root", ":", "cmd", ".", "extend", "(", "[", "'--root'", ",", "root", "]", ")", "if", "lastday", ":", "cmd", ".", "extend", "(", "[", "'--lastday'", ",", "lastday", "]", ")", "if", "expiredate", ":", "cmd", ".", "extend", "(", "[", "'--expiredate'", ",", "expiredate", "]", ")", "if", "inactive", ":", "cmd", ".", "extend", "(", "[", "'--inactive'", ",", "inactive", "]", ")", "if", "mindays", ":", "cmd", ".", "extend", "(", "[", "'--mindays'", ",", "mindays", "]", ")", "if", "maxdays", ":", "cmd", ".", "extend", "(", "[", "'--maxdays'", ",", "maxdays", "]", ")", "if", "warndays", ":", "cmd", ".", "extend", "(", "[", "'--warndays'", ",", "warndays", "]", ")", "cmd", ".", "append", "(", "username", ")", "subprocess", ".", "check_call", "(", "cmd", ")" ]
Change user password expiry information :param str username: User to update :param str lastday: Set when password was changed in YYYY-MM-DD format :param str expiredate: Set when user's account will no longer be accessible in YYYY-MM-DD format. -1 will remove an account expiration date. :param str inactive: Set the number of days of inactivity after a password has expired before the account is locked. -1 will remove an account's inactivity. :param str mindays: Set the minimum number of days between password changes to MIN_DAYS. 0 indicates the password can be changed anytime. :param str maxdays: Set the maximum number of days during which a password is valid. -1 as MAX_DAYS will remove checking maxdays :param str root: Apply changes in the CHROOT_DIR directory :param str warndays: Set the number of days of warning before a password change is required :raises subprocess.CalledProcessError: if call to chage fails
[ "Change", "user", "password", "expiry", "information" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L447-L486
12,622
juju/charm-helpers
charmhelpers/core/host.py
rsync
def rsync(from_path, to_path, flags='-r', options=None, timeout=None): """Replicate the contents of a path""" options = options or ['--delete', '--executability'] cmd = ['/usr/bin/rsync', flags] if timeout: cmd = ['timeout', str(timeout)] + cmd cmd.extend(options) cmd.append(from_path) cmd.append(to_path) log(" ".join(cmd)) return subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('UTF-8').strip()
python
def rsync(from_path, to_path, flags='-r', options=None, timeout=None): """Replicate the contents of a path""" options = options or ['--delete', '--executability'] cmd = ['/usr/bin/rsync', flags] if timeout: cmd = ['timeout', str(timeout)] + cmd cmd.extend(options) cmd.append(from_path) cmd.append(to_path) log(" ".join(cmd)) return subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('UTF-8').strip()
[ "def", "rsync", "(", "from_path", ",", "to_path", ",", "flags", "=", "'-r'", ",", "options", "=", "None", ",", "timeout", "=", "None", ")", ":", "options", "=", "options", "or", "[", "'--delete'", ",", "'--executability'", "]", "cmd", "=", "[", "'/usr/bin/rsync'", ",", "flags", "]", "if", "timeout", ":", "cmd", "=", "[", "'timeout'", ",", "str", "(", "timeout", ")", "]", "+", "cmd", "cmd", ".", "extend", "(", "options", ")", "cmd", ".", "append", "(", "from_path", ")", "cmd", ".", "append", "(", "to_path", ")", "log", "(", "\" \"", ".", "join", "(", "cmd", ")", ")", "return", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ".", "decode", "(", "'UTF-8'", ")", ".", "strip", "(", ")" ]
Replicate the contents of a path
[ "Replicate", "the", "contents", "of", "a", "path" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L492-L502
12,623
juju/charm-helpers
charmhelpers/core/host.py
write_file
def write_file(path, content, owner='root', group='root', perms=0o444): """Create or overwrite a file with the contents of a byte string.""" uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid # lets see if we can grab the file and compare the context, to avoid doing # a write. existing_content = None existing_uid, existing_gid, existing_perms = None, None, None try: with open(path, 'rb') as target: existing_content = target.read() stat = os.stat(path) existing_uid, existing_gid, existing_perms = ( stat.st_uid, stat.st_gid, stat.st_mode ) except Exception: pass if content != existing_content: log("Writing file {} {}:{} {:o}".format(path, owner, group, perms), level=DEBUG) with open(path, 'wb') as target: os.fchown(target.fileno(), uid, gid) os.fchmod(target.fileno(), perms) if six.PY3 and isinstance(content, six.string_types): content = content.encode('UTF-8') target.write(content) return # the contents were the same, but we might still need to change the # ownership or permissions. if existing_uid != uid: log("Changing uid on already existing content: {} -> {}" .format(existing_uid, uid), level=DEBUG) os.chown(path, uid, -1) if existing_gid != gid: log("Changing gid on already existing content: {} -> {}" .format(existing_gid, gid), level=DEBUG) os.chown(path, -1, gid) if existing_perms != perms: log("Changing permissions on existing content: {} -> {}" .format(existing_perms, perms), level=DEBUG) os.chmod(path, perms)
python
def write_file(path, content, owner='root', group='root', perms=0o444): """Create or overwrite a file with the contents of a byte string.""" uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid # lets see if we can grab the file and compare the context, to avoid doing # a write. existing_content = None existing_uid, existing_gid, existing_perms = None, None, None try: with open(path, 'rb') as target: existing_content = target.read() stat = os.stat(path) existing_uid, existing_gid, existing_perms = ( stat.st_uid, stat.st_gid, stat.st_mode ) except Exception: pass if content != existing_content: log("Writing file {} {}:{} {:o}".format(path, owner, group, perms), level=DEBUG) with open(path, 'wb') as target: os.fchown(target.fileno(), uid, gid) os.fchmod(target.fileno(), perms) if six.PY3 and isinstance(content, six.string_types): content = content.encode('UTF-8') target.write(content) return # the contents were the same, but we might still need to change the # ownership or permissions. if existing_uid != uid: log("Changing uid on already existing content: {} -> {}" .format(existing_uid, uid), level=DEBUG) os.chown(path, uid, -1) if existing_gid != gid: log("Changing gid on already existing content: {} -> {}" .format(existing_gid, gid), level=DEBUG) os.chown(path, -1, gid) if existing_perms != perms: log("Changing permissions on existing content: {} -> {}" .format(existing_perms, perms), level=DEBUG) os.chmod(path, perms)
[ "def", "write_file", "(", "path", ",", "content", ",", "owner", "=", "'root'", ",", "group", "=", "'root'", ",", "perms", "=", "0o444", ")", ":", "uid", "=", "pwd", ".", "getpwnam", "(", "owner", ")", ".", "pw_uid", "gid", "=", "grp", ".", "getgrnam", "(", "group", ")", ".", "gr_gid", "# lets see if we can grab the file and compare the context, to avoid doing", "# a write.", "existing_content", "=", "None", "existing_uid", ",", "existing_gid", ",", "existing_perms", "=", "None", ",", "None", ",", "None", "try", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "target", ":", "existing_content", "=", "target", ".", "read", "(", ")", "stat", "=", "os", ".", "stat", "(", "path", ")", "existing_uid", ",", "existing_gid", ",", "existing_perms", "=", "(", "stat", ".", "st_uid", ",", "stat", ".", "st_gid", ",", "stat", ".", "st_mode", ")", "except", "Exception", ":", "pass", "if", "content", "!=", "existing_content", ":", "log", "(", "\"Writing file {} {}:{} {:o}\"", ".", "format", "(", "path", ",", "owner", ",", "group", ",", "perms", ")", ",", "level", "=", "DEBUG", ")", "with", "open", "(", "path", ",", "'wb'", ")", "as", "target", ":", "os", ".", "fchown", "(", "target", ".", "fileno", "(", ")", ",", "uid", ",", "gid", ")", "os", ".", "fchmod", "(", "target", ".", "fileno", "(", ")", ",", "perms", ")", "if", "six", ".", "PY3", "and", "isinstance", "(", "content", ",", "six", ".", "string_types", ")", ":", "content", "=", "content", ".", "encode", "(", "'UTF-8'", ")", "target", ".", "write", "(", "content", ")", "return", "# the contents were the same, but we might still need to change the", "# ownership or permissions.", "if", "existing_uid", "!=", "uid", ":", "log", "(", "\"Changing uid on already existing content: {} -> {}\"", ".", "format", "(", "existing_uid", ",", "uid", ")", ",", "level", "=", "DEBUG", ")", "os", ".", "chown", "(", "path", ",", "uid", ",", "-", "1", ")", "if", "existing_gid", "!=", "gid", ":", "log", "(", "\"Changing gid on already existing content: {} -> {}\"", ".", "format", "(", "existing_gid", ",", "gid", ")", ",", "level", "=", "DEBUG", ")", "os", ".", "chown", "(", "path", ",", "-", "1", ",", "gid", ")", "if", "existing_perms", "!=", "perms", ":", "log", "(", "\"Changing permissions on existing content: {} -> {}\"", ".", "format", "(", "existing_perms", ",", "perms", ")", ",", "level", "=", "DEBUG", ")", "os", ".", "chmod", "(", "path", ",", "perms", ")" ]
Create or overwrite a file with the contents of a byte string.
[ "Create", "or", "overwrite", "a", "file", "with", "the", "contents", "of", "a", "byte", "string", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L536-L576
12,624
juju/charm-helpers
charmhelpers/core/host.py
mount
def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): """Mount a filesystem at a particular mountpoint""" cmd_args = ['mount'] if options is not None: cmd_args.extend(['-o', options]) cmd_args.extend([device, mountpoint]) try: subprocess.check_output(cmd_args) except subprocess.CalledProcessError as e: log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) return False if persist: return fstab_add(device, mountpoint, filesystem, options=options) return True
python
def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): """Mount a filesystem at a particular mountpoint""" cmd_args = ['mount'] if options is not None: cmd_args.extend(['-o', options]) cmd_args.extend([device, mountpoint]) try: subprocess.check_output(cmd_args) except subprocess.CalledProcessError as e: log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) return False if persist: return fstab_add(device, mountpoint, filesystem, options=options) return True
[ "def", "mount", "(", "device", ",", "mountpoint", ",", "options", "=", "None", ",", "persist", "=", "False", ",", "filesystem", "=", "\"ext3\"", ")", ":", "cmd_args", "=", "[", "'mount'", "]", "if", "options", "is", "not", "None", ":", "cmd_args", ".", "extend", "(", "[", "'-o'", ",", "options", "]", ")", "cmd_args", ".", "extend", "(", "[", "device", ",", "mountpoint", "]", ")", "try", ":", "subprocess", ".", "check_output", "(", "cmd_args", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "log", "(", "'Error mounting {} at {}\\n{}'", ".", "format", "(", "device", ",", "mountpoint", ",", "e", ".", "output", ")", ")", "return", "False", "if", "persist", ":", "return", "fstab_add", "(", "device", ",", "mountpoint", ",", "filesystem", ",", "options", "=", "options", ")", "return", "True" ]
Mount a filesystem at a particular mountpoint
[ "Mount", "a", "filesystem", "at", "a", "particular", "mountpoint" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L589-L603
12,625
juju/charm-helpers
charmhelpers/core/host.py
umount
def umount(mountpoint, persist=False): """Unmount a filesystem""" cmd_args = ['umount', mountpoint] try: subprocess.check_output(cmd_args) except subprocess.CalledProcessError as e: log('Error unmounting {}\n{}'.format(mountpoint, e.output)) return False if persist: return fstab_remove(mountpoint) return True
python
def umount(mountpoint, persist=False): """Unmount a filesystem""" cmd_args = ['umount', mountpoint] try: subprocess.check_output(cmd_args) except subprocess.CalledProcessError as e: log('Error unmounting {}\n{}'.format(mountpoint, e.output)) return False if persist: return fstab_remove(mountpoint) return True
[ "def", "umount", "(", "mountpoint", ",", "persist", "=", "False", ")", ":", "cmd_args", "=", "[", "'umount'", ",", "mountpoint", "]", "try", ":", "subprocess", ".", "check_output", "(", "cmd_args", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "log", "(", "'Error unmounting {}\\n{}'", ".", "format", "(", "mountpoint", ",", "e", ".", "output", ")", ")", "return", "False", "if", "persist", ":", "return", "fstab_remove", "(", "mountpoint", ")", "return", "True" ]
Unmount a filesystem
[ "Unmount", "a", "filesystem" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L606-L617
12,626
juju/charm-helpers
charmhelpers/core/host.py
fstab_mount
def fstab_mount(mountpoint): """Mount filesystem using fstab""" cmd_args = ['mount', mountpoint] try: subprocess.check_output(cmd_args) except subprocess.CalledProcessError as e: log('Error unmounting {}\n{}'.format(mountpoint, e.output)) return False return True
python
def fstab_mount(mountpoint): """Mount filesystem using fstab""" cmd_args = ['mount', mountpoint] try: subprocess.check_output(cmd_args) except subprocess.CalledProcessError as e: log('Error unmounting {}\n{}'.format(mountpoint, e.output)) return False return True
[ "def", "fstab_mount", "(", "mountpoint", ")", ":", "cmd_args", "=", "[", "'mount'", ",", "mountpoint", "]", "try", ":", "subprocess", ".", "check_output", "(", "cmd_args", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "log", "(", "'Error unmounting {}\\n{}'", ".", "format", "(", "mountpoint", ",", "e", ".", "output", ")", ")", "return", "False", "return", "True" ]
Mount filesystem using fstab
[ "Mount", "filesystem", "using", "fstab" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L629-L637
12,627
juju/charm-helpers
charmhelpers/core/host.py
file_hash
def file_hash(path, hash_type='md5'): """Generate a hash checksum of the contents of 'path' or None if not found. :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. """ if os.path.exists(path): h = getattr(hashlib, hash_type)() with open(path, 'rb') as source: h.update(source.read()) return h.hexdigest() else: return None
python
def file_hash(path, hash_type='md5'): """Generate a hash checksum of the contents of 'path' or None if not found. :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. """ if os.path.exists(path): h = getattr(hashlib, hash_type)() with open(path, 'rb') as source: h.update(source.read()) return h.hexdigest() else: return None
[ "def", "file_hash", "(", "path", ",", "hash_type", "=", "'md5'", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "h", "=", "getattr", "(", "hashlib", ",", "hash_type", ")", "(", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "source", ":", "h", ".", "update", "(", "source", ".", "read", "(", ")", ")", "return", "h", ".", "hexdigest", "(", ")", "else", ":", "return", "None" ]
Generate a hash checksum of the contents of 'path' or None if not found. :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc.
[ "Generate", "a", "hash", "checksum", "of", "the", "contents", "of", "path", "or", "None", "if", "not", "found", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L640-L652
12,628
juju/charm-helpers
charmhelpers/core/host.py
check_hash
def check_hash(path, checksum, hash_type='md5'): """Validate a file using a cryptographic checksum. :param str checksum: Value of the checksum used to validate the file. :param str hash_type: Hash algorithm used to generate `checksum`. Can be any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. :raises ChecksumError: If the file fails the checksum """ actual_checksum = file_hash(path, hash_type) if checksum != actual_checksum: raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum))
python
def check_hash(path, checksum, hash_type='md5'): """Validate a file using a cryptographic checksum. :param str checksum: Value of the checksum used to validate the file. :param str hash_type: Hash algorithm used to generate `checksum`. Can be any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. :raises ChecksumError: If the file fails the checksum """ actual_checksum = file_hash(path, hash_type) if checksum != actual_checksum: raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum))
[ "def", "check_hash", "(", "path", ",", "checksum", ",", "hash_type", "=", "'md5'", ")", ":", "actual_checksum", "=", "file_hash", "(", "path", ",", "hash_type", ")", "if", "checksum", "!=", "actual_checksum", ":", "raise", "ChecksumError", "(", "\"'%s' != '%s'\"", "%", "(", "checksum", ",", "actual_checksum", ")", ")" ]
Validate a file using a cryptographic checksum. :param str checksum: Value of the checksum used to validate the file. :param str hash_type: Hash algorithm used to generate `checksum`. Can be any hash alrgorithm supported by :mod:`hashlib`, such as md5, sha1, sha256, sha512, etc. :raises ChecksumError: If the file fails the checksum
[ "Validate", "a", "file", "using", "a", "cryptographic", "checksum", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L669-L681
12,629
juju/charm-helpers
charmhelpers/core/host.py
restart_on_change
def restart_on_change(restart_map, stopstart=False, restart_functions=None): """Restart services based on configuration files changing This function is used a decorator, for example:: @restart_on_change({ '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] '/etc/apache/sites-enabled/*': [ 'apache2' ] }) def config_changed(): pass # your code here In this example, the cinder-api and cinder-volume services would be restarted if /etc/ceph/ceph.conf is changed by the ceph_client_changed function. The apache2 service would be restarted if any file matching the pattern got changed, created or removed. Standard wildcards are supported, see documentation for the 'glob' module for more information. @param restart_map: {path_file_name: [service_name, ...] @param stopstart: DEFAULT false; whether to stop, start OR restart @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result from decorated function """ def wrap(f): @functools.wraps(f) def wrapped_f(*args, **kwargs): return restart_on_change_helper( (lambda: f(*args, **kwargs)), restart_map, stopstart, restart_functions) return wrapped_f return wrap
python
def restart_on_change(restart_map, stopstart=False, restart_functions=None): """Restart services based on configuration files changing This function is used a decorator, for example:: @restart_on_change({ '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] '/etc/apache/sites-enabled/*': [ 'apache2' ] }) def config_changed(): pass # your code here In this example, the cinder-api and cinder-volume services would be restarted if /etc/ceph/ceph.conf is changed by the ceph_client_changed function. The apache2 service would be restarted if any file matching the pattern got changed, created or removed. Standard wildcards are supported, see documentation for the 'glob' module for more information. @param restart_map: {path_file_name: [service_name, ...] @param stopstart: DEFAULT false; whether to stop, start OR restart @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result from decorated function """ def wrap(f): @functools.wraps(f) def wrapped_f(*args, **kwargs): return restart_on_change_helper( (lambda: f(*args, **kwargs)), restart_map, stopstart, restart_functions) return wrapped_f return wrap
[ "def", "restart_on_change", "(", "restart_map", ",", "stopstart", "=", "False", ",", "restart_functions", "=", "None", ")", ":", "def", "wrap", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapped_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "restart_on_change_helper", "(", "(", "lambda", ":", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", ",", "restart_map", ",", "stopstart", ",", "restart_functions", ")", "return", "wrapped_f", "return", "wrap" ]
Restart services based on configuration files changing This function is used a decorator, for example:: @restart_on_change({ '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] '/etc/apache/sites-enabled/*': [ 'apache2' ] }) def config_changed(): pass # your code here In this example, the cinder-api and cinder-volume services would be restarted if /etc/ceph/ceph.conf is changed by the ceph_client_changed function. The apache2 service would be restarted if any file matching the pattern got changed, created or removed. Standard wildcards are supported, see documentation for the 'glob' module for more information. @param restart_map: {path_file_name: [service_name, ...] @param stopstart: DEFAULT false; whether to stop, start OR restart @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result from decorated function
[ "Restart", "services", "based", "on", "configuration", "files", "changing" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L689-L721
12,630
juju/charm-helpers
charmhelpers/core/host.py
restart_on_change_helper
def restart_on_change_helper(lambda_f, restart_map, stopstart=False, restart_functions=None): """Helper function to perform the restart_on_change function. This is provided for decorators to restart services if files described in the restart_map have changed after an invocation of lambda_f(). @param lambda_f: function to call. @param restart_map: {file: [service, ...]} @param stopstart: whether to stop, start or restart a service @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result of lambda_f() """ if restart_functions is None: restart_functions = {} checksums = {path: path_hash(path) for path in restart_map} r = lambda_f() # create a list of lists of the services to restart restarts = [restart_map[path] for path in restart_map if path_hash(path) != checksums[path]] # create a flat list of ordered services without duplicates from lists services_list = list(OrderedDict.fromkeys(itertools.chain(*restarts))) if services_list: actions = ('stop', 'start') if stopstart else ('restart',) for service_name in services_list: if service_name in restart_functions: restart_functions[service_name](service_name) else: for action in actions: service(action, service_name) return r
python
def restart_on_change_helper(lambda_f, restart_map, stopstart=False, restart_functions=None): """Helper function to perform the restart_on_change function. This is provided for decorators to restart services if files described in the restart_map have changed after an invocation of lambda_f(). @param lambda_f: function to call. @param restart_map: {file: [service, ...]} @param stopstart: whether to stop, start or restart a service @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result of lambda_f() """ if restart_functions is None: restart_functions = {} checksums = {path: path_hash(path) for path in restart_map} r = lambda_f() # create a list of lists of the services to restart restarts = [restart_map[path] for path in restart_map if path_hash(path) != checksums[path]] # create a flat list of ordered services without duplicates from lists services_list = list(OrderedDict.fromkeys(itertools.chain(*restarts))) if services_list: actions = ('stop', 'start') if stopstart else ('restart',) for service_name in services_list: if service_name in restart_functions: restart_functions[service_name](service_name) else: for action in actions: service(action, service_name) return r
[ "def", "restart_on_change_helper", "(", "lambda_f", ",", "restart_map", ",", "stopstart", "=", "False", ",", "restart_functions", "=", "None", ")", ":", "if", "restart_functions", "is", "None", ":", "restart_functions", "=", "{", "}", "checksums", "=", "{", "path", ":", "path_hash", "(", "path", ")", "for", "path", "in", "restart_map", "}", "r", "=", "lambda_f", "(", ")", "# create a list of lists of the services to restart", "restarts", "=", "[", "restart_map", "[", "path", "]", "for", "path", "in", "restart_map", "if", "path_hash", "(", "path", ")", "!=", "checksums", "[", "path", "]", "]", "# create a flat list of ordered services without duplicates from lists", "services_list", "=", "list", "(", "OrderedDict", ".", "fromkeys", "(", "itertools", ".", "chain", "(", "*", "restarts", ")", ")", ")", "if", "services_list", ":", "actions", "=", "(", "'stop'", ",", "'start'", ")", "if", "stopstart", "else", "(", "'restart'", ",", ")", "for", "service_name", "in", "services_list", ":", "if", "service_name", "in", "restart_functions", ":", "restart_functions", "[", "service_name", "]", "(", "service_name", ")", "else", ":", "for", "action", "in", "actions", ":", "service", "(", "action", ",", "service_name", ")", "return", "r" ]
Helper function to perform the restart_on_change function. This is provided for decorators to restart services if files described in the restart_map have changed after an invocation of lambda_f(). @param lambda_f: function to call. @param restart_map: {file: [service, ...]} @param stopstart: whether to stop, start or restart a service @param restart_functions: nonstandard functions to use to restart services {svc: func, ...} @returns result of lambda_f()
[ "Helper", "function", "to", "perform", "the", "restart_on_change", "function", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L724-L756
12,631
juju/charm-helpers
charmhelpers/core/host.py
pwgen
def pwgen(length=None): """Generate a random pasword.""" if length is None: # A random length is ok to use a weak PRNG length = random.choice(range(35, 45)) alphanumeric_chars = [ l for l in (string.ascii_letters + string.digits) if l not in 'l0QD1vAEIOUaeiou'] # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the # actual password random_generator = random.SystemRandom() random_chars = [ random_generator.choice(alphanumeric_chars) for _ in range(length)] return(''.join(random_chars))
python
def pwgen(length=None): """Generate a random pasword.""" if length is None: # A random length is ok to use a weak PRNG length = random.choice(range(35, 45)) alphanumeric_chars = [ l for l in (string.ascii_letters + string.digits) if l not in 'l0QD1vAEIOUaeiou'] # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the # actual password random_generator = random.SystemRandom() random_chars = [ random_generator.choice(alphanumeric_chars) for _ in range(length)] return(''.join(random_chars))
[ "def", "pwgen", "(", "length", "=", "None", ")", ":", "if", "length", "is", "None", ":", "# A random length is ok to use a weak PRNG", "length", "=", "random", ".", "choice", "(", "range", "(", "35", ",", "45", ")", ")", "alphanumeric_chars", "=", "[", "l", "for", "l", "in", "(", "string", ".", "ascii_letters", "+", "string", ".", "digits", ")", "if", "l", "not", "in", "'l0QD1vAEIOUaeiou'", "]", "# Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the", "# actual password", "random_generator", "=", "random", ".", "SystemRandom", "(", ")", "random_chars", "=", "[", "random_generator", ".", "choice", "(", "alphanumeric_chars", ")", "for", "_", "in", "range", "(", "length", ")", "]", "return", "(", "''", ".", "join", "(", "random_chars", ")", ")" ]
Generate a random pasword.
[ "Generate", "a", "random", "pasword", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L759-L772
12,632
juju/charm-helpers
charmhelpers/core/host.py
is_phy_iface
def is_phy_iface(interface): """Returns True if interface is not virtual, otherwise False.""" if interface: sys_net = '/sys/class/net' if os.path.isdir(sys_net): for iface in glob.glob(os.path.join(sys_net, '*')): if '/virtual/' in os.path.realpath(iface): continue if interface == os.path.basename(iface): return True return False
python
def is_phy_iface(interface): """Returns True if interface is not virtual, otherwise False.""" if interface: sys_net = '/sys/class/net' if os.path.isdir(sys_net): for iface in glob.glob(os.path.join(sys_net, '*')): if '/virtual/' in os.path.realpath(iface): continue if interface == os.path.basename(iface): return True return False
[ "def", "is_phy_iface", "(", "interface", ")", ":", "if", "interface", ":", "sys_net", "=", "'/sys/class/net'", "if", "os", ".", "path", ".", "isdir", "(", "sys_net", ")", ":", "for", "iface", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "sys_net", ",", "'*'", ")", ")", ":", "if", "'/virtual/'", "in", "os", ".", "path", ".", "realpath", "(", "iface", ")", ":", "continue", "if", "interface", "==", "os", ".", "path", ".", "basename", "(", "iface", ")", ":", "return", "True", "return", "False" ]
Returns True if interface is not virtual, otherwise False.
[ "Returns", "True", "if", "interface", "is", "not", "virtual", "otherwise", "False", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L775-L787
12,633
juju/charm-helpers
charmhelpers/core/host.py
get_bond_master
def get_bond_master(interface): """Returns bond master if interface is bond slave otherwise None. NOTE: the provided interface is expected to be physical """ if interface: iface_path = '/sys/class/net/%s' % (interface) if os.path.exists(iface_path): if '/virtual/' in os.path.realpath(iface_path): return None master = os.path.join(iface_path, 'master') if os.path.exists(master): master = os.path.realpath(master) # make sure it is a bond master if os.path.exists(os.path.join(master, 'bonding')): return os.path.basename(master) return None
python
def get_bond_master(interface): """Returns bond master if interface is bond slave otherwise None. NOTE: the provided interface is expected to be physical """ if interface: iface_path = '/sys/class/net/%s' % (interface) if os.path.exists(iface_path): if '/virtual/' in os.path.realpath(iface_path): return None master = os.path.join(iface_path, 'master') if os.path.exists(master): master = os.path.realpath(master) # make sure it is a bond master if os.path.exists(os.path.join(master, 'bonding')): return os.path.basename(master) return None
[ "def", "get_bond_master", "(", "interface", ")", ":", "if", "interface", ":", "iface_path", "=", "'/sys/class/net/%s'", "%", "(", "interface", ")", "if", "os", ".", "path", ".", "exists", "(", "iface_path", ")", ":", "if", "'/virtual/'", "in", "os", ".", "path", ".", "realpath", "(", "iface_path", ")", ":", "return", "None", "master", "=", "os", ".", "path", ".", "join", "(", "iface_path", ",", "'master'", ")", "if", "os", ".", "path", ".", "exists", "(", "master", ")", ":", "master", "=", "os", ".", "path", ".", "realpath", "(", "master", ")", "# make sure it is a bond master", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "master", ",", "'bonding'", ")", ")", ":", "return", "os", ".", "path", ".", "basename", "(", "master", ")", "return", "None" ]
Returns bond master if interface is bond slave otherwise None. NOTE: the provided interface is expected to be physical
[ "Returns", "bond", "master", "if", "interface", "is", "bond", "slave", "otherwise", "None", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L790-L808
12,634
juju/charm-helpers
charmhelpers/core/host.py
chdir
def chdir(directory): """Change the current working directory to a different directory for a code block and return the previous directory after the block exits. Useful to run commands from a specificed directory. :param str directory: The directory path to change to for this context. """ cur = os.getcwd() try: yield os.chdir(directory) finally: os.chdir(cur)
python
def chdir(directory): """Change the current working directory to a different directory for a code block and return the previous directory after the block exits. Useful to run commands from a specificed directory. :param str directory: The directory path to change to for this context. """ cur = os.getcwd() try: yield os.chdir(directory) finally: os.chdir(cur)
[ "def", "chdir", "(", "directory", ")", ":", "cur", "=", "os", ".", "getcwd", "(", ")", "try", ":", "yield", "os", ".", "chdir", "(", "directory", ")", "finally", ":", "os", ".", "chdir", "(", "cur", ")" ]
Change the current working directory to a different directory for a code block and return the previous directory after the block exits. Useful to run commands from a specificed directory. :param str directory: The directory path to change to for this context.
[ "Change", "the", "current", "working", "directory", "to", "a", "different", "directory", "for", "a", "code", "block", "and", "return", "the", "previous", "directory", "after", "the", "block", "exits", ".", "Useful", "to", "run", "commands", "from", "a", "specificed", "directory", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L883-L894
12,635
juju/charm-helpers
charmhelpers/core/host.py
chownr
def chownr(path, owner, group, follow_links=True, chowntopdir=False): """Recursively change user and group ownership of files and directories in given path. Doesn't chown path itself by default, only its children. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. :param bool follow_links: Also follow and chown links if True :param bool chowntopdir: Also chown path itself if True """ uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid if follow_links: chown = os.chown else: chown = os.lchown if chowntopdir: broken_symlink = os.path.lexists(path) and not os.path.exists(path) if not broken_symlink: chown(path, uid, gid) for root, dirs, files in os.walk(path, followlinks=follow_links): for name in dirs + files: full = os.path.join(root, name) broken_symlink = os.path.lexists(full) and not os.path.exists(full) if not broken_symlink: chown(full, uid, gid)
python
def chownr(path, owner, group, follow_links=True, chowntopdir=False): """Recursively change user and group ownership of files and directories in given path. Doesn't chown path itself by default, only its children. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. :param bool follow_links: Also follow and chown links if True :param bool chowntopdir: Also chown path itself if True """ uid = pwd.getpwnam(owner).pw_uid gid = grp.getgrnam(group).gr_gid if follow_links: chown = os.chown else: chown = os.lchown if chowntopdir: broken_symlink = os.path.lexists(path) and not os.path.exists(path) if not broken_symlink: chown(path, uid, gid) for root, dirs, files in os.walk(path, followlinks=follow_links): for name in dirs + files: full = os.path.join(root, name) broken_symlink = os.path.lexists(full) and not os.path.exists(full) if not broken_symlink: chown(full, uid, gid)
[ "def", "chownr", "(", "path", ",", "owner", ",", "group", ",", "follow_links", "=", "True", ",", "chowntopdir", "=", "False", ")", ":", "uid", "=", "pwd", ".", "getpwnam", "(", "owner", ")", ".", "pw_uid", "gid", "=", "grp", ".", "getgrnam", "(", "group", ")", ".", "gr_gid", "if", "follow_links", ":", "chown", "=", "os", ".", "chown", "else", ":", "chown", "=", "os", ".", "lchown", "if", "chowntopdir", ":", "broken_symlink", "=", "os", ".", "path", ".", "lexists", "(", "path", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "path", ")", "if", "not", "broken_symlink", ":", "chown", "(", "path", ",", "uid", ",", "gid", ")", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ",", "followlinks", "=", "follow_links", ")", ":", "for", "name", "in", "dirs", "+", "files", ":", "full", "=", "os", ".", "path", ".", "join", "(", "root", ",", "name", ")", "broken_symlink", "=", "os", ".", "path", ".", "lexists", "(", "full", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "full", ")", "if", "not", "broken_symlink", ":", "chown", "(", "full", ",", "uid", ",", "gid", ")" ]
Recursively change user and group ownership of files and directories in given path. Doesn't chown path itself by default, only its children. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. :param bool follow_links: Also follow and chown links if True :param bool chowntopdir: Also chown path itself if True
[ "Recursively", "change", "user", "and", "group", "ownership", "of", "files", "and", "directories", "in", "given", "path", ".", "Doesn", "t", "chown", "path", "itself", "by", "default", "only", "its", "children", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L897-L923
12,636
juju/charm-helpers
charmhelpers/core/host.py
lchownr
def lchownr(path, owner, group): """Recursively change user and group ownership of files and directories in a given path, not following symbolic links. See the documentation for 'os.lchown' for more information. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. """ chownr(path, owner, group, follow_links=False)
python
def lchownr(path, owner, group): """Recursively change user and group ownership of files and directories in a given path, not following symbolic links. See the documentation for 'os.lchown' for more information. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid. """ chownr(path, owner, group, follow_links=False)
[ "def", "lchownr", "(", "path", ",", "owner", ",", "group", ")", ":", "chownr", "(", "path", ",", "owner", ",", "group", ",", "follow_links", "=", "False", ")" ]
Recursively change user and group ownership of files and directories in a given path, not following symbolic links. See the documentation for 'os.lchown' for more information. :param str path: The string path to start changing ownership. :param str owner: The owner string to use when looking up the uid. :param str group: The group string to use when looking up the gid.
[ "Recursively", "change", "user", "and", "group", "ownership", "of", "files", "and", "directories", "in", "a", "given", "path", "not", "following", "symbolic", "links", ".", "See", "the", "documentation", "for", "os", ".", "lchown", "for", "more", "information", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L926-L935
12,637
juju/charm-helpers
charmhelpers/core/host.py
owner
def owner(path): """Returns a tuple containing the username & groupname owning the path. :param str path: the string path to retrieve the ownership :return tuple(str, str): A (username, groupname) tuple containing the name of the user and group owning the path. :raises OSError: if the specified path does not exist """ stat = os.stat(path) username = pwd.getpwuid(stat.st_uid)[0] groupname = grp.getgrgid(stat.st_gid)[0] return username, groupname
python
def owner(path): """Returns a tuple containing the username & groupname owning the path. :param str path: the string path to retrieve the ownership :return tuple(str, str): A (username, groupname) tuple containing the name of the user and group owning the path. :raises OSError: if the specified path does not exist """ stat = os.stat(path) username = pwd.getpwuid(stat.st_uid)[0] groupname = grp.getgrgid(stat.st_gid)[0] return username, groupname
[ "def", "owner", "(", "path", ")", ":", "stat", "=", "os", ".", "stat", "(", "path", ")", "username", "=", "pwd", ".", "getpwuid", "(", "stat", ".", "st_uid", ")", "[", "0", "]", "groupname", "=", "grp", ".", "getgrgid", "(", "stat", ".", "st_gid", ")", "[", "0", "]", "return", "username", ",", "groupname" ]
Returns a tuple containing the username & groupname owning the path. :param str path: the string path to retrieve the ownership :return tuple(str, str): A (username, groupname) tuple containing the name of the user and group owning the path. :raises OSError: if the specified path does not exist
[ "Returns", "a", "tuple", "containing", "the", "username", "&", "groupname", "owning", "the", "path", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L938-L949
12,638
juju/charm-helpers
charmhelpers/core/host.py
get_total_ram
def get_total_ram(): """The total amount of system RAM in bytes. This is what is reported by the OS, and may be overcommitted when there are multiple containers hosted on the same machine. """ with open('/proc/meminfo', 'r') as f: for line in f.readlines(): if line: key, value, unit = line.split() if key == 'MemTotal:': assert unit == 'kB', 'Unknown unit' return int(value) * 1024 # Classic, not KiB. raise NotImplementedError()
python
def get_total_ram(): """The total amount of system RAM in bytes. This is what is reported by the OS, and may be overcommitted when there are multiple containers hosted on the same machine. """ with open('/proc/meminfo', 'r') as f: for line in f.readlines(): if line: key, value, unit = line.split() if key == 'MemTotal:': assert unit == 'kB', 'Unknown unit' return int(value) * 1024 # Classic, not KiB. raise NotImplementedError()
[ "def", "get_total_ram", "(", ")", ":", "with", "open", "(", "'/proc/meminfo'", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "if", "line", ":", "key", ",", "value", ",", "unit", "=", "line", ".", "split", "(", ")", "if", "key", "==", "'MemTotal:'", ":", "assert", "unit", "==", "'kB'", ",", "'Unknown unit'", "return", "int", "(", "value", ")", "*", "1024", "# Classic, not KiB.", "raise", "NotImplementedError", "(", ")" ]
The total amount of system RAM in bytes. This is what is reported by the OS, and may be overcommitted when there are multiple containers hosted on the same machine.
[ "The", "total", "amount", "of", "system", "RAM", "in", "bytes", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L952-L965
12,639
juju/charm-helpers
charmhelpers/core/host.py
add_to_updatedb_prunepath
def add_to_updatedb_prunepath(path, updatedb_path=UPDATEDB_PATH): """Adds the specified path to the mlocate's udpatedb.conf PRUNEPATH list. This method has no effect if the path specified by updatedb_path does not exist or is not a file. @param path: string the path to add to the updatedb.conf PRUNEPATHS value @param updatedb_path: the path the updatedb.conf file """ if not os.path.exists(updatedb_path) or os.path.isdir(updatedb_path): # If the updatedb.conf file doesn't exist then don't attempt to update # the file as the package providing mlocate may not be installed on # the local system return with open(updatedb_path, 'r+') as f_id: updatedb_text = f_id.read() output = updatedb(updatedb_text, path) f_id.seek(0) f_id.write(output) f_id.truncate()
python
def add_to_updatedb_prunepath(path, updatedb_path=UPDATEDB_PATH): """Adds the specified path to the mlocate's udpatedb.conf PRUNEPATH list. This method has no effect if the path specified by updatedb_path does not exist or is not a file. @param path: string the path to add to the updatedb.conf PRUNEPATHS value @param updatedb_path: the path the updatedb.conf file """ if not os.path.exists(updatedb_path) or os.path.isdir(updatedb_path): # If the updatedb.conf file doesn't exist then don't attempt to update # the file as the package providing mlocate may not be installed on # the local system return with open(updatedb_path, 'r+') as f_id: updatedb_text = f_id.read() output = updatedb(updatedb_text, path) f_id.seek(0) f_id.write(output) f_id.truncate()
[ "def", "add_to_updatedb_prunepath", "(", "path", ",", "updatedb_path", "=", "UPDATEDB_PATH", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "updatedb_path", ")", "or", "os", ".", "path", ".", "isdir", "(", "updatedb_path", ")", ":", "# If the updatedb.conf file doesn't exist then don't attempt to update", "# the file as the package providing mlocate may not be installed on", "# the local system", "return", "with", "open", "(", "updatedb_path", ",", "'r+'", ")", "as", "f_id", ":", "updatedb_text", "=", "f_id", ".", "read", "(", ")", "output", "=", "updatedb", "(", "updatedb_text", ",", "path", ")", "f_id", ".", "seek", "(", "0", ")", "f_id", ".", "write", "(", "output", ")", "f_id", ".", "truncate", "(", ")" ]
Adds the specified path to the mlocate's udpatedb.conf PRUNEPATH list. This method has no effect if the path specified by updatedb_path does not exist or is not a file. @param path: string the path to add to the updatedb.conf PRUNEPATHS value @param updatedb_path: the path the updatedb.conf file
[ "Adds", "the", "specified", "path", "to", "the", "mlocate", "s", "udpatedb", ".", "conf", "PRUNEPATH", "list", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L985-L1005
12,640
juju/charm-helpers
charmhelpers/core/host.py
install_ca_cert
def install_ca_cert(ca_cert, name=None): """ Install the given cert as a trusted CA. The ``name`` is the stem of the filename where the cert is written, and if not provided, it will default to ``juju-{charm_name}``. If the cert is empty or None, or is unchanged, nothing is done. """ if not ca_cert: return if not isinstance(ca_cert, bytes): ca_cert = ca_cert.encode('utf8') if not name: name = 'juju-{}'.format(charm_name()) cert_file = '/usr/local/share/ca-certificates/{}.crt'.format(name) new_hash = hashlib.md5(ca_cert).hexdigest() if file_hash(cert_file) == new_hash: return log("Installing new CA cert at: {}".format(cert_file), level=INFO) write_file(cert_file, ca_cert) subprocess.check_call(['update-ca-certificates', '--fresh'])
python
def install_ca_cert(ca_cert, name=None): """ Install the given cert as a trusted CA. The ``name`` is the stem of the filename where the cert is written, and if not provided, it will default to ``juju-{charm_name}``. If the cert is empty or None, or is unchanged, nothing is done. """ if not ca_cert: return if not isinstance(ca_cert, bytes): ca_cert = ca_cert.encode('utf8') if not name: name = 'juju-{}'.format(charm_name()) cert_file = '/usr/local/share/ca-certificates/{}.crt'.format(name) new_hash = hashlib.md5(ca_cert).hexdigest() if file_hash(cert_file) == new_hash: return log("Installing new CA cert at: {}".format(cert_file), level=INFO) write_file(cert_file, ca_cert) subprocess.check_call(['update-ca-certificates', '--fresh'])
[ "def", "install_ca_cert", "(", "ca_cert", ",", "name", "=", "None", ")", ":", "if", "not", "ca_cert", ":", "return", "if", "not", "isinstance", "(", "ca_cert", ",", "bytes", ")", ":", "ca_cert", "=", "ca_cert", ".", "encode", "(", "'utf8'", ")", "if", "not", "name", ":", "name", "=", "'juju-{}'", ".", "format", "(", "charm_name", "(", ")", ")", "cert_file", "=", "'/usr/local/share/ca-certificates/{}.crt'", ".", "format", "(", "name", ")", "new_hash", "=", "hashlib", ".", "md5", "(", "ca_cert", ")", ".", "hexdigest", "(", ")", "if", "file_hash", "(", "cert_file", ")", "==", "new_hash", ":", "return", "log", "(", "\"Installing new CA cert at: {}\"", ".", "format", "(", "cert_file", ")", ",", "level", "=", "INFO", ")", "write_file", "(", "cert_file", ",", "ca_cert", ")", "subprocess", ".", "check_call", "(", "[", "'update-ca-certificates'", ",", "'--fresh'", "]", ")" ]
Install the given cert as a trusted CA. The ``name`` is the stem of the filename where the cert is written, and if not provided, it will default to ``juju-{charm_name}``. If the cert is empty or None, or is unchanged, nothing is done.
[ "Install", "the", "given", "cert", "as", "a", "trusted", "CA", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host.py#L1056-L1077
12,641
juju/charm-helpers
charmhelpers/contrib/hardening/host/checks/securetty.py
get_audits
def get_audits(): """Get OS hardening Secure TTY audits. :returns: dictionary of audits """ audits = [] audits.append(TemplatedFile('/etc/securetty', SecureTTYContext(), template_dir=TEMPLATES_DIR, mode=0o0400, user='root', group='root')) return audits
python
def get_audits(): """Get OS hardening Secure TTY audits. :returns: dictionary of audits """ audits = [] audits.append(TemplatedFile('/etc/securetty', SecureTTYContext(), template_dir=TEMPLATES_DIR, mode=0o0400, user='root', group='root')) return audits
[ "def", "get_audits", "(", ")", ":", "audits", "=", "[", "]", "audits", ".", "append", "(", "TemplatedFile", "(", "'/etc/securetty'", ",", "SecureTTYContext", "(", ")", ",", "template_dir", "=", "TEMPLATES_DIR", ",", "mode", "=", "0o0400", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ")", ")", "return", "audits" ]
Get OS hardening Secure TTY audits. :returns: dictionary of audits
[ "Get", "OS", "hardening", "Secure", "TTY", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/securetty.py#L20-L29
12,642
juju/charm-helpers
charmhelpers/contrib/templating/contexts.py
dict_keys_without_hyphens
def dict_keys_without_hyphens(a_dict): """Return the a new dict with underscores instead of hyphens in keys.""" return dict( (key.replace('-', '_'), val) for key, val in a_dict.items())
python
def dict_keys_without_hyphens(a_dict): """Return the a new dict with underscores instead of hyphens in keys.""" return dict( (key.replace('-', '_'), val) for key, val in a_dict.items())
[ "def", "dict_keys_without_hyphens", "(", "a_dict", ")", ":", "return", "dict", "(", "(", "key", ".", "replace", "(", "'-'", ",", "'_'", ")", ",", "val", ")", "for", "key", ",", "val", "in", "a_dict", ".", "items", "(", ")", ")" ]
Return the a new dict with underscores instead of hyphens in keys.
[ "Return", "the", "a", "new", "dict", "with", "underscores", "instead", "of", "hyphens", "in", "keys", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/templating/contexts.py#L31-L34
12,643
juju/charm-helpers
charmhelpers/contrib/templating/contexts.py
update_relations
def update_relations(context, namespace_separator=':'): """Update the context with the relation data.""" # Add any relation data prefixed with the relation type. relation_type = charmhelpers.core.hookenv.relation_type() relations = [] context['current_relation'] = {} if relation_type is not None: relation_data = charmhelpers.core.hookenv.relation_get() context['current_relation'] = relation_data # Deprecated: the following use of relation data as keys # directly in the context will be removed. relation_data = dict( ("{relation_type}{namespace_separator}{key}".format( relation_type=relation_type, key=key, namespace_separator=namespace_separator), val) for key, val in relation_data.items()) relation_data = dict_keys_without_hyphens(relation_data) context.update(relation_data) relations = charmhelpers.core.hookenv.relations_of_type(relation_type) relations = [dict_keys_without_hyphens(rel) for rel in relations] context['relations_full'] = charmhelpers.core.hookenv.relations() # the hookenv.relations() data structure is effectively unusable in # templates and other contexts when trying to access relation data other # than the current relation. So provide a more useful structure that works # with any hook. local_unit = charmhelpers.core.hookenv.local_unit() relations = {} for rname, rids in context['relations_full'].items(): relations[rname] = [] for rid, rdata in rids.items(): data = rdata.copy() if local_unit in rdata: data.pop(local_unit) for unit_name, rel_data in data.items(): new_data = {'__relid__': rid, '__unit__': unit_name} new_data.update(rel_data) relations[rname].append(new_data) context['relations'] = relations
python
def update_relations(context, namespace_separator=':'): """Update the context with the relation data.""" # Add any relation data prefixed with the relation type. relation_type = charmhelpers.core.hookenv.relation_type() relations = [] context['current_relation'] = {} if relation_type is not None: relation_data = charmhelpers.core.hookenv.relation_get() context['current_relation'] = relation_data # Deprecated: the following use of relation data as keys # directly in the context will be removed. relation_data = dict( ("{relation_type}{namespace_separator}{key}".format( relation_type=relation_type, key=key, namespace_separator=namespace_separator), val) for key, val in relation_data.items()) relation_data = dict_keys_without_hyphens(relation_data) context.update(relation_data) relations = charmhelpers.core.hookenv.relations_of_type(relation_type) relations = [dict_keys_without_hyphens(rel) for rel in relations] context['relations_full'] = charmhelpers.core.hookenv.relations() # the hookenv.relations() data structure is effectively unusable in # templates and other contexts when trying to access relation data other # than the current relation. So provide a more useful structure that works # with any hook. local_unit = charmhelpers.core.hookenv.local_unit() relations = {} for rname, rids in context['relations_full'].items(): relations[rname] = [] for rid, rdata in rids.items(): data = rdata.copy() if local_unit in rdata: data.pop(local_unit) for unit_name, rel_data in data.items(): new_data = {'__relid__': rid, '__unit__': unit_name} new_data.update(rel_data) relations[rname].append(new_data) context['relations'] = relations
[ "def", "update_relations", "(", "context", ",", "namespace_separator", "=", "':'", ")", ":", "# Add any relation data prefixed with the relation type.", "relation_type", "=", "charmhelpers", ".", "core", ".", "hookenv", ".", "relation_type", "(", ")", "relations", "=", "[", "]", "context", "[", "'current_relation'", "]", "=", "{", "}", "if", "relation_type", "is", "not", "None", ":", "relation_data", "=", "charmhelpers", ".", "core", ".", "hookenv", ".", "relation_get", "(", ")", "context", "[", "'current_relation'", "]", "=", "relation_data", "# Deprecated: the following use of relation data as keys", "# directly in the context will be removed.", "relation_data", "=", "dict", "(", "(", "\"{relation_type}{namespace_separator}{key}\"", ".", "format", "(", "relation_type", "=", "relation_type", ",", "key", "=", "key", ",", "namespace_separator", "=", "namespace_separator", ")", ",", "val", ")", "for", "key", ",", "val", "in", "relation_data", ".", "items", "(", ")", ")", "relation_data", "=", "dict_keys_without_hyphens", "(", "relation_data", ")", "context", ".", "update", "(", "relation_data", ")", "relations", "=", "charmhelpers", ".", "core", ".", "hookenv", ".", "relations_of_type", "(", "relation_type", ")", "relations", "=", "[", "dict_keys_without_hyphens", "(", "rel", ")", "for", "rel", "in", "relations", "]", "context", "[", "'relations_full'", "]", "=", "charmhelpers", ".", "core", ".", "hookenv", ".", "relations", "(", ")", "# the hookenv.relations() data structure is effectively unusable in", "# templates and other contexts when trying to access relation data other", "# than the current relation. So provide a more useful structure that works", "# with any hook.", "local_unit", "=", "charmhelpers", ".", "core", ".", "hookenv", ".", "local_unit", "(", ")", "relations", "=", "{", "}", "for", "rname", ",", "rids", "in", "context", "[", "'relations_full'", "]", ".", "items", "(", ")", ":", "relations", "[", "rname", "]", "=", "[", "]", "for", "rid", ",", "rdata", "in", "rids", ".", "items", "(", ")", ":", "data", "=", "rdata", ".", "copy", "(", ")", "if", "local_unit", "in", "rdata", ":", "data", ".", "pop", "(", "local_unit", ")", "for", "unit_name", ",", "rel_data", "in", "data", ".", "items", "(", ")", ":", "new_data", "=", "{", "'__relid__'", ":", "rid", ",", "'__unit__'", ":", "unit_name", "}", "new_data", ".", "update", "(", "rel_data", ")", "relations", "[", "rname", "]", ".", "append", "(", "new_data", ")", "context", "[", "'relations'", "]", "=", "relations" ]
Update the context with the relation data.
[ "Update", "the", "context", "with", "the", "relation", "data", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/templating/contexts.py#L37-L77
12,644
juju/charm-helpers
charmhelpers/contrib/templating/contexts.py
juju_state_to_yaml
def juju_state_to_yaml(yaml_path, namespace_separator=':', allow_hyphens_in_keys=True, mode=None): """Update the juju config and state in a yaml file. This includes any current relation-get data, and the charm directory. This function was created for the ansible and saltstack support, as those libraries can use a yaml file to supply context to templates, but it may be useful generally to create and update an on-disk cache of all the config, including previous relation data. By default, hyphens are allowed in keys as this is supported by yaml, but for tools like ansible, hyphens are not valid [1]. [1] http://www.ansibleworks.com/docs/playbooks_variables.html#what-makes-a-valid-variable-name """ config = charmhelpers.core.hookenv.config() # Add the charm_dir which we will need to refer to charm # file resources etc. config['charm_dir'] = charm_dir config['local_unit'] = charmhelpers.core.hookenv.local_unit() config['unit_private_address'] = charmhelpers.core.hookenv.unit_private_ip() config['unit_public_address'] = charmhelpers.core.hookenv.unit_get( 'public-address' ) # Don't use non-standard tags for unicode which will not # work when salt uses yaml.load_safe. yaml.add_representer(six.text_type, lambda dumper, value: dumper.represent_scalar( six.u('tag:yaml.org,2002:str'), value)) yaml_dir = os.path.dirname(yaml_path) if not os.path.exists(yaml_dir): os.makedirs(yaml_dir) if os.path.exists(yaml_path): with open(yaml_path, "r") as existing_vars_file: existing_vars = yaml.load(existing_vars_file.read()) else: with open(yaml_path, "w+"): pass existing_vars = {} if mode is not None: os.chmod(yaml_path, mode) if not allow_hyphens_in_keys: config = dict_keys_without_hyphens(config) existing_vars.update(config) update_relations(existing_vars, namespace_separator) with open(yaml_path, "w+") as fp: fp.write(yaml.dump(existing_vars, default_flow_style=False))
python
def juju_state_to_yaml(yaml_path, namespace_separator=':', allow_hyphens_in_keys=True, mode=None): """Update the juju config and state in a yaml file. This includes any current relation-get data, and the charm directory. This function was created for the ansible and saltstack support, as those libraries can use a yaml file to supply context to templates, but it may be useful generally to create and update an on-disk cache of all the config, including previous relation data. By default, hyphens are allowed in keys as this is supported by yaml, but for tools like ansible, hyphens are not valid [1]. [1] http://www.ansibleworks.com/docs/playbooks_variables.html#what-makes-a-valid-variable-name """ config = charmhelpers.core.hookenv.config() # Add the charm_dir which we will need to refer to charm # file resources etc. config['charm_dir'] = charm_dir config['local_unit'] = charmhelpers.core.hookenv.local_unit() config['unit_private_address'] = charmhelpers.core.hookenv.unit_private_ip() config['unit_public_address'] = charmhelpers.core.hookenv.unit_get( 'public-address' ) # Don't use non-standard tags for unicode which will not # work when salt uses yaml.load_safe. yaml.add_representer(six.text_type, lambda dumper, value: dumper.represent_scalar( six.u('tag:yaml.org,2002:str'), value)) yaml_dir = os.path.dirname(yaml_path) if not os.path.exists(yaml_dir): os.makedirs(yaml_dir) if os.path.exists(yaml_path): with open(yaml_path, "r") as existing_vars_file: existing_vars = yaml.load(existing_vars_file.read()) else: with open(yaml_path, "w+"): pass existing_vars = {} if mode is not None: os.chmod(yaml_path, mode) if not allow_hyphens_in_keys: config = dict_keys_without_hyphens(config) existing_vars.update(config) update_relations(existing_vars, namespace_separator) with open(yaml_path, "w+") as fp: fp.write(yaml.dump(existing_vars, default_flow_style=False))
[ "def", "juju_state_to_yaml", "(", "yaml_path", ",", "namespace_separator", "=", "':'", ",", "allow_hyphens_in_keys", "=", "True", ",", "mode", "=", "None", ")", ":", "config", "=", "charmhelpers", ".", "core", ".", "hookenv", ".", "config", "(", ")", "# Add the charm_dir which we will need to refer to charm", "# file resources etc.", "config", "[", "'charm_dir'", "]", "=", "charm_dir", "config", "[", "'local_unit'", "]", "=", "charmhelpers", ".", "core", ".", "hookenv", ".", "local_unit", "(", ")", "config", "[", "'unit_private_address'", "]", "=", "charmhelpers", ".", "core", ".", "hookenv", ".", "unit_private_ip", "(", ")", "config", "[", "'unit_public_address'", "]", "=", "charmhelpers", ".", "core", ".", "hookenv", ".", "unit_get", "(", "'public-address'", ")", "# Don't use non-standard tags for unicode which will not", "# work when salt uses yaml.load_safe.", "yaml", ".", "add_representer", "(", "six", ".", "text_type", ",", "lambda", "dumper", ",", "value", ":", "dumper", ".", "represent_scalar", "(", "six", ".", "u", "(", "'tag:yaml.org,2002:str'", ")", ",", "value", ")", ")", "yaml_dir", "=", "os", ".", "path", ".", "dirname", "(", "yaml_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "yaml_dir", ")", ":", "os", ".", "makedirs", "(", "yaml_dir", ")", "if", "os", ".", "path", ".", "exists", "(", "yaml_path", ")", ":", "with", "open", "(", "yaml_path", ",", "\"r\"", ")", "as", "existing_vars_file", ":", "existing_vars", "=", "yaml", ".", "load", "(", "existing_vars_file", ".", "read", "(", ")", ")", "else", ":", "with", "open", "(", "yaml_path", ",", "\"w+\"", ")", ":", "pass", "existing_vars", "=", "{", "}", "if", "mode", "is", "not", "None", ":", "os", ".", "chmod", "(", "yaml_path", ",", "mode", ")", "if", "not", "allow_hyphens_in_keys", ":", "config", "=", "dict_keys_without_hyphens", "(", "config", ")", "existing_vars", ".", "update", "(", "config", ")", "update_relations", "(", "existing_vars", ",", "namespace_separator", ")", "with", "open", "(", "yaml_path", ",", "\"w+\"", ")", "as", "fp", ":", "fp", ".", "write", "(", "yaml", ".", "dump", "(", "existing_vars", ",", "default_flow_style", "=", "False", ")", ")" ]
Update the juju config and state in a yaml file. This includes any current relation-get data, and the charm directory. This function was created for the ansible and saltstack support, as those libraries can use a yaml file to supply context to templates, but it may be useful generally to create and update an on-disk cache of all the config, including previous relation data. By default, hyphens are allowed in keys as this is supported by yaml, but for tools like ansible, hyphens are not valid [1]. [1] http://www.ansibleworks.com/docs/playbooks_variables.html#what-makes-a-valid-variable-name
[ "Update", "the", "juju", "config", "and", "state", "in", "a", "yaml", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/templating/contexts.py#L80-L137
12,645
juju/charm-helpers
charmhelpers/contrib/hardening/apache/checks/config.py
get_audits
def get_audits(): """Get Apache hardening config audits. :returns: dictionary of audits """ if subprocess.call(['which', 'apache2'], stdout=subprocess.PIPE) != 0: log("Apache server does not appear to be installed on this node - " "skipping apache hardening", level=INFO) return [] context = ApacheConfContext() settings = utils.get_settings('apache') audits = [ FilePermissionAudit(paths=os.path.join( settings['common']['apache_dir'], 'apache2.conf'), user='root', group='root', mode=0o0640), TemplatedFile(os.path.join(settings['common']['apache_dir'], 'mods-available/alias.conf'), context, TEMPLATES_DIR, mode=0o0640, user='root', service_actions=[{'service': 'apache2', 'actions': ['restart']}]), TemplatedFile(os.path.join(settings['common']['apache_dir'], 'conf-enabled/99-hardening.conf'), context, TEMPLATES_DIR, mode=0o0640, user='root', service_actions=[{'service': 'apache2', 'actions': ['restart']}]), DirectoryPermissionAudit(settings['common']['apache_dir'], user='root', group='root', mode=0o0750), DisabledModuleAudit(settings['hardening']['modules_to_disable']), NoReadWriteForOther(settings['common']['apache_dir']), DeletedFile(['/var/www/html/index.html']) ] return audits
python
def get_audits(): """Get Apache hardening config audits. :returns: dictionary of audits """ if subprocess.call(['which', 'apache2'], stdout=subprocess.PIPE) != 0: log("Apache server does not appear to be installed on this node - " "skipping apache hardening", level=INFO) return [] context = ApacheConfContext() settings = utils.get_settings('apache') audits = [ FilePermissionAudit(paths=os.path.join( settings['common']['apache_dir'], 'apache2.conf'), user='root', group='root', mode=0o0640), TemplatedFile(os.path.join(settings['common']['apache_dir'], 'mods-available/alias.conf'), context, TEMPLATES_DIR, mode=0o0640, user='root', service_actions=[{'service': 'apache2', 'actions': ['restart']}]), TemplatedFile(os.path.join(settings['common']['apache_dir'], 'conf-enabled/99-hardening.conf'), context, TEMPLATES_DIR, mode=0o0640, user='root', service_actions=[{'service': 'apache2', 'actions': ['restart']}]), DirectoryPermissionAudit(settings['common']['apache_dir'], user='root', group='root', mode=0o0750), DisabledModuleAudit(settings['hardening']['modules_to_disable']), NoReadWriteForOther(settings['common']['apache_dir']), DeletedFile(['/var/www/html/index.html']) ] return audits
[ "def", "get_audits", "(", ")", ":", "if", "subprocess", ".", "call", "(", "[", "'which'", ",", "'apache2'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "!=", "0", ":", "log", "(", "\"Apache server does not appear to be installed on this node - \"", "\"skipping apache hardening\"", ",", "level", "=", "INFO", ")", "return", "[", "]", "context", "=", "ApacheConfContext", "(", ")", "settings", "=", "utils", ".", "get_settings", "(", "'apache'", ")", "audits", "=", "[", "FilePermissionAudit", "(", "paths", "=", "os", ".", "path", ".", "join", "(", "settings", "[", "'common'", "]", "[", "'apache_dir'", "]", ",", "'apache2.conf'", ")", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ",", "mode", "=", "0o0640", ")", ",", "TemplatedFile", "(", "os", ".", "path", ".", "join", "(", "settings", "[", "'common'", "]", "[", "'apache_dir'", "]", ",", "'mods-available/alias.conf'", ")", ",", "context", ",", "TEMPLATES_DIR", ",", "mode", "=", "0o0640", ",", "user", "=", "'root'", ",", "service_actions", "=", "[", "{", "'service'", ":", "'apache2'", ",", "'actions'", ":", "[", "'restart'", "]", "}", "]", ")", ",", "TemplatedFile", "(", "os", ".", "path", ".", "join", "(", "settings", "[", "'common'", "]", "[", "'apache_dir'", "]", ",", "'conf-enabled/99-hardening.conf'", ")", ",", "context", ",", "TEMPLATES_DIR", ",", "mode", "=", "0o0640", ",", "user", "=", "'root'", ",", "service_actions", "=", "[", "{", "'service'", ":", "'apache2'", ",", "'actions'", ":", "[", "'restart'", "]", "}", "]", ")", ",", "DirectoryPermissionAudit", "(", "settings", "[", "'common'", "]", "[", "'apache_dir'", "]", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ",", "mode", "=", "0o0750", ")", ",", "DisabledModuleAudit", "(", "settings", "[", "'hardening'", "]", "[", "'modules_to_disable'", "]", ")", ",", "NoReadWriteForOther", "(", "settings", "[", "'common'", "]", "[", "'apache_dir'", "]", ")", ",", "DeletedFile", "(", "[", "'/var/www/html/index.html'", "]", ")", "]", "return", "audits" ]
Get Apache hardening config audits. :returns: dictionary of audits
[ "Get", "Apache", "hardening", "config", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/apache/checks/config.py#L37-L84
12,646
juju/charm-helpers
charmhelpers/contrib/hardening/host/checks/minimize_access.py
get_audits
def get_audits(): """Get OS hardening access audits. :returns: dictionary of audits """ audits = [] settings = utils.get_settings('os') # Remove write permissions from $PATH folders for all regular users. # This prevents changing system-wide commands from normal users. path_folders = {'/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/bin'} extra_user_paths = settings['environment']['extra_user_paths'] path_folders.update(extra_user_paths) audits.append(ReadOnly(path_folders)) # Only allow the root user to have access to the shadow file. audits.append(FilePermissionAudit('/etc/shadow', 'root', 'root', 0o0600)) if 'change_user' not in settings['security']['users_allow']: # su should only be accessible to user and group root, unless it is # expressly defined to allow users to change to root via the # security_users_allow config option. audits.append(FilePermissionAudit('/bin/su', 'root', 'root', 0o750)) return audits
python
def get_audits(): """Get OS hardening access audits. :returns: dictionary of audits """ audits = [] settings = utils.get_settings('os') # Remove write permissions from $PATH folders for all regular users. # This prevents changing system-wide commands from normal users. path_folders = {'/usr/local/sbin', '/usr/local/bin', '/usr/sbin', '/usr/bin', '/bin'} extra_user_paths = settings['environment']['extra_user_paths'] path_folders.update(extra_user_paths) audits.append(ReadOnly(path_folders)) # Only allow the root user to have access to the shadow file. audits.append(FilePermissionAudit('/etc/shadow', 'root', 'root', 0o0600)) if 'change_user' not in settings['security']['users_allow']: # su should only be accessible to user and group root, unless it is # expressly defined to allow users to change to root via the # security_users_allow config option. audits.append(FilePermissionAudit('/bin/su', 'root', 'root', 0o750)) return audits
[ "def", "get_audits", "(", ")", ":", "audits", "=", "[", "]", "settings", "=", "utils", ".", "get_settings", "(", "'os'", ")", "# Remove write permissions from $PATH folders for all regular users.", "# This prevents changing system-wide commands from normal users.", "path_folders", "=", "{", "'/usr/local/sbin'", ",", "'/usr/local/bin'", ",", "'/usr/sbin'", ",", "'/usr/bin'", ",", "'/bin'", "}", "extra_user_paths", "=", "settings", "[", "'environment'", "]", "[", "'extra_user_paths'", "]", "path_folders", ".", "update", "(", "extra_user_paths", ")", "audits", ".", "append", "(", "ReadOnly", "(", "path_folders", ")", ")", "# Only allow the root user to have access to the shadow file.", "audits", ".", "append", "(", "FilePermissionAudit", "(", "'/etc/shadow'", ",", "'root'", ",", "'root'", ",", "0o0600", ")", ")", "if", "'change_user'", "not", "in", "settings", "[", "'security'", "]", "[", "'users_allow'", "]", ":", "# su should only be accessible to user and group root, unless it is", "# expressly defined to allow users to change to root via the", "# security_users_allow config option.", "audits", ".", "append", "(", "FilePermissionAudit", "(", "'/bin/su'", ",", "'root'", ",", "'root'", ",", "0o750", ")", ")", "return", "audits" ]
Get OS hardening access audits. :returns: dictionary of audits
[ "Get", "OS", "hardening", "access", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/host/checks/minimize_access.py#L22-L50
12,647
juju/charm-helpers
charmhelpers/contrib/hardening/harden.py
harden
def harden(overrides=None): """Hardening decorator. This is the main entry point for running the hardening stack. In order to run modules of the stack you must add this decorator to charm hook(s) and ensure that your charm config.yaml contains the 'harden' option set to one or more of the supported modules. Setting these will cause the corresponding hardening code to be run when the hook fires. This decorator can and should be applied to more than one hook or function such that hardening modules are called multiple times. This is because subsequent calls will perform auditing checks that will report any changes to resources hardened by the first run (and possibly perform compliance actions as a result of any detected infractions). :param overrides: Optional list of stack modules used to override those provided with 'harden' config. :returns: Returns value returned by decorated function once executed. """ if overrides is None: overrides = [] def _harden_inner1(f): # As this has to be py2.7 compat, we can't use nonlocal. Use a trick # to capture the dictionary that can then be updated. _logged = {'done': False} def _harden_inner2(*args, **kwargs): # knock out hardening via a config var; normally it won't get # disabled. if _DISABLE_HARDENING_FOR_UNIT_TEST: return f(*args, **kwargs) if not _logged['done']: log("Hardening function '%s'" % (f.__name__), level=DEBUG) _logged['done'] = True RUN_CATALOG = OrderedDict([('os', run_os_checks), ('ssh', run_ssh_checks), ('mysql', run_mysql_checks), ('apache', run_apache_checks)]) enabled = overrides[:] or (config("harden") or "").split() if enabled: modules_to_run = [] # modules will always be performed in the following order for module, func in six.iteritems(RUN_CATALOG): if module in enabled: enabled.remove(module) modules_to_run.append(func) if enabled: log("Unknown hardening modules '%s' - ignoring" % (', '.join(enabled)), level=WARNING) for hardener in modules_to_run: log("Executing hardening module '%s'" % (hardener.__name__), level=DEBUG) hardener() else: log("No hardening applied to '%s'" % (f.__name__), level=DEBUG) return f(*args, **kwargs) return _harden_inner2 return _harden_inner1
python
def harden(overrides=None): """Hardening decorator. This is the main entry point for running the hardening stack. In order to run modules of the stack you must add this decorator to charm hook(s) and ensure that your charm config.yaml contains the 'harden' option set to one or more of the supported modules. Setting these will cause the corresponding hardening code to be run when the hook fires. This decorator can and should be applied to more than one hook or function such that hardening modules are called multiple times. This is because subsequent calls will perform auditing checks that will report any changes to resources hardened by the first run (and possibly perform compliance actions as a result of any detected infractions). :param overrides: Optional list of stack modules used to override those provided with 'harden' config. :returns: Returns value returned by decorated function once executed. """ if overrides is None: overrides = [] def _harden_inner1(f): # As this has to be py2.7 compat, we can't use nonlocal. Use a trick # to capture the dictionary that can then be updated. _logged = {'done': False} def _harden_inner2(*args, **kwargs): # knock out hardening via a config var; normally it won't get # disabled. if _DISABLE_HARDENING_FOR_UNIT_TEST: return f(*args, **kwargs) if not _logged['done']: log("Hardening function '%s'" % (f.__name__), level=DEBUG) _logged['done'] = True RUN_CATALOG = OrderedDict([('os', run_os_checks), ('ssh', run_ssh_checks), ('mysql', run_mysql_checks), ('apache', run_apache_checks)]) enabled = overrides[:] or (config("harden") or "").split() if enabled: modules_to_run = [] # modules will always be performed in the following order for module, func in six.iteritems(RUN_CATALOG): if module in enabled: enabled.remove(module) modules_to_run.append(func) if enabled: log("Unknown hardening modules '%s' - ignoring" % (', '.join(enabled)), level=WARNING) for hardener in modules_to_run: log("Executing hardening module '%s'" % (hardener.__name__), level=DEBUG) hardener() else: log("No hardening applied to '%s'" % (f.__name__), level=DEBUG) return f(*args, **kwargs) return _harden_inner2 return _harden_inner1
[ "def", "harden", "(", "overrides", "=", "None", ")", ":", "if", "overrides", "is", "None", ":", "overrides", "=", "[", "]", "def", "_harden_inner1", "(", "f", ")", ":", "# As this has to be py2.7 compat, we can't use nonlocal. Use a trick", "# to capture the dictionary that can then be updated.", "_logged", "=", "{", "'done'", ":", "False", "}", "def", "_harden_inner2", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# knock out hardening via a config var; normally it won't get", "# disabled.", "if", "_DISABLE_HARDENING_FOR_UNIT_TEST", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "_logged", "[", "'done'", "]", ":", "log", "(", "\"Hardening function '%s'\"", "%", "(", "f", ".", "__name__", ")", ",", "level", "=", "DEBUG", ")", "_logged", "[", "'done'", "]", "=", "True", "RUN_CATALOG", "=", "OrderedDict", "(", "[", "(", "'os'", ",", "run_os_checks", ")", ",", "(", "'ssh'", ",", "run_ssh_checks", ")", ",", "(", "'mysql'", ",", "run_mysql_checks", ")", ",", "(", "'apache'", ",", "run_apache_checks", ")", "]", ")", "enabled", "=", "overrides", "[", ":", "]", "or", "(", "config", "(", "\"harden\"", ")", "or", "\"\"", ")", ".", "split", "(", ")", "if", "enabled", ":", "modules_to_run", "=", "[", "]", "# modules will always be performed in the following order", "for", "module", ",", "func", "in", "six", ".", "iteritems", "(", "RUN_CATALOG", ")", ":", "if", "module", "in", "enabled", ":", "enabled", ".", "remove", "(", "module", ")", "modules_to_run", ".", "append", "(", "func", ")", "if", "enabled", ":", "log", "(", "\"Unknown hardening modules '%s' - ignoring\"", "%", "(", "', '", ".", "join", "(", "enabled", ")", ")", ",", "level", "=", "WARNING", ")", "for", "hardener", "in", "modules_to_run", ":", "log", "(", "\"Executing hardening module '%s'\"", "%", "(", "hardener", ".", "__name__", ")", ",", "level", "=", "DEBUG", ")", "hardener", "(", ")", "else", ":", "log", "(", "\"No hardening applied to '%s'\"", "%", "(", "f", ".", "__name__", ")", ",", "level", "=", "DEBUG", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_harden_inner2", "return", "_harden_inner1" ]
Hardening decorator. This is the main entry point for running the hardening stack. In order to run modules of the stack you must add this decorator to charm hook(s) and ensure that your charm config.yaml contains the 'harden' option set to one or more of the supported modules. Setting these will cause the corresponding hardening code to be run when the hook fires. This decorator can and should be applied to more than one hook or function such that hardening modules are called multiple times. This is because subsequent calls will perform auditing checks that will report any changes to resources hardened by the first run (and possibly perform compliance actions as a result of any detected infractions). :param overrides: Optional list of stack modules used to override those provided with 'harden' config. :returns: Returns value returned by decorated function once executed.
[ "Hardening", "decorator", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/harden.py#L33-L96
12,648
juju/charm-helpers
charmhelpers/contrib/openstack/neutron.py
parse_mappings
def parse_mappings(mappings, key_rvalue=False): """By default mappings are lvalue keyed. If key_rvalue is True, the mapping will be reversed to allow multiple configs for the same lvalue. """ parsed = {} if mappings: mappings = mappings.split() for m in mappings: p = m.partition(':') if key_rvalue: key_index = 2 val_index = 0 # if there is no rvalue skip to next if not p[1]: continue else: key_index = 0 val_index = 2 key = p[key_index].strip() parsed[key] = p[val_index].strip() return parsed
python
def parse_mappings(mappings, key_rvalue=False): """By default mappings are lvalue keyed. If key_rvalue is True, the mapping will be reversed to allow multiple configs for the same lvalue. """ parsed = {} if mappings: mappings = mappings.split() for m in mappings: p = m.partition(':') if key_rvalue: key_index = 2 val_index = 0 # if there is no rvalue skip to next if not p[1]: continue else: key_index = 0 val_index = 2 key = p[key_index].strip() parsed[key] = p[val_index].strip() return parsed
[ "def", "parse_mappings", "(", "mappings", ",", "key_rvalue", "=", "False", ")", ":", "parsed", "=", "{", "}", "if", "mappings", ":", "mappings", "=", "mappings", ".", "split", "(", ")", "for", "m", "in", "mappings", ":", "p", "=", "m", ".", "partition", "(", "':'", ")", "if", "key_rvalue", ":", "key_index", "=", "2", "val_index", "=", "0", "# if there is no rvalue skip to next", "if", "not", "p", "[", "1", "]", ":", "continue", "else", ":", "key_index", "=", "0", "val_index", "=", "2", "key", "=", "p", "[", "key_index", "]", ".", "strip", "(", ")", "parsed", "[", "key", "]", "=", "p", "[", "val_index", "]", ".", "strip", "(", ")", "return", "parsed" ]
By default mappings are lvalue keyed. If key_rvalue is True, the mapping will be reversed to allow multiple configs for the same lvalue.
[ "By", "default", "mappings", "are", "lvalue", "keyed", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/neutron.py#L270-L295
12,649
juju/charm-helpers
charmhelpers/contrib/openstack/neutron.py
parse_data_port_mappings
def parse_data_port_mappings(mappings, default_bridge='br-data'): """Parse data port mappings. Mappings must be a space-delimited list of bridge:port. Returns dict of the form {port:bridge} where ports may be mac addresses or interface names. """ # NOTE(dosaboy): we use rvalue for key to allow multiple values to be # proposed for <port> since it may be a mac address which will differ # across units this allowing first-known-good to be chosen. _mappings = parse_mappings(mappings, key_rvalue=True) if not _mappings or list(_mappings.values()) == ['']: if not mappings: return {} # For backwards-compatibility we need to support port-only provided in # config. _mappings = {mappings.split()[0]: default_bridge} ports = _mappings.keys() if len(set(ports)) != len(ports): raise Exception("It is not allowed to have the same port configured " "on more than one bridge") return _mappings
python
def parse_data_port_mappings(mappings, default_bridge='br-data'): """Parse data port mappings. Mappings must be a space-delimited list of bridge:port. Returns dict of the form {port:bridge} where ports may be mac addresses or interface names. """ # NOTE(dosaboy): we use rvalue for key to allow multiple values to be # proposed for <port> since it may be a mac address which will differ # across units this allowing first-known-good to be chosen. _mappings = parse_mappings(mappings, key_rvalue=True) if not _mappings or list(_mappings.values()) == ['']: if not mappings: return {} # For backwards-compatibility we need to support port-only provided in # config. _mappings = {mappings.split()[0]: default_bridge} ports = _mappings.keys() if len(set(ports)) != len(ports): raise Exception("It is not allowed to have the same port configured " "on more than one bridge") return _mappings
[ "def", "parse_data_port_mappings", "(", "mappings", ",", "default_bridge", "=", "'br-data'", ")", ":", "# NOTE(dosaboy): we use rvalue for key to allow multiple values to be", "# proposed for <port> since it may be a mac address which will differ", "# across units this allowing first-known-good to be chosen.", "_mappings", "=", "parse_mappings", "(", "mappings", ",", "key_rvalue", "=", "True", ")", "if", "not", "_mappings", "or", "list", "(", "_mappings", ".", "values", "(", ")", ")", "==", "[", "''", "]", ":", "if", "not", "mappings", ":", "return", "{", "}", "# For backwards-compatibility we need to support port-only provided in", "# config.", "_mappings", "=", "{", "mappings", ".", "split", "(", ")", "[", "0", "]", ":", "default_bridge", "}", "ports", "=", "_mappings", ".", "keys", "(", ")", "if", "len", "(", "set", "(", "ports", ")", ")", "!=", "len", "(", "ports", ")", ":", "raise", "Exception", "(", "\"It is not allowed to have the same port configured \"", "\"on more than one bridge\"", ")", "return", "_mappings" ]
Parse data port mappings. Mappings must be a space-delimited list of bridge:port. Returns dict of the form {port:bridge} where ports may be mac addresses or interface names.
[ "Parse", "data", "port", "mappings", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/neutron.py#L308-L334
12,650
juju/charm-helpers
charmhelpers/contrib/openstack/neutron.py
parse_vlan_range_mappings
def parse_vlan_range_mappings(mappings): """Parse vlan range mappings. Mappings must be a space-delimited list of provider:start:end mappings. The start:end range is optional and may be omitted. Returns dict of the form {provider: (start, end)}. """ _mappings = parse_mappings(mappings) if not _mappings: return {} mappings = {} for p, r in six.iteritems(_mappings): mappings[p] = tuple(r.split(':')) return mappings
python
def parse_vlan_range_mappings(mappings): """Parse vlan range mappings. Mappings must be a space-delimited list of provider:start:end mappings. The start:end range is optional and may be omitted. Returns dict of the form {provider: (start, end)}. """ _mappings = parse_mappings(mappings) if not _mappings: return {} mappings = {} for p, r in six.iteritems(_mappings): mappings[p] = tuple(r.split(':')) return mappings
[ "def", "parse_vlan_range_mappings", "(", "mappings", ")", ":", "_mappings", "=", "parse_mappings", "(", "mappings", ")", "if", "not", "_mappings", ":", "return", "{", "}", "mappings", "=", "{", "}", "for", "p", ",", "r", "in", "six", ".", "iteritems", "(", "_mappings", ")", ":", "mappings", "[", "p", "]", "=", "tuple", "(", "r", ".", "split", "(", "':'", ")", ")", "return", "mappings" ]
Parse vlan range mappings. Mappings must be a space-delimited list of provider:start:end mappings. The start:end range is optional and may be omitted. Returns dict of the form {provider: (start, end)}.
[ "Parse", "vlan", "range", "mappings", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/neutron.py#L337-L354
12,651
juju/charm-helpers
charmhelpers/payload/archive.py
extract_tarfile
def extract_tarfile(archive_name, destpath): "Unpack a tar archive, optionally compressed" archive = tarfile.open(archive_name) archive.extractall(destpath)
python
def extract_tarfile(archive_name, destpath): "Unpack a tar archive, optionally compressed" archive = tarfile.open(archive_name) archive.extractall(destpath)
[ "def", "extract_tarfile", "(", "archive_name", ",", "destpath", ")", ":", "archive", "=", "tarfile", ".", "open", "(", "archive_name", ")", "archive", ".", "extractall", "(", "destpath", ")" ]
Unpack a tar archive, optionally compressed
[ "Unpack", "a", "tar", "archive", "optionally", "compressed" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/archive.py#L62-L65
12,652
juju/charm-helpers
charmhelpers/payload/archive.py
extract_zipfile
def extract_zipfile(archive_name, destpath): "Unpack a zip file" archive = zipfile.ZipFile(archive_name) archive.extractall(destpath)
python
def extract_zipfile(archive_name, destpath): "Unpack a zip file" archive = zipfile.ZipFile(archive_name) archive.extractall(destpath)
[ "def", "extract_zipfile", "(", "archive_name", ",", "destpath", ")", ":", "archive", "=", "zipfile", ".", "ZipFile", "(", "archive_name", ")", "archive", ".", "extractall", "(", "destpath", ")" ]
Unpack a zip file
[ "Unpack", "a", "zip", "file" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/payload/archive.py#L68-L71
12,653
juju/charm-helpers
charmhelpers/contrib/network/ip.py
get_address_in_network
def get_address_in_network(network, fallback=None, fatal=False): """Get an IPv4 or IPv6 address within the network from the host. :param network (str): CIDR presentation format. For example, '192.168.1.0/24'. Supports multiple networks as a space-delimited list. :param fallback (str): If no address is found, return fallback. :param fatal (boolean): If no address is found, fallback is not set and fatal is True then exit(1). """ if network is None: if fallback is not None: return fallback if fatal: no_ip_found_error_out(network) else: return None networks = network.split() or [network] for network in networks: _validate_cidr(network) network = netaddr.IPNetwork(network) for iface in netifaces.interfaces(): try: addresses = netifaces.ifaddresses(iface) except ValueError: # If an instance was deleted between # netifaces.interfaces() run and now, its interfaces are gone continue if network.version == 4 and netifaces.AF_INET in addresses: for addr in addresses[netifaces.AF_INET]: cidr = netaddr.IPNetwork("%s/%s" % (addr['addr'], addr['netmask'])) if cidr in network: return str(cidr.ip) if network.version == 6 and netifaces.AF_INET6 in addresses: for addr in addresses[netifaces.AF_INET6]: cidr = _get_ipv6_network_from_address(addr) if cidr and cidr in network: return str(cidr.ip) if fallback is not None: return fallback if fatal: no_ip_found_error_out(network) return None
python
def get_address_in_network(network, fallback=None, fatal=False): """Get an IPv4 or IPv6 address within the network from the host. :param network (str): CIDR presentation format. For example, '192.168.1.0/24'. Supports multiple networks as a space-delimited list. :param fallback (str): If no address is found, return fallback. :param fatal (boolean): If no address is found, fallback is not set and fatal is True then exit(1). """ if network is None: if fallback is not None: return fallback if fatal: no_ip_found_error_out(network) else: return None networks = network.split() or [network] for network in networks: _validate_cidr(network) network = netaddr.IPNetwork(network) for iface in netifaces.interfaces(): try: addresses = netifaces.ifaddresses(iface) except ValueError: # If an instance was deleted between # netifaces.interfaces() run and now, its interfaces are gone continue if network.version == 4 and netifaces.AF_INET in addresses: for addr in addresses[netifaces.AF_INET]: cidr = netaddr.IPNetwork("%s/%s" % (addr['addr'], addr['netmask'])) if cidr in network: return str(cidr.ip) if network.version == 6 and netifaces.AF_INET6 in addresses: for addr in addresses[netifaces.AF_INET6]: cidr = _get_ipv6_network_from_address(addr) if cidr and cidr in network: return str(cidr.ip) if fallback is not None: return fallback if fatal: no_ip_found_error_out(network) return None
[ "def", "get_address_in_network", "(", "network", ",", "fallback", "=", "None", ",", "fatal", "=", "False", ")", ":", "if", "network", "is", "None", ":", "if", "fallback", "is", "not", "None", ":", "return", "fallback", "if", "fatal", ":", "no_ip_found_error_out", "(", "network", ")", "else", ":", "return", "None", "networks", "=", "network", ".", "split", "(", ")", "or", "[", "network", "]", "for", "network", "in", "networks", ":", "_validate_cidr", "(", "network", ")", "network", "=", "netaddr", ".", "IPNetwork", "(", "network", ")", "for", "iface", "in", "netifaces", ".", "interfaces", "(", ")", ":", "try", ":", "addresses", "=", "netifaces", ".", "ifaddresses", "(", "iface", ")", "except", "ValueError", ":", "# If an instance was deleted between", "# netifaces.interfaces() run and now, its interfaces are gone", "continue", "if", "network", ".", "version", "==", "4", "and", "netifaces", ".", "AF_INET", "in", "addresses", ":", "for", "addr", "in", "addresses", "[", "netifaces", ".", "AF_INET", "]", ":", "cidr", "=", "netaddr", ".", "IPNetwork", "(", "\"%s/%s\"", "%", "(", "addr", "[", "'addr'", "]", ",", "addr", "[", "'netmask'", "]", ")", ")", "if", "cidr", "in", "network", ":", "return", "str", "(", "cidr", ".", "ip", ")", "if", "network", ".", "version", "==", "6", "and", "netifaces", ".", "AF_INET6", "in", "addresses", ":", "for", "addr", "in", "addresses", "[", "netifaces", ".", "AF_INET6", "]", ":", "cidr", "=", "_get_ipv6_network_from_address", "(", "addr", ")", "if", "cidr", "and", "cidr", "in", "network", ":", "return", "str", "(", "cidr", ".", "ip", ")", "if", "fallback", "is", "not", "None", ":", "return", "fallback", "if", "fatal", ":", "no_ip_found_error_out", "(", "network", ")", "return", "None" ]
Get an IPv4 or IPv6 address within the network from the host. :param network (str): CIDR presentation format. For example, '192.168.1.0/24'. Supports multiple networks as a space-delimited list. :param fallback (str): If no address is found, return fallback. :param fatal (boolean): If no address is found, fallback is not set and fatal is True then exit(1).
[ "Get", "an", "IPv4", "or", "IPv6", "address", "within", "the", "network", "from", "the", "host", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L90-L138
12,654
juju/charm-helpers
charmhelpers/contrib/network/ip.py
is_ipv6
def is_ipv6(address): """Determine whether provided address is IPv6 or not.""" try: address = netaddr.IPAddress(address) except netaddr.AddrFormatError: # probably a hostname - so not an address at all! return False return address.version == 6
python
def is_ipv6(address): """Determine whether provided address is IPv6 or not.""" try: address = netaddr.IPAddress(address) except netaddr.AddrFormatError: # probably a hostname - so not an address at all! return False return address.version == 6
[ "def", "is_ipv6", "(", "address", ")", ":", "try", ":", "address", "=", "netaddr", ".", "IPAddress", "(", "address", ")", "except", "netaddr", ".", "AddrFormatError", ":", "# probably a hostname - so not an address at all!", "return", "False", "return", "address", ".", "version", "==", "6" ]
Determine whether provided address is IPv6 or not.
[ "Determine", "whether", "provided", "address", "is", "IPv6", "or", "not", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L141-L149
12,655
juju/charm-helpers
charmhelpers/contrib/network/ip.py
is_address_in_network
def is_address_in_network(network, address): """ Determine whether the provided address is within a network range. :param network (str): CIDR presentation format. For example, '192.168.1.0/24'. :param address: An individual IPv4 or IPv6 address without a net mask or subnet prefix. For example, '192.168.1.1'. :returns boolean: Flag indicating whether address is in network. """ try: network = netaddr.IPNetwork(network) except (netaddr.core.AddrFormatError, ValueError): raise ValueError("Network (%s) is not in CIDR presentation format" % network) try: address = netaddr.IPAddress(address) except (netaddr.core.AddrFormatError, ValueError): raise ValueError("Address (%s) is not in correct presentation format" % address) if address in network: return True else: return False
python
def is_address_in_network(network, address): """ Determine whether the provided address is within a network range. :param network (str): CIDR presentation format. For example, '192.168.1.0/24'. :param address: An individual IPv4 or IPv6 address without a net mask or subnet prefix. For example, '192.168.1.1'. :returns boolean: Flag indicating whether address is in network. """ try: network = netaddr.IPNetwork(network) except (netaddr.core.AddrFormatError, ValueError): raise ValueError("Network (%s) is not in CIDR presentation format" % network) try: address = netaddr.IPAddress(address) except (netaddr.core.AddrFormatError, ValueError): raise ValueError("Address (%s) is not in correct presentation format" % address) if address in network: return True else: return False
[ "def", "is_address_in_network", "(", "network", ",", "address", ")", ":", "try", ":", "network", "=", "netaddr", ".", "IPNetwork", "(", "network", ")", "except", "(", "netaddr", ".", "core", ".", "AddrFormatError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "\"Network (%s) is not in CIDR presentation format\"", "%", "network", ")", "try", ":", "address", "=", "netaddr", ".", "IPAddress", "(", "address", ")", "except", "(", "netaddr", ".", "core", ".", "AddrFormatError", ",", "ValueError", ")", ":", "raise", "ValueError", "(", "\"Address (%s) is not in correct presentation format\"", "%", "address", ")", "if", "address", "in", "network", ":", "return", "True", "else", ":", "return", "False" ]
Determine whether the provided address is within a network range. :param network (str): CIDR presentation format. For example, '192.168.1.0/24'. :param address: An individual IPv4 or IPv6 address without a net mask or subnet prefix. For example, '192.168.1.1'. :returns boolean: Flag indicating whether address is in network.
[ "Determine", "whether", "the", "provided", "address", "is", "within", "a", "network", "range", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L152-L177
12,656
juju/charm-helpers
charmhelpers/contrib/network/ip.py
_get_for_address
def _get_for_address(address, key): """Retrieve an attribute of or the physical interface that the IP address provided could be bound to. :param address (str): An individual IPv4 or IPv6 address without a net mask or subnet prefix. For example, '192.168.1.1'. :param key: 'iface' for the physical interface name or an attribute of the configured interface, for example 'netmask'. :returns str: Requested attribute or None if address is not bindable. """ address = netaddr.IPAddress(address) for iface in netifaces.interfaces(): addresses = netifaces.ifaddresses(iface) if address.version == 4 and netifaces.AF_INET in addresses: addr = addresses[netifaces.AF_INET][0]['addr'] netmask = addresses[netifaces.AF_INET][0]['netmask'] network = netaddr.IPNetwork("%s/%s" % (addr, netmask)) cidr = network.cidr if address in cidr: if key == 'iface': return iface else: return addresses[netifaces.AF_INET][0][key] if address.version == 6 and netifaces.AF_INET6 in addresses: for addr in addresses[netifaces.AF_INET6]: network = _get_ipv6_network_from_address(addr) if not network: continue cidr = network.cidr if address in cidr: if key == 'iface': return iface elif key == 'netmask' and cidr: return str(cidr).split('/')[1] else: return addr[key] return None
python
def _get_for_address(address, key): """Retrieve an attribute of or the physical interface that the IP address provided could be bound to. :param address (str): An individual IPv4 or IPv6 address without a net mask or subnet prefix. For example, '192.168.1.1'. :param key: 'iface' for the physical interface name or an attribute of the configured interface, for example 'netmask'. :returns str: Requested attribute or None if address is not bindable. """ address = netaddr.IPAddress(address) for iface in netifaces.interfaces(): addresses = netifaces.ifaddresses(iface) if address.version == 4 and netifaces.AF_INET in addresses: addr = addresses[netifaces.AF_INET][0]['addr'] netmask = addresses[netifaces.AF_INET][0]['netmask'] network = netaddr.IPNetwork("%s/%s" % (addr, netmask)) cidr = network.cidr if address in cidr: if key == 'iface': return iface else: return addresses[netifaces.AF_INET][0][key] if address.version == 6 and netifaces.AF_INET6 in addresses: for addr in addresses[netifaces.AF_INET6]: network = _get_ipv6_network_from_address(addr) if not network: continue cidr = network.cidr if address in cidr: if key == 'iface': return iface elif key == 'netmask' and cidr: return str(cidr).split('/')[1] else: return addr[key] return None
[ "def", "_get_for_address", "(", "address", ",", "key", ")", ":", "address", "=", "netaddr", ".", "IPAddress", "(", "address", ")", "for", "iface", "in", "netifaces", ".", "interfaces", "(", ")", ":", "addresses", "=", "netifaces", ".", "ifaddresses", "(", "iface", ")", "if", "address", ".", "version", "==", "4", "and", "netifaces", ".", "AF_INET", "in", "addresses", ":", "addr", "=", "addresses", "[", "netifaces", ".", "AF_INET", "]", "[", "0", "]", "[", "'addr'", "]", "netmask", "=", "addresses", "[", "netifaces", ".", "AF_INET", "]", "[", "0", "]", "[", "'netmask'", "]", "network", "=", "netaddr", ".", "IPNetwork", "(", "\"%s/%s\"", "%", "(", "addr", ",", "netmask", ")", ")", "cidr", "=", "network", ".", "cidr", "if", "address", "in", "cidr", ":", "if", "key", "==", "'iface'", ":", "return", "iface", "else", ":", "return", "addresses", "[", "netifaces", ".", "AF_INET", "]", "[", "0", "]", "[", "key", "]", "if", "address", ".", "version", "==", "6", "and", "netifaces", ".", "AF_INET6", "in", "addresses", ":", "for", "addr", "in", "addresses", "[", "netifaces", ".", "AF_INET6", "]", ":", "network", "=", "_get_ipv6_network_from_address", "(", "addr", ")", "if", "not", "network", ":", "continue", "cidr", "=", "network", ".", "cidr", "if", "address", "in", "cidr", ":", "if", "key", "==", "'iface'", ":", "return", "iface", "elif", "key", "==", "'netmask'", "and", "cidr", ":", "return", "str", "(", "cidr", ")", ".", "split", "(", "'/'", ")", "[", "1", "]", "else", ":", "return", "addr", "[", "key", "]", "return", "None" ]
Retrieve an attribute of or the physical interface that the IP address provided could be bound to. :param address (str): An individual IPv4 or IPv6 address without a net mask or subnet prefix. For example, '192.168.1.1'. :param key: 'iface' for the physical interface name or an attribute of the configured interface, for example 'netmask'. :returns str: Requested attribute or None if address is not bindable.
[ "Retrieve", "an", "attribute", "of", "or", "the", "physical", "interface", "that", "the", "IP", "address", "provided", "could", "be", "bound", "to", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L180-L218
12,657
juju/charm-helpers
charmhelpers/contrib/network/ip.py
resolve_network_cidr
def resolve_network_cidr(ip_address): ''' Resolves the full address cidr of an ip_address based on configured network interfaces ''' netmask = get_netmask_for_address(ip_address) return str(netaddr.IPNetwork("%s/%s" % (ip_address, netmask)).cidr)
python
def resolve_network_cidr(ip_address): ''' Resolves the full address cidr of an ip_address based on configured network interfaces ''' netmask = get_netmask_for_address(ip_address) return str(netaddr.IPNetwork("%s/%s" % (ip_address, netmask)).cidr)
[ "def", "resolve_network_cidr", "(", "ip_address", ")", ":", "netmask", "=", "get_netmask_for_address", "(", "ip_address", ")", "return", "str", "(", "netaddr", ".", "IPNetwork", "(", "\"%s/%s\"", "%", "(", "ip_address", ",", "netmask", ")", ")", ".", "cidr", ")" ]
Resolves the full address cidr of an ip_address based on configured network interfaces
[ "Resolves", "the", "full", "address", "cidr", "of", "an", "ip_address", "based", "on", "configured", "network", "interfaces" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L227-L233
12,658
juju/charm-helpers
charmhelpers/contrib/network/ip.py
get_iface_addr
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False, fatal=True, exc_list=None): """Return the assigned IP address for a given interface, if any. :param iface: network interface on which address(es) are expected to be found. :param inet_type: inet address family :param inc_aliases: include alias interfaces in search :param fatal: if True, raise exception if address not found :param exc_list: list of addresses to ignore :return: list of ip addresses """ # Extract nic if passed /dev/ethX if '/' in iface: iface = iface.split('/')[-1] if not exc_list: exc_list = [] try: inet_num = getattr(netifaces, inet_type) except AttributeError: raise Exception("Unknown inet type '%s'" % str(inet_type)) interfaces = netifaces.interfaces() if inc_aliases: ifaces = [] for _iface in interfaces: if iface == _iface or _iface.split(':')[0] == iface: ifaces.append(_iface) if fatal and not ifaces: raise Exception("Invalid interface '%s'" % iface) ifaces.sort() else: if iface not in interfaces: if fatal: raise Exception("Interface '%s' not found " % (iface)) else: return [] else: ifaces = [iface] addresses = [] for netiface in ifaces: net_info = netifaces.ifaddresses(netiface) if inet_num in net_info: for entry in net_info[inet_num]: if 'addr' in entry and entry['addr'] not in exc_list: addresses.append(entry['addr']) if fatal and not addresses: raise Exception("Interface '%s' doesn't have any %s addresses." % (iface, inet_type)) return sorted(addresses)
python
def get_iface_addr(iface='eth0', inet_type='AF_INET', inc_aliases=False, fatal=True, exc_list=None): """Return the assigned IP address for a given interface, if any. :param iface: network interface on which address(es) are expected to be found. :param inet_type: inet address family :param inc_aliases: include alias interfaces in search :param fatal: if True, raise exception if address not found :param exc_list: list of addresses to ignore :return: list of ip addresses """ # Extract nic if passed /dev/ethX if '/' in iface: iface = iface.split('/')[-1] if not exc_list: exc_list = [] try: inet_num = getattr(netifaces, inet_type) except AttributeError: raise Exception("Unknown inet type '%s'" % str(inet_type)) interfaces = netifaces.interfaces() if inc_aliases: ifaces = [] for _iface in interfaces: if iface == _iface or _iface.split(':')[0] == iface: ifaces.append(_iface) if fatal and not ifaces: raise Exception("Invalid interface '%s'" % iface) ifaces.sort() else: if iface not in interfaces: if fatal: raise Exception("Interface '%s' not found " % (iface)) else: return [] else: ifaces = [iface] addresses = [] for netiface in ifaces: net_info = netifaces.ifaddresses(netiface) if inet_num in net_info: for entry in net_info[inet_num]: if 'addr' in entry and entry['addr'] not in exc_list: addresses.append(entry['addr']) if fatal and not addresses: raise Exception("Interface '%s' doesn't have any %s addresses." % (iface, inet_type)) return sorted(addresses)
[ "def", "get_iface_addr", "(", "iface", "=", "'eth0'", ",", "inet_type", "=", "'AF_INET'", ",", "inc_aliases", "=", "False", ",", "fatal", "=", "True", ",", "exc_list", "=", "None", ")", ":", "# Extract nic if passed /dev/ethX", "if", "'/'", "in", "iface", ":", "iface", "=", "iface", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "not", "exc_list", ":", "exc_list", "=", "[", "]", "try", ":", "inet_num", "=", "getattr", "(", "netifaces", ",", "inet_type", ")", "except", "AttributeError", ":", "raise", "Exception", "(", "\"Unknown inet type '%s'\"", "%", "str", "(", "inet_type", ")", ")", "interfaces", "=", "netifaces", ".", "interfaces", "(", ")", "if", "inc_aliases", ":", "ifaces", "=", "[", "]", "for", "_iface", "in", "interfaces", ":", "if", "iface", "==", "_iface", "or", "_iface", ".", "split", "(", "':'", ")", "[", "0", "]", "==", "iface", ":", "ifaces", ".", "append", "(", "_iface", ")", "if", "fatal", "and", "not", "ifaces", ":", "raise", "Exception", "(", "\"Invalid interface '%s'\"", "%", "iface", ")", "ifaces", ".", "sort", "(", ")", "else", ":", "if", "iface", "not", "in", "interfaces", ":", "if", "fatal", ":", "raise", "Exception", "(", "\"Interface '%s' not found \"", "%", "(", "iface", ")", ")", "else", ":", "return", "[", "]", "else", ":", "ifaces", "=", "[", "iface", "]", "addresses", "=", "[", "]", "for", "netiface", "in", "ifaces", ":", "net_info", "=", "netifaces", ".", "ifaddresses", "(", "netiface", ")", "if", "inet_num", "in", "net_info", ":", "for", "entry", "in", "net_info", "[", "inet_num", "]", ":", "if", "'addr'", "in", "entry", "and", "entry", "[", "'addr'", "]", "not", "in", "exc_list", ":", "addresses", ".", "append", "(", "entry", "[", "'addr'", "]", ")", "if", "fatal", "and", "not", "addresses", ":", "raise", "Exception", "(", "\"Interface '%s' doesn't have any %s addresses.\"", "%", "(", "iface", ",", "inet_type", ")", ")", "return", "sorted", "(", "addresses", ")" ]
Return the assigned IP address for a given interface, if any. :param iface: network interface on which address(es) are expected to be found. :param inet_type: inet address family :param inc_aliases: include alias interfaces in search :param fatal: if True, raise exception if address not found :param exc_list: list of addresses to ignore :return: list of ip addresses
[ "Return", "the", "assigned", "IP", "address", "for", "a", "given", "interface", "if", "any", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L260-L317
12,659
juju/charm-helpers
charmhelpers/contrib/network/ip.py
get_iface_from_addr
def get_iface_from_addr(addr): """Work out on which interface the provided address is configured.""" for iface in netifaces.interfaces(): addresses = netifaces.ifaddresses(iface) for inet_type in addresses: for _addr in addresses[inet_type]: _addr = _addr['addr'] # link local ll_key = re.compile("(.+)%.*") raw = re.match(ll_key, _addr) if raw: _addr = raw.group(1) if _addr == addr: log("Address '%s' is configured on iface '%s'" % (addr, iface)) return iface msg = "Unable to infer net iface on which '%s' is configured" % (addr) raise Exception(msg)
python
def get_iface_from_addr(addr): """Work out on which interface the provided address is configured.""" for iface in netifaces.interfaces(): addresses = netifaces.ifaddresses(iface) for inet_type in addresses: for _addr in addresses[inet_type]: _addr = _addr['addr'] # link local ll_key = re.compile("(.+)%.*") raw = re.match(ll_key, _addr) if raw: _addr = raw.group(1) if _addr == addr: log("Address '%s' is configured on iface '%s'" % (addr, iface)) return iface msg = "Unable to infer net iface on which '%s' is configured" % (addr) raise Exception(msg)
[ "def", "get_iface_from_addr", "(", "addr", ")", ":", "for", "iface", "in", "netifaces", ".", "interfaces", "(", ")", ":", "addresses", "=", "netifaces", ".", "ifaddresses", "(", "iface", ")", "for", "inet_type", "in", "addresses", ":", "for", "_addr", "in", "addresses", "[", "inet_type", "]", ":", "_addr", "=", "_addr", "[", "'addr'", "]", "# link local", "ll_key", "=", "re", ".", "compile", "(", "\"(.+)%.*\"", ")", "raw", "=", "re", ".", "match", "(", "ll_key", ",", "_addr", ")", "if", "raw", ":", "_addr", "=", "raw", ".", "group", "(", "1", ")", "if", "_addr", "==", "addr", ":", "log", "(", "\"Address '%s' is configured on iface '%s'\"", "%", "(", "addr", ",", "iface", ")", ")", "return", "iface", "msg", "=", "\"Unable to infer net iface on which '%s' is configured\"", "%", "(", "addr", ")", "raise", "Exception", "(", "msg", ")" ]
Work out on which interface the provided address is configured.
[ "Work", "out", "on", "which", "interface", "the", "provided", "address", "is", "configured", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L323-L342
12,660
juju/charm-helpers
charmhelpers/contrib/network/ip.py
sniff_iface
def sniff_iface(f): """Ensure decorated function is called with a value for iface. If no iface provided, inject net iface inferred from unit private address. """ def iface_sniffer(*args, **kwargs): if not kwargs.get('iface', None): kwargs['iface'] = get_iface_from_addr(unit_get('private-address')) return f(*args, **kwargs) return iface_sniffer
python
def sniff_iface(f): """Ensure decorated function is called with a value for iface. If no iface provided, inject net iface inferred from unit private address. """ def iface_sniffer(*args, **kwargs): if not kwargs.get('iface', None): kwargs['iface'] = get_iface_from_addr(unit_get('private-address')) return f(*args, **kwargs) return iface_sniffer
[ "def", "sniff_iface", "(", "f", ")", ":", "def", "iface_sniffer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ".", "get", "(", "'iface'", ",", "None", ")", ":", "kwargs", "[", "'iface'", "]", "=", "get_iface_from_addr", "(", "unit_get", "(", "'private-address'", ")", ")", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "iface_sniffer" ]
Ensure decorated function is called with a value for iface. If no iface provided, inject net iface inferred from unit private address.
[ "Ensure", "decorated", "function", "is", "called", "with", "a", "value", "for", "iface", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L345-L356
12,661
juju/charm-helpers
charmhelpers/contrib/network/ip.py
get_ipv6_addr
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None, dynamic_only=True): """Get assigned IPv6 address for a given interface. Returns list of addresses found. If no address found, returns empty list. If iface is None, we infer the current primary interface by doing a reverse lookup on the unit private-address. We currently only support scope global IPv6 addresses i.e. non-temporary addresses. If no global IPv6 address is found, return the first one found in the ipv6 address list. :param iface: network interface on which ipv6 address(es) are expected to be found. :param inc_aliases: include alias interfaces in search :param fatal: if True, raise exception if address not found :param exc_list: list of addresses to ignore :param dynamic_only: only recognise dynamic addresses :return: list of ipv6 addresses """ addresses = get_iface_addr(iface=iface, inet_type='AF_INET6', inc_aliases=inc_aliases, fatal=fatal, exc_list=exc_list) if addresses: global_addrs = [] for addr in addresses: key_scope_link_local = re.compile("^fe80::..(.+)%(.+)") m = re.match(key_scope_link_local, addr) if m: eui_64_mac = m.group(1) iface = m.group(2) else: global_addrs.append(addr) if global_addrs: # Make sure any found global addresses are not temporary cmd = ['ip', 'addr', 'show', iface] out = subprocess.check_output(cmd).decode('UTF-8') if dynamic_only: key = re.compile("inet6 (.+)/[0-9]+ scope global.* dynamic.*") else: key = re.compile("inet6 (.+)/[0-9]+ scope global.*") addrs = [] for line in out.split('\n'): line = line.strip() m = re.match(key, line) if m and 'temporary' not in line: # Return the first valid address we find for addr in global_addrs: if m.group(1) == addr: if not dynamic_only or \ m.group(1).endswith(eui_64_mac): addrs.append(addr) if addrs: return addrs if fatal: raise Exception("Interface '%s' does not have a scope global " "non-temporary ipv6 address." % iface) return []
python
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None, dynamic_only=True): """Get assigned IPv6 address for a given interface. Returns list of addresses found. If no address found, returns empty list. If iface is None, we infer the current primary interface by doing a reverse lookup on the unit private-address. We currently only support scope global IPv6 addresses i.e. non-temporary addresses. If no global IPv6 address is found, return the first one found in the ipv6 address list. :param iface: network interface on which ipv6 address(es) are expected to be found. :param inc_aliases: include alias interfaces in search :param fatal: if True, raise exception if address not found :param exc_list: list of addresses to ignore :param dynamic_only: only recognise dynamic addresses :return: list of ipv6 addresses """ addresses = get_iface_addr(iface=iface, inet_type='AF_INET6', inc_aliases=inc_aliases, fatal=fatal, exc_list=exc_list) if addresses: global_addrs = [] for addr in addresses: key_scope_link_local = re.compile("^fe80::..(.+)%(.+)") m = re.match(key_scope_link_local, addr) if m: eui_64_mac = m.group(1) iface = m.group(2) else: global_addrs.append(addr) if global_addrs: # Make sure any found global addresses are not temporary cmd = ['ip', 'addr', 'show', iface] out = subprocess.check_output(cmd).decode('UTF-8') if dynamic_only: key = re.compile("inet6 (.+)/[0-9]+ scope global.* dynamic.*") else: key = re.compile("inet6 (.+)/[0-9]+ scope global.*") addrs = [] for line in out.split('\n'): line = line.strip() m = re.match(key, line) if m and 'temporary' not in line: # Return the first valid address we find for addr in global_addrs: if m.group(1) == addr: if not dynamic_only or \ m.group(1).endswith(eui_64_mac): addrs.append(addr) if addrs: return addrs if fatal: raise Exception("Interface '%s' does not have a scope global " "non-temporary ipv6 address." % iface) return []
[ "def", "get_ipv6_addr", "(", "iface", "=", "None", ",", "inc_aliases", "=", "False", ",", "fatal", "=", "True", ",", "exc_list", "=", "None", ",", "dynamic_only", "=", "True", ")", ":", "addresses", "=", "get_iface_addr", "(", "iface", "=", "iface", ",", "inet_type", "=", "'AF_INET6'", ",", "inc_aliases", "=", "inc_aliases", ",", "fatal", "=", "fatal", ",", "exc_list", "=", "exc_list", ")", "if", "addresses", ":", "global_addrs", "=", "[", "]", "for", "addr", "in", "addresses", ":", "key_scope_link_local", "=", "re", ".", "compile", "(", "\"^fe80::..(.+)%(.+)\"", ")", "m", "=", "re", ".", "match", "(", "key_scope_link_local", ",", "addr", ")", "if", "m", ":", "eui_64_mac", "=", "m", ".", "group", "(", "1", ")", "iface", "=", "m", ".", "group", "(", "2", ")", "else", ":", "global_addrs", ".", "append", "(", "addr", ")", "if", "global_addrs", ":", "# Make sure any found global addresses are not temporary", "cmd", "=", "[", "'ip'", ",", "'addr'", ",", "'show'", ",", "iface", "]", "out", "=", "subprocess", ".", "check_output", "(", "cmd", ")", ".", "decode", "(", "'UTF-8'", ")", "if", "dynamic_only", ":", "key", "=", "re", ".", "compile", "(", "\"inet6 (.+)/[0-9]+ scope global.* dynamic.*\"", ")", "else", ":", "key", "=", "re", ".", "compile", "(", "\"inet6 (.+)/[0-9]+ scope global.*\"", ")", "addrs", "=", "[", "]", "for", "line", "in", "out", ".", "split", "(", "'\\n'", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "m", "=", "re", ".", "match", "(", "key", ",", "line", ")", "if", "m", "and", "'temporary'", "not", "in", "line", ":", "# Return the first valid address we find", "for", "addr", "in", "global_addrs", ":", "if", "m", ".", "group", "(", "1", ")", "==", "addr", ":", "if", "not", "dynamic_only", "or", "m", ".", "group", "(", "1", ")", ".", "endswith", "(", "eui_64_mac", ")", ":", "addrs", ".", "append", "(", "addr", ")", "if", "addrs", ":", "return", "addrs", "if", "fatal", ":", "raise", "Exception", "(", "\"Interface '%s' does not have a scope global \"", "\"non-temporary ipv6 address.\"", "%", "iface", ")", "return", "[", "]" ]
Get assigned IPv6 address for a given interface. Returns list of addresses found. If no address found, returns empty list. If iface is None, we infer the current primary interface by doing a reverse lookup on the unit private-address. We currently only support scope global IPv6 addresses i.e. non-temporary addresses. If no global IPv6 address is found, return the first one found in the ipv6 address list. :param iface: network interface on which ipv6 address(es) are expected to be found. :param inc_aliases: include alias interfaces in search :param fatal: if True, raise exception if address not found :param exc_list: list of addresses to ignore :param dynamic_only: only recognise dynamic addresses :return: list of ipv6 addresses
[ "Get", "assigned", "IPv6", "address", "for", "a", "given", "interface", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L360-L424
12,662
juju/charm-helpers
charmhelpers/contrib/network/ip.py
get_bridges
def get_bridges(vnic_dir='/sys/devices/virtual/net'): """Return a list of bridges on the system.""" b_regex = "%s/*/bridge" % vnic_dir return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
python
def get_bridges(vnic_dir='/sys/devices/virtual/net'): """Return a list of bridges on the system.""" b_regex = "%s/*/bridge" % vnic_dir return [x.replace(vnic_dir, '').split('/')[1] for x in glob.glob(b_regex)]
[ "def", "get_bridges", "(", "vnic_dir", "=", "'/sys/devices/virtual/net'", ")", ":", "b_regex", "=", "\"%s/*/bridge\"", "%", "vnic_dir", "return", "[", "x", ".", "replace", "(", "vnic_dir", ",", "''", ")", ".", "split", "(", "'/'", ")", "[", "1", "]", "for", "x", "in", "glob", ".", "glob", "(", "b_regex", ")", "]" ]
Return a list of bridges on the system.
[ "Return", "a", "list", "of", "bridges", "on", "the", "system", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L427-L430
12,663
juju/charm-helpers
charmhelpers/contrib/network/ip.py
get_bridge_nics
def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'): """Return a list of nics comprising a given bridge on the system.""" brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge) return [x.split('/')[-1] for x in glob.glob(brif_regex)]
python
def get_bridge_nics(bridge, vnic_dir='/sys/devices/virtual/net'): """Return a list of nics comprising a given bridge on the system.""" brif_regex = "%s/%s/brif/*" % (vnic_dir, bridge) return [x.split('/')[-1] for x in glob.glob(brif_regex)]
[ "def", "get_bridge_nics", "(", "bridge", ",", "vnic_dir", "=", "'/sys/devices/virtual/net'", ")", ":", "brif_regex", "=", "\"%s/%s/brif/*\"", "%", "(", "vnic_dir", ",", "bridge", ")", "return", "[", "x", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "for", "x", "in", "glob", ".", "glob", "(", "brif_regex", ")", "]" ]
Return a list of nics comprising a given bridge on the system.
[ "Return", "a", "list", "of", "nics", "comprising", "a", "given", "bridge", "on", "the", "system", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L433-L436
12,664
juju/charm-helpers
charmhelpers/contrib/network/ip.py
is_ip
def is_ip(address): """ Returns True if address is a valid IP address. """ try: # Test to see if already an IPv4/IPv6 address address = netaddr.IPAddress(address) return True except (netaddr.AddrFormatError, ValueError): return False
python
def is_ip(address): """ Returns True if address is a valid IP address. """ try: # Test to see if already an IPv4/IPv6 address address = netaddr.IPAddress(address) return True except (netaddr.AddrFormatError, ValueError): return False
[ "def", "is_ip", "(", "address", ")", ":", "try", ":", "# Test to see if already an IPv4/IPv6 address", "address", "=", "netaddr", ".", "IPAddress", "(", "address", ")", "return", "True", "except", "(", "netaddr", ".", "AddrFormatError", ",", "ValueError", ")", ":", "return", "False" ]
Returns True if address is a valid IP address.
[ "Returns", "True", "if", "address", "is", "a", "valid", "IP", "address", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L448-L457
12,665
juju/charm-helpers
charmhelpers/contrib/network/ip.py
get_host_ip
def get_host_ip(hostname, fallback=None): """ Resolves the IP for a given hostname, or returns the input if it is already an IP. """ if is_ip(hostname): return hostname ip_addr = ns_query(hostname) if not ip_addr: try: ip_addr = socket.gethostbyname(hostname) except Exception: log("Failed to resolve hostname '%s'" % (hostname), level=WARNING) return fallback return ip_addr
python
def get_host_ip(hostname, fallback=None): """ Resolves the IP for a given hostname, or returns the input if it is already an IP. """ if is_ip(hostname): return hostname ip_addr = ns_query(hostname) if not ip_addr: try: ip_addr = socket.gethostbyname(hostname) except Exception: log("Failed to resolve hostname '%s'" % (hostname), level=WARNING) return fallback return ip_addr
[ "def", "get_host_ip", "(", "hostname", ",", "fallback", "=", "None", ")", ":", "if", "is_ip", "(", "hostname", ")", ":", "return", "hostname", "ip_addr", "=", "ns_query", "(", "hostname", ")", "if", "not", "ip_addr", ":", "try", ":", "ip_addr", "=", "socket", ".", "gethostbyname", "(", "hostname", ")", "except", "Exception", ":", "log", "(", "\"Failed to resolve hostname '%s'\"", "%", "(", "hostname", ")", ",", "level", "=", "WARNING", ")", "return", "fallback", "return", "ip_addr" ]
Resolves the IP for a given hostname, or returns the input if it is already an IP.
[ "Resolves", "the", "IP", "for", "a", "given", "hostname", "or", "returns", "the", "input", "if", "it", "is", "already", "an", "IP", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L487-L503
12,666
juju/charm-helpers
charmhelpers/contrib/network/ip.py
get_hostname
def get_hostname(address, fqdn=True): """ Resolves hostname for given IP, or returns the input if it is already a hostname. """ if is_ip(address): try: import dns.reversename except ImportError: if six.PY2: apt_install("python-dnspython", fatal=True) else: apt_install("python3-dnspython", fatal=True) import dns.reversename rev = dns.reversename.from_address(address) result = ns_query(rev) if not result: try: result = socket.gethostbyaddr(address)[0] except Exception: return None else: result = address if fqdn: # strip trailing . if result.endswith('.'): return result[:-1] else: return result else: return result.split('.')[0]
python
def get_hostname(address, fqdn=True): """ Resolves hostname for given IP, or returns the input if it is already a hostname. """ if is_ip(address): try: import dns.reversename except ImportError: if six.PY2: apt_install("python-dnspython", fatal=True) else: apt_install("python3-dnspython", fatal=True) import dns.reversename rev = dns.reversename.from_address(address) result = ns_query(rev) if not result: try: result = socket.gethostbyaddr(address)[0] except Exception: return None else: result = address if fqdn: # strip trailing . if result.endswith('.'): return result[:-1] else: return result else: return result.split('.')[0]
[ "def", "get_hostname", "(", "address", ",", "fqdn", "=", "True", ")", ":", "if", "is_ip", "(", "address", ")", ":", "try", ":", "import", "dns", ".", "reversename", "except", "ImportError", ":", "if", "six", ".", "PY2", ":", "apt_install", "(", "\"python-dnspython\"", ",", "fatal", "=", "True", ")", "else", ":", "apt_install", "(", "\"python3-dnspython\"", ",", "fatal", "=", "True", ")", "import", "dns", ".", "reversename", "rev", "=", "dns", ".", "reversename", ".", "from_address", "(", "address", ")", "result", "=", "ns_query", "(", "rev", ")", "if", "not", "result", ":", "try", ":", "result", "=", "socket", ".", "gethostbyaddr", "(", "address", ")", "[", "0", "]", "except", "Exception", ":", "return", "None", "else", ":", "result", "=", "address", "if", "fqdn", ":", "# strip trailing .", "if", "result", ".", "endswith", "(", "'.'", ")", ":", "return", "result", "[", ":", "-", "1", "]", "else", ":", "return", "result", "else", ":", "return", "result", ".", "split", "(", "'.'", ")", "[", "0", "]" ]
Resolves hostname for given IP, or returns the input if it is already a hostname.
[ "Resolves", "hostname", "for", "given", "IP", "or", "returns", "the", "input", "if", "it", "is", "already", "a", "hostname", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L506-L539
12,667
juju/charm-helpers
charmhelpers/contrib/network/ip.py
get_relation_ip
def get_relation_ip(interface, cidr_network=None): """Return this unit's IP for the given interface. Allow for an arbitrary interface to use with network-get to select an IP. Handle all address selection options including passed cidr network and IPv6. Usage: get_relation_ip('amqp', cidr_network='10.0.0.0/8') @param interface: string name of the relation. @param cidr_network: string CIDR Network to select an address from. @raises Exception if prefer-ipv6 is configured but IPv6 unsupported. @returns IPv6 or IPv4 address """ # Select the interface address first # For possible use as a fallback bellow with get_address_in_network try: # Get the interface specific IP address = network_get_primary_address(interface) except NotImplementedError: # If network-get is not available address = get_host_ip(unit_get('private-address')) except NoNetworkBinding: log("No network binding for {}".format(interface), WARNING) address = get_host_ip(unit_get('private-address')) if config('prefer-ipv6'): # Currently IPv6 has priority, eventually we want IPv6 to just be # another network space. assert_charm_supports_ipv6() return get_ipv6_addr()[0] elif cidr_network: # If a specific CIDR network is passed get the address from that # network. return get_address_in_network(cidr_network, address) # Return the interface address return address
python
def get_relation_ip(interface, cidr_network=None): """Return this unit's IP for the given interface. Allow for an arbitrary interface to use with network-get to select an IP. Handle all address selection options including passed cidr network and IPv6. Usage: get_relation_ip('amqp', cidr_network='10.0.0.0/8') @param interface: string name of the relation. @param cidr_network: string CIDR Network to select an address from. @raises Exception if prefer-ipv6 is configured but IPv6 unsupported. @returns IPv6 or IPv4 address """ # Select the interface address first # For possible use as a fallback bellow with get_address_in_network try: # Get the interface specific IP address = network_get_primary_address(interface) except NotImplementedError: # If network-get is not available address = get_host_ip(unit_get('private-address')) except NoNetworkBinding: log("No network binding for {}".format(interface), WARNING) address = get_host_ip(unit_get('private-address')) if config('prefer-ipv6'): # Currently IPv6 has priority, eventually we want IPv6 to just be # another network space. assert_charm_supports_ipv6() return get_ipv6_addr()[0] elif cidr_network: # If a specific CIDR network is passed get the address from that # network. return get_address_in_network(cidr_network, address) # Return the interface address return address
[ "def", "get_relation_ip", "(", "interface", ",", "cidr_network", "=", "None", ")", ":", "# Select the interface address first", "# For possible use as a fallback bellow with get_address_in_network", "try", ":", "# Get the interface specific IP", "address", "=", "network_get_primary_address", "(", "interface", ")", "except", "NotImplementedError", ":", "# If network-get is not available", "address", "=", "get_host_ip", "(", "unit_get", "(", "'private-address'", ")", ")", "except", "NoNetworkBinding", ":", "log", "(", "\"No network binding for {}\"", ".", "format", "(", "interface", ")", ",", "WARNING", ")", "address", "=", "get_host_ip", "(", "unit_get", "(", "'private-address'", ")", ")", "if", "config", "(", "'prefer-ipv6'", ")", ":", "# Currently IPv6 has priority, eventually we want IPv6 to just be", "# another network space.", "assert_charm_supports_ipv6", "(", ")", "return", "get_ipv6_addr", "(", ")", "[", "0", "]", "elif", "cidr_network", ":", "# If a specific CIDR network is passed get the address from that", "# network.", "return", "get_address_in_network", "(", "cidr_network", ",", "address", ")", "# Return the interface address", "return", "address" ]
Return this unit's IP for the given interface. Allow for an arbitrary interface to use with network-get to select an IP. Handle all address selection options including passed cidr network and IPv6. Usage: get_relation_ip('amqp', cidr_network='10.0.0.0/8') @param interface: string name of the relation. @param cidr_network: string CIDR Network to select an address from. @raises Exception if prefer-ipv6 is configured but IPv6 unsupported. @returns IPv6 or IPv4 address
[ "Return", "this", "unit", "s", "IP", "for", "the", "given", "interface", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L565-L602
12,668
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
BaseFileAudit.ensure_compliance
def ensure_compliance(self): """Ensure that the all registered files comply to registered criteria. """ for p in self.paths: if os.path.exists(p): if self.is_compliant(p): continue log('File %s is not in compliance.' % p, level=INFO) else: if not self.always_comply: log("Non-existent path '%s' - skipping compliance check" % (p), level=INFO) continue if self._take_action(): log("Applying compliance criteria to '%s'" % (p), level=INFO) self.comply(p)
python
def ensure_compliance(self): """Ensure that the all registered files comply to registered criteria. """ for p in self.paths: if os.path.exists(p): if self.is_compliant(p): continue log('File %s is not in compliance.' % p, level=INFO) else: if not self.always_comply: log("Non-existent path '%s' - skipping compliance check" % (p), level=INFO) continue if self._take_action(): log("Applying compliance criteria to '%s'" % (p), level=INFO) self.comply(p)
[ "def", "ensure_compliance", "(", "self", ")", ":", "for", "p", "in", "self", ".", "paths", ":", "if", "os", ".", "path", ".", "exists", "(", "p", ")", ":", "if", "self", ".", "is_compliant", "(", "p", ")", ":", "continue", "log", "(", "'File %s is not in compliance.'", "%", "p", ",", "level", "=", "INFO", ")", "else", ":", "if", "not", "self", ".", "always_comply", ":", "log", "(", "\"Non-existent path '%s' - skipping compliance check\"", "%", "(", "p", ")", ",", "level", "=", "INFO", ")", "continue", "if", "self", ".", "_take_action", "(", ")", ":", "log", "(", "\"Applying compliance criteria to '%s'\"", "%", "(", "p", ")", ",", "level", "=", "INFO", ")", "self", ".", "comply", "(", "p", ")" ]
Ensure that the all registered files comply to registered criteria.
[ "Ensure", "that", "the", "all", "registered", "files", "comply", "to", "registered", "criteria", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L71-L88
12,669
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
FilePermissionAudit.is_compliant
def is_compliant(self, path): """Checks if the path is in compliance. Used to determine if the path specified meets the necessary requirements to be in compliance with the check itself. :param path: the file path to check :returns: True if the path is compliant, False otherwise. """ stat = self._get_stat(path) user = self.user group = self.group compliant = True if stat.st_uid != user.pw_uid or stat.st_gid != group.gr_gid: log('File %s is not owned by %s:%s.' % (path, user.pw_name, group.gr_name), level=INFO) compliant = False # POSIX refers to the st_mode bits as corresponding to both the # file type and file permission bits, where the least significant 12 # bits (o7777) are the suid (11), sgid (10), sticky bits (9), and the # file permission bits (8-0) perms = stat.st_mode & 0o7777 if perms != self.mode: log('File %s has incorrect permissions, currently set to %s' % (path, oct(stat.st_mode & 0o7777)), level=INFO) compliant = False return compliant
python
def is_compliant(self, path): """Checks if the path is in compliance. Used to determine if the path specified meets the necessary requirements to be in compliance with the check itself. :param path: the file path to check :returns: True if the path is compliant, False otherwise. """ stat = self._get_stat(path) user = self.user group = self.group compliant = True if stat.st_uid != user.pw_uid or stat.st_gid != group.gr_gid: log('File %s is not owned by %s:%s.' % (path, user.pw_name, group.gr_name), level=INFO) compliant = False # POSIX refers to the st_mode bits as corresponding to both the # file type and file permission bits, where the least significant 12 # bits (o7777) are the suid (11), sgid (10), sticky bits (9), and the # file permission bits (8-0) perms = stat.st_mode & 0o7777 if perms != self.mode: log('File %s has incorrect permissions, currently set to %s' % (path, oct(stat.st_mode & 0o7777)), level=INFO) compliant = False return compliant
[ "def", "is_compliant", "(", "self", ",", "path", ")", ":", "stat", "=", "self", ".", "_get_stat", "(", "path", ")", "user", "=", "self", ".", "user", "group", "=", "self", ".", "group", "compliant", "=", "True", "if", "stat", ".", "st_uid", "!=", "user", ".", "pw_uid", "or", "stat", ".", "st_gid", "!=", "group", ".", "gr_gid", ":", "log", "(", "'File %s is not owned by %s:%s.'", "%", "(", "path", ",", "user", ".", "pw_name", ",", "group", ".", "gr_name", ")", ",", "level", "=", "INFO", ")", "compliant", "=", "False", "# POSIX refers to the st_mode bits as corresponding to both the", "# file type and file permission bits, where the least significant 12", "# bits (o7777) are the suid (11), sgid (10), sticky bits (9), and the", "# file permission bits (8-0)", "perms", "=", "stat", ".", "st_mode", "&", "0o7777", "if", "perms", "!=", "self", ".", "mode", ":", "log", "(", "'File %s has incorrect permissions, currently set to %s'", "%", "(", "path", ",", "oct", "(", "stat", ".", "st_mode", "&", "0o7777", ")", ")", ",", "level", "=", "INFO", ")", "compliant", "=", "False", "return", "compliant" ]
Checks if the path is in compliance. Used to determine if the path specified meets the necessary requirements to be in compliance with the check itself. :param path: the file path to check :returns: True if the path is compliant, False otherwise.
[ "Checks", "if", "the", "path", "is", "in", "compliance", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L158-L188
12,670
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
FilePermissionAudit.comply
def comply(self, path): """Issues a chown and chmod to the file paths specified.""" utils.ensure_permissions(path, self.user.pw_name, self.group.gr_name, self.mode)
python
def comply(self, path): """Issues a chown and chmod to the file paths specified.""" utils.ensure_permissions(path, self.user.pw_name, self.group.gr_name, self.mode)
[ "def", "comply", "(", "self", ",", "path", ")", ":", "utils", ".", "ensure_permissions", "(", "path", ",", "self", ".", "user", ".", "pw_name", ",", "self", ".", "group", ".", "gr_name", ",", "self", ".", "mode", ")" ]
Issues a chown and chmod to the file paths specified.
[ "Issues", "a", "chown", "and", "chmod", "to", "the", "file", "paths", "specified", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L190-L193
12,671
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
DirectoryPermissionAudit.is_compliant
def is_compliant(self, path): """Checks if the directory is compliant. Used to determine if the path specified and all of its children directories are in compliance with the check itself. :param path: the directory path to check :returns: True if the directory tree is compliant, otherwise False. """ if not os.path.isdir(path): log('Path specified %s is not a directory.' % path, level=ERROR) raise ValueError("%s is not a directory." % path) if not self.recursive: return super(DirectoryPermissionAudit, self).is_compliant(path) compliant = True for root, dirs, _ in os.walk(path): if len(dirs) > 0: continue if not super(DirectoryPermissionAudit, self).is_compliant(root): compliant = False continue return compliant
python
def is_compliant(self, path): """Checks if the directory is compliant. Used to determine if the path specified and all of its children directories are in compliance with the check itself. :param path: the directory path to check :returns: True if the directory tree is compliant, otherwise False. """ if not os.path.isdir(path): log('Path specified %s is not a directory.' % path, level=ERROR) raise ValueError("%s is not a directory." % path) if not self.recursive: return super(DirectoryPermissionAudit, self).is_compliant(path) compliant = True for root, dirs, _ in os.walk(path): if len(dirs) > 0: continue if not super(DirectoryPermissionAudit, self).is_compliant(root): compliant = False continue return compliant
[ "def", "is_compliant", "(", "self", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "log", "(", "'Path specified %s is not a directory.'", "%", "path", ",", "level", "=", "ERROR", ")", "raise", "ValueError", "(", "\"%s is not a directory.\"", "%", "path", ")", "if", "not", "self", ".", "recursive", ":", "return", "super", "(", "DirectoryPermissionAudit", ",", "self", ")", ".", "is_compliant", "(", "path", ")", "compliant", "=", "True", "for", "root", ",", "dirs", ",", "_", "in", "os", ".", "walk", "(", "path", ")", ":", "if", "len", "(", "dirs", ")", ">", "0", ":", "continue", "if", "not", "super", "(", "DirectoryPermissionAudit", ",", "self", ")", ".", "is_compliant", "(", "root", ")", ":", "compliant", "=", "False", "continue", "return", "compliant" ]
Checks if the directory is compliant. Used to determine if the path specified and all of its children directories are in compliance with the check itself. :param path: the directory path to check :returns: True if the directory tree is compliant, otherwise False.
[ "Checks", "if", "the", "directory", "is", "compliant", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L205-L230
12,672
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
TemplatedFile.is_compliant
def is_compliant(self, path): """Determines if the templated file is compliant. A templated file is only compliant if it has not changed (as determined by its sha256 hashsum) AND its file permissions are set appropriately. :param path: the path to check compliance. """ same_templates = self.templates_match(path) same_content = self.contents_match(path) same_permissions = self.permissions_match(path) if same_content and same_permissions and same_templates: return True return False
python
def is_compliant(self, path): """Determines if the templated file is compliant. A templated file is only compliant if it has not changed (as determined by its sha256 hashsum) AND its file permissions are set appropriately. :param path: the path to check compliance. """ same_templates = self.templates_match(path) same_content = self.contents_match(path) same_permissions = self.permissions_match(path) if same_content and same_permissions and same_templates: return True return False
[ "def", "is_compliant", "(", "self", ",", "path", ")", ":", "same_templates", "=", "self", ".", "templates_match", "(", "path", ")", "same_content", "=", "self", ".", "contents_match", "(", "path", ")", "same_permissions", "=", "self", ".", "permissions_match", "(", "path", ")", "if", "same_content", "and", "same_permissions", "and", "same_templates", ":", "return", "True", "return", "False" ]
Determines if the templated file is compliant. A templated file is only compliant if it has not changed (as determined by its sha256 hashsum) AND its file permissions are set appropriately. :param path: the path to check compliance.
[ "Determines", "if", "the", "templated", "file", "is", "compliant", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L347-L363
12,673
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
TemplatedFile.run_service_actions
def run_service_actions(self): """Run any actions on services requested.""" if not self.service_actions: return for svc_action in self.service_actions: name = svc_action['service'] actions = svc_action['actions'] log("Running service '%s' actions '%s'" % (name, actions), level=DEBUG) for action in actions: cmd = ['service', name, action] try: check_call(cmd) except CalledProcessError as exc: log("Service name='%s' action='%s' failed - %s" % (name, action, exc), level=WARNING)
python
def run_service_actions(self): """Run any actions on services requested.""" if not self.service_actions: return for svc_action in self.service_actions: name = svc_action['service'] actions = svc_action['actions'] log("Running service '%s' actions '%s'" % (name, actions), level=DEBUG) for action in actions: cmd = ['service', name, action] try: check_call(cmd) except CalledProcessError as exc: log("Service name='%s' action='%s' failed - %s" % (name, action, exc), level=WARNING)
[ "def", "run_service_actions", "(", "self", ")", ":", "if", "not", "self", ".", "service_actions", ":", "return", "for", "svc_action", "in", "self", ".", "service_actions", ":", "name", "=", "svc_action", "[", "'service'", "]", "actions", "=", "svc_action", "[", "'actions'", "]", "log", "(", "\"Running service '%s' actions '%s'\"", "%", "(", "name", ",", "actions", ")", ",", "level", "=", "DEBUG", ")", "for", "action", "in", "actions", ":", "cmd", "=", "[", "'service'", ",", "name", ",", "action", "]", "try", ":", "check_call", "(", "cmd", ")", "except", "CalledProcessError", "as", "exc", ":", "log", "(", "\"Service name='%s' action='%s' failed - %s\"", "%", "(", "name", ",", "action", ",", "exc", ")", ",", "level", "=", "WARNING", ")" ]
Run any actions on services requested.
[ "Run", "any", "actions", "on", "services", "requested", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L365-L381
12,674
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
TemplatedFile.comply
def comply(self, path): """Ensures the contents and the permissions of the file. :param path: the path to correct """ dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) self.pre_write() render_and_write(self.template_dir, path, self.context()) utils.ensure_permissions(path, self.user, self.group, self.mode) self.run_service_actions() self.save_checksum(path) self.post_write()
python
def comply(self, path): """Ensures the contents and the permissions of the file. :param path: the path to correct """ dirname = os.path.dirname(path) if not os.path.exists(dirname): os.makedirs(dirname) self.pre_write() render_and_write(self.template_dir, path, self.context()) utils.ensure_permissions(path, self.user, self.group, self.mode) self.run_service_actions() self.save_checksum(path) self.post_write()
[ "def", "comply", "(", "self", ",", "path", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "self", ".", "pre_write", "(", ")", "render_and_write", "(", "self", ".", "template_dir", ",", "path", ",", "self", ".", "context", "(", ")", ")", "utils", ".", "ensure_permissions", "(", "path", ",", "self", ".", "user", ",", "self", ".", "group", ",", "self", ".", "mode", ")", "self", ".", "run_service_actions", "(", ")", "self", ".", "save_checksum", "(", "path", ")", "self", ".", "post_write", "(", ")" ]
Ensures the contents and the permissions of the file. :param path: the path to correct
[ "Ensures", "the", "contents", "and", "the", "permissions", "of", "the", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L383-L397
12,675
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
TemplatedFile.templates_match
def templates_match(self, path): """Determines if the template files are the same. The template file equality is determined by the hashsum of the template files themselves. If there is no hashsum, then the content cannot be sure to be the same so treat it as if they changed. Otherwise, return whether or not the hashsums are the same. :param path: the path to check :returns: boolean """ template_path = get_template_path(self.template_dir, path) key = 'hardening:template:%s' % template_path template_checksum = file_hash(template_path) kv = unitdata.kv() stored_tmplt_checksum = kv.get(key) if not stored_tmplt_checksum: kv.set(key, template_checksum) kv.flush() log('Saved template checksum for %s.' % template_path, level=DEBUG) # Since we don't have a template checksum, then assume it doesn't # match and return that the template is different. return False elif stored_tmplt_checksum != template_checksum: kv.set(key, template_checksum) kv.flush() log('Updated template checksum for %s.' % template_path, level=DEBUG) return False # Here the template hasn't changed based upon the calculated # checksum of the template and what was previously stored. return True
python
def templates_match(self, path): """Determines if the template files are the same. The template file equality is determined by the hashsum of the template files themselves. If there is no hashsum, then the content cannot be sure to be the same so treat it as if they changed. Otherwise, return whether or not the hashsums are the same. :param path: the path to check :returns: boolean """ template_path = get_template_path(self.template_dir, path) key = 'hardening:template:%s' % template_path template_checksum = file_hash(template_path) kv = unitdata.kv() stored_tmplt_checksum = kv.get(key) if not stored_tmplt_checksum: kv.set(key, template_checksum) kv.flush() log('Saved template checksum for %s.' % template_path, level=DEBUG) # Since we don't have a template checksum, then assume it doesn't # match and return that the template is different. return False elif stored_tmplt_checksum != template_checksum: kv.set(key, template_checksum) kv.flush() log('Updated template checksum for %s.' % template_path, level=DEBUG) return False # Here the template hasn't changed based upon the calculated # checksum of the template and what was previously stored. return True
[ "def", "templates_match", "(", "self", ",", "path", ")", ":", "template_path", "=", "get_template_path", "(", "self", ".", "template_dir", ",", "path", ")", "key", "=", "'hardening:template:%s'", "%", "template_path", "template_checksum", "=", "file_hash", "(", "template_path", ")", "kv", "=", "unitdata", ".", "kv", "(", ")", "stored_tmplt_checksum", "=", "kv", ".", "get", "(", "key", ")", "if", "not", "stored_tmplt_checksum", ":", "kv", ".", "set", "(", "key", ",", "template_checksum", ")", "kv", ".", "flush", "(", ")", "log", "(", "'Saved template checksum for %s.'", "%", "template_path", ",", "level", "=", "DEBUG", ")", "# Since we don't have a template checksum, then assume it doesn't", "# match and return that the template is different.", "return", "False", "elif", "stored_tmplt_checksum", "!=", "template_checksum", ":", "kv", ".", "set", "(", "key", ",", "template_checksum", ")", "kv", ".", "flush", "(", ")", "log", "(", "'Updated template checksum for %s.'", "%", "template_path", ",", "level", "=", "DEBUG", ")", "return", "False", "# Here the template hasn't changed based upon the calculated", "# checksum of the template and what was previously stored.", "return", "True" ]
Determines if the template files are the same. The template file equality is determined by the hashsum of the template files themselves. If there is no hashsum, then the content cannot be sure to be the same so treat it as if they changed. Otherwise, return whether or not the hashsums are the same. :param path: the path to check :returns: boolean
[ "Determines", "if", "the", "template", "files", "are", "the", "same", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L407-L440
12,676
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
TemplatedFile.contents_match
def contents_match(self, path): """Determines if the file content is the same. This is determined by comparing hashsum of the file contents and the saved hashsum. If there is no hashsum, then the content cannot be sure to be the same so treat them as if they are not the same. Otherwise, return True if the hashsums are the same, False if they are not the same. :param path: the file to check. """ checksum = file_hash(path) kv = unitdata.kv() stored_checksum = kv.get('hardening:%s' % path) if not stored_checksum: # If the checksum hasn't been generated, return False to ensure # the file is written and the checksum stored. log('Checksum for %s has not been calculated.' % path, level=DEBUG) return False elif stored_checksum != checksum: log('Checksum mismatch for %s.' % path, level=DEBUG) return False return True
python
def contents_match(self, path): """Determines if the file content is the same. This is determined by comparing hashsum of the file contents and the saved hashsum. If there is no hashsum, then the content cannot be sure to be the same so treat them as if they are not the same. Otherwise, return True if the hashsums are the same, False if they are not the same. :param path: the file to check. """ checksum = file_hash(path) kv = unitdata.kv() stored_checksum = kv.get('hardening:%s' % path) if not stored_checksum: # If the checksum hasn't been generated, return False to ensure # the file is written and the checksum stored. log('Checksum for %s has not been calculated.' % path, level=DEBUG) return False elif stored_checksum != checksum: log('Checksum mismatch for %s.' % path, level=DEBUG) return False return True
[ "def", "contents_match", "(", "self", ",", "path", ")", ":", "checksum", "=", "file_hash", "(", "path", ")", "kv", "=", "unitdata", ".", "kv", "(", ")", "stored_checksum", "=", "kv", ".", "get", "(", "'hardening:%s'", "%", "path", ")", "if", "not", "stored_checksum", ":", "# If the checksum hasn't been generated, return False to ensure", "# the file is written and the checksum stored.", "log", "(", "'Checksum for %s has not been calculated.'", "%", "path", ",", "level", "=", "DEBUG", ")", "return", "False", "elif", "stored_checksum", "!=", "checksum", ":", "log", "(", "'Checksum mismatch for %s.'", "%", "path", ",", "level", "=", "DEBUG", ")", "return", "False", "return", "True" ]
Determines if the file content is the same. This is determined by comparing hashsum of the file contents and the saved hashsum. If there is no hashsum, then the content cannot be sure to be the same so treat them as if they are not the same. Otherwise, return True if the hashsums are the same, False if they are not the same. :param path: the file to check.
[ "Determines", "if", "the", "file", "content", "is", "the", "same", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L442-L466
12,677
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
TemplatedFile.permissions_match
def permissions_match(self, path): """Determines if the file owner and permissions match. :param path: the path to check. """ audit = FilePermissionAudit(path, self.user, self.group, self.mode) return audit.is_compliant(path)
python
def permissions_match(self, path): """Determines if the file owner and permissions match. :param path: the path to check. """ audit = FilePermissionAudit(path, self.user, self.group, self.mode) return audit.is_compliant(path)
[ "def", "permissions_match", "(", "self", ",", "path", ")", ":", "audit", "=", "FilePermissionAudit", "(", "path", ",", "self", ".", "user", ",", "self", ".", "group", ",", "self", ".", "mode", ")", "return", "audit", ".", "is_compliant", "(", "path", ")" ]
Determines if the file owner and permissions match. :param path: the path to check.
[ "Determines", "if", "the", "file", "owner", "and", "permissions", "match", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L468-L474
12,678
juju/charm-helpers
charmhelpers/contrib/hardening/audits/file.py
TemplatedFile.save_checksum
def save_checksum(self, path): """Calculates and saves the checksum for the path specified. :param path: the path of the file to save the checksum. """ checksum = file_hash(path) kv = unitdata.kv() kv.set('hardening:%s' % path, checksum) kv.flush()
python
def save_checksum(self, path): """Calculates and saves the checksum for the path specified. :param path: the path of the file to save the checksum. """ checksum = file_hash(path) kv = unitdata.kv() kv.set('hardening:%s' % path, checksum) kv.flush()
[ "def", "save_checksum", "(", "self", ",", "path", ")", ":", "checksum", "=", "file_hash", "(", "path", ")", "kv", "=", "unitdata", ".", "kv", "(", ")", "kv", ".", "set", "(", "'hardening:%s'", "%", "path", ",", "checksum", ")", "kv", ".", "flush", "(", ")" ]
Calculates and saves the checksum for the path specified. :param path: the path of the file to save the checksum.
[ "Calculates", "and", "saves", "the", "checksum", "for", "the", "path", "specified", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/audits/file.py#L476-L484
12,679
juju/charm-helpers
charmhelpers/core/strutils.py
bool_from_string
def bool_from_string(value): """Interpret string value as boolean. Returns True if value translates to True otherwise False. """ if isinstance(value, six.string_types): value = six.text_type(value) else: msg = "Unable to interpret non-string value '%s' as boolean" % (value) raise ValueError(msg) value = value.strip().lower() if value in ['y', 'yes', 'true', 't', 'on']: return True elif value in ['n', 'no', 'false', 'f', 'off']: return False msg = "Unable to interpret string value '%s' as boolean" % (value) raise ValueError(msg)
python
def bool_from_string(value): """Interpret string value as boolean. Returns True if value translates to True otherwise False. """ if isinstance(value, six.string_types): value = six.text_type(value) else: msg = "Unable to interpret non-string value '%s' as boolean" % (value) raise ValueError(msg) value = value.strip().lower() if value in ['y', 'yes', 'true', 't', 'on']: return True elif value in ['n', 'no', 'false', 'f', 'off']: return False msg = "Unable to interpret string value '%s' as boolean" % (value) raise ValueError(msg)
[ "def", "bool_from_string", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", "=", "six", ".", "text_type", "(", "value", ")", "else", ":", "msg", "=", "\"Unable to interpret non-string value '%s' as boolean\"", "%", "(", "value", ")", "raise", "ValueError", "(", "msg", ")", "value", "=", "value", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "value", "in", "[", "'y'", ",", "'yes'", ",", "'true'", ",", "'t'", ",", "'on'", "]", ":", "return", "True", "elif", "value", "in", "[", "'n'", ",", "'no'", ",", "'false'", ",", "'f'", ",", "'off'", "]", ":", "return", "False", "msg", "=", "\"Unable to interpret string value '%s' as boolean\"", "%", "(", "value", ")", "raise", "ValueError", "(", "msg", ")" ]
Interpret string value as boolean. Returns True if value translates to True otherwise False.
[ "Interpret", "string", "value", "as", "boolean", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/strutils.py#L22-L41
12,680
juju/charm-helpers
charmhelpers/core/strutils.py
bytes_from_string
def bytes_from_string(value): """Interpret human readable string value as bytes. Returns int """ BYTE_POWER = { 'K': 1, 'KB': 1, 'M': 2, 'MB': 2, 'G': 3, 'GB': 3, 'T': 4, 'TB': 4, 'P': 5, 'PB': 5, } if isinstance(value, six.string_types): value = six.text_type(value) else: msg = "Unable to interpret non-string value '%s' as bytes" % (value) raise ValueError(msg) matches = re.match("([0-9]+)([a-zA-Z]+)", value) if matches: size = int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)]) else: # Assume that value passed in is bytes try: size = int(value) except ValueError: msg = "Unable to interpret string value '%s' as bytes" % (value) raise ValueError(msg) return size
python
def bytes_from_string(value): """Interpret human readable string value as bytes. Returns int """ BYTE_POWER = { 'K': 1, 'KB': 1, 'M': 2, 'MB': 2, 'G': 3, 'GB': 3, 'T': 4, 'TB': 4, 'P': 5, 'PB': 5, } if isinstance(value, six.string_types): value = six.text_type(value) else: msg = "Unable to interpret non-string value '%s' as bytes" % (value) raise ValueError(msg) matches = re.match("([0-9]+)([a-zA-Z]+)", value) if matches: size = int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)]) else: # Assume that value passed in is bytes try: size = int(value) except ValueError: msg = "Unable to interpret string value '%s' as bytes" % (value) raise ValueError(msg) return size
[ "def", "bytes_from_string", "(", "value", ")", ":", "BYTE_POWER", "=", "{", "'K'", ":", "1", ",", "'KB'", ":", "1", ",", "'M'", ":", "2", ",", "'MB'", ":", "2", ",", "'G'", ":", "3", ",", "'GB'", ":", "3", ",", "'T'", ":", "4", ",", "'TB'", ":", "4", ",", "'P'", ":", "5", ",", "'PB'", ":", "5", ",", "}", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "value", "=", "six", ".", "text_type", "(", "value", ")", "else", ":", "msg", "=", "\"Unable to interpret non-string value '%s' as bytes\"", "%", "(", "value", ")", "raise", "ValueError", "(", "msg", ")", "matches", "=", "re", ".", "match", "(", "\"([0-9]+)([a-zA-Z]+)\"", ",", "value", ")", "if", "matches", ":", "size", "=", "int", "(", "matches", ".", "group", "(", "1", ")", ")", "*", "(", "1024", "**", "BYTE_POWER", "[", "matches", ".", "group", "(", "2", ")", "]", ")", "else", ":", "# Assume that value passed in is bytes", "try", ":", "size", "=", "int", "(", "value", ")", "except", "ValueError", ":", "msg", "=", "\"Unable to interpret string value '%s' as bytes\"", "%", "(", "value", ")", "raise", "ValueError", "(", "msg", ")", "return", "size" ]
Interpret human readable string value as bytes. Returns int
[ "Interpret", "human", "readable", "string", "value", "as", "bytes", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/strutils.py#L44-L76
12,681
juju/charm-helpers
charmhelpers/contrib/openstack/audits/__init__.py
audit
def audit(*args): """Decorator to register an audit. These are used to generate audits that can be run on a deployed system that matches the given configuration :param args: List of functions to filter tests against :type args: List[Callable[Dict]] """ def wrapper(f): test_name = f.__name__ if _audits.get(test_name): raise RuntimeError( "Test name '{}' used more than once" .format(test_name)) non_callables = [fn for fn in args if not callable(fn)] if non_callables: raise RuntimeError( "Configuration includes non-callable filters: {}" .format(non_callables)) _audits[test_name] = Audit(func=f, filters=args) return f return wrapper
python
def audit(*args): """Decorator to register an audit. These are used to generate audits that can be run on a deployed system that matches the given configuration :param args: List of functions to filter tests against :type args: List[Callable[Dict]] """ def wrapper(f): test_name = f.__name__ if _audits.get(test_name): raise RuntimeError( "Test name '{}' used more than once" .format(test_name)) non_callables = [fn for fn in args if not callable(fn)] if non_callables: raise RuntimeError( "Configuration includes non-callable filters: {}" .format(non_callables)) _audits[test_name] = Audit(func=f, filters=args) return f return wrapper
[ "def", "audit", "(", "*", "args", ")", ":", "def", "wrapper", "(", "f", ")", ":", "test_name", "=", "f", ".", "__name__", "if", "_audits", ".", "get", "(", "test_name", ")", ":", "raise", "RuntimeError", "(", "\"Test name '{}' used more than once\"", ".", "format", "(", "test_name", ")", ")", "non_callables", "=", "[", "fn", "for", "fn", "in", "args", "if", "not", "callable", "(", "fn", ")", "]", "if", "non_callables", ":", "raise", "RuntimeError", "(", "\"Configuration includes non-callable filters: {}\"", ".", "format", "(", "non_callables", ")", ")", "_audits", "[", "test_name", "]", "=", "Audit", "(", "func", "=", "f", ",", "filters", "=", "args", ")", "return", "f", "return", "wrapper" ]
Decorator to register an audit. These are used to generate audits that can be run on a deployed system that matches the given configuration :param args: List of functions to filter tests against :type args: List[Callable[Dict]]
[ "Decorator", "to", "register", "an", "audit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/__init__.py#L35-L57
12,682
juju/charm-helpers
charmhelpers/contrib/openstack/audits/__init__.py
is_audit_type
def is_audit_type(*args): """This audit is included in the specified kinds of audits. :param *args: List of AuditTypes to include this audit in :type args: List[AuditType] :rtype: Callable[Dict] """ def _is_audit_type(audit_options): if audit_options.get('audit_type') in args: return True else: return False return _is_audit_type
python
def is_audit_type(*args): """This audit is included in the specified kinds of audits. :param *args: List of AuditTypes to include this audit in :type args: List[AuditType] :rtype: Callable[Dict] """ def _is_audit_type(audit_options): if audit_options.get('audit_type') in args: return True else: return False return _is_audit_type
[ "def", "is_audit_type", "(", "*", "args", ")", ":", "def", "_is_audit_type", "(", "audit_options", ")", ":", "if", "audit_options", ".", "get", "(", "'audit_type'", ")", "in", "args", ":", "return", "True", "else", ":", "return", "False", "return", "_is_audit_type" ]
This audit is included in the specified kinds of audits. :param *args: List of AuditTypes to include this audit in :type args: List[AuditType] :rtype: Callable[Dict]
[ "This", "audit", "is", "included", "in", "the", "specified", "kinds", "of", "audits", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/__init__.py#L60-L72
12,683
juju/charm-helpers
charmhelpers/contrib/openstack/audits/__init__.py
run
def run(audit_options): """Run the configured audits with the specified audit_options. :param audit_options: Configuration for the audit :type audit_options: Config :rtype: Dict[str, str] """ errors = {} results = {} for name, audit in sorted(_audits.items()): result_name = name.replace('_', '-') if result_name in audit_options.get('excludes', []): print( "Skipping {} because it is" "excluded in audit config" .format(result_name)) continue if all(p(audit_options) for p in audit.filters): try: audit.func(audit_options) print("{}: PASS".format(name)) results[result_name] = { 'success': True, } except AssertionError as e: print("{}: FAIL ({})".format(name, e)) results[result_name] = { 'success': False, 'message': e, } except Exception as e: print("{}: ERROR ({})".format(name, e)) errors[name] = e results[result_name] = { 'success': False, 'message': e, } for name, error in errors.items(): print("=" * 20) print("Error in {}: ".format(name)) traceback.print_tb(error.__traceback__) print() return results
python
def run(audit_options): """Run the configured audits with the specified audit_options. :param audit_options: Configuration for the audit :type audit_options: Config :rtype: Dict[str, str] """ errors = {} results = {} for name, audit in sorted(_audits.items()): result_name = name.replace('_', '-') if result_name in audit_options.get('excludes', []): print( "Skipping {} because it is" "excluded in audit config" .format(result_name)) continue if all(p(audit_options) for p in audit.filters): try: audit.func(audit_options) print("{}: PASS".format(name)) results[result_name] = { 'success': True, } except AssertionError as e: print("{}: FAIL ({})".format(name, e)) results[result_name] = { 'success': False, 'message': e, } except Exception as e: print("{}: ERROR ({})".format(name, e)) errors[name] = e results[result_name] = { 'success': False, 'message': e, } for name, error in errors.items(): print("=" * 20) print("Error in {}: ".format(name)) traceback.print_tb(error.__traceback__) print() return results
[ "def", "run", "(", "audit_options", ")", ":", "errors", "=", "{", "}", "results", "=", "{", "}", "for", "name", ",", "audit", "in", "sorted", "(", "_audits", ".", "items", "(", ")", ")", ":", "result_name", "=", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", "if", "result_name", "in", "audit_options", ".", "get", "(", "'excludes'", ",", "[", "]", ")", ":", "print", "(", "\"Skipping {} because it is\"", "\"excluded in audit config\"", ".", "format", "(", "result_name", ")", ")", "continue", "if", "all", "(", "p", "(", "audit_options", ")", "for", "p", "in", "audit", ".", "filters", ")", ":", "try", ":", "audit", ".", "func", "(", "audit_options", ")", "print", "(", "\"{}: PASS\"", ".", "format", "(", "name", ")", ")", "results", "[", "result_name", "]", "=", "{", "'success'", ":", "True", ",", "}", "except", "AssertionError", "as", "e", ":", "print", "(", "\"{}: FAIL ({})\"", ".", "format", "(", "name", ",", "e", ")", ")", "results", "[", "result_name", "]", "=", "{", "'success'", ":", "False", ",", "'message'", ":", "e", ",", "}", "except", "Exception", "as", "e", ":", "print", "(", "\"{}: ERROR ({})\"", ".", "format", "(", "name", ",", "e", ")", ")", "errors", "[", "name", "]", "=", "e", "results", "[", "result_name", "]", "=", "{", "'success'", ":", "False", ",", "'message'", ":", "e", ",", "}", "for", "name", ",", "error", "in", "errors", ".", "items", "(", ")", ":", "print", "(", "\"=\"", "*", "20", ")", "print", "(", "\"Error in {}: \"", ".", "format", "(", "name", ")", ")", "traceback", ".", "print_tb", "(", "error", ".", "__traceback__", ")", "print", "(", ")", "return", "results" ]
Run the configured audits with the specified audit_options. :param audit_options: Configuration for the audit :type audit_options: Config :rtype: Dict[str, str]
[ "Run", "the", "configured", "audits", "with", "the", "specified", "audit_options", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/__init__.py#L149-L192
12,684
juju/charm-helpers
charmhelpers/contrib/openstack/audits/__init__.py
action_parse_results
def action_parse_results(result): """Parse the result of `run` in the context of an action. :param result: The result of running the security-checklist action on a unit :type result: Dict[str, Dict[str, str]] :rtype: int """ passed = True for test, result in result.items(): if result['success']: hookenv.action_set({test: 'PASS'}) else: hookenv.action_set({test: 'FAIL - {}'.format(result['message'])}) passed = False if not passed: hookenv.action_fail("One or more tests failed") return 0 if passed else 1
python
def action_parse_results(result): """Parse the result of `run` in the context of an action. :param result: The result of running the security-checklist action on a unit :type result: Dict[str, Dict[str, str]] :rtype: int """ passed = True for test, result in result.items(): if result['success']: hookenv.action_set({test: 'PASS'}) else: hookenv.action_set({test: 'FAIL - {}'.format(result['message'])}) passed = False if not passed: hookenv.action_fail("One or more tests failed") return 0 if passed else 1
[ "def", "action_parse_results", "(", "result", ")", ":", "passed", "=", "True", "for", "test", ",", "result", "in", "result", ".", "items", "(", ")", ":", "if", "result", "[", "'success'", "]", ":", "hookenv", ".", "action_set", "(", "{", "test", ":", "'PASS'", "}", ")", "else", ":", "hookenv", ".", "action_set", "(", "{", "test", ":", "'FAIL - {}'", ".", "format", "(", "result", "[", "'message'", "]", ")", "}", ")", "passed", "=", "False", "if", "not", "passed", ":", "hookenv", ".", "action_fail", "(", "\"One or more tests failed\"", ")", "return", "0", "if", "passed", "else", "1" ]
Parse the result of `run` in the context of an action. :param result: The result of running the security-checklist action on a unit :type result: Dict[str, Dict[str, str]] :rtype: int
[ "Parse", "the", "result", "of", "run", "in", "the", "context", "of", "an", "action", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/audits/__init__.py#L195-L212
12,685
juju/charm-helpers
charmhelpers/contrib/ssl/__init__.py
generate_selfsigned
def generate_selfsigned(keyfile, certfile, keysize="1024", config=None, subject=None, cn=None): """Generate selfsigned SSL keypair You must provide one of the 3 optional arguments: config, subject or cn If more than one is provided the leftmost will be used Arguments: keyfile -- (required) full path to the keyfile to be created certfile -- (required) full path to the certfile to be created keysize -- (optional) SSL key length config -- (optional) openssl configuration file subject -- (optional) dictionary with SSL subject variables cn -- (optional) cerfificate common name Required keys in subject dict: cn -- Common name (eq. FQDN) Optional keys in subject dict country -- Country Name (2 letter code) state -- State or Province Name (full name) locality -- Locality Name (eg, city) organization -- Organization Name (eg, company) organizational_unit -- Organizational Unit Name (eg, section) email -- Email Address """ cmd = [] if config: cmd = ["/usr/bin/openssl", "req", "-new", "-newkey", "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509", "-keyout", keyfile, "-out", certfile, "-config", config] elif subject: ssl_subject = "" if "country" in subject: ssl_subject = ssl_subject + "/C={}".format(subject["country"]) if "state" in subject: ssl_subject = ssl_subject + "/ST={}".format(subject["state"]) if "locality" in subject: ssl_subject = ssl_subject + "/L={}".format(subject["locality"]) if "organization" in subject: ssl_subject = ssl_subject + "/O={}".format(subject["organization"]) if "organizational_unit" in subject: ssl_subject = ssl_subject + "/OU={}".format(subject["organizational_unit"]) if "cn" in subject: ssl_subject = ssl_subject + "/CN={}".format(subject["cn"]) else: hookenv.log("When using \"subject\" argument you must " "provide \"cn\" field at very least") return False if "email" in subject: ssl_subject = ssl_subject + "/emailAddress={}".format(subject["email"]) cmd = ["/usr/bin/openssl", "req", "-new", "-newkey", "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509", "-keyout", keyfile, "-out", certfile, "-subj", ssl_subject] elif cn: cmd = ["/usr/bin/openssl", "req", "-new", "-newkey", "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509", "-keyout", keyfile, "-out", certfile, "-subj", "/CN={}".format(cn)] if not cmd: hookenv.log("No config, subject or cn provided," "unable to generate self signed SSL certificates") return False try: subprocess.check_call(cmd) return True except Exception as e: print("Execution of openssl command failed:\n{}".format(e)) return False
python
def generate_selfsigned(keyfile, certfile, keysize="1024", config=None, subject=None, cn=None): """Generate selfsigned SSL keypair You must provide one of the 3 optional arguments: config, subject or cn If more than one is provided the leftmost will be used Arguments: keyfile -- (required) full path to the keyfile to be created certfile -- (required) full path to the certfile to be created keysize -- (optional) SSL key length config -- (optional) openssl configuration file subject -- (optional) dictionary with SSL subject variables cn -- (optional) cerfificate common name Required keys in subject dict: cn -- Common name (eq. FQDN) Optional keys in subject dict country -- Country Name (2 letter code) state -- State or Province Name (full name) locality -- Locality Name (eg, city) organization -- Organization Name (eg, company) organizational_unit -- Organizational Unit Name (eg, section) email -- Email Address """ cmd = [] if config: cmd = ["/usr/bin/openssl", "req", "-new", "-newkey", "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509", "-keyout", keyfile, "-out", certfile, "-config", config] elif subject: ssl_subject = "" if "country" in subject: ssl_subject = ssl_subject + "/C={}".format(subject["country"]) if "state" in subject: ssl_subject = ssl_subject + "/ST={}".format(subject["state"]) if "locality" in subject: ssl_subject = ssl_subject + "/L={}".format(subject["locality"]) if "organization" in subject: ssl_subject = ssl_subject + "/O={}".format(subject["organization"]) if "organizational_unit" in subject: ssl_subject = ssl_subject + "/OU={}".format(subject["organizational_unit"]) if "cn" in subject: ssl_subject = ssl_subject + "/CN={}".format(subject["cn"]) else: hookenv.log("When using \"subject\" argument you must " "provide \"cn\" field at very least") return False if "email" in subject: ssl_subject = ssl_subject + "/emailAddress={}".format(subject["email"]) cmd = ["/usr/bin/openssl", "req", "-new", "-newkey", "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509", "-keyout", keyfile, "-out", certfile, "-subj", ssl_subject] elif cn: cmd = ["/usr/bin/openssl", "req", "-new", "-newkey", "rsa:{}".format(keysize), "-days", "365", "-nodes", "-x509", "-keyout", keyfile, "-out", certfile, "-subj", "/CN={}".format(cn)] if not cmd: hookenv.log("No config, subject or cn provided," "unable to generate self signed SSL certificates") return False try: subprocess.check_call(cmd) return True except Exception as e: print("Execution of openssl command failed:\n{}".format(e)) return False
[ "def", "generate_selfsigned", "(", "keyfile", ",", "certfile", ",", "keysize", "=", "\"1024\"", ",", "config", "=", "None", ",", "subject", "=", "None", ",", "cn", "=", "None", ")", ":", "cmd", "=", "[", "]", "if", "config", ":", "cmd", "=", "[", "\"/usr/bin/openssl\"", ",", "\"req\"", ",", "\"-new\"", ",", "\"-newkey\"", ",", "\"rsa:{}\"", ".", "format", "(", "keysize", ")", ",", "\"-days\"", ",", "\"365\"", ",", "\"-nodes\"", ",", "\"-x509\"", ",", "\"-keyout\"", ",", "keyfile", ",", "\"-out\"", ",", "certfile", ",", "\"-config\"", ",", "config", "]", "elif", "subject", ":", "ssl_subject", "=", "\"\"", "if", "\"country\"", "in", "subject", ":", "ssl_subject", "=", "ssl_subject", "+", "\"/C={}\"", ".", "format", "(", "subject", "[", "\"country\"", "]", ")", "if", "\"state\"", "in", "subject", ":", "ssl_subject", "=", "ssl_subject", "+", "\"/ST={}\"", ".", "format", "(", "subject", "[", "\"state\"", "]", ")", "if", "\"locality\"", "in", "subject", ":", "ssl_subject", "=", "ssl_subject", "+", "\"/L={}\"", ".", "format", "(", "subject", "[", "\"locality\"", "]", ")", "if", "\"organization\"", "in", "subject", ":", "ssl_subject", "=", "ssl_subject", "+", "\"/O={}\"", ".", "format", "(", "subject", "[", "\"organization\"", "]", ")", "if", "\"organizational_unit\"", "in", "subject", ":", "ssl_subject", "=", "ssl_subject", "+", "\"/OU={}\"", ".", "format", "(", "subject", "[", "\"organizational_unit\"", "]", ")", "if", "\"cn\"", "in", "subject", ":", "ssl_subject", "=", "ssl_subject", "+", "\"/CN={}\"", ".", "format", "(", "subject", "[", "\"cn\"", "]", ")", "else", ":", "hookenv", ".", "log", "(", "\"When using \\\"subject\\\" argument you must \"", "\"provide \\\"cn\\\" field at very least\"", ")", "return", "False", "if", "\"email\"", "in", "subject", ":", "ssl_subject", "=", "ssl_subject", "+", "\"/emailAddress={}\"", ".", "format", "(", "subject", "[", "\"email\"", "]", ")", "cmd", "=", "[", "\"/usr/bin/openssl\"", ",", "\"req\"", ",", "\"-new\"", ",", "\"-newkey\"", ",", "\"rsa:{}\"", ".", "format", "(", "keysize", ")", ",", "\"-days\"", ",", "\"365\"", ",", "\"-nodes\"", ",", "\"-x509\"", ",", "\"-keyout\"", ",", "keyfile", ",", "\"-out\"", ",", "certfile", ",", "\"-subj\"", ",", "ssl_subject", "]", "elif", "cn", ":", "cmd", "=", "[", "\"/usr/bin/openssl\"", ",", "\"req\"", ",", "\"-new\"", ",", "\"-newkey\"", ",", "\"rsa:{}\"", ".", "format", "(", "keysize", ")", ",", "\"-days\"", ",", "\"365\"", ",", "\"-nodes\"", ",", "\"-x509\"", ",", "\"-keyout\"", ",", "keyfile", ",", "\"-out\"", ",", "certfile", ",", "\"-subj\"", ",", "\"/CN={}\"", ".", "format", "(", "cn", ")", "]", "if", "not", "cmd", ":", "hookenv", ".", "log", "(", "\"No config, subject or cn provided,\"", "\"unable to generate self signed SSL certificates\"", ")", "return", "False", "try", ":", "subprocess", ".", "check_call", "(", "cmd", ")", "return", "True", "except", "Exception", "as", "e", ":", "print", "(", "\"Execution of openssl command failed:\\n{}\"", ".", "format", "(", "e", ")", ")", "return", "False" ]
Generate selfsigned SSL keypair You must provide one of the 3 optional arguments: config, subject or cn If more than one is provided the leftmost will be used Arguments: keyfile -- (required) full path to the keyfile to be created certfile -- (required) full path to the certfile to be created keysize -- (optional) SSL key length config -- (optional) openssl configuration file subject -- (optional) dictionary with SSL subject variables cn -- (optional) cerfificate common name Required keys in subject dict: cn -- Common name (eq. FQDN) Optional keys in subject dict country -- Country Name (2 letter code) state -- State or Province Name (full name) locality -- Locality Name (eg, city) organization -- Organization Name (eg, company) organizational_unit -- Organizational Unit Name (eg, section) email -- Email Address
[ "Generate", "selfsigned", "SSL", "keypair" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ssl/__init__.py#L19-L92
12,686
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
ssh_directory_for_unit
def ssh_directory_for_unit(application_name, user=None): """Return the directory used to store ssh assets for the application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Fully qualified directory path. :rtype: str """ if user: application_name = "{}_{}".format(application_name, user) _dir = os.path.join(NOVA_SSH_DIR, application_name) for d in [NOVA_SSH_DIR, _dir]: if not os.path.isdir(d): os.mkdir(d) for f in ['authorized_keys', 'known_hosts']: f = os.path.join(_dir, f) if not os.path.isfile(f): open(f, 'w').close() return _dir
python
def ssh_directory_for_unit(application_name, user=None): """Return the directory used to store ssh assets for the application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Fully qualified directory path. :rtype: str """ if user: application_name = "{}_{}".format(application_name, user) _dir = os.path.join(NOVA_SSH_DIR, application_name) for d in [NOVA_SSH_DIR, _dir]: if not os.path.isdir(d): os.mkdir(d) for f in ['authorized_keys', 'known_hosts']: f = os.path.join(_dir, f) if not os.path.isfile(f): open(f, 'w').close() return _dir
[ "def", "ssh_directory_for_unit", "(", "application_name", ",", "user", "=", "None", ")", ":", "if", "user", ":", "application_name", "=", "\"{}_{}\"", ".", "format", "(", "application_name", ",", "user", ")", "_dir", "=", "os", ".", "path", ".", "join", "(", "NOVA_SSH_DIR", ",", "application_name", ")", "for", "d", "in", "[", "NOVA_SSH_DIR", ",", "_dir", "]", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "d", ")", ":", "os", ".", "mkdir", "(", "d", ")", "for", "f", "in", "[", "'authorized_keys'", ",", "'known_hosts'", "]", ":", "f", "=", "os", ".", "path", ".", "join", "(", "_dir", ",", "f", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "f", ")", ":", "open", "(", "f", ",", "'w'", ")", ".", "close", "(", ")", "return", "_dir" ]
Return the directory used to store ssh assets for the application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Fully qualified directory path. :rtype: str
[ "Return", "the", "directory", "used", "to", "store", "ssh", "assets", "for", "the", "application", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L36-L56
12,687
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
ssh_known_host_key
def ssh_known_host_key(host, application_name, user=None): """Return the first entry in known_hosts for host. :param host: hostname to lookup in file. :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Host key :rtype: str or None """ cmd = [ 'ssh-keygen', '-f', known_hosts(application_name, user), '-H', '-F', host] try: # The first line of output is like '# Host xx found: line 1 type RSA', # which should be excluded. output = subprocess.check_output(cmd) except subprocess.CalledProcessError as e: # RC of 1 seems to be legitimate for most ssh-keygen -F calls. if e.returncode == 1: output = e.output else: raise output = output.strip() if output: # Bug #1500589 cmd has 0 rc on precise if entry not present lines = output.split('\n') if len(lines) >= 1: return lines[0] return None
python
def ssh_known_host_key(host, application_name, user=None): """Return the first entry in known_hosts for host. :param host: hostname to lookup in file. :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Host key :rtype: str or None """ cmd = [ 'ssh-keygen', '-f', known_hosts(application_name, user), '-H', '-F', host] try: # The first line of output is like '# Host xx found: line 1 type RSA', # which should be excluded. output = subprocess.check_output(cmd) except subprocess.CalledProcessError as e: # RC of 1 seems to be legitimate for most ssh-keygen -F calls. if e.returncode == 1: output = e.output else: raise output = output.strip() if output: # Bug #1500589 cmd has 0 rc on precise if entry not present lines = output.split('\n') if len(lines) >= 1: return lines[0] return None
[ "def", "ssh_known_host_key", "(", "host", ",", "application_name", ",", "user", "=", "None", ")", ":", "cmd", "=", "[", "'ssh-keygen'", ",", "'-f'", ",", "known_hosts", "(", "application_name", ",", "user", ")", ",", "'-H'", ",", "'-F'", ",", "host", "]", "try", ":", "# The first line of output is like '# Host xx found: line 1 type RSA',", "# which should be excluded.", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "# RC of 1 seems to be legitimate for most ssh-keygen -F calls.", "if", "e", ".", "returncode", "==", "1", ":", "output", "=", "e", ".", "output", "else", ":", "raise", "output", "=", "output", ".", "strip", "(", ")", "if", "output", ":", "# Bug #1500589 cmd has 0 rc on precise if entry not present", "lines", "=", "output", ".", "split", "(", "'\\n'", ")", "if", "len", "(", "lines", ")", ">=", "1", ":", "return", "lines", "[", "0", "]", "return", "None" ]
Return the first entry in known_hosts for host. :param host: hostname to lookup in file. :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Host key :rtype: str or None
[ "Return", "the", "first", "entry", "in", "known_hosts", "for", "host", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L89-L125
12,688
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
remove_known_host
def remove_known_host(host, application_name, user=None): """Remove the entry in known_hosts for host. :param host: hostname to lookup in file. :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ log('Removing SSH known host entry for compute host at %s' % host) cmd = ['ssh-keygen', '-f', known_hosts(application_name, user), '-R', host] subprocess.check_call(cmd)
python
def remove_known_host(host, application_name, user=None): """Remove the entry in known_hosts for host. :param host: hostname to lookup in file. :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ log('Removing SSH known host entry for compute host at %s' % host) cmd = ['ssh-keygen', '-f', known_hosts(application_name, user), '-R', host] subprocess.check_call(cmd)
[ "def", "remove_known_host", "(", "host", ",", "application_name", ",", "user", "=", "None", ")", ":", "log", "(", "'Removing SSH known host entry for compute host at %s'", "%", "host", ")", "cmd", "=", "[", "'ssh-keygen'", ",", "'-f'", ",", "known_hosts", "(", "application_name", ",", "user", ")", ",", "'-R'", ",", "host", "]", "subprocess", ".", "check_call", "(", "cmd", ")" ]
Remove the entry in known_hosts for host. :param host: hostname to lookup in file. :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str
[ "Remove", "the", "entry", "in", "known_hosts", "for", "host", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L128-L140
12,689
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
is_same_key
def is_same_key(key_1, key_2): """Extract the key from two host entries and compare them. :param key_1: Host key :type key_1: str :param key_2: Host key :type key_2: str """ # The key format get will be like '|1|2rUumCavEXWVaVyB5uMl6m85pZo=|Cp' # 'EL6l7VTY37T/fg/ihhNb/GPgs= ssh-rsa AAAAB', we only need to compare # the part start with 'ssh-rsa' followed with '= ', because the hash # value in the beginning will change each time. k_1 = key_1.split('= ')[1] k_2 = key_2.split('= ')[1] return k_1 == k_2
python
def is_same_key(key_1, key_2): """Extract the key from two host entries and compare them. :param key_1: Host key :type key_1: str :param key_2: Host key :type key_2: str """ # The key format get will be like '|1|2rUumCavEXWVaVyB5uMl6m85pZo=|Cp' # 'EL6l7VTY37T/fg/ihhNb/GPgs= ssh-rsa AAAAB', we only need to compare # the part start with 'ssh-rsa' followed with '= ', because the hash # value in the beginning will change each time. k_1 = key_1.split('= ')[1] k_2 = key_2.split('= ')[1] return k_1 == k_2
[ "def", "is_same_key", "(", "key_1", ",", "key_2", ")", ":", "# The key format get will be like '|1|2rUumCavEXWVaVyB5uMl6m85pZo=|Cp'", "# 'EL6l7VTY37T/fg/ihhNb/GPgs= ssh-rsa AAAAB', we only need to compare", "# the part start with 'ssh-rsa' followed with '= ', because the hash", "# value in the beginning will change each time.", "k_1", "=", "key_1", ".", "split", "(", "'= '", ")", "[", "1", "]", "k_2", "=", "key_2", ".", "split", "(", "'= '", ")", "[", "1", "]", "return", "k_1", "==", "k_2" ]
Extract the key from two host entries and compare them. :param key_1: Host key :type key_1: str :param key_2: Host key :type key_2: str
[ "Extract", "the", "key", "from", "two", "host", "entries", "and", "compare", "them", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L143-L157
12,690
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
add_known_host
def add_known_host(host, application_name, user=None): """Add the given host key to the known hosts file. :param host: host name :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ cmd = ['ssh-keyscan', '-H', '-t', 'rsa', host] try: remote_key = subprocess.check_output(cmd).strip() except Exception as e: log('Could not obtain SSH host key from %s' % host, level=ERROR) raise e current_key = ssh_known_host_key(host, application_name, user) if current_key and remote_key: if is_same_key(remote_key, current_key): log('Known host key for compute host %s up to date.' % host) return else: remove_known_host(host, application_name, user) log('Adding SSH host key to known hosts for compute node at %s.' % host) with open(known_hosts(application_name, user), 'a') as out: out.write("{}\n".format(remote_key))
python
def add_known_host(host, application_name, user=None): """Add the given host key to the known hosts file. :param host: host name :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ cmd = ['ssh-keyscan', '-H', '-t', 'rsa', host] try: remote_key = subprocess.check_output(cmd).strip() except Exception as e: log('Could not obtain SSH host key from %s' % host, level=ERROR) raise e current_key = ssh_known_host_key(host, application_name, user) if current_key and remote_key: if is_same_key(remote_key, current_key): log('Known host key for compute host %s up to date.' % host) return else: remove_known_host(host, application_name, user) log('Adding SSH host key to known hosts for compute node at %s.' % host) with open(known_hosts(application_name, user), 'a') as out: out.write("{}\n".format(remote_key))
[ "def", "add_known_host", "(", "host", ",", "application_name", ",", "user", "=", "None", ")", ":", "cmd", "=", "[", "'ssh-keyscan'", ",", "'-H'", ",", "'-t'", ",", "'rsa'", ",", "host", "]", "try", ":", "remote_key", "=", "subprocess", ".", "check_output", "(", "cmd", ")", ".", "strip", "(", ")", "except", "Exception", "as", "e", ":", "log", "(", "'Could not obtain SSH host key from %s'", "%", "host", ",", "level", "=", "ERROR", ")", "raise", "e", "current_key", "=", "ssh_known_host_key", "(", "host", ",", "application_name", ",", "user", ")", "if", "current_key", "and", "remote_key", ":", "if", "is_same_key", "(", "remote_key", ",", "current_key", ")", ":", "log", "(", "'Known host key for compute host %s up to date.'", "%", "host", ")", "return", "else", ":", "remove_known_host", "(", "host", ",", "application_name", ",", "user", ")", "log", "(", "'Adding SSH host key to known hosts for compute node at %s.'", "%", "host", ")", "with", "open", "(", "known_hosts", "(", "application_name", ",", "user", ")", ",", "'a'", ")", "as", "out", ":", "out", ".", "write", "(", "\"{}\\n\"", ".", "format", "(", "remote_key", ")", ")" ]
Add the given host key to the known hosts file. :param host: host name :type host: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str
[ "Add", "the", "given", "host", "key", "to", "the", "known", "hosts", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L160-L187
12,691
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
ssh_authorized_key_exists
def ssh_authorized_key_exists(public_key, application_name, user=None): """Check if given key is in the authorized_key file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Whether given key is in the authorized_key file. :rtype: boolean """ with open(authorized_keys(application_name, user)) as keys: return ('%s' % public_key) in keys.read()
python
def ssh_authorized_key_exists(public_key, application_name, user=None): """Check if given key is in the authorized_key file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Whether given key is in the authorized_key file. :rtype: boolean """ with open(authorized_keys(application_name, user)) as keys: return ('%s' % public_key) in keys.read()
[ "def", "ssh_authorized_key_exists", "(", "public_key", ",", "application_name", ",", "user", "=", "None", ")", ":", "with", "open", "(", "authorized_keys", "(", "application_name", ",", "user", ")", ")", "as", "keys", ":", "return", "(", "'%s'", "%", "public_key", ")", "in", "keys", ".", "read", "(", ")" ]
Check if given key is in the authorized_key file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Whether given key is in the authorized_key file. :rtype: boolean
[ "Check", "if", "given", "key", "is", "in", "the", "authorized_key", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L190-L203
12,692
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
add_authorized_key
def add_authorized_key(public_key, application_name, user=None): """Add given key to the authorized_key file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ with open(authorized_keys(application_name, user), 'a') as keys: keys.write("{}\n".format(public_key))
python
def add_authorized_key(public_key, application_name, user=None): """Add given key to the authorized_key file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ with open(authorized_keys(application_name, user), 'a') as keys: keys.write("{}\n".format(public_key))
[ "def", "add_authorized_key", "(", "public_key", ",", "application_name", ",", "user", "=", "None", ")", ":", "with", "open", "(", "authorized_keys", "(", "application_name", ",", "user", ")", ",", "'a'", ")", "as", "keys", ":", "keys", ".", "write", "(", "\"{}\\n\"", ".", "format", "(", "public_key", ")", ")" ]
Add given key to the authorized_key file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str
[ "Add", "given", "key", "to", "the", "authorized_key", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L206-L217
12,693
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
ssh_known_hosts_lines
def ssh_known_hosts_lines(application_name, user=None): """Return contents of known_hosts file for given application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ known_hosts_list = [] with open(known_hosts(application_name, user)) as hosts: for hosts_line in hosts: if hosts_line.rstrip(): known_hosts_list.append(hosts_line.rstrip()) return(known_hosts_list)
python
def ssh_known_hosts_lines(application_name, user=None): """Return contents of known_hosts file for given application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ known_hosts_list = [] with open(known_hosts(application_name, user)) as hosts: for hosts_line in hosts: if hosts_line.rstrip(): known_hosts_list.append(hosts_line.rstrip()) return(known_hosts_list)
[ "def", "ssh_known_hosts_lines", "(", "application_name", ",", "user", "=", "None", ")", ":", "known_hosts_list", "=", "[", "]", "with", "open", "(", "known_hosts", "(", "application_name", ",", "user", ")", ")", "as", "hosts", ":", "for", "hosts_line", "in", "hosts", ":", "if", "hosts_line", ".", "rstrip", "(", ")", ":", "known_hosts_list", ".", "append", "(", "hosts_line", ".", "rstrip", "(", ")", ")", "return", "(", "known_hosts_list", ")" ]
Return contents of known_hosts file for given application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str
[ "Return", "contents", "of", "known_hosts", "file", "for", "given", "application", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L300-L313
12,694
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
ssh_authorized_keys_lines
def ssh_authorized_keys_lines(application_name, user=None): """Return contents of authorized_keys file for given application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ authorized_keys_list = [] with open(authorized_keys(application_name, user)) as keys: for authkey_line in keys: if authkey_line.rstrip(): authorized_keys_list.append(authkey_line.rstrip()) return(authorized_keys_list)
python
def ssh_authorized_keys_lines(application_name, user=None): """Return contents of authorized_keys file for given application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ authorized_keys_list = [] with open(authorized_keys(application_name, user)) as keys: for authkey_line in keys: if authkey_line.rstrip(): authorized_keys_list.append(authkey_line.rstrip()) return(authorized_keys_list)
[ "def", "ssh_authorized_keys_lines", "(", "application_name", ",", "user", "=", "None", ")", ":", "authorized_keys_list", "=", "[", "]", "with", "open", "(", "authorized_keys", "(", "application_name", ",", "user", ")", ")", "as", "keys", ":", "for", "authkey_line", "in", "keys", ":", "if", "authkey_line", ".", "rstrip", "(", ")", ":", "authorized_keys_list", ".", "append", "(", "authkey_line", ".", "rstrip", "(", ")", ")", "return", "(", "authorized_keys_list", ")" ]
Return contents of authorized_keys file for given application. :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str
[ "Return", "contents", "of", "authorized_keys", "file", "for", "given", "application", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L316-L330
12,695
juju/charm-helpers
charmhelpers/contrib/openstack/ssh_migrations.py
ssh_compute_remove
def ssh_compute_remove(public_key, application_name, user=None): """Remove given public key from authorized_keys file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ if not (os.path.isfile(authorized_keys(application_name, user)) or os.path.isfile(known_hosts(application_name, user))): return keys = ssh_authorized_keys_lines(application_name, user=None) keys = [k.strip() for k in keys] if public_key not in keys: return [keys.remove(key) for key in keys if key == public_key] with open(authorized_keys(application_name, user), 'w') as _keys: keys = '\n'.join(keys) if not keys.endswith('\n'): keys += '\n' _keys.write(keys)
python
def ssh_compute_remove(public_key, application_name, user=None): """Remove given public key from authorized_keys file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str """ if not (os.path.isfile(authorized_keys(application_name, user)) or os.path.isfile(known_hosts(application_name, user))): return keys = ssh_authorized_keys_lines(application_name, user=None) keys = [k.strip() for k in keys] if public_key not in keys: return [keys.remove(key) for key in keys if key == public_key] with open(authorized_keys(application_name, user), 'w') as _keys: keys = '\n'.join(keys) if not keys.endswith('\n'): keys += '\n' _keys.write(keys)
[ "def", "ssh_compute_remove", "(", "public_key", ",", "application_name", ",", "user", "=", "None", ")", ":", "if", "not", "(", "os", ".", "path", ".", "isfile", "(", "authorized_keys", "(", "application_name", ",", "user", ")", ")", "or", "os", ".", "path", ".", "isfile", "(", "known_hosts", "(", "application_name", ",", "user", ")", ")", ")", ":", "return", "keys", "=", "ssh_authorized_keys_lines", "(", "application_name", ",", "user", "=", "None", ")", "keys", "=", "[", "k", ".", "strip", "(", ")", "for", "k", "in", "keys", "]", "if", "public_key", "not", "in", "keys", ":", "return", "[", "keys", ".", "remove", "(", "key", ")", "for", "key", "in", "keys", "if", "key", "==", "public_key", "]", "with", "open", "(", "authorized_keys", "(", "application_name", ",", "user", ")", ",", "'w'", ")", "as", "_keys", ":", "keys", "=", "'\\n'", ".", "join", "(", "keys", ")", "if", "not", "keys", ".", "endswith", "(", "'\\n'", ")", ":", "keys", "+=", "'\\n'", "_keys", ".", "write", "(", "keys", ")" ]
Remove given public key from authorized_keys file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str
[ "Remove", "given", "public", "key", "from", "authorized_keys", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ssh_migrations.py#L333-L359
12,696
juju/charm-helpers
charmhelpers/fetch/ubuntu.py
apt_cache
def apt_cache(in_memory=True, progress=None): """Build and return an apt cache.""" from apt import apt_pkg apt_pkg.init() if in_memory: apt_pkg.config.set("Dir::Cache::pkgcache", "") apt_pkg.config.set("Dir::Cache::srcpkgcache", "") return apt_pkg.Cache(progress)
python
def apt_cache(in_memory=True, progress=None): """Build and return an apt cache.""" from apt import apt_pkg apt_pkg.init() if in_memory: apt_pkg.config.set("Dir::Cache::pkgcache", "") apt_pkg.config.set("Dir::Cache::srcpkgcache", "") return apt_pkg.Cache(progress)
[ "def", "apt_cache", "(", "in_memory", "=", "True", ",", "progress", "=", "None", ")", ":", "from", "apt", "import", "apt_pkg", "apt_pkg", ".", "init", "(", ")", "if", "in_memory", ":", "apt_pkg", ".", "config", ".", "set", "(", "\"Dir::Cache::pkgcache\"", ",", "\"\"", ")", "apt_pkg", ".", "config", ".", "set", "(", "\"Dir::Cache::srcpkgcache\"", ",", "\"\"", ")", "return", "apt_pkg", ".", "Cache", "(", "progress", ")" ]
Build and return an apt cache.
[ "Build", "and", "return", "an", "apt", "cache", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L211-L218
12,697
juju/charm-helpers
charmhelpers/fetch/ubuntu.py
apt_mark
def apt_mark(packages, mark, fatal=False): """Flag one or more packages using apt-mark.""" log("Marking {} as {}".format(packages, mark)) cmd = ['apt-mark', mark] if isinstance(packages, six.string_types): cmd.append(packages) else: cmd.extend(packages) if fatal: subprocess.check_call(cmd, universal_newlines=True) else: subprocess.call(cmd, universal_newlines=True)
python
def apt_mark(packages, mark, fatal=False): """Flag one or more packages using apt-mark.""" log("Marking {} as {}".format(packages, mark)) cmd = ['apt-mark', mark] if isinstance(packages, six.string_types): cmd.append(packages) else: cmd.extend(packages) if fatal: subprocess.check_call(cmd, universal_newlines=True) else: subprocess.call(cmd, universal_newlines=True)
[ "def", "apt_mark", "(", "packages", ",", "mark", ",", "fatal", "=", "False", ")", ":", "log", "(", "\"Marking {} as {}\"", ".", "format", "(", "packages", ",", "mark", ")", ")", "cmd", "=", "[", "'apt-mark'", ",", "mark", "]", "if", "isinstance", "(", "packages", ",", "six", ".", "string_types", ")", ":", "cmd", ".", "append", "(", "packages", ")", "else", ":", "cmd", ".", "extend", "(", "packages", ")", "if", "fatal", ":", "subprocess", ".", "check_call", "(", "cmd", ",", "universal_newlines", "=", "True", ")", "else", ":", "subprocess", ".", "call", "(", "cmd", ",", "universal_newlines", "=", "True", ")" ]
Flag one or more packages using apt-mark.
[ "Flag", "one", "or", "more", "packages", "using", "apt", "-", "mark", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L278-L290
12,698
juju/charm-helpers
charmhelpers/fetch/ubuntu.py
import_key
def import_key(key): """Import an ASCII Armor key. A Radix64 format keyid is also supported for backwards compatibility. In this case Ubuntu keyserver will be queried for a key via HTTPS by its keyid. This method is less preferrable because https proxy servers may require traffic decryption which is equivalent to a man-in-the-middle attack (a proxy server impersonates keyserver TLS certificates and has to be explicitly trusted by the system). :param key: A GPG key in ASCII armor format, including BEGIN and END markers or a keyid. :type key: (bytes, str) :raises: GPGKeyError if the key could not be imported """ key = key.strip() if '-' in key or '\n' in key: # Send everything not obviously a keyid to GPG to import, as # we trust its validation better than our own. eg. handling # comments before the key. log("PGP key found (looks like ASCII Armor format)", level=DEBUG) if ('-----BEGIN PGP PUBLIC KEY BLOCK-----' in key and '-----END PGP PUBLIC KEY BLOCK-----' in key): log("Writing provided PGP key in the binary format", level=DEBUG) if six.PY3: key_bytes = key.encode('utf-8') else: key_bytes = key key_name = _get_keyid_by_gpg_key(key_bytes) key_gpg = _dearmor_gpg_key(key_bytes) _write_apt_gpg_keyfile(key_name=key_name, key_material=key_gpg) else: raise GPGKeyError("ASCII armor markers missing from GPG key") else: log("PGP key found (looks like Radix64 format)", level=WARNING) log("SECURELY importing PGP key from keyserver; " "full key not provided.", level=WARNING) # as of bionic add-apt-repository uses curl with an HTTPS keyserver URL # to retrieve GPG keys. `apt-key adv` command is deprecated as is # apt-key in general as noted in its manpage. See lp:1433761 for more # history. Instead, /etc/apt/trusted.gpg.d is used directly to drop # gpg key_asc = _get_key_by_keyid(key) # write the key in GPG format so that apt-key list shows it key_gpg = _dearmor_gpg_key(key_asc) _write_apt_gpg_keyfile(key_name=key, key_material=key_gpg)
python
def import_key(key): """Import an ASCII Armor key. A Radix64 format keyid is also supported for backwards compatibility. In this case Ubuntu keyserver will be queried for a key via HTTPS by its keyid. This method is less preferrable because https proxy servers may require traffic decryption which is equivalent to a man-in-the-middle attack (a proxy server impersonates keyserver TLS certificates and has to be explicitly trusted by the system). :param key: A GPG key in ASCII armor format, including BEGIN and END markers or a keyid. :type key: (bytes, str) :raises: GPGKeyError if the key could not be imported """ key = key.strip() if '-' in key or '\n' in key: # Send everything not obviously a keyid to GPG to import, as # we trust its validation better than our own. eg. handling # comments before the key. log("PGP key found (looks like ASCII Armor format)", level=DEBUG) if ('-----BEGIN PGP PUBLIC KEY BLOCK-----' in key and '-----END PGP PUBLIC KEY BLOCK-----' in key): log("Writing provided PGP key in the binary format", level=DEBUG) if six.PY3: key_bytes = key.encode('utf-8') else: key_bytes = key key_name = _get_keyid_by_gpg_key(key_bytes) key_gpg = _dearmor_gpg_key(key_bytes) _write_apt_gpg_keyfile(key_name=key_name, key_material=key_gpg) else: raise GPGKeyError("ASCII armor markers missing from GPG key") else: log("PGP key found (looks like Radix64 format)", level=WARNING) log("SECURELY importing PGP key from keyserver; " "full key not provided.", level=WARNING) # as of bionic add-apt-repository uses curl with an HTTPS keyserver URL # to retrieve GPG keys. `apt-key adv` command is deprecated as is # apt-key in general as noted in its manpage. See lp:1433761 for more # history. Instead, /etc/apt/trusted.gpg.d is used directly to drop # gpg key_asc = _get_key_by_keyid(key) # write the key in GPG format so that apt-key list shows it key_gpg = _dearmor_gpg_key(key_asc) _write_apt_gpg_keyfile(key_name=key, key_material=key_gpg)
[ "def", "import_key", "(", "key", ")", ":", "key", "=", "key", ".", "strip", "(", ")", "if", "'-'", "in", "key", "or", "'\\n'", "in", "key", ":", "# Send everything not obviously a keyid to GPG to import, as", "# we trust its validation better than our own. eg. handling", "# comments before the key.", "log", "(", "\"PGP key found (looks like ASCII Armor format)\"", ",", "level", "=", "DEBUG", ")", "if", "(", "'-----BEGIN PGP PUBLIC KEY BLOCK-----'", "in", "key", "and", "'-----END PGP PUBLIC KEY BLOCK-----'", "in", "key", ")", ":", "log", "(", "\"Writing provided PGP key in the binary format\"", ",", "level", "=", "DEBUG", ")", "if", "six", ".", "PY3", ":", "key_bytes", "=", "key", ".", "encode", "(", "'utf-8'", ")", "else", ":", "key_bytes", "=", "key", "key_name", "=", "_get_keyid_by_gpg_key", "(", "key_bytes", ")", "key_gpg", "=", "_dearmor_gpg_key", "(", "key_bytes", ")", "_write_apt_gpg_keyfile", "(", "key_name", "=", "key_name", ",", "key_material", "=", "key_gpg", ")", "else", ":", "raise", "GPGKeyError", "(", "\"ASCII armor markers missing from GPG key\"", ")", "else", ":", "log", "(", "\"PGP key found (looks like Radix64 format)\"", ",", "level", "=", "WARNING", ")", "log", "(", "\"SECURELY importing PGP key from keyserver; \"", "\"full key not provided.\"", ",", "level", "=", "WARNING", ")", "# as of bionic add-apt-repository uses curl with an HTTPS keyserver URL", "# to retrieve GPG keys. `apt-key adv` command is deprecated as is", "# apt-key in general as noted in its manpage. See lp:1433761 for more", "# history. Instead, /etc/apt/trusted.gpg.d is used directly to drop", "# gpg", "key_asc", "=", "_get_key_by_keyid", "(", "key", ")", "# write the key in GPG format so that apt-key list shows it", "key_gpg", "=", "_dearmor_gpg_key", "(", "key_asc", ")", "_write_apt_gpg_keyfile", "(", "key_name", "=", "key", ",", "key_material", "=", "key_gpg", ")" ]
Import an ASCII Armor key. A Radix64 format keyid is also supported for backwards compatibility. In this case Ubuntu keyserver will be queried for a key via HTTPS by its keyid. This method is less preferrable because https proxy servers may require traffic decryption which is equivalent to a man-in-the-middle attack (a proxy server impersonates keyserver TLS certificates and has to be explicitly trusted by the system). :param key: A GPG key in ASCII armor format, including BEGIN and END markers or a keyid. :type key: (bytes, str) :raises: GPGKeyError if the key could not be imported
[ "Import", "an", "ASCII", "Armor", "key", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L301-L348
12,699
juju/charm-helpers
charmhelpers/fetch/ubuntu.py
_dearmor_gpg_key
def _dearmor_gpg_key(key_asc): """Converts a GPG key in the ASCII armor format to the binary format. :param key_asc: A GPG key in ASCII armor format. :type key_asc: (str, bytes) :returns: A GPG key in binary format :rtype: (str, bytes) :raises: GPGKeyError """ ps = subprocess.Popen(['gpg', '--dearmor'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) out, err = ps.communicate(input=key_asc) # no need to decode output as it is binary (invalid utf-8), only error if six.PY3: err = err.decode('utf-8') if 'gpg: no valid OpenPGP data found.' in err: raise GPGKeyError('Invalid GPG key material. Check your network setup' ' (MTU, routing, DNS) and/or proxy server settings' ' as well as destination keyserver status.') else: return out
python
def _dearmor_gpg_key(key_asc): """Converts a GPG key in the ASCII armor format to the binary format. :param key_asc: A GPG key in ASCII armor format. :type key_asc: (str, bytes) :returns: A GPG key in binary format :rtype: (str, bytes) :raises: GPGKeyError """ ps = subprocess.Popen(['gpg', '--dearmor'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) out, err = ps.communicate(input=key_asc) # no need to decode output as it is binary (invalid utf-8), only error if six.PY3: err = err.decode('utf-8') if 'gpg: no valid OpenPGP data found.' in err: raise GPGKeyError('Invalid GPG key material. Check your network setup' ' (MTU, routing, DNS) and/or proxy server settings' ' as well as destination keyserver status.') else: return out
[ "def", "_dearmor_gpg_key", "(", "key_asc", ")", ":", "ps", "=", "subprocess", ".", "Popen", "(", "[", "'gpg'", ",", "'--dearmor'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "ps", ".", "communicate", "(", "input", "=", "key_asc", ")", "# no need to decode output as it is binary (invalid utf-8), only error", "if", "six", ".", "PY3", ":", "err", "=", "err", ".", "decode", "(", "'utf-8'", ")", "if", "'gpg: no valid OpenPGP data found.'", "in", "err", ":", "raise", "GPGKeyError", "(", "'Invalid GPG key material. Check your network setup'", "' (MTU, routing, DNS) and/or proxy server settings'", "' as well as destination keyserver status.'", ")", "else", ":", "return", "out" ]
Converts a GPG key in the ASCII armor format to the binary format. :param key_asc: A GPG key in ASCII armor format. :type key_asc: (str, bytes) :returns: A GPG key in binary format :rtype: (str, bytes) :raises: GPGKeyError
[ "Converts", "a", "GPG", "key", "in", "the", "ASCII", "armor", "format", "to", "the", "binary", "format", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L415-L437