desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Find the specified result by name'
@staticmethod def find_result(results, _name):
rval = None for result in results: if (('metadata' in result) and (result['metadata']['name'] == _name)): rval = result break return rval
'return the service file'
@staticmethod def get_resource_file(sfile, sfile_type='yaml'):
contents = None with open(sfile) as sfd: contents = sfd.read() if (sfile_type == 'yaml'): if hasattr(yaml, 'RoundTripLoader'): contents = yaml.load(contents, yaml.RoundTripLoader) else: contents = yaml.safe_load(contents) elif (sfile_type == 'json'): ...
'filter the oc version output'
@staticmethod def filter_versions(stdout):
version_dict = {} version_search = ['oc', 'openshift', 'kubernetes'] for line in stdout.strip().split('\n'): for term in version_search: if (not line): continue if line.startswith(term): version_dict[term] = line.split()[(-1)] if ('openshif...
'create custom versions strings'
@staticmethod def add_custom_versions(versions):
versions_dict = {} for (tech, version) in versions.items(): if ('-' in version): version = version.split('-')[0] if version.startswith('v'): versions_dict[(tech + '_numeric')] = version[1:].split('+')[0] versions_dict[(tech + '_short')] = version[1:4] retu...
'check if openshift is installed'
@staticmethod def openshift_installed():
import yum yum_base = yum.YumBase() if yum_base.rpmdb.searchNevra(name='atomic-openshift'): return True return False
'Given a user defined definition, compare it with the results given back by our query.'
@staticmethod def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
skip = ['metadata', 'status'] if skip_keys: skip.extend(skip_keys) for (key, value) in result_def.items(): if (key in skip): continue if isinstance(value, list): if (key not in user_def): if debug: print(('User data do...
'return config options'
@property def config_options(self):
return self._options
'return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs'
def to_option_list(self, ascommalist=''):
return self.stringify(ascommalist)
'return the options hash as cli params in a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs'
def stringify(self, ascommalist=''):
rval = [] for key in sorted(self.config_options.keys()): data = self.config_options[key] if (data['include'] and (data['value'] or isinstance(data['value'], int))): if (key == ascommalist): val = ','.join(['{}={}'.format(kk, vv) for (kk, vv) in sorted(data['value'].it...
'constructor for handling rolebinding options'
def __init__(self, name, namespace, kubeconfig, group_names=None, role_ref=None, subjects=None, usernames=None):
self.kubeconfig = kubeconfig self.name = name self.namespace = namespace self.group_names = group_names self.role_ref = role_ref self.subjects = subjects self.usernames = usernames self.data = {} self.create_dict()
'create a default rolebinding as a dict'
def create_dict(self):
self.data['apiVersion'] = 'v1' self.data['kind'] = 'RoleBinding' self.data['groupNames'] = self.group_names self.data['metadata']['name'] = self.name self.data['metadata']['namespace'] = self.namespace self.data['roleRef'] = self.role_ref self.data['subjects'] = self.subjects self.data['...
'RoleBinding constructor'
def __init__(self, content):
super(RoleBinding, self).__init__(content=content) self._subjects = None self._role_ref = None self._group_names = None self._user_names = None
'subjects property'
@property def subjects(self):
if (self._subjects is None): self._subjects = self.get_subjects() return self._subjects
'subjects property setter'
@subjects.setter def subjects(self, data):
self._subjects = data
'role_ref property'
@property def role_ref(self):
if (self._role_ref is None): self._role_ref = self.get_role_ref() return self._role_ref
'role_ref property setter'
@role_ref.setter def role_ref(self, data):
self._role_ref = data
'group_names property'
@property def group_names(self):
if (self._group_names is None): self._group_names = self.get_group_names() return self._group_names
'group_names property setter'
@group_names.setter def group_names(self, data):
self._group_names = data
'user_names property'
@property def user_names(self):
if (self._user_names is None): self._user_names = self.get_user_names() return self._user_names
'user_names property setter'
@user_names.setter def user_names(self, data):
self._user_names = data
'return groupNames'
def get_group_names(self):
return (self.get(RoleBinding.group_names_path) or [])
'return usernames'
def get_user_names(self):
return (self.get(RoleBinding.user_names_path) or [])
'return role_ref'
def get_role_ref(self):
return (self.get(RoleBinding.role_ref_path) or {})
'return subjects'
def get_subjects(self):
return (self.get(RoleBinding.subjects_path) or [])
'add a subject'
def add_subject(self, inc_subject):
if self.subjects: self.subjects.append(inc_subject) else: self.put(RoleBinding.subjects_path, [inc_subject]) return True
'add a role_ref'
def add_role_ref(self, inc_role_ref):
if (not self.role_ref): self.put(RoleBinding.role_ref_path, {'name': inc_role_ref}) return True return False
'add a group_names'
def add_group_names(self, inc_group_names):
if self.group_names: self.group_names.append(inc_group_names) else: self.put(RoleBinding.group_names_path, [inc_group_names]) return True
'add a username'
def add_user_name(self, inc_user_name):
if self.user_names: self.user_names.append(inc_user_name) else: self.put(RoleBinding.user_names_path, [inc_user_name]) return True
'remove a subject'
def remove_subject(self, inc_subject):
try: self.subjects.remove(inc_subject) except ValueError as _: return False return True
'remove a role_ref'
def remove_role_ref(self, inc_role_ref):
if (self.role_ref and (self.role_ref['name'] == inc_role_ref)): del self.role_ref['name'] return True return False
'remove a groupname'
def remove_group_name(self, inc_group_name):
try: self.group_names.remove(inc_group_name) except ValueError as _: return False return True
'remove a username'
def remove_user_name(self, inc_user_name):
try: self.user_names.remove(inc_user_name) except ValueError as _: return False return True
'update a subject'
def update_subject(self, inc_subject):
try: index = self.subjects.index(inc_subject) except ValueError as _: return self.add_subject(inc_subject) self.subjects[index] = inc_subject return True
'update a groupname'
def update_group_name(self, inc_group_name):
try: index = self.group_names.index(inc_group_name) except ValueError as _: return self.add_group_names(inc_group_name) self.group_names[index] = inc_group_name return True
'update a username'
def update_user_name(self, inc_user_name):
try: index = self.user_names.index(inc_user_name) except ValueError as _: return self.add_user_name(inc_user_name) self.user_names[index] = inc_user_name return True
'update a role_ref'
def update_role_ref(self, inc_role_ref):
self.role_ref['name'] = inc_role_ref return True
'find a subject'
def find_subject(self, inc_subject):
index = None try: index = self.subjects.index(inc_subject) except ValueError as _: return index return index
'find a group_name'
def find_group_name(self, inc_group_name):
index = None try: index = self.group_names.index(inc_group_name) except ValueError as _: return index return index
'find a user_name'
def find_user_name(self, inc_user_name):
index = None try: index = self.user_names.index(inc_user_name) except ValueError as _: return index return index
'find a user_name'
def find_role_ref(self, inc_role_ref):
if (self.role_ref and (self.role_ref['name'] == inc_role_ref['name'])): return self.role_ref return None
'constructor for handling scc options'
def __init__(self, sname, kubeconfig, options=None, fs_group='MustRunAs', default_add_capabilities=None, groups=None, priority=None, required_drop_capabilities=None, run_as_user='MustRunAsRange', se_linux_context='MustRunAs', supplemental_groups='RunAsAny', users=None, annotations=None):
self.kubeconfig = kubeconfig self.name = sname self.options = options self.fs_group = fs_group self.default_add_capabilities = default_add_capabilities self.groups = groups self.priority = priority self.required_drop_capabilities = required_drop_capabilities self.run_as_user = run_as...
'assign the correct properties for a scc dict'
def create_dict(self):
if self.options: for (key, value) in self.options.items(): self.data[key] = value else: self.data['allowHostDirVolumePlugin'] = False self.data['allowHostIPC'] = False self.data['allowHostNetwork'] = False self.data['allowHostPID'] = False self.data['a...
'SecurityContextConstraints constructor'
def __init__(self, content):
super(SecurityContextConstraints, self).__init__(content=content) self._users = None self._groups = None
'users property getter'
@property def users(self):
if (self._users is None): self._users = self.get_users() return self._users
'groups property getter'
@property def groups(self):
if (self._groups is None): self._groups = self.get_groups() return self._groups
'users property setter'
@users.setter def users(self, data):
self._users = data
'groups property setter'
@groups.setter def groups(self, data):
self._groups = data
'get scc users'
def get_users(self):
return (self.get(SecurityContextConstraints.users_path) or [])
'get scc groups'
def get_groups(self):
return (self.get(SecurityContextConstraints.groups_path) or [])
'add a user'
def add_user(self, inc_user):
if self.users: self.users.append(inc_user) else: self.put(SecurityContextConstraints.users_path, [inc_user]) return True
'add a group'
def add_group(self, inc_group):
if self.groups: self.groups.append(inc_group) else: self.put(SecurityContextConstraints.groups_path, [inc_group]) return True
'remove a user'
def remove_user(self, inc_user):
try: self.users.remove(inc_user) except ValueError as _: return False return True
'remove a group'
def remove_group(self, inc_group):
try: self.groups.remove(inc_group) except ValueError as _: return False return True
'update a user'
def update_user(self, inc_user):
try: index = self.users.index(inc_user) except ValueError as _: return self.add_user(inc_user) self.users[index] = inc_user return True
'update a group'
def update_group(self, inc_group):
try: index = self.groups.index(inc_group) except ValueError as _: return self.add_group(inc_group) self.groups[index] = inc_group return True
'find a user'
def find_user(self, inc_user):
index = None try: index = self.users.index(inc_user) except ValueError as _: return index return index
'find a group'
def find_group(self, inc_group):
index = None try: index = self.groups.index(inc_group) except ValueError as _: return index return index
'return the kind we are working with'
def get_kind(self):
if (self.config_options['resource_kind']['value'] == 'role'): return 'rolebinding' elif (self.config_options['resource_kind']['value'] == 'cluster-role'): return 'clusterrolebinding' elif (self.config_options['resource_kind']['value'] == 'scc'): return 'scc' return None
'Constructor for PolicyGroup'
def __init__(self, config, verbose=False):
super(PolicyGroup, self).__init__(config.namespace, config.kubeconfig, verbose) self.config = config self.verbose = verbose self._rolebinding = None self._scc = None self._cluster_role_bindings = None self._role_bindings = None
'role_binding getter'
@property def role_binding(self):
return self._rolebinding
'role_binding setter'
@role_binding.setter def role_binding(self, binding):
self._rolebinding = binding
'security_context_constraint getter'
@property def security_context_constraint(self):
return self._scc
'security_context_constraint setter'
@security_context_constraint.setter def security_context_constraint(self, scc):
self._scc = scc
'fetch the desired kind'
def get(self):
resource_name = self.config.config_options['name']['value'] if (resource_name == 'cluster-reader'): resource_name += 's' results = self._get(self.config.kind, resource_name) if (results['returncode'] == 0): return results return self._get(self.config.kind, (resource_name + '-binding'...
'return whether role_binding exists'
def exists_role_binding(self):
bindings = None if (self.config.config_options['resource_kind']['value'] == 'cluster-role'): bindings = self.clusterrolebindings else: bindings = self.rolebindings if (bindings is None): return False for binding in bindings: if ((binding['roleRef']['name'] == self.con...
'return whether scc exists'
def exists_scc(self):
results = self.get() if (results['returncode'] == 0): self.security_context_constraint = SecurityContextConstraints(results['results'][0]) if (self.security_context_constraint.find_group(self.config.config_options['group']['value']) != None): return True return False retu...
'does the object exist?'
def exists(self):
if (self.config.config_options['resource_kind']['value'] == 'cluster-role'): return self.exists_role_binding() elif (self.config.config_options['resource_kind']['value'] == 'role'): return self.exists_role_binding() elif (self.config.config_options['resource_kind']['value'] == 'scc'): ...
'perform action on resource'
def perform(self):
cmd = ['policy', self.config.config_options['action']['value'], self.config.config_options['name']['value'], self.config.config_options['group']['value']] return self.openshift_cmd(cmd, oadm=True)
'run the idempotent ansible code'
@staticmethod def run_ansible(params, check_mode):
state = params['state'] action = None if (state == 'present'): action = (('add-' + params['resource_kind']) + '-to-group') else: action = (('remove-' + params['resource_kind']) + '-from-group') nconfig = PolicyGroupConfig(params['namespace'], params['kubeconfig'], {'action': {'value'...
'Skip hosts that do not have package requirements.'
def is_active(self):
group_names = self.get_var('group_names', default=[]) master_or_node = (('masters' in group_names) or ('nodes' in group_names)) return (super(PackageVersion, self).is_active() and master_or_node)
'Return the correct Open vSwitch version(s) for the current OpenShift version.'
def get_required_ovs_version(self):
openshift_version = self.get_openshift_version_tuple() earliest = min(self.openshift_to_ovs_version) latest = max(self.openshift_to_ovs_version) if (openshift_version < earliest): return self.openshift_to_ovs_version[earliest] if (openshift_version > latest): return self.openshift_to...
'Return the correct Docker version(s) for the current OpenShift version.'
def get_required_docker_version(self):
openshift_version = self.get_openshift_version_tuple() earliest = min(self.openshift_to_docker_version) latest = max(self.openshift_to_docker_version) if (openshift_version < earliest): return self.openshift_to_docker_version[earliest] if (openshift_version > latest): return self.ope...
'Return received image tag as a normalized (X, Y) minor version tuple.'
def get_openshift_version_tuple(self):
version = self.get_var('openshift_image_tag') comps = [int(component) for component in re.findall('\\d+', version)] if (len(comps) < 2): msg = 'An invalid version of OpenShift was found for this host: {}' raise OpenShiftCheckException(msg.format(version)) co...
'Run only when yum is the package manager as the code is specific to it.'
def is_active(self):
return (super(PackageAvailability, self).is_active() and (self.get_var('ansible_pkg_mgr') == 'yum'))
'Return a list of RPMs that we expect a master install to have available.'
@staticmethod def master_packages(rpm_prefix):
return ['{rpm_prefix}'.format(rpm_prefix=rpm_prefix), '{rpm_prefix}-clients'.format(rpm_prefix=rpm_prefix), '{rpm_prefix}-master'.format(rpm_prefix=rpm_prefix), 'bash-completion', 'cockpit-bridge', 'cockpit-docker', 'cockpit-system', 'cockpit-ws', 'etcd', 'httpd-tools']
'Return a list of RPMs that we expect a node install to have available.'
@staticmethod def node_packages(rpm_prefix):
return ['{rpm_prefix}'.format(rpm_prefix=rpm_prefix), '{rpm_prefix}-node'.format(rpm_prefix=rpm_prefix), '{rpm_prefix}-sdn-ovs'.format(rpm_prefix=rpm_prefix), 'bind', 'ceph-common', 'dnsmasq', 'docker', 'firewalld', 'flannel', 'glusterfs-fuse', 'iptables-services', 'iptables', 'iscsi-initiator-utils', 'libselinux-p...
'Only run on non-containerized hosts.'
def is_active(self):
is_containerized = self.get_var('openshift', 'common', 'is_containerized') return (super(NotContainerizedMixin, self).is_active() and (not is_containerized))
'Only run on hosts that depend on Docker.'
def is_active(self):
is_containerized = self.get_var('openshift', 'common', 'is_containerized') is_node = ('nodes' in self.get_var('group_names', default=[])) return (super(DockerHostMixin, self).is_active() and (is_containerized or is_node))
'Ensure that docker-related packages exist, but not on atomic hosts (which would not be able to install but should already have them). Returns: msg, failed'
def ensure_dependencies(self):
if self.get_var('openshift', 'common', 'is_atomic'): return ('', False) result = self.execute_module(self.get_var('ansible_pkg_mgr', default='yum'), {'name': self.dependencies, 'state': 'present'}) msg = result.get('msg', '') if result.get('failed'): if ('No package matching' in ms...
'The name of this check, usually derived from the class name.'
@abstractproperty def name(self):
return 'openshift_check'
'A list of tags that this check satisfy. Tags are used to reference multiple checks with a single \'@tagname\' special check name.'
@property def tags(self):
return []
'Returns true if this check applies to the ansible-playbook run.'
@staticmethod def is_active():
return True
'Executes a check, normally implemented as a module.'
@abstractmethod def run(self):
return {}
'Returns a generator of subclasses of this class and its subclasses.'
@classmethod def subclasses(cls):
for subclass in cls.__subclasses__(): (yield subclass) for subclass in subclass.subclasses(): (yield subclass)
'Invoke an Ansible module from a check. Invoke stored _execute_module, normally copied from the action plugin, with its params and the task_vars and tmp given at check initialization. No positional parameters beyond these are specified. If it\'s necessary to specify any of the other parameters to _execute_module then t...
def execute_module(self, module_name=None, module_args=None):
if (self._execute_module is None): raise NotImplementedError((self.__class__.__name__ + ' invoked execute_module without providing the method at initialization.')) return self._execute_module(module_name, module_args, self.tmp, self.task_vars)
'Get deeply nested values from task_vars. Ansible task_vars structures are Python dicts, often mapping strings to other dicts. This helper makes it easier to get a nested value, raising OpenShiftCheckException when a key is not found. Keyword args: default: On missing key, return this as default value instead of raisin...
def get_var(self, *keys, **kwargs):
if (len(keys) == 1): keys = keys[0].split('.') try: value = reduce(operator.getitem, keys, self.task_vars) except (KeyError, TypeError): if ('default' not in kwargs): raise OpenShiftCheckException("This check expects the '{}' inventory variable to ...
'Parse and return the deployed version of OpenShift as a tuple.'
@staticmethod def get_major_minor_version(openshift_image_tag):
if (openshift_image_tag and (openshift_image_tag[0] == 'v')): openshift_image_tag = openshift_image_tag[1:] openshift_major_release_version = {'1': '3'} components = openshift_image_tag.split('.') if ((not components) or (len(components) < 2)): msg = 'An invalid version of Op...
'Skip hosts that do not have recommended memory requirements.'
def is_active(self):
group_names = self.get_var('group_names', default=[]) has_memory_recommendation = bool(set(group_names).intersection(self.recommended_memory_bytes)) return (super(MemoryAvailability, self).is_active() and has_memory_recommendation)
'Skip hosts that do not have recommended disk space requirements.'
def is_active(self):
group_names = self.get_var('group_names', default=[]) active_groups = set() for recommendation in self.recommended_disk_space_bytes.values(): active_groups.update(recommendation.keys()) has_disk_space_recommendation = bool(active_groups.intersection(group_names)) return (super(DiskAvailabili...
'Return the size available in path based on ansible_mounts.'
@staticmethod def free_bytes(path, ansible_mounts):
mount_point = path max_depth = 32 while ((mount_point not in ansible_mounts) and (max_depth > 0)): mount_point = os.path.dirname(mount_point) max_depth -= 1 try: free_bytes = ansible_mounts[mount_point]['size_available'] except KeyError: known_mounts = (', '.join((...
'Check if dm storage driver is supported as configured. Return: result dict.'
def check_devicemapper_support(self, driver_status):
if driver_status.get('Data loop file'): msg = 'Use of loopback devices with the Docker devicemapper storage driver\n(the default storage configuration) is unsupported in production.\nPlease use docker-storage-setup to configure a backin...
'Check usage thresholds for Docker dm storage driver. Return: result dict. Backing assumptions: We expect devicemapper to be backed by an auto-expanding thin pool implemented as an LV in an LVM2 VG. This is how docker-storage-setup currently configures devicemapper storage. The LV is "thin" because it does not use all ...
def check_dm_usage(self, driver_status):
vals = dict(vg_free=self.get_vg_free(driver_status.get('Pool Name')), data_used=driver_status.get('Data Space Used'), data_total=driver_status.get('Data Space Total'), metadata_used=driver_status.get('Metadata Space Used'), metadata_total=driver_status.get('Metadata Space Total')) for...
'Determine which VG to examine according to the pool name. Return: size vgs reports. Pool name is the only indicator currently available from the Docker API driver info. We assume a name that looks like "vg--name-docker--pool"; vg and lv names with inner hyphens doubled, joined by a hyphen.'
def get_vg_free(self, pool):
match = re.match('((?:[^-]|--)+)-(?!-)', pool) if (not match): raise OpenShiftCheckException("This host's Docker reports it is using a storage pool named '{}'.\nHowever this name does not have the expected format of 'vgname-lvname'\nso th...
'Convert string like "10.3 G" to bytes (binary units assumed). Return: float bytes.'
@staticmethod def convert_to_bytes(string):
units = dict(b=1, k=1024, m=(1024 ** 2), g=(1024 ** 3), t=(1024 ** 4), p=(1024 ** 5)) string = (string or '') match = re.match('(\\d+(?:\\.\\d+)?)\\s*(\\w)?', string) if (not match): raise ValueError(('Cannot convert to a byte size: ' + string)) (number, unit) = match.group...
'Check if overlay storage driver is supported for this host. Return: result dict.'
def check_overlay_support(self, docker_info, driver_status):
backing_fs = driver_status.get('Backing Filesystem', '[NONE]') if (backing_fs != 'xfs'): msg = "Docker storage drivers 'overlay' and 'overlay2' are only supported with\n'xfs' as the backing storage, but this host's storage is type '{fs}'.".f...
'Check disk usage on OverlayFS backing store volume. Return: result dict.'
def check_overlay_usage(self, docker_info):
path = ((docker_info.get('DockerRootDir', '/var/lib/docker') + '/') + docker_info['Driver']) threshold = self.get_var('max_overlay_usage_percent', default=self.max_overlay_usage_percent) try: threshold = float(threshold) except ValueError: return {'failed': True, 'msg': "Specified 'ma...
'Return the mount point for path from ansible_mounts.'
@staticmethod def find_ansible_mount(path, ansible_mounts):
mount_for_path = {mount['mount']: mount for mount in ansible_mounts} mount_point = path while (mount_point not in mount_for_path): if (mount_point in ['/', '']): break mount_point = os.path.dirname(mount_point) try: return mount_for_path[mount_point] except KeyErr...
'Check various things and gather errors. Returns: result as hash'
def run(self):
curator_pods = self.get_pods_for_component('curator') self.check_curator(curator_pods) return {}
'Check to see if curator is up and working. Returns: error string'
def check_curator(self, pods):
if (not pods): raise OpenShiftCheckException('MissingComponentPods', 'There are no Curator pods for the logging stack,\nso nothing will prune Elasticsearch indexes.\nIs Curator correctly deployed?') not_running = self.not_running_pods(pods) if (len(not...
'Determine if running on first master. Returns: bool'
def is_first_master(self):
hostname = (self.get_var('ansible_ssh_host') or [None]) masters = (self.get_var('groups', 'masters', default=None) or [None]) return (masters[0] == hostname)