desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Get all pods for a given component. Returns: list of pods.'
| def get_pods_for_component(self, logging_component):
| pod_output = self.exec_oc('get pods -l component={} -o json'.format(logging_component), [])
try:
pods = json.loads(pod_output)
if ((not pods) or (not pods.get('items'))):
raise ValueError()
except ValueError:
raise MissingComponentPods('There are no ... |
'Returns: list of pods not in a ready and running state'
| @staticmethod
def not_running_pods(pods):
| return [pod for pod in pods if ((not pod.get('status', {}).get('containerStatuses')) or any(((container['ready'] is False) for container in pod['status']['containerStatuses'])) or (not any((((condition['type'] == 'Ready') and (condition['status'] == 'True')) for condition in pod['status'].get('conditions', [])))))]... |
'Returns the namespace in which logging is configured to deploy.'
| def logging_namespace(self):
| return self.get_var('openshift_logging_namespace', default='logging')
|
'Execute an \'oc\' command in the remote host.
Returns: output of command and namespace,
or raises CouldNotUseOc on error'
| def exec_oc(self, cmd_str='', extra_args=None):
| config_base = self.get_var('openshift', 'common', 'config_base')
args = {'namespace': self.logging_namespace(), 'config_file': os.path.join(config_base, 'master', 'admin.kubeconfig'), 'cmd': cmd_str, 'extra_args': (list(extra_args) if extra_args else [])}
result = self.execute_module('ocutil', args)
if ... |
'Check that Fluentd has running pods, and that its logging config matches Docker\'s logging config.'
| def run(self):
| config_error = self.check_logging_config()
if config_error:
msg = 'The following Fluentd logging configuration problem was found:\n{}'.format(config_error)
return {'failed': True, 'msg': msg}
return {}
|
'Ensure that the configured Docker logging driver matches fluentd settings.
This means that, at least for now, if the following condition is met:
openshift_logging_fluentd_use_journal == True
then the value of the configured Docker logging driver should be "journald".
Otherwise, the value of the Docker logging driver s... | def check_logging_config(self):
| use_journald = self.get_var('openshift_logging_fluentd_use_journal', default=True)
group_names = self.get_var('group_names')
if ('masters' in group_names):
use_journald = self.check_fluentd_env_var()
docker_info = self.execute_module('docker_info', {})
try:
logging_driver = docker_in... |
'Read and return the value of the \'USE_JOURNAL\' environment variable on a fluentd pod.'
| def check_fluentd_env_var(self):
| running_pods = self.running_fluentd_pods()
try:
pod_containers = running_pods[0]['spec']['containers']
except KeyError:
return 'Unable to detect running containers on selected Fluentd pod.'
if (not pod_containers):
msg = 'There are no running c... |
'Return a list of running fluentd pods.'
| def running_fluentd_pods(self):
| fluentd_pods = self.get_pods_for_component('fluentd')
running_fluentd_pods = [pod for pod in fluentd_pods if (pod['status']['phase'] == 'Running')]
if (not running_fluentd_pods):
raise OpenShiftCheckException('No Fluentd pods were found to be in the "Running" state. ... |
'Check various things and gather errors. Returns: result as hash'
| def run(self):
| kibana_pods = self.get_pods_for_component('kibana')
self.check_kibana(kibana_pods)
self.check_kibana_route()
return {}
|
'Try to reach a URL from the host.
Returns: success (bool), reason (for failure)'
| def _verify_url_internal(self, url):
| args = dict(url=url, follow_redirects='none', validate_certs='no', status_code=302)
result = self.execute_module('uri', args)
if result.get('failed'):
return result['msg']
return None
|
'Try to reach a URL from ansible control host.
Raise an OpenShiftCheckException if anything goes wrong.'
| @staticmethod
def _verify_url_external(url):
| ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
return_code = urllib2.urlopen(url, context=ctx).getcode()
except HTTPError as httperr:
return httperr.reason
except URLError as urlerr:
return str(urlerr)
if (return_cod... |
'Check to see if Kibana is up and working. Raises OpenShiftCheckException if not.'
| def check_kibana(self, pods):
| if (not pods):
raise OpenShiftCheckException('MissingComponentPods', 'There are no Kibana pods deployed, so no access to the logging UI.')
not_running = self.not_running_pods(pods)
if (len(not_running) == len(pods)):
raise OpenShiftCheckException('NoRunnin... |
'Get kibana route or report error.
Returns: url'
| def _get_kibana_url(self):
| get_route = self.exec_oc('get route logging-kibana -o json', [])
if (not get_route):
raise OpenShiftCheckException('no_route_exists', 'No route is defined for Kibana in the logging namespace,\nso the logging stack is not accessible. Is loggi... |
'Check to see if kibana route is up and working.
Raises exception if not.'
| def check_kibana_route(self):
| kibana_url = self._get_kibana_url()
error = self._verify_url_internal(kibana_url)
if error:
if ('urlopen error [Errno 111] Connection refused' in error):
raise OpenShiftCheckException('FailedToConnectInternal', 'Failed to connect from this master to Ki... |
'Check the Fluentd deployment and raise an error if any problems are found.'
| def run(self):
| fluentd_pods = self.get_pods_for_component('fluentd')
self.check_fluentd(fluentd_pods)
return {}
|
'Verify fluentd is running everywhere. Raises OpenShiftCheckExceptionList if error(s) found.'
| def check_fluentd(self, pods):
| node_selector = self.get_var('openshift_logging_fluentd_nodeselector', default='logging-infra-fluentd=true')
nodes_by_name = self.get_nodes_by_name()
fluentd_nodes = self.filter_fluentd_labeled_nodes(nodes_by_name, node_selector)
errors = []
errors += self.check_node_labeling(nodes_by_name, fluentd_... |
'Retrieve all the node definitions. Returns: dict(name: node)'
| def get_nodes_by_name(self):
| nodes_json = self.exec_oc('get nodes -o json', [])
try:
nodes = json.loads(nodes_json)
except ValueError:
raise OpenShiftCheckException('BadOcNodeList', ('Could not obtain a list of nodes to validate fluentd.\nOutput from oc get:\n' + nodes_json))... |
'Filter to all nodes with fluentd label. Returns dict(name: node)'
| @staticmethod
def filter_fluentd_labeled_nodes(nodes_by_name, node_selector):
| (label, value) = node_selector.split('=', 1)
fluentd_nodes = {name: node for (name, node) in nodes_by_name.items() if (node['metadata']['labels'].get(label) == value)}
if (not fluentd_nodes):
raise OpenShiftCheckException('NoNodesLabeled', 'There are no nodes with the fluentd la... |
'Note if nodes are not labeled as expected. Returns: error list'
| def check_node_labeling(self, nodes_by_name, fluentd_nodes, node_selector):
| intended_nodes = self.get_var('openshift_logging_fluentd_hosts', default=['--all'])
if ((not intended_nodes) or ('--all' in intended_nodes)):
intended_nodes = nodes_by_name.keys()
nodes_missing_labels = (set(intended_nodes) - set(fluentd_nodes.keys()))
if nodes_missing_labels:
return [Op... |
'Make sure fluentd is on all the labeled nodes. Returns: error list'
| @staticmethod
def check_nodes_have_fluentd(pods, fluentd_nodes):
| unmatched_nodes = fluentd_nodes.copy()
node_names_by_label = {node['metadata']['labels']['kubernetes.io/hostname']: name for (name, node) in fluentd_nodes.items()}
node_names_by_internal_ip = {address['address']: name for (name, node) in fluentd_nodes.items() for address in node['status']['addresses'] if (a... |
'Make sure all fluentd pods are running. Returns: error string'
| def check_fluentd_pods_running(self, pods):
| not_running = super(Fluentd, self).not_running_pods(pods)
if not_running:
return [OpenShiftCheckException('FluentdNotRunning', 'The following Fluentd pods are supposed to be running but are not:\n {pods}\nThese pods will not aggregate logs from ... |
'Check various things and gather errors. Returns: result as hash'
| def run(self):
| es_pods = self.get_pods_for_component('es')
self.check_elasticsearch(es_pods)
return {}
|
'Perform checks for Elasticsearch. Raises OpenShiftCheckExceptionList on any errors.'
| def check_elasticsearch(self, es_pods):
| (running_pods, errors) = self.running_elasticsearch_pods(es_pods)
pods_by_name = {pod['metadata']['name']: pod for pod in running_pods if pod['metadata'].get('labels', {}).get('deploymentconfig')}
if (not pods_by_name):
errors.append(OpenShiftCheckException('NoRunningPods', 'No logging Elastic... |
'Returns: list of running pods, list of errors about non-running pods'
| def running_elasticsearch_pods(self, es_pods):
| not_running = self.not_running_pods(es_pods)
running_pods = [pod for pod in es_pods if (pod not in not_running)]
if not_running:
return (running_pods, [OpenShiftCheckException('PodNotRunning', 'The following Elasticsearch pods are defined but not running:\n{pods}'.format(pods... |
'Check that Elasticsearch masters are sane. Returns: list of errors'
| def check_elasticsearch_masters(self, pods_by_name):
| es_master_names = set()
errors = []
for pod_name in pods_by_name.keys():
get_master_cmd = self._build_es_curl_cmd(pod_name, 'https://localhost:9200/_cat/master')
master_name_str = self.exec_oc(get_master_cmd, [])
master_names = (master_name_str or '').split(' ')
if (len(ma... |
'Check that reported ES masters are accounted for by pods. Returns: list of errors'
| def check_elasticsearch_node_list(self, pods_by_name):
| if (not pods_by_name):
return [OpenShiftCheckException('MissingComponentPods', 'No logging Elasticsearch pods were found.')]
node_cmd = self._build_es_curl_cmd(list(pods_by_name.keys())[0], 'https://localhost:9200/_nodes')
cluster_node_data = self.exec_oc(node_cmd, [])
try:
... |
'Exec into the elasticsearch pods and check the cluster health. Returns: list of errors'
| def check_es_cluster_health(self, pods_by_name):
| errors = []
for pod_name in pods_by_name.keys():
cluster_health_cmd = self._build_es_curl_cmd(pod_name, 'https://localhost:9200/_cluster/health?pretty=true')
cluster_health_data = self.exec_oc(cluster_health_cmd, [])
try:
health_res = json.loads(cluster_health_data)
... |
'Exec into an ES pod and query the diskspace on the persistent volume.
Returns: list of errors'
| def check_elasticsearch_diskspace(self, pods_by_name):
| errors = []
for pod_name in pods_by_name.keys():
df_cmd = 'exec {} -- df --output=ipcent,pcent /elasticsearch/persistent'.format(pod_name)
disk_output = self.exec_oc(df_cmd, [])
lines = disk_output.splitlines()
body_re = '\\s*(\\d+)%?\\s+(\\d+)%?\\s*$'
if (... |
'Add log entry by making unique request to Kibana. Check for unique entry in the ElasticSearch pod logs.'
| def run(self):
| try:
log_index_timeout = int(self.get_var('openshift_check_logging_index_timeout_seconds', default=ES_CMD_TIMEOUT_SECONDS))
except ValueError:
raise OpenShiftCheckException('InvalidTimeout', 'Invalid value provided for "openshift_check_logging_index_timeout_seconds". Value must... |
'Retry an Elasticsearch query every second until query success, or a defined
length of time has passed.'
| def wait_until_cmd_or_err(self, es_pod, uuid, timeout_secs):
| deadline = (time.time() + timeout_secs)
interval = 1
while (not self.query_es_from_es(es_pod, uuid)):
if ((time.time() + interval) > deadline):
raise OpenShiftCheckException('NoMatchFound', 'expecting match in Elasticsearch for message with uuid {}, but no ... |
'curl Kibana with a unique uuid.'
| def curl_kibana_with_uuid(self, kibana_pod):
| uuid = self.generate_uuid()
pod_name = kibana_pod['metadata']['name']
exec_cmd = 'exec {pod_name} -c kibana -- curl --max-time 30 -s http://localhost:5601/{uuid}'
exec_cmd = exec_cmd.format(pod_name=pod_name, uuid=uuid)
error_str = self.exec_oc(exec_cmd, [])
try:
... |
'curl the Elasticsearch pod and look for a unique uuid in its logs.'
| def query_es_from_es(self, es_pod, uuid):
| pod_name = es_pod['metadata']['name']
exec_cmd = 'exec {pod_name} -- curl --max-time 30 -s -f --cacert /etc/elasticsearch/secret/admin-ca --cert /etc/elasticsearch/secret/admin-cert --key /etc/elasticsearch/secret/admin-key https://logging-es:9200/project.{namespace}*/_... |
'Filter pods that are running.'
| @staticmethod
def running_pods(pods):
| return [pod for pod in pods if (pod['status']['phase'] == 'Running')]
|
'Wrap uuid generator. Allows for testing with expected values.'
| @staticmethod
def generate_uuid():
| return str(uuid4())
|
'Skip hosts that do not have etcd in their group names.'
| def is_active(self):
| group_names = self.get_var('group_names', default=[])
valid_group_names = ('etcd' in group_names)
version = self.get_var('openshift', 'common', 'short_version')
valid_version = (version in ('3.4', '3.5', '1.4', '1.5'))
return (super(EtcdTraffic, self).is_active() and valid_group_names and valid_vers... |
'Skip hosts with unsupported deployment types.'
| def is_active(self):
| deployment_type = self.get_var('openshift_deployment_type')
has_valid_deployment_type = (deployment_type in DEPLOYMENT_IMAGE_INFO)
return (super(DockerImageAvailability, self).is_active() and has_valid_deployment_type)
|
'Determine which images we expect to need for this host.
Returns: a set of required images like \'openshift/origin:v3.6\'
The thorny issue of determining the image names from the variables is under consideration
via https://github.com/openshift/openshift-ansible/issues/4415
For now we operate as follows:
* For containe... | def required_images(self):
| required = set()
deployment_type = self.get_var('openshift_deployment_type')
host_groups = self.get_var('group_names')
image_tag = self.get_var('openshift_image_tag', default='latest')
image_info = DEPLOYMENT_IMAGE_INFO[deployment_type]
if (not image_info):
return required
image_url ... |
'Filter a list of images and return those available locally.'
| def local_images(self, images):
| return [image for image in images if self.is_image_local(image)]
|
'Check if image is already in local docker index.'
| def is_image_local(self, image):
| result = self.execute_module('docker_image_facts', {'name': image})
if result.get('failed', False):
return False
return bool(result.get('images', []))
|
'Build a list of docker registries available according to inventory vars.'
| def known_docker_registries(self):
| docker_facts = self.get_var('openshift', 'docker')
regs = set(docker_facts['additional_registries'])
deployment_type = self.get_var('openshift_deployment_type')
if (deployment_type == 'origin'):
regs.update(['docker.io'])
elif ('enterprise' in deployment_type):
regs.update(['registry... |
'Search remotely for images. Returns: list of images found.'
| def available_images(self, images, default_registries):
| return [image for image in images if self.is_available_skopeo_image(image, default_registries)]
|
'Use Skopeo to determine if required image exists in known registry(s).'
| def is_available_skopeo_image(self, image, default_registries):
| registries = default_registries
if (image.count('/') > 1):
(registry, image) = image.split('/', 1)
registries = [registry]
for registry in registries:
args = {'_raw_params': 'skopeo inspect --tls-verify=false docker://{}/{}'.format(registry, image)}
result = self.exe... |
'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(OvsVersion, self).is_active() and master_or_node)
|
'Return the correct Open vSwitch version for the current OpenShift version'
| def get_required_ovs_version(self):
| openshift_version_tuple = self.get_major_minor_version(self.get_var('openshift_image_tag'))
if (openshift_version_tuple < (3, 5)):
return self.openshift_to_ovs_version['3.4']
openshift_version = '.'.join((str(x) for x in openshift_version_tuple))
ovs_version = self.openshift_to_ovs_version.get(o... |
'Returns parameters used to update a container'
| @property
def update_parameters(self):
| update_parameters = dict(blkio_weight='blkio_weight', cpu_period='cpu_period', cpu_quota='cpu_quota', cpu_shares='cpu_shares', cpuset_cpus='cpuset_cpus', mem_limit='memory', mem_reservation='mem_reservation', memswap_limit='memory_swap', kernel_memory='kernel_memory')
result = dict()
for (key, value) in upd... |
'Returns parameters used to create a container'
| @property
def create_parameters(self):
| create_params = dict(command='command', hostname='hostname', user='user', detach='detach', stdin_open='interactive', tty='tty', ports='ports', environment='env', name='name', entrypoint='entrypoint', cpu_shares='cpu_shares', mac_address='mac_address', labels='labels', stop_signal='stop_signal', volume_driver='volum... |
'Return a list of container mounts.
:return:'
| def _get_mounts(self):
| result = []
if self.volumes:
for vol in self.volumes:
if (':' in vol):
if (len(vol.split(':')) == 3):
(host, container, _) = vol.split(':')
result.append(container)
continue
if (len(vol.split(':')) ==... |
'Returns parameters used to create a HostConfig object'
| def _host_config(self):
| host_config_params = dict(port_bindings='published_ports', publish_all_ports='publish_all_ports', links='links', privileged='privileged', dns='dns_servers', dns_search='dns_search_domains', binds='volume_binds', volumes_from='volumes_from', network_mode='network_mode', cap_add='capabilities', extra_hosts='etc_hosts... |
'Parse ports from docker CLI syntax'
| def _parse_publish_ports(self):
| if (self.published_ports is None):
return None
if ('all' in self.published_ports):
return 'all'
default_ip = self.default_host_ip
binds = {}
for port in self.published_ports:
parts = str(port).split(':')
container_port = parts[(-1)]
if ('/' not in container_po... |
'Extract host bindings, if any, from list of volume mapping strings.
:return: dictionary of bind mappings'
| @staticmethod
def _get_volume_binds(volumes):
| result = dict()
if volumes:
for vol in volumes:
host = None
if (':' in vol):
if (len(vol.split(':')) == 3):
(host, container, mode) = vol.split(':')
if (len(vol.split(':')) == 2):
parts = vol.split(':')
... |
'Parse exposed ports from docker CLI-style ports syntax.'
| def _parse_exposed_ports(self, published_ports):
| exposed = []
if self.exposed_ports:
for port in self.exposed_ports:
port = str(port).strip()
protocol = 'tcp'
match = re.search('(/.+$)', port)
if match:
protocol = match.group(1).replace('/', '')
port = re.sub('/.+$', '', p... |
'Turn links into a dictionary'
| @staticmethod
def _parse_links(links):
| if (links is None):
return None
result = {}
for link in links:
parsed_link = link.split(':', 1)
if (len(parsed_link) == 2):
result[parsed_link[0]] = parsed_link[1]
else:
result[parsed_link[0]] = parsed_link[0]
return result
|
'Turn ulimits into an array of Ulimit objects'
| def _parse_ulimits(self):
| if (self.ulimits is None):
return None
results = []
for limit in self.ulimits:
limits = dict()
pieces = limit.split(':')
if (len(pieces) >= 2):
limits['name'] = pieces[0]
limits['soft'] = int(pieces[1])
limits['hard'] = int(pieces[1])
... |
'Create a LogConfig object'
| def _parse_log_config(self):
| if (self.log_driver is None):
return None
options = dict(Type=self.log_driver, Config=dict())
if (self.log_options is not None):
options['Config'] = self.log_options
try:
return LogConfig(**options)
except ValueError as exc:
self.fail(('Error parsing logging ... |
'If environment file is combined with explicit environment variables, the explicit environment variables
take precedence.'
| def _get_environment(self):
| final_env = {}
if self.env_file:
parsed_env_file = utils.parse_env_file(self.env_file)
for (name, value) in parsed_env_file.items():
final_env[name] = str(value)
if self.env:
for (name, value) in self.env.items():
final_env[name] = str(value)
return final_... |
'Diff parameters vs existing container config. Returns tuple: (True | False, List of differences)'
| def has_different_configuration(self, image):
| self.log('Starting has_different_configuration')
self.parameters.expected_entrypoint = self._get_expected_entrypoint()
self.parameters.expected_links = self._get_expected_links()
self.parameters.expected_ports = self._get_expected_ports()
self.parameters.expected_exposed = self._get_expected_expo... |
'If all of list_a exists in list_b, return True'
| def _compare_dictionary_lists(self, list_a, list_b):
| if ((not isinstance(list_a, list)) or (not isinstance(list_b, list))):
return False
matches = 0
for dict_a in list_a:
for dict_b in list_b:
if self._compare_dicts(dict_a, dict_b):
matches += 1
break
result = (matches == len(list_a))
return ... |
'If dict_a in dict_b, return True'
| def _compare_dicts(self, dict_a, dict_b):
| if ((not isinstance(dict_a, dict)) or (not isinstance(dict_b, dict))):
return False
for (key, value) in dict_a.items():
if isinstance(value, dict):
match = self._compare_dicts(value, dict_b.get(key))
elif isinstance(value, list):
if ((len(value) > 0) and isinstanc... |
'Diff parameters and container resource limits'
| def has_different_resource_limits(self):
| if (not self.container.get('HostConfig')):
self.fail('limits_differ_from_container: Error parsing container properties. HostConfig missing.')
host_config = self.container['HostConfig']
config_mapping = dict(cpu_period=host_config.get('CpuPeriod'), cpu_quota=host_config.get('CpuQuot... |
'Check if the container is connected to requested networks with expected options: links, aliases, ipv4, ipv6'
| def has_network_differences(self):
| different = False
differences = []
if (not self.parameters.networks):
return (different, differences)
if (not self.container.get('NetworkSettings')):
self.fail('has_missing_networks: Error parsing container properties. NetworkSettings missing.')
connected_networks =... |
'Check if the container is connected to non-requested networks'
| def has_extra_networks(self):
| extra_networks = []
extra = False
if (not self.container.get('NetworkSettings')):
self.fail('has_extra_networks: Error parsing container properties. NetworkSettings missing.')
connected_networks = self.container['NetworkSettings'].get('Networks')
if connected_networks:
... |
'Convert array of binds to array of strings with format host_path:container_path:mode
:param volumes: array of bind dicts
:return: array of strings'
| def _get_image_binds(self, volumes):
| results = []
if isinstance(volumes, dict):
results += self._get_bind_from_dict(volumes)
elif isinstance(volumes, list):
for vol in volumes:
results += self._get_bind_from_dict(vol)
return results
|
'Expects container ID or Name. Returns a container object'
| def _get_container(self, container):
| return Container(self.client.get_container(container), self.parameters)
|
'Print a summary of failed tasks or checks.'
| def _print_failure_details(self, failures):
| self._display.display(u'\nFailure summary:\n')
width = len(str(len(failures)))
initial_indent_format = u' {{:>{width}}}. '.format(width=width)
initial_indent_len = len(initial_indent_format.format(0))
subsequent_indent = (u' ' * initial_indent_len)
subsequent_extra_indent = (u' ... |
'the init method of OCBaseCommand class'
| def __init__(self, binary, kubeconfig, namespace):
| self.binary = binary
self.kubeconfig = kubeconfig
self.user = self.get_system_admin(self.kubeconfig)
self.namespace = namespace
|
'Retrieves the system admin'
| def get_system_admin(self, kubeconfig):
| with open(kubeconfig, 'r') as kubeconfig_file:
config = yaml.load(kubeconfig_file)
for user in config['users']:
if user['name'].startswith('system:admin'):
return user['name']
raise Exception(('Unable to find system:admin in: ' + kubeconfig))
|
'Wrapper method for the "oc" command'
| def oc_command(self, sub, kind, namespace=None, name=None, add_options=None):
| cmd = [self.binary, sub, kind]
if (name is not None):
cmd = (cmd + [name])
if (namespace is not None):
cmd = (cmd + ['-n', namespace])
if (add_options is None):
add_options = []
cmd = (((cmd + [('--user=' + self.user), ('--config=' + self.kubeconfig)]) + DEFAULT_OC_OPTIONS) +... |
'The init method for OpenshiftLoggingFacts'
| def __init__(self, logger, binary, kubeconfig, namespace):
| super(OpenshiftLoggingFacts, self).__init__(binary, kubeconfig, namespace)
self.logger = logger
self.facts = dict()
|
'Sets the default key values for kind'
| def default_keys_for(self, kind):
| for comp in COMPONENTS:
self.add_facts_for(comp, kind)
|
'Add facts for the provided kind'
| def add_facts_for(self, comp, kind, name=None, facts=None):
| if (comp not in self.facts):
self.facts[comp] = dict()
if (kind not in self.facts[comp]):
self.facts[comp][kind] = dict()
if name:
self.facts[comp][kind][name] = facts
|
'Gathers facts for Routes in logging namespace'
| def facts_for_routes(self, namespace):
| self.default_keys_for('routes')
route_list = self.oc_command('get', 'routes', namespace=namespace, add_options=['-l', ROUTE_SELECTOR])
if (len(route_list['items']) == 0):
return None
for route in route_list['items']:
name = route['metadata']['name']
comp = self.comp(name)
... |
'Gathers facts for Daemonsets in logging namespace'
| def facts_for_daemonsets(self, namespace):
| self.default_keys_for('daemonsets')
ds_list = self.oc_command('get', 'daemonsets', namespace=namespace, add_options=['-l', (LOGGING_INFRA_KEY + '=fluentd')])
if (len(ds_list['items']) == 0):
return
for ds_item in ds_list['items']:
name = ds_item['metadata']['name']
comp = self.co... |
'Gathers facts for PVCS in logging namespace'
| def facts_for_pvcs(self, namespace):
| self.default_keys_for('pvcs')
pvclist = self.oc_command('get', 'pvc', namespace=namespace, add_options=['-l', LOGGING_INFRA_KEY])
if (len(pvclist['items']) == 0):
return
for pvc in pvclist['items']:
name = pvc['metadata']['name']
comp = self.comp(name)
self.add_facts_for(... |
'Gathers facts for DeploymentConfigs in logging namespace'
| def facts_for_deploymentconfigs(self, namespace):
| self.default_keys_for('deploymentconfigs')
dclist = self.oc_command('get', 'deploymentconfigs', namespace=namespace, add_options=['-l', LOGGING_INFRA_KEY])
if (len(dclist['items']) == 0):
return
dcs = dclist['items']
for dc_item in dcs:
name = dc_item['metadata']['name']
comp... |
'Gathers facts for services in logging namespace'
| def facts_for_services(self, namespace):
| self.default_keys_for('services')
servicelist = self.oc_command('get', 'services', namespace=namespace, add_options=['-l', LOGGING_SELECTOR])
if (len(servicelist['items']) == 0):
return
for service in servicelist['items']:
name = service['metadata']['name']
comp = self.comp(name)... |
'Gathers facts for configmaps in logging namespace'
| def facts_for_configmaps(self, namespace):
| self.default_keys_for('configmaps')
a_list = self.oc_command('get', 'configmaps', namespace=namespace, add_options=['-l', LOGGING_SELECTOR])
if (len(a_list['items']) == 0):
return
for item in a_list['items']:
name = item['metadata']['name']
comp = self.comp(name)
if (comp... |
'Gathers facts for oauthclients used with logging'
| def facts_for_oauthclients(self, namespace):
| self.default_keys_for('oauthclients')
a_list = self.oc_command('get', 'oauthclients', namespace=namespace, add_options=['-l', LOGGING_SELECTOR])
if (len(a_list['items']) == 0):
return
for item in a_list['items']:
name = item['metadata']['name']
comp = self.comp(name)
if (... |
'Gathers facts for secrets in the logging namespace'
| def facts_for_secrets(self, namespace):
| self.default_keys_for('secrets')
a_list = self.oc_command('get', 'secrets', namespace=namespace)
if (len(a_list['items']) == 0):
return
for item in a_list['items']:
name = item['metadata']['name']
comp = self.comp(name)
if ((comp is not None) and (item['type'] == 'Opaque'... |
'Gathers facts for SCCs used with logging'
| def facts_for_sccs(self):
| self.default_keys_for('sccs')
scc = self.oc_command('get', 'scc', name='privileged')
if (len(scc['users']) == 0):
return
for item in scc['users']:
comp = self.comp(item)
if (comp is not None):
self.add_facts_for(comp, 'sccs', 'privileged', dict())
|
'Gathers ClusterRoleBindings used with logging'
| def facts_for_clusterrolebindings(self, namespace):
| self.default_keys_for('clusterrolebindings')
role = self.oc_command('get', 'clusterrolebindings', name='cluster-readers')
if (('subjects' not in role) or (len(role['subjects']) == 0)):
return
for item in role['subjects']:
comp = self.comp(item['name'])
if ((comp is not None) and ... |
'Gathers facts for RoleBindings used with logging'
| def facts_for_rolebindings(self, namespace):
| self.default_keys_for('rolebindings')
role = self.oc_command('get', 'rolebindings', namespace=namespace, name='logging-elasticsearch-view-role')
if (('subjects' not in role) or (len(role['subjects']) == 0)):
return
for item in role['subjects']:
comp = self.comp(item['name'])
if (... |
'Does a comparison to evaluate the logging component'
| def comp(self, name):
| if name.startswith('logging-curator-ops'):
return 'curator_ops'
elif (name.startswith('logging-kibana-ops') or name.startswith('kibana-ops')):
return 'kibana_ops'
elif (name.startswith('logging-es-ops') or name.startswith('logging-elasticsearch-ops')):
return 'elasticsearch_ops'
... |
'Builds the logging facts and returns them'
| def build_facts(self):
| self.facts_for_routes(self.namespace)
self.facts_for_daemonsets(self.namespace)
self.facts_for_deploymentconfigs(self.namespace)
self.facts_for_services(self.namespace)
self.facts_for_configmaps(self.namespace)
self.facts_for_sccs()
self.facts_for_oauthclients(self.namespace)
self.facts_... |
'Returns the names of the filters provided by this class'
| def filters(self):
| return {'random_word': random_word, 'entry_from_named_pair': entry_from_named_pair, 'map_from_pairs': map_from_pairs, 'es_storage': es_storage}
|
'`cert_string` is a certificate in the form you get from running a
.crt through \'openssl x509 -in CERT.cert -text\''
| def __init__(self, cert_string):
| self.cert_string = cert_string
self.serial = None
self.subject = None
self.extensions = []
self.not_after = None
self._parse_cert()
|
'Manually parse the certificate line by line'
| def _parse_cert(self):
| self.extensions = []
PARSING_ALT_NAMES = False
PARSING_HEX_SERIAL = False
for line in self.cert_string.split('\n'):
l = line.strip()
if PARSING_ALT_NAMES:
self.extensions.append(FakeOpenSSLCertificateSANExtension(l))
PARSING_ALT_NAMES = False
continue
... |
'Return the serial number of the cert'
| def get_serial_number(self):
| return self.serial
|
'Subjects must implement get_components() and return dicts or
tuples. An \'openssl x509 -in CERT.cert -text\' with \'Subject\':
Subject: Subject: O=system:nodes, CN=system:node:m01.example.com
might return: [(\'O=system\', \'nodes\'), (\'CN=system\', \'node:m01.example.com\')]'
| def get_subject(self):
| return self.subject
|
'Extensions must implement get_short_name() and return the string
\'subjectAltName\''
| def get_extension(self, i):
| return self.extensions[i]
|
'get_extension_count'
| def get_extension_count(self):
| return len(self.extensions)
|
'Returns a date stamp as a string in the form
\'20180922170439Z\'. strptime the result with format param:
\'%Y%m%d%H%M%SZ\'.'
| def get_notAfter(self):
| return self.not_after
|
'With `san_string` as you get from:
$ openssl x509 -in certificate.crt -text'
| def __init__(self, san_string):
| self.san_string = san_string
self.short_name = 'subjectAltName'
|
'Return the \'type\' of this extension. It\'s always the same though
because we only care about subjectAltName\'s'
| def get_short_name(self):
| return self.short_name
|
'Return this extension and the value as a simple string'
| def __str__(self):
| return self.san_string
|
'With `subject_string` as you get from:
$ openssl x509 -in certificate.crt -text'
| def __init__(self, subject_string):
| self.subjects = []
for s in subject_string.split(', '):
(name, _, value) = s.partition(' = ')
self.subjects.append((name, value))
|
'Returns a list of tuples'
| def get_components(self):
| return self.subjects
|
'Takes results (`hostvars`) from the openshift_cert_expiry role
check and serializes them into proper machine-readable JSON
output. This filter parameter **MUST** be the playbook `hostvars`
variable. The `play_hosts` parameter is so we know what to loop over
when we\'re extrating the values.
Returns:
Results are collec... | @staticmethod
def oo_cert_expiry_results_to_json(hostvars, play_hosts):
| json_result = {'data': {}, 'summary': {}}
for host in play_hosts:
json_result['data'][host] = hostvars[host]['check_results']['check_results']
total_warnings = sum([hostvars[h]['check_results']['summary']['warning'] for h in play_hosts])
total_expired = sum([hostvars[h]['check_results']['summary... |
'returns a mapping of filters to methods'
| def filters(self):
| return {'oo_cert_expiry_results_to_json': self.oo_cert_expiry_results_to_json}
|
'Ensure the given binary name exists and links to the expected binary.'
| def _sync_symlink(self, binary_name, link_to):
| link_path = os.path.join(self.bin_dir, binary_name)
link_dest = os.path.join(self.bin_dir, link_to)
if ((not os.path.exists(link_path)) or (not os.path.islink(link_path)) or (os.path.realpath(link_path) != os.path.realpath(link_dest))):
if os.path.exists(link_path):
os.remove(link_path)
... |
'Constructor for RepoqueryCLI'
| def __init__(self, verbose=False):
| self.verbose = verbose
self.verbose = True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.