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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
226,000 | RedHatInsights/insights-core | insights/collect.py | create_context | def create_context(ctx):
"""
Loads and constructs the specified context with the specified arguments.
If a '.' isn't in the class name, the 'insights.core.context' package is
assumed.
"""
ctx_cls_name = ctx.get("class", "insights.core.context.HostContext")
if "." not in ctx_cls_name:
ctx_cls_name = "insights.core.context." + ctx_cls_name
ctx_cls = dr.get_component(ctx_cls_name)
ctx_args = ctx.get("args", {})
return ctx_cls(**ctx_args) | python | def create_context(ctx):
"""
Loads and constructs the specified context with the specified arguments.
If a '.' isn't in the class name, the 'insights.core.context' package is
assumed.
"""
ctx_cls_name = ctx.get("class", "insights.core.context.HostContext")
if "." not in ctx_cls_name:
ctx_cls_name = "insights.core.context." + ctx_cls_name
ctx_cls = dr.get_component(ctx_cls_name)
ctx_args = ctx.get("args", {})
return ctx_cls(**ctx_args) | [
"def",
"create_context",
"(",
"ctx",
")",
":",
"ctx_cls_name",
"=",
"ctx",
".",
"get",
"(",
"\"class\"",
",",
"\"insights.core.context.HostContext\"",
")",
"if",
"\".\"",
"not",
"in",
"ctx_cls_name",
":",
"ctx_cls_name",
"=",
"\"insights.core.context.\"",
"+",
"ct... | Loads and constructs the specified context with the specified arguments.
If a '.' isn't in the class name, the 'insights.core.context' package is
assumed. | [
"Loads",
"and",
"constructs",
"the",
"specified",
"context",
"with",
"the",
"specified",
"arguments",
".",
"If",
"a",
".",
"isn",
"t",
"in",
"the",
"class",
"name",
"the",
"insights",
".",
"core",
".",
"context",
"package",
"is",
"assumed",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/collect.py#L141-L152 |
226,001 | RedHatInsights/insights-core | insights/collect.py | get_to_persist | def get_to_persist(persisters):
"""
Given a specification of what to persist, generates the corresponding set
of components.
"""
def specs():
for p in persisters:
if isinstance(p, dict):
yield p["name"], p.get("enabled", True)
else:
yield p, True
components = sorted(dr.DELEGATES, key=dr.get_name)
names = dict((c, dr.get_name(c)) for c in components)
results = set()
for p, e in specs():
for c in components:
if names[c].startswith(p):
if e:
results.add(c)
elif c in results:
results.remove(c)
return results | python | def get_to_persist(persisters):
"""
Given a specification of what to persist, generates the corresponding set
of components.
"""
def specs():
for p in persisters:
if isinstance(p, dict):
yield p["name"], p.get("enabled", True)
else:
yield p, True
components = sorted(dr.DELEGATES, key=dr.get_name)
names = dict((c, dr.get_name(c)) for c in components)
results = set()
for p, e in specs():
for c in components:
if names[c].startswith(p):
if e:
results.add(c)
elif c in results:
results.remove(c)
return results | [
"def",
"get_to_persist",
"(",
"persisters",
")",
":",
"def",
"specs",
"(",
")",
":",
"for",
"p",
"in",
"persisters",
":",
"if",
"isinstance",
"(",
"p",
",",
"dict",
")",
":",
"yield",
"p",
"[",
"\"name\"",
"]",
",",
"p",
".",
"get",
"(",
"\"enabled... | Given a specification of what to persist, generates the corresponding set
of components. | [
"Given",
"a",
"specification",
"of",
"what",
"to",
"persist",
"generates",
"the",
"corresponding",
"set",
"of",
"components",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/collect.py#L155-L178 |
226,002 | RedHatInsights/insights-core | insights/collect.py | create_archive | def create_archive(path, remove_path=True):
"""
Creates a tar.gz of the path using the path basename + "tar.gz"
The resulting file is in the parent directory of the original path, and
the original path is removed.
"""
root_path = os.path.dirname(path)
relative_path = os.path.basename(path)
archive_path = path + ".tar.gz"
cmd = [["tar", "-C", root_path, "-czf", archive_path, relative_path]]
call(cmd, env=SAFE_ENV)
if remove_path:
fs.remove(path)
return archive_path | python | def create_archive(path, remove_path=True):
"""
Creates a tar.gz of the path using the path basename + "tar.gz"
The resulting file is in the parent directory of the original path, and
the original path is removed.
"""
root_path = os.path.dirname(path)
relative_path = os.path.basename(path)
archive_path = path + ".tar.gz"
cmd = [["tar", "-C", root_path, "-czf", archive_path, relative_path]]
call(cmd, env=SAFE_ENV)
if remove_path:
fs.remove(path)
return archive_path | [
"def",
"create_archive",
"(",
"path",
",",
"remove_path",
"=",
"True",
")",
":",
"root_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"relative_path",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"archive_path",
"=",
"pa... | Creates a tar.gz of the path using the path basename + "tar.gz"
The resulting file is in the parent directory of the original path, and
the original path is removed. | [
"Creates",
"a",
"tar",
".",
"gz",
"of",
"the",
"path",
"using",
"the",
"path",
"basename",
"+",
"tar",
".",
"gz",
"The",
"resulting",
"file",
"is",
"in",
"the",
"parent",
"directory",
"of",
"the",
"original",
"path",
"and",
"the",
"original",
"path",
"... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/collect.py#L181-L195 |
226,003 | RedHatInsights/insights-core | insights/collect.py | collect | def collect(manifest=default_manifest, tmp_path=None, compress=False):
"""
This is the collection entry point. It accepts a manifest, a temporary
directory in which to store output, and a boolean for optional compression.
Args:
manifest (str or dict): json document or dictionary containing the
collection manifest. See default_manifest for an example.
tmp_path (str): The temporary directory that will be used to create a
working directory for storing component output as well as the final
tar.gz if one is generated.
compress (boolean): True to create a tar.gz and remove the original
workspace containing output. False to leave the workspace without
creating a tar.gz
Returns:
The full path to the created tar.gz or workspace.
"""
manifest = load_manifest(manifest)
client = manifest.get("client", {})
plugins = manifest.get("plugins", {})
run_strategy = client.get("run_strategy", {"name": "parallel"})
apply_default_enabled(plugins.get("default_component_enabled", False))
load_packages(plugins.get("packages", []))
apply_blacklist(client.get("blacklist", {}))
apply_configs(plugins)
to_persist = get_to_persist(client.get("persist", set()))
hostname = call("hostname -f", env=SAFE_ENV).strip()
suffix = datetime.utcnow().strftime("%Y%m%d%H%M%S")
relative_path = "insights-%s-%s" % (hostname, suffix)
tmp_path = tmp_path or tempfile.gettempdir()
output_path = os.path.join(tmp_path, relative_path)
fs.ensure_path(output_path)
fs.touch(os.path.join(output_path, "insights_archive.txt"))
broker = dr.Broker()
ctx = create_context(client.get("context", {}))
broker[ctx.__class__] = ctx
parallel = run_strategy.get("name") == "parallel"
pool_args = run_strategy.get("args", {})
with get_pool(parallel, pool_args) as pool:
h = Hydration(output_path, pool=pool)
broker.add_observer(h.make_persister(to_persist))
dr.run_all(broker=broker, pool=pool)
if compress:
return create_archive(output_path)
return output_path | python | def collect(manifest=default_manifest, tmp_path=None, compress=False):
"""
This is the collection entry point. It accepts a manifest, a temporary
directory in which to store output, and a boolean for optional compression.
Args:
manifest (str or dict): json document or dictionary containing the
collection manifest. See default_manifest for an example.
tmp_path (str): The temporary directory that will be used to create a
working directory for storing component output as well as the final
tar.gz if one is generated.
compress (boolean): True to create a tar.gz and remove the original
workspace containing output. False to leave the workspace without
creating a tar.gz
Returns:
The full path to the created tar.gz or workspace.
"""
manifest = load_manifest(manifest)
client = manifest.get("client", {})
plugins = manifest.get("plugins", {})
run_strategy = client.get("run_strategy", {"name": "parallel"})
apply_default_enabled(plugins.get("default_component_enabled", False))
load_packages(plugins.get("packages", []))
apply_blacklist(client.get("blacklist", {}))
apply_configs(plugins)
to_persist = get_to_persist(client.get("persist", set()))
hostname = call("hostname -f", env=SAFE_ENV).strip()
suffix = datetime.utcnow().strftime("%Y%m%d%H%M%S")
relative_path = "insights-%s-%s" % (hostname, suffix)
tmp_path = tmp_path or tempfile.gettempdir()
output_path = os.path.join(tmp_path, relative_path)
fs.ensure_path(output_path)
fs.touch(os.path.join(output_path, "insights_archive.txt"))
broker = dr.Broker()
ctx = create_context(client.get("context", {}))
broker[ctx.__class__] = ctx
parallel = run_strategy.get("name") == "parallel"
pool_args = run_strategy.get("args", {})
with get_pool(parallel, pool_args) as pool:
h = Hydration(output_path, pool=pool)
broker.add_observer(h.make_persister(to_persist))
dr.run_all(broker=broker, pool=pool)
if compress:
return create_archive(output_path)
return output_path | [
"def",
"collect",
"(",
"manifest",
"=",
"default_manifest",
",",
"tmp_path",
"=",
"None",
",",
"compress",
"=",
"False",
")",
":",
"manifest",
"=",
"load_manifest",
"(",
"manifest",
")",
"client",
"=",
"manifest",
".",
"get",
"(",
"\"client\"",
",",
"{",
... | This is the collection entry point. It accepts a manifest, a temporary
directory in which to store output, and a boolean for optional compression.
Args:
manifest (str or dict): json document or dictionary containing the
collection manifest. See default_manifest for an example.
tmp_path (str): The temporary directory that will be used to create a
working directory for storing component output as well as the final
tar.gz if one is generated.
compress (boolean): True to create a tar.gz and remove the original
workspace containing output. False to leave the workspace without
creating a tar.gz
Returns:
The full path to the created tar.gz or workspace. | [
"This",
"is",
"the",
"collection",
"entry",
"point",
".",
"It",
"accepts",
"a",
"manifest",
"a",
"temporary",
"directory",
"in",
"which",
"to",
"store",
"output",
"and",
"a",
"boolean",
"for",
"optional",
"compression",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/collect.py#L217-L269 |
226,004 | RedHatInsights/insights-core | insights/__init__.py | _run | def _run(broker, graph=None, root=None, context=None, inventory=None):
"""
run is a general interface that is meant for stand alone scripts to use
when executing insights components.
Args:
root (str): None will causes a host collection in which command and
file specs are run. A directory or archive path will cause
collection from the directory or archive, and only file type specs
or those that depend on `insights.core.context.HostArchiveContext`
will execute.
component (function or class): The component to execute. Will only execute
the component and its dependency graph. If None, all components with
met dependencies will execute.
Returns:
broker: object containing the result of the evaluation.
"""
if not root:
context = context or HostContext
broker[context] = context()
return dr.run(graph, broker=broker)
if os.path.isdir(root):
return process_dir(broker, root, graph, context, inventory=inventory)
else:
with extract(root) as ex:
return process_dir(broker, ex.tmp_dir, graph, context, inventory=inventory) | python | def _run(broker, graph=None, root=None, context=None, inventory=None):
"""
run is a general interface that is meant for stand alone scripts to use
when executing insights components.
Args:
root (str): None will causes a host collection in which command and
file specs are run. A directory or archive path will cause
collection from the directory or archive, and only file type specs
or those that depend on `insights.core.context.HostArchiveContext`
will execute.
component (function or class): The component to execute. Will only execute
the component and its dependency graph. If None, all components with
met dependencies will execute.
Returns:
broker: object containing the result of the evaluation.
"""
if not root:
context = context or HostContext
broker[context] = context()
return dr.run(graph, broker=broker)
if os.path.isdir(root):
return process_dir(broker, root, graph, context, inventory=inventory)
else:
with extract(root) as ex:
return process_dir(broker, ex.tmp_dir, graph, context, inventory=inventory) | [
"def",
"_run",
"(",
"broker",
",",
"graph",
"=",
"None",
",",
"root",
"=",
"None",
",",
"context",
"=",
"None",
",",
"inventory",
"=",
"None",
")",
":",
"if",
"not",
"root",
":",
"context",
"=",
"context",
"or",
"HostContext",
"broker",
"[",
"context... | run is a general interface that is meant for stand alone scripts to use
when executing insights components.
Args:
root (str): None will causes a host collection in which command and
file specs are run. A directory or archive path will cause
collection from the directory or archive, and only file type specs
or those that depend on `insights.core.context.HostArchiveContext`
will execute.
component (function or class): The component to execute. Will only execute
the component and its dependency graph. If None, all components with
met dependencies will execute.
Returns:
broker: object containing the result of the evaluation. | [
"run",
"is",
"a",
"general",
"interface",
"that",
"is",
"meant",
"for",
"stand",
"alone",
"scripts",
"to",
"use",
"when",
"executing",
"insights",
"components",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/__init__.py#L98-L126 |
226,005 | RedHatInsights/insights-core | insights/__init__.py | apply_default_enabled | def apply_default_enabled(default_enabled):
"""
Configures dr and already loaded components with a default enabled
value.
"""
for k in dr.ENABLED:
dr.ENABLED[k] = default_enabled
enabled = defaultdict(lambda: default_enabled)
enabled.update(dr.ENABLED)
dr.ENABLED = enabled | python | def apply_default_enabled(default_enabled):
"""
Configures dr and already loaded components with a default enabled
value.
"""
for k in dr.ENABLED:
dr.ENABLED[k] = default_enabled
enabled = defaultdict(lambda: default_enabled)
enabled.update(dr.ENABLED)
dr.ENABLED = enabled | [
"def",
"apply_default_enabled",
"(",
"default_enabled",
")",
":",
"for",
"k",
"in",
"dr",
".",
"ENABLED",
":",
"dr",
".",
"ENABLED",
"[",
"k",
"]",
"=",
"default_enabled",
"enabled",
"=",
"defaultdict",
"(",
"lambda",
":",
"default_enabled",
")",
"enabled",
... | Configures dr and already loaded components with a default enabled
value. | [
"Configures",
"dr",
"and",
"already",
"loaded",
"components",
"with",
"a",
"default",
"enabled",
"value",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/__init__.py#L158-L168 |
226,006 | RedHatInsights/insights-core | insights/__init__.py | apply_configs | def apply_configs(config):
"""
Configures components. They can be enabled or disabled, have timeouts set
if applicable, and have metadata customized. Valid keys are name, enabled,
metadata, and timeout.
Args:
config (list): a list of dictionaries with the following keys:
default_component_enabled (bool): default value for whether compoments
are enable if not specifically declared in the config section
packages (list): a list of packages to be loaded. These will be in
addition to any packages previosly loaded for the `-p` option
configs:
name, enabled, metadata, and timeout. All keys are optional except
name.
name is the prefix or exact name of any loaded component. Any
component starting with name will have the associated configuration
applied.
enabled is whether the matching components will execute even if
their dependencies are met. Defaults to True.
timeout sets the class level timeout attribute of any component so
long as the attribute already exists.
metadata is any dictionary that you want to attach to the
component. The dictionary can be retrieved by the component at
runtime.
"""
default_enabled = config.get('default_component_enabled', False)
delegate_keys = sorted(dr.DELEGATES, key=dr.get_name)
for comp_cfg in config.get('configs', []):
name = comp_cfg.get("name")
for c in delegate_keys:
delegate = dr.DELEGATES[c]
cname = dr.get_name(c)
if cname.startswith(name):
dr.ENABLED[c] = comp_cfg.get("enabled", default_enabled)
delegate.metadata.update(comp_cfg.get("metadata", {}))
delegate.tags = set(comp_cfg.get("tags", delegate.tags))
for k, v in delegate.metadata.items():
if hasattr(c, k):
log.debug("Setting %s.%s to %s", cname, k, v)
setattr(c, k, v)
if hasattr(c, "timeout"):
c.timeout = comp_cfg.get("timeout", c.timeout)
if cname == name:
break | python | def apply_configs(config):
"""
Configures components. They can be enabled or disabled, have timeouts set
if applicable, and have metadata customized. Valid keys are name, enabled,
metadata, and timeout.
Args:
config (list): a list of dictionaries with the following keys:
default_component_enabled (bool): default value for whether compoments
are enable if not specifically declared in the config section
packages (list): a list of packages to be loaded. These will be in
addition to any packages previosly loaded for the `-p` option
configs:
name, enabled, metadata, and timeout. All keys are optional except
name.
name is the prefix or exact name of any loaded component. Any
component starting with name will have the associated configuration
applied.
enabled is whether the matching components will execute even if
their dependencies are met. Defaults to True.
timeout sets the class level timeout attribute of any component so
long as the attribute already exists.
metadata is any dictionary that you want to attach to the
component. The dictionary can be retrieved by the component at
runtime.
"""
default_enabled = config.get('default_component_enabled', False)
delegate_keys = sorted(dr.DELEGATES, key=dr.get_name)
for comp_cfg in config.get('configs', []):
name = comp_cfg.get("name")
for c in delegate_keys:
delegate = dr.DELEGATES[c]
cname = dr.get_name(c)
if cname.startswith(name):
dr.ENABLED[c] = comp_cfg.get("enabled", default_enabled)
delegate.metadata.update(comp_cfg.get("metadata", {}))
delegate.tags = set(comp_cfg.get("tags", delegate.tags))
for k, v in delegate.metadata.items():
if hasattr(c, k):
log.debug("Setting %s.%s to %s", cname, k, v)
setattr(c, k, v)
if hasattr(c, "timeout"):
c.timeout = comp_cfg.get("timeout", c.timeout)
if cname == name:
break | [
"def",
"apply_configs",
"(",
"config",
")",
":",
"default_enabled",
"=",
"config",
".",
"get",
"(",
"'default_component_enabled'",
",",
"False",
")",
"delegate_keys",
"=",
"sorted",
"(",
"dr",
".",
"DELEGATES",
",",
"key",
"=",
"dr",
".",
"get_name",
")",
... | Configures components. They can be enabled or disabled, have timeouts set
if applicable, and have metadata customized. Valid keys are name, enabled,
metadata, and timeout.
Args:
config (list): a list of dictionaries with the following keys:
default_component_enabled (bool): default value for whether compoments
are enable if not specifically declared in the config section
packages (list): a list of packages to be loaded. These will be in
addition to any packages previosly loaded for the `-p` option
configs:
name, enabled, metadata, and timeout. All keys are optional except
name.
name is the prefix or exact name of any loaded component. Any
component starting with name will have the associated configuration
applied.
enabled is whether the matching components will execute even if
their dependencies are met. Defaults to True.
timeout sets the class level timeout attribute of any component so
long as the attribute already exists.
metadata is any dictionary that you want to attach to the
component. The dictionary can be retrieved by the component at
runtime. | [
"Configures",
"components",
".",
"They",
"can",
"be",
"enabled",
"or",
"disabled",
"have",
"timeouts",
"set",
"if",
"applicable",
"and",
"have",
"metadata",
"customized",
".",
"Valid",
"keys",
"are",
"name",
"enabled",
"metadata",
"and",
"timeout",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/__init__.py#L171-L221 |
226,007 | RedHatInsights/insights-core | insights/contrib/ConfigParser.py | RawConfigParser._read | def _read(self, fp, fpname):
"""Parse a sectioned setup file.
The sections in setup file contains a title line at the top,
indicated by a name in square brackets (`[]'), plus key/value
options lines, indicated by `name: value' format lines.
Continuations are represented by an embedded newline then
leading whitespace. Blank lines, lines beginning with a '#',
and just about everything else are ignored.
"""
cursect = None # None, or a dictionary
optname = None
lineno = 0
e = None # None, or an exception
while True:
line = fp.readline()
if not line:
break
lineno = lineno + 1
# comment or blank line?
if line.strip() == '' or line[0] in '#;':
continue
if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
# no leading whitespace
continue
# continuation line?
if line[0].isspace() and cursect is not None and optname:
value = line.strip()
if value:
cursect[optname].append(value)
# a section header or option header?
else:
# is it a section header?
mo = self.SECTCRE.match(line)
if mo:
sectname = mo.group('header')
if sectname in self._sections:
cursect = self._sections[sectname]
elif sectname == DEFAULTSECT:
cursect = self._defaults
else:
cursect = self._dict()
cursect['__name__'] = sectname
self._sections[sectname] = cursect
# So sections can't start with a continuation line
optname = None
# no section header in the file?
elif cursect is None:
raise MissingSectionHeaderError(fpname, lineno, line)
# an option line?
else:
mo = self._optcre.match(line)
if mo:
optname, vi, optval = mo.group('option', 'vi', 'value')
optname = self.optionxform(optname.rstrip())
# This check is fine because the OPTCRE cannot
# match if it would set optval to None
if optval is not None:
if vi in ('=', ':') and ';' in optval:
# ';' is a comment delimiter only if it follows
# a spacing character
pos = optval.find(';')
if pos != -1 and optval[pos-1].isspace():
optval = optval[:pos]
optval = optval.strip()
# allow empty values
if optval == '""':
optval = ''
cursect[optname] = [optval]
else:
# valueless option handling
cursect[optname] = optval
else:
# a non-fatal parsing error occurred. set up the
# exception but keep going. the exception will be
# raised at the end of the file and will contain a
# list of all bogus lines
if not e:
e = ParsingError(fpname)
e.append(lineno, repr(line))
# if any parsing errors occurred, raise an exception
if e:
raise e
# join the multi-line values collected while reading
all_sections = [self._defaults]
all_sections.extend(self._sections.values())
for options in all_sections:
for name, val in options.items():
if isinstance(val, list):
options[name] = '\n'.join(val) | python | def _read(self, fp, fpname):
"""Parse a sectioned setup file.
The sections in setup file contains a title line at the top,
indicated by a name in square brackets (`[]'), plus key/value
options lines, indicated by `name: value' format lines.
Continuations are represented by an embedded newline then
leading whitespace. Blank lines, lines beginning with a '#',
and just about everything else are ignored.
"""
cursect = None # None, or a dictionary
optname = None
lineno = 0
e = None # None, or an exception
while True:
line = fp.readline()
if not line:
break
lineno = lineno + 1
# comment or blank line?
if line.strip() == '' or line[0] in '#;':
continue
if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
# no leading whitespace
continue
# continuation line?
if line[0].isspace() and cursect is not None and optname:
value = line.strip()
if value:
cursect[optname].append(value)
# a section header or option header?
else:
# is it a section header?
mo = self.SECTCRE.match(line)
if mo:
sectname = mo.group('header')
if sectname in self._sections:
cursect = self._sections[sectname]
elif sectname == DEFAULTSECT:
cursect = self._defaults
else:
cursect = self._dict()
cursect['__name__'] = sectname
self._sections[sectname] = cursect
# So sections can't start with a continuation line
optname = None
# no section header in the file?
elif cursect is None:
raise MissingSectionHeaderError(fpname, lineno, line)
# an option line?
else:
mo = self._optcre.match(line)
if mo:
optname, vi, optval = mo.group('option', 'vi', 'value')
optname = self.optionxform(optname.rstrip())
# This check is fine because the OPTCRE cannot
# match if it would set optval to None
if optval is not None:
if vi in ('=', ':') and ';' in optval:
# ';' is a comment delimiter only if it follows
# a spacing character
pos = optval.find(';')
if pos != -1 and optval[pos-1].isspace():
optval = optval[:pos]
optval = optval.strip()
# allow empty values
if optval == '""':
optval = ''
cursect[optname] = [optval]
else:
# valueless option handling
cursect[optname] = optval
else:
# a non-fatal parsing error occurred. set up the
# exception but keep going. the exception will be
# raised at the end of the file and will contain a
# list of all bogus lines
if not e:
e = ParsingError(fpname)
e.append(lineno, repr(line))
# if any parsing errors occurred, raise an exception
if e:
raise e
# join the multi-line values collected while reading
all_sections = [self._defaults]
all_sections.extend(self._sections.values())
for options in all_sections:
for name, val in options.items():
if isinstance(val, list):
options[name] = '\n'.join(val) | [
"def",
"_read",
"(",
"self",
",",
"fp",
",",
"fpname",
")",
":",
"cursect",
"=",
"None",
"# None, or a dictionary",
"optname",
"=",
"None",
"lineno",
"=",
"0",
"e",
"=",
"None",
"# None, or an exception",
"while",
"True",
":",
"line",
"=",
"fp",
".",
"re... | Parse a sectioned setup file.
The sections in setup file contains a title line at the top,
indicated by a name in square brackets (`[]'), plus key/value
options lines, indicated by `name: value' format lines.
Continuations are represented by an embedded newline then
leading whitespace. Blank lines, lines beginning with a '#',
and just about everything else are ignored. | [
"Parse",
"a",
"sectioned",
"setup",
"file",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/ConfigParser.py#L464-L554 |
226,008 | RedHatInsights/insights-core | insights/client/utilities.py | determine_hostname | def determine_hostname(display_name=None):
"""
Find fqdn if we can
"""
if display_name:
# if display_name is provided, just return the given name
return display_name
else:
socket_gethostname = socket.gethostname()
socket_fqdn = socket.getfqdn()
try:
socket_ex = socket.gethostbyname_ex(socket_gethostname)[0]
except (LookupError, socket.gaierror):
socket_ex = ''
gethostname_len = len(socket_gethostname)
fqdn_len = len(socket_fqdn)
ex_len = len(socket_ex)
if fqdn_len > gethostname_len or ex_len > gethostname_len:
if "localhost" not in socket_ex and len(socket_ex):
return socket_ex
if "localhost" not in socket_fqdn:
return socket_fqdn
return socket_gethostname | python | def determine_hostname(display_name=None):
"""
Find fqdn if we can
"""
if display_name:
# if display_name is provided, just return the given name
return display_name
else:
socket_gethostname = socket.gethostname()
socket_fqdn = socket.getfqdn()
try:
socket_ex = socket.gethostbyname_ex(socket_gethostname)[0]
except (LookupError, socket.gaierror):
socket_ex = ''
gethostname_len = len(socket_gethostname)
fqdn_len = len(socket_fqdn)
ex_len = len(socket_ex)
if fqdn_len > gethostname_len or ex_len > gethostname_len:
if "localhost" not in socket_ex and len(socket_ex):
return socket_ex
if "localhost" not in socket_fqdn:
return socket_fqdn
return socket_gethostname | [
"def",
"determine_hostname",
"(",
"display_name",
"=",
"None",
")",
":",
"if",
"display_name",
":",
"# if display_name is provided, just return the given name",
"return",
"display_name",
"else",
":",
"socket_gethostname",
"=",
"socket",
".",
"gethostname",
"(",
")",
"so... | Find fqdn if we can | [
"Find",
"fqdn",
"if",
"we",
"can"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/utilities.py#L21-L47 |
226,009 | RedHatInsights/insights-core | insights/client/utilities.py | write_unregistered_file | def write_unregistered_file(date=None):
"""
Write .unregistered out to disk
"""
delete_registered_file()
if date is None:
date = get_time()
for f in constants.unregistered_files:
if os.path.lexists(f):
if os.path.islink(f):
# kill symlinks and regenerate
os.remove(f)
write_to_disk(f, content=str(date))
else:
write_to_disk(f, content=str(date)) | python | def write_unregistered_file(date=None):
"""
Write .unregistered out to disk
"""
delete_registered_file()
if date is None:
date = get_time()
for f in constants.unregistered_files:
if os.path.lexists(f):
if os.path.islink(f):
# kill symlinks and regenerate
os.remove(f)
write_to_disk(f, content=str(date))
else:
write_to_disk(f, content=str(date)) | [
"def",
"write_unregistered_file",
"(",
"date",
"=",
"None",
")",
":",
"delete_registered_file",
"(",
")",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"get_time",
"(",
")",
"for",
"f",
"in",
"constants",
".",
"unregistered_files",
":",
"if",
"os",
".",
... | Write .unregistered out to disk | [
"Write",
".",
"unregistered",
"out",
"to",
"disk"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/utilities.py#L66-L80 |
226,010 | RedHatInsights/insights-core | insights/client/utilities.py | write_to_disk | def write_to_disk(filename, delete=False, content=get_time()):
"""
Write filename out to disk
"""
if not os.path.exists(os.path.dirname(filename)):
return
if delete:
if os.path.lexists(filename):
os.remove(filename)
else:
with open(filename, 'wb') as f:
f.write(content.encode('utf-8')) | python | def write_to_disk(filename, delete=False, content=get_time()):
"""
Write filename out to disk
"""
if not os.path.exists(os.path.dirname(filename)):
return
if delete:
if os.path.lexists(filename):
os.remove(filename)
else:
with open(filename, 'wb') as f:
f.write(content.encode('utf-8')) | [
"def",
"write_to_disk",
"(",
"filename",
",",
"delete",
"=",
"False",
",",
"content",
"=",
"get_time",
"(",
")",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
")",
":",
"retur... | Write filename out to disk | [
"Write",
"filename",
"out",
"to",
"disk"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/utilities.py#L93-L104 |
226,011 | RedHatInsights/insights-core | insights/client/utilities.py | _expand_paths | def _expand_paths(path):
"""
Expand wildcarded paths
"""
dir_name = os.path.dirname(path)
paths = []
logger.debug("Attempting to expand %s", path)
if os.path.isdir(dir_name):
files = os.listdir(dir_name)
match = os.path.basename(path)
for file_path in files:
if re.match(match, file_path):
expanded_path = os.path.join(dir_name, file_path)
paths.append(expanded_path)
logger.debug("Expanded paths %s", paths)
return paths
else:
logger.debug("Could not expand %s", path) | python | def _expand_paths(path):
"""
Expand wildcarded paths
"""
dir_name = os.path.dirname(path)
paths = []
logger.debug("Attempting to expand %s", path)
if os.path.isdir(dir_name):
files = os.listdir(dir_name)
match = os.path.basename(path)
for file_path in files:
if re.match(match, file_path):
expanded_path = os.path.join(dir_name, file_path)
paths.append(expanded_path)
logger.debug("Expanded paths %s", paths)
return paths
else:
logger.debug("Could not expand %s", path) | [
"def",
"_expand_paths",
"(",
"path",
")",
":",
"dir_name",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"paths",
"=",
"[",
"]",
"logger",
".",
"debug",
"(",
"\"Attempting to expand %s\"",
",",
"path",
")",
"if",
"os",
".",
"path",
".",
"... | Expand wildcarded paths | [
"Expand",
"wildcarded",
"paths"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/utilities.py#L129-L146 |
226,012 | RedHatInsights/insights-core | insights/client/utilities.py | validate_remove_file | def validate_remove_file(remove_file):
"""
Validate the remove file
"""
if not os.path.isfile(remove_file):
logger.warn("WARN: Remove file does not exist")
return False
# Make sure permissions are 600
mode = stat.S_IMODE(os.stat(remove_file).st_mode)
if not mode == 0o600:
logger.error("ERROR: Invalid remove file permissions"
"Expected 0600 got %s" % oct(mode))
return False
else:
logger.debug("Correct file permissions")
if os.path.isfile(remove_file):
parsedconfig = RawConfigParser()
parsedconfig.read(remove_file)
rm_conf = {}
for item, value in parsedconfig.items('remove'):
rm_conf[item] = value.strip().split(',')
# Using print here as this could contain sensitive information
logger.debug("Remove file parsed contents")
logger.debug(rm_conf)
logger.info("JSON parsed correctly")
return True | python | def validate_remove_file(remove_file):
"""
Validate the remove file
"""
if not os.path.isfile(remove_file):
logger.warn("WARN: Remove file does not exist")
return False
# Make sure permissions are 600
mode = stat.S_IMODE(os.stat(remove_file).st_mode)
if not mode == 0o600:
logger.error("ERROR: Invalid remove file permissions"
"Expected 0600 got %s" % oct(mode))
return False
else:
logger.debug("Correct file permissions")
if os.path.isfile(remove_file):
parsedconfig = RawConfigParser()
parsedconfig.read(remove_file)
rm_conf = {}
for item, value in parsedconfig.items('remove'):
rm_conf[item] = value.strip().split(',')
# Using print here as this could contain sensitive information
logger.debug("Remove file parsed contents")
logger.debug(rm_conf)
logger.info("JSON parsed correctly")
return True | [
"def",
"validate_remove_file",
"(",
"remove_file",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"remove_file",
")",
":",
"logger",
".",
"warn",
"(",
"\"WARN: Remove file does not exist\"",
")",
"return",
"False",
"# Make sure permissions are 600",
... | Validate the remove file | [
"Validate",
"the",
"remove",
"file"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/utilities.py#L149-L175 |
226,013 | RedHatInsights/insights-core | insights/client/utilities.py | write_data_to_file | def write_data_to_file(data, filepath):
'''
Write data to file
'''
try:
os.makedirs(os.path.dirname(filepath), 0o700)
except OSError:
pass
write_to_disk(filepath, content=data) | python | def write_data_to_file(data, filepath):
'''
Write data to file
'''
try:
os.makedirs(os.path.dirname(filepath), 0o700)
except OSError:
pass
write_to_disk(filepath, content=data) | [
"def",
"write_data_to_file",
"(",
"data",
",",
"filepath",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filepath",
")",
",",
"0o700",
")",
"except",
"OSError",
":",
"pass",
"write_to_disk",
"(",
"filepath",
... | Write data to file | [
"Write",
"data",
"to",
"file"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/utilities.py#L178-L187 |
226,014 | RedHatInsights/insights-core | insights/client/utilities.py | magic_plan_b | def magic_plan_b(filename):
'''
Use this in instances where
python-magic is MIA and can't be installed
for whatever reason
'''
cmd = shlex.split('file --mime-type --mime-encoding ' + filename)
stdout, stderr = Popen(cmd, stdout=PIPE).communicate()
stdout = stdout.decode("utf-8")
mime_str = stdout.split(filename + ': ')[1].strip()
return mime_str | python | def magic_plan_b(filename):
'''
Use this in instances where
python-magic is MIA and can't be installed
for whatever reason
'''
cmd = shlex.split('file --mime-type --mime-encoding ' + filename)
stdout, stderr = Popen(cmd, stdout=PIPE).communicate()
stdout = stdout.decode("utf-8")
mime_str = stdout.split(filename + ': ')[1].strip()
return mime_str | [
"def",
"magic_plan_b",
"(",
"filename",
")",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"'file --mime-type --mime-encoding '",
"+",
"filename",
")",
"stdout",
",",
"stderr",
"=",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"PIPE",
")",
".",
"communicate",
"... | Use this in instances where
python-magic is MIA and can't be installed
for whatever reason | [
"Use",
"this",
"in",
"instances",
"where",
"python",
"-",
"magic",
"is",
"MIA",
"and",
"can",
"t",
"be",
"installed",
"for",
"whatever",
"reason"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/utilities.py#L190-L200 |
226,015 | RedHatInsights/insights-core | insights/client/utilities.py | modify_config_file | def modify_config_file(updates):
'''
Update the config file with certain things
'''
cmd = '/bin/sed '
for key in updates:
cmd = cmd + '-e \'s/^#*{key}.*=.*$/{key}={value}/\' '.format(key=key, value=updates[key])
cmd = cmd + constants.default_conf_file
status = run_command_get_output(cmd)
write_to_disk(constants.default_conf_file, content=status['output']) | python | def modify_config_file(updates):
'''
Update the config file with certain things
'''
cmd = '/bin/sed '
for key in updates:
cmd = cmd + '-e \'s/^#*{key}.*=.*$/{key}={value}/\' '.format(key=key, value=updates[key])
cmd = cmd + constants.default_conf_file
status = run_command_get_output(cmd)
write_to_disk(constants.default_conf_file, content=status['output']) | [
"def",
"modify_config_file",
"(",
"updates",
")",
":",
"cmd",
"=",
"'/bin/sed '",
"for",
"key",
"in",
"updates",
":",
"cmd",
"=",
"cmd",
"+",
"'-e \\'s/^#*{key}.*=.*$/{key}={value}/\\' '",
".",
"format",
"(",
"key",
"=",
"key",
",",
"value",
"=",
"updates",
... | Update the config file with certain things | [
"Update",
"the",
"config",
"file",
"with",
"certain",
"things"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/utilities.py#L214-L223 |
226,016 | RedHatInsights/insights-core | insights/parsers/ps.py | Ps.users | def users(self, proc):
"""
Searches for all users running a given command.
Returns:
dict: each username as a key to a list of PIDs (as strings) that
are running the given process.
``{}`` if neither ``USER`` nor ``UID`` is found or ``proc`` is not found.
.. note::
'proc' must match the entire command and arguments.
"""
ret = {}
if self.first_column in ['USER', 'UID']:
for row in self.data:
if proc == row[self.command_name]:
if row[self.first_column] not in ret:
ret[row[self.first_column]] = []
ret[row[self.first_column]].append(row["PID"])
return ret | python | def users(self, proc):
"""
Searches for all users running a given command.
Returns:
dict: each username as a key to a list of PIDs (as strings) that
are running the given process.
``{}`` if neither ``USER`` nor ``UID`` is found or ``proc`` is not found.
.. note::
'proc' must match the entire command and arguments.
"""
ret = {}
if self.first_column in ['USER', 'UID']:
for row in self.data:
if proc == row[self.command_name]:
if row[self.first_column] not in ret:
ret[row[self.first_column]] = []
ret[row[self.first_column]].append(row["PID"])
return ret | [
"def",
"users",
"(",
"self",
",",
"proc",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"self",
".",
"first_column",
"in",
"[",
"'USER'",
",",
"'UID'",
"]",
":",
"for",
"row",
"in",
"self",
".",
"data",
":",
"if",
"proc",
"==",
"row",
"[",
"self",
".",... | Searches for all users running a given command.
Returns:
dict: each username as a key to a list of PIDs (as strings) that
are running the given process.
``{}`` if neither ``USER`` nor ``UID`` is found or ``proc`` is not found.
.. note::
'proc' must match the entire command and arguments. | [
"Searches",
"for",
"all",
"users",
"running",
"a",
"given",
"command",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/ps.py#L104-L123 |
226,017 | RedHatInsights/insights-core | insights/parsers/ps.py | Ps.fuzzy_match | def fuzzy_match(self, proc):
"""
Are there any commands that contain the given text?
Returns:
boolean: ``True`` if the word ``proc`` appears in the command column.
.. note::
'proc' can match anywhere in the command path, name or arguments.
"""
return any(proc in row[self.command_name] for row in self.data) | python | def fuzzy_match(self, proc):
"""
Are there any commands that contain the given text?
Returns:
boolean: ``True`` if the word ``proc`` appears in the command column.
.. note::
'proc' can match anywhere in the command path, name or arguments.
"""
return any(proc in row[self.command_name] for row in self.data) | [
"def",
"fuzzy_match",
"(",
"self",
",",
"proc",
")",
":",
"return",
"any",
"(",
"proc",
"in",
"row",
"[",
"self",
".",
"command_name",
"]",
"for",
"row",
"in",
"self",
".",
"data",
")"
] | Are there any commands that contain the given text?
Returns:
boolean: ``True`` if the word ``proc`` appears in the command column.
.. note::
'proc' can match anywhere in the command path, name or arguments. | [
"Are",
"there",
"any",
"commands",
"that",
"contain",
"the",
"given",
"text?"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/ps.py#L125-L135 |
226,018 | RedHatInsights/insights-core | insights/parsers/ps.py | Ps.number_occurences | def number_occurences(self, proc):
"""
Returns the number of occurencies of commands that contain given text
Returns:
int: The number of occurencies of commands with given text
.. note::
'proc' can match anywhere in the command path, name or arguments.
"""
return len([True for row in self.data if proc in row[self.command_name]]) | python | def number_occurences(self, proc):
"""
Returns the number of occurencies of commands that contain given text
Returns:
int: The number of occurencies of commands with given text
.. note::
'proc' can match anywhere in the command path, name or arguments.
"""
return len([True for row in self.data if proc in row[self.command_name]]) | [
"def",
"number_occurences",
"(",
"self",
",",
"proc",
")",
":",
"return",
"len",
"(",
"[",
"True",
"for",
"row",
"in",
"self",
".",
"data",
"if",
"proc",
"in",
"row",
"[",
"self",
".",
"command_name",
"]",
"]",
")"
] | Returns the number of occurencies of commands that contain given text
Returns:
int: The number of occurencies of commands with given text
.. note::
'proc' can match anywhere in the command path, name or arguments. | [
"Returns",
"the",
"number",
"of",
"occurencies",
"of",
"commands",
"that",
"contain",
"given",
"text"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/ps.py#L137-L147 |
226,019 | RedHatInsights/insights-core | insights/parsers/journald_conf.py | JournaldConf.parse_content | def parse_content(self, content):
"""
Main parsing class method which stores all interesting data from the content.
Args:
content (context.content): Parser context content
"""
# note, the Parser class sets:
# * self.file_path = context.path and
# * self.file_name = os.path.basename(context.path)
self.active_lines_unparsed = get_active_lines(content) if content is not None else []
# (man page shows all options with "=")
self.active_settings = split_kv_pairs(content, use_partition=False) if content is not None else [] | python | def parse_content(self, content):
"""
Main parsing class method which stores all interesting data from the content.
Args:
content (context.content): Parser context content
"""
# note, the Parser class sets:
# * self.file_path = context.path and
# * self.file_name = os.path.basename(context.path)
self.active_lines_unparsed = get_active_lines(content) if content is not None else []
# (man page shows all options with "=")
self.active_settings = split_kv_pairs(content, use_partition=False) if content is not None else [] | [
"def",
"parse_content",
"(",
"self",
",",
"content",
")",
":",
"# note, the Parser class sets:",
"# * self.file_path = context.path and",
"# * self.file_name = os.path.basename(context.path)",
"self",
".",
"active_lines_unparsed",
"=",
"get_active_lines",
"(",
"content",
")",
"... | Main parsing class method which stores all interesting data from the content.
Args:
content (context.content): Parser context content | [
"Main",
"parsing",
"class",
"method",
"which",
"stores",
"all",
"interesting",
"data",
"from",
"the",
"content",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/journald_conf.py#L54-L66 |
226,020 | RedHatInsights/insights-core | examples/cluster_rules/allnodes_cpu.py | cluster_info | def cluster_info(cpu, cfg):
"""
Collects fact for each host
Collects the cpu and node configuration facts to be used by the rule.
Arguments:
cpu (CpuInfo): Parser object for the cpu info.
cfg (NodeConfig): Parser object for the node configuration.
Returns:
dict: Dictionary of fact information including the keys
``cpu_count``, ``pods_per_core_int``, ``pods_per_core_customized``,
``max_pods``, and ``max_pods_customized``.
"""
cpus = cpu.cpu_count
pods_per_core = cfg.doc.find("pods-per-core")
pods_per_core_int = int(pods_per_core.value) if pods_per_core else PODS_PER_CORE
cfg_max_pods = cfg.doc.find("max-pods")
cfg_max_pods_int = int(cfg_max_pods.value) if cfg_max_pods else MAX_PODS
calc_max_pods = cpus * pods_per_core_int
return {
"cpu_count": cpus,
"pods_per_core": pods_per_core_int,
"pods_per_core_customized": bool(pods_per_core),
"max_pods": min(cfg_max_pods_int, calc_max_pods),
"max_pods_customized": bool(cfg_max_pods)
} | python | def cluster_info(cpu, cfg):
"""
Collects fact for each host
Collects the cpu and node configuration facts to be used by the rule.
Arguments:
cpu (CpuInfo): Parser object for the cpu info.
cfg (NodeConfig): Parser object for the node configuration.
Returns:
dict: Dictionary of fact information including the keys
``cpu_count``, ``pods_per_core_int``, ``pods_per_core_customized``,
``max_pods``, and ``max_pods_customized``.
"""
cpus = cpu.cpu_count
pods_per_core = cfg.doc.find("pods-per-core")
pods_per_core_int = int(pods_per_core.value) if pods_per_core else PODS_PER_CORE
cfg_max_pods = cfg.doc.find("max-pods")
cfg_max_pods_int = int(cfg_max_pods.value) if cfg_max_pods else MAX_PODS
calc_max_pods = cpus * pods_per_core_int
return {
"cpu_count": cpus,
"pods_per_core": pods_per_core_int,
"pods_per_core_customized": bool(pods_per_core),
"max_pods": min(cfg_max_pods_int, calc_max_pods),
"max_pods_customized": bool(cfg_max_pods)
} | [
"def",
"cluster_info",
"(",
"cpu",
",",
"cfg",
")",
":",
"cpus",
"=",
"cpu",
".",
"cpu_count",
"pods_per_core",
"=",
"cfg",
".",
"doc",
".",
"find",
"(",
"\"pods-per-core\"",
")",
"pods_per_core_int",
"=",
"int",
"(",
"pods_per_core",
".",
"value",
")",
... | Collects fact for each host
Collects the cpu and node configuration facts to be used by the rule.
Arguments:
cpu (CpuInfo): Parser object for the cpu info.
cfg (NodeConfig): Parser object for the node configuration.
Returns:
dict: Dictionary of fact information including the keys
``cpu_count``, ``pods_per_core_int``, ``pods_per_core_customized``,
``max_pods``, and ``max_pods_customized``. | [
"Collects",
"fact",
"for",
"each",
"host"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/examples/cluster_rules/allnodes_cpu.py#L53-L81 |
226,021 | RedHatInsights/insights-core | examples/cluster_rules/allnodes_cpu.py | master_etcd | def master_etcd(info, meta, max_pod_cluster, label):
""" Function used to create the response for all master node types """
nodes = meta.get(label, []) or []
info = info[info["machine_id"].isin(nodes)]
if info.empty:
return
cpu_factor = max_pod_cluster / 1000.0
nocpu_expected = MASTER_MIN_CORE + (max_pod_cluster / 1000.0)
bad = info[info["cpu_count"] < nocpu_expected]
good = info[info["cpu_count"] >= nocpu_expected]
return make_response("MASTER_ETCD",
nocpu_expected=nocpu_expected, cpu_factor=cpu_factor,
bad=bad, good=good, max_pod_cluster=max_pod_cluster,
GREEN=Fore.GREEN, RED=Fore.RED, YELLOW=Fore.YELLOW, NC=Style.RESET_ALL) | python | def master_etcd(info, meta, max_pod_cluster, label):
""" Function used to create the response for all master node types """
nodes = meta.get(label, []) or []
info = info[info["machine_id"].isin(nodes)]
if info.empty:
return
cpu_factor = max_pod_cluster / 1000.0
nocpu_expected = MASTER_MIN_CORE + (max_pod_cluster / 1000.0)
bad = info[info["cpu_count"] < nocpu_expected]
good = info[info["cpu_count"] >= nocpu_expected]
return make_response("MASTER_ETCD",
nocpu_expected=nocpu_expected, cpu_factor=cpu_factor,
bad=bad, good=good, max_pod_cluster=max_pod_cluster,
GREEN=Fore.GREEN, RED=Fore.RED, YELLOW=Fore.YELLOW, NC=Style.RESET_ALL) | [
"def",
"master_etcd",
"(",
"info",
",",
"meta",
",",
"max_pod_cluster",
",",
"label",
")",
":",
"nodes",
"=",
"meta",
".",
"get",
"(",
"label",
",",
"[",
"]",
")",
"or",
"[",
"]",
"info",
"=",
"info",
"[",
"info",
"[",
"\"machine_id\"",
"]",
".",
... | Function used to create the response for all master node types | [
"Function",
"used",
"to",
"create",
"the",
"response",
"for",
"all",
"master",
"node",
"types"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/examples/cluster_rules/allnodes_cpu.py#L84-L98 |
226,022 | RedHatInsights/insights-core | examples/cluster_rules/allnodes_cpu.py | infra_nodes | def infra_nodes(info, meta, max_pod_cluster, label, key):
""" Function used to create the response for all infra node types """
nodes = meta.get(label, []) or []
infos = info[info["machine_id"].isin(nodes)]
if infos.empty:
return
return make_response(key, max_pod_cluster=max_pod_cluster, infos=infos,
GREEN=Fore.GREEN, RED=Fore.RED, YELLOW=Fore.YELLOW, NC=Style.RESET_ALL) | python | def infra_nodes(info, meta, max_pod_cluster, label, key):
""" Function used to create the response for all infra node types """
nodes = meta.get(label, []) or []
infos = info[info["machine_id"].isin(nodes)]
if infos.empty:
return
return make_response(key, max_pod_cluster=max_pod_cluster, infos=infos,
GREEN=Fore.GREEN, RED=Fore.RED, YELLOW=Fore.YELLOW, NC=Style.RESET_ALL) | [
"def",
"infra_nodes",
"(",
"info",
",",
"meta",
",",
"max_pod_cluster",
",",
"label",
",",
"key",
")",
":",
"nodes",
"=",
"meta",
".",
"get",
"(",
"label",
",",
"[",
"]",
")",
"or",
"[",
"]",
"infos",
"=",
"info",
"[",
"info",
"[",
"\"machine_id\""... | Function used to create the response for all infra node types | [
"Function",
"used",
"to",
"create",
"the",
"response",
"for",
"all",
"infra",
"node",
"types"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/examples/cluster_rules/allnodes_cpu.py#L101-L108 |
226,023 | RedHatInsights/insights-core | insights/parsers/df.py | parse_df_lines | def parse_df_lines(df_content):
"""Parse contents of each line in ``df`` output.
Parse each line of ``df`` output ensuring that wrapped lines are
reassembled prior to parsing, and that mount names containing spaces
are maintained.
Parameters:
df_content (list): Lines of df output to be parsed.
Returns:
list: A list of ``Record`` ``namedtuple``'s. One for each line of the
``df`` output with columns as the key values. The fields of
``Record`` provide information about the file system attributes
as determined by the arguments to the ``df`` command. So, for
example, if ``df`` is given the ``-alP``, the values are in
terms of 1024 blocks. If ``-li`` is given, then the values are
in terms of inodes::
- filesystem: Name of the filesystem
- total: total number of resources on the filesystem
- used: number of the resources used on the filesystem
- available: number of the resource available on the filesystem
- capacity: percentage of the resource used on the filesystem
- mounted_on: mount point of the filesystem
"""
df_ls = {}
df_out = []
is_sep = False
columns = Record._fields
for line in df_content[1:]: # [1:] -> Skip the header
# Stop at 5 splits to avoid splitting spaces in path
line_splits = line.rstrip().split(None, 5)
if len(line_splits) >= 6:
for i, name in enumerate(columns):
df_ls[name] = line_splits[i]
is_sep = False
elif len(line_splits) == 1:
# First line of the separated line
df_ls[columns[0]] = line_splits[0]
is_sep = True
elif is_sep and len(line_splits) >= 5:
# Re-split to avoid this kind of "Mounted on": "VMware Tools"
line_splits = line.split(None, 4)
# Last line of the separated line
for i, name in enumerate(columns[1:]):
df_ls[name] = line_splits[i]
is_sep = False
elif not line_splits: # Skip empty lines (might in sosreport)
continue
else:
raise ParseException("Could not parse line '{l}'".format(l=line))
# Only add this record if we've got a line and it's not separated
if df_ls and not is_sep:
rec = Record(**df_ls)
df_out.append(rec)
df_ls = {}
return df_out | python | def parse_df_lines(df_content):
"""Parse contents of each line in ``df`` output.
Parse each line of ``df`` output ensuring that wrapped lines are
reassembled prior to parsing, and that mount names containing spaces
are maintained.
Parameters:
df_content (list): Lines of df output to be parsed.
Returns:
list: A list of ``Record`` ``namedtuple``'s. One for each line of the
``df`` output with columns as the key values. The fields of
``Record`` provide information about the file system attributes
as determined by the arguments to the ``df`` command. So, for
example, if ``df`` is given the ``-alP``, the values are in
terms of 1024 blocks. If ``-li`` is given, then the values are
in terms of inodes::
- filesystem: Name of the filesystem
- total: total number of resources on the filesystem
- used: number of the resources used on the filesystem
- available: number of the resource available on the filesystem
- capacity: percentage of the resource used on the filesystem
- mounted_on: mount point of the filesystem
"""
df_ls = {}
df_out = []
is_sep = False
columns = Record._fields
for line in df_content[1:]: # [1:] -> Skip the header
# Stop at 5 splits to avoid splitting spaces in path
line_splits = line.rstrip().split(None, 5)
if len(line_splits) >= 6:
for i, name in enumerate(columns):
df_ls[name] = line_splits[i]
is_sep = False
elif len(line_splits) == 1:
# First line of the separated line
df_ls[columns[0]] = line_splits[0]
is_sep = True
elif is_sep and len(line_splits) >= 5:
# Re-split to avoid this kind of "Mounted on": "VMware Tools"
line_splits = line.split(None, 4)
# Last line of the separated line
for i, name in enumerate(columns[1:]):
df_ls[name] = line_splits[i]
is_sep = False
elif not line_splits: # Skip empty lines (might in sosreport)
continue
else:
raise ParseException("Could not parse line '{l}'".format(l=line))
# Only add this record if we've got a line and it's not separated
if df_ls and not is_sep:
rec = Record(**df_ls)
df_out.append(rec)
df_ls = {}
return df_out | [
"def",
"parse_df_lines",
"(",
"df_content",
")",
":",
"df_ls",
"=",
"{",
"}",
"df_out",
"=",
"[",
"]",
"is_sep",
"=",
"False",
"columns",
"=",
"Record",
".",
"_fields",
"for",
"line",
"in",
"df_content",
"[",
"1",
":",
"]",
":",
"# [1:] -> Skip the heade... | Parse contents of each line in ``df`` output.
Parse each line of ``df`` output ensuring that wrapped lines are
reassembled prior to parsing, and that mount names containing spaces
are maintained.
Parameters:
df_content (list): Lines of df output to be parsed.
Returns:
list: A list of ``Record`` ``namedtuple``'s. One for each line of the
``df`` output with columns as the key values. The fields of
``Record`` provide information about the file system attributes
as determined by the arguments to the ``df`` command. So, for
example, if ``df`` is given the ``-alP``, the values are in
terms of 1024 blocks. If ``-li`` is given, then the values are
in terms of inodes::
- filesystem: Name of the filesystem
- total: total number of resources on the filesystem
- used: number of the resources used on the filesystem
- available: number of the resource available on the filesystem
- capacity: percentage of the resource used on the filesystem
- mounted_on: mount point of the filesystem | [
"Parse",
"contents",
"of",
"each",
"line",
"in",
"df",
"output",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/df.py#L68-L125 |
226,024 | RedHatInsights/insights-core | insights/parsers/system_time.py | NTPConfParser.get_param | def get_param(self, keyword, param=None, default=None):
"""
Get all the parameters for a given keyword, or default if keyword or
parameter are not present in the configuration.
This finds every declaration of the given parameter (which is the
one which takes effect). If no parameter is given, then the entire
line is treated as the parameter. There is always at least one
element returned - the default, or
Parameters:
keyword(str): The keyword name, e.g. 'tinker' or 'driftfile'
param(str): The parameter name, e.g. 'panic' or 'step'. If not
given, all the definitions of that keyword are given.
default(str): The default (singular) value if the keyword or
parameter is not found. If not given, None is used.
Returns:
list: All the values of the given parameter, or an empty list if
not found.
"""
if not keyword or keyword not in self.data:
return [default]
# keyword in data - if no value, we store None, so return that in a list
if self.data[keyword] is None:
return [None]
# If we're not searching for a particular parameter, just return all
# the values for this keyword.
if not param:
return self.data[keyword]
found = []
for line in self.data[keyword]:
# Line has already had keyword removed.
words = line.strip().split()
if len(words) > 1:
# Line has param and value - check param:
if words[0] == param:
found.append(words[1])
else:
found.append(words[0])
if found == []:
return [default]
else:
return found | python | def get_param(self, keyword, param=None, default=None):
"""
Get all the parameters for a given keyword, or default if keyword or
parameter are not present in the configuration.
This finds every declaration of the given parameter (which is the
one which takes effect). If no parameter is given, then the entire
line is treated as the parameter. There is always at least one
element returned - the default, or
Parameters:
keyword(str): The keyword name, e.g. 'tinker' or 'driftfile'
param(str): The parameter name, e.g. 'panic' or 'step'. If not
given, all the definitions of that keyword are given.
default(str): The default (singular) value if the keyword or
parameter is not found. If not given, None is used.
Returns:
list: All the values of the given parameter, or an empty list if
not found.
"""
if not keyword or keyword not in self.data:
return [default]
# keyword in data - if no value, we store None, so return that in a list
if self.data[keyword] is None:
return [None]
# If we're not searching for a particular parameter, just return all
# the values for this keyword.
if not param:
return self.data[keyword]
found = []
for line in self.data[keyword]:
# Line has already had keyword removed.
words = line.strip().split()
if len(words) > 1:
# Line has param and value - check param:
if words[0] == param:
found.append(words[1])
else:
found.append(words[0])
if found == []:
return [default]
else:
return found | [
"def",
"get_param",
"(",
"self",
",",
"keyword",
",",
"param",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"keyword",
"or",
"keyword",
"not",
"in",
"self",
".",
"data",
":",
"return",
"[",
"default",
"]",
"# keyword in data - if no v... | Get all the parameters for a given keyword, or default if keyword or
parameter are not present in the configuration.
This finds every declaration of the given parameter (which is the
one which takes effect). If no parameter is given, then the entire
line is treated as the parameter. There is always at least one
element returned - the default, or
Parameters:
keyword(str): The keyword name, e.g. 'tinker' or 'driftfile'
param(str): The parameter name, e.g. 'panic' or 'step'. If not
given, all the definitions of that keyword are given.
default(str): The default (singular) value if the keyword or
parameter is not found. If not given, None is used.
Returns:
list: All the values of the given parameter, or an empty list if
not found. | [
"Get",
"all",
"the",
"parameters",
"for",
"a",
"given",
"keyword",
"or",
"default",
"if",
"keyword",
"or",
"parameter",
"are",
"not",
"present",
"in",
"the",
"configuration",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/system_time.py#L89-L133 |
226,025 | RedHatInsights/insights-core | insights/parsers/system_time.py | NTPConfParser.get_last | def get_last(self, keyword, param=None, default=None):
"""
Get the parameters for a given keyword, or default if keyword or
parameter are not present in the configuration.
This finds the last declaration of the given parameter (which is the
one which takes effect). If no parameter is given, then the entire
line is treated as the parameter and returned.
Parameters:
keyword(str): The keyword name, e.g. 'tinker' or 'driftfile'
param(str): The parameter name, e.g. 'panic' or 'step'. If not
given, the last definition of that keyword is given.
Returns:
str or None: The value of the given parameter, or None if not
found.
"""
return self.get_param(keyword, param, default)[-1] | python | def get_last(self, keyword, param=None, default=None):
"""
Get the parameters for a given keyword, or default if keyword or
parameter are not present in the configuration.
This finds the last declaration of the given parameter (which is the
one which takes effect). If no parameter is given, then the entire
line is treated as the parameter and returned.
Parameters:
keyword(str): The keyword name, e.g. 'tinker' or 'driftfile'
param(str): The parameter name, e.g. 'panic' or 'step'. If not
given, the last definition of that keyword is given.
Returns:
str or None: The value of the given parameter, or None if not
found.
"""
return self.get_param(keyword, param, default)[-1] | [
"def",
"get_last",
"(",
"self",
",",
"keyword",
",",
"param",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_param",
"(",
"keyword",
",",
"param",
",",
"default",
")",
"[",
"-",
"1",
"]"
] | Get the parameters for a given keyword, or default if keyword or
parameter are not present in the configuration.
This finds the last declaration of the given parameter (which is the
one which takes effect). If no parameter is given, then the entire
line is treated as the parameter and returned.
Parameters:
keyword(str): The keyword name, e.g. 'tinker' or 'driftfile'
param(str): The parameter name, e.g. 'panic' or 'step'. If not
given, the last definition of that keyword is given.
Returns:
str or None: The value of the given parameter, or None if not
found. | [
"Get",
"the",
"parameters",
"for",
"a",
"given",
"keyword",
"or",
"default",
"if",
"keyword",
"or",
"parameter",
"are",
"not",
"present",
"in",
"the",
"configuration",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/system_time.py#L135-L153 |
226,026 | RedHatInsights/insights-core | insights/parsers/rhn_schema_stats.py | _replace_tabs | def _replace_tabs(s, ts=8):
"""
Replace the tabs in 's' and keep its original alignment with the tab-stop
equals to 'ts'
"""
result = ''
for c in s:
if c == '\t':
while True:
result += ' '
if len(result) % ts == 0:
break
else:
result += c
return result | python | def _replace_tabs(s, ts=8):
"""
Replace the tabs in 's' and keep its original alignment with the tab-stop
equals to 'ts'
"""
result = ''
for c in s:
if c == '\t':
while True:
result += ' '
if len(result) % ts == 0:
break
else:
result += c
return result | [
"def",
"_replace_tabs",
"(",
"s",
",",
"ts",
"=",
"8",
")",
":",
"result",
"=",
"''",
"for",
"c",
"in",
"s",
":",
"if",
"c",
"==",
"'\\t'",
":",
"while",
"True",
":",
"result",
"+=",
"' '",
"if",
"len",
"(",
"result",
")",
"%",
"ts",
"==",
"0... | Replace the tabs in 's' and keep its original alignment with the tab-stop
equals to 'ts' | [
"Replace",
"the",
"tabs",
"in",
"s",
"and",
"keep",
"its",
"original",
"alignment",
"with",
"the",
"tab",
"-",
"stop",
"equals",
"to",
"ts"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/rhn_schema_stats.py#L6-L20 |
226,027 | RedHatInsights/insights-core | insights/core/archives.py | extract | def extract(path, timeout=None, extract_dir=None, content_type=None):
"""
Extract path into a temporary directory in `extract_dir`.
Yields an object containing the temporary path and the content type of the
original archive.
If the extraction takes longer than `timeout` seconds, the temporary path
is removed, and an exception is raised.
"""
content_type = content_type or content_type_from_file(path)
if content_type == "application/zip":
extractor = ZipExtractor(timeout=timeout)
else:
extractor = TarExtractor(timeout=timeout)
try:
ctx = extractor.from_path(path, extract_dir=extract_dir, content_type=content_type)
content_type = extractor.content_type
yield Extraction(ctx.tmp_dir, content_type)
finally:
if extractor.created_tmp_dir:
fs.remove(extractor.tmp_dir, chmod=True) | python | def extract(path, timeout=None, extract_dir=None, content_type=None):
"""
Extract path into a temporary directory in `extract_dir`.
Yields an object containing the temporary path and the content type of the
original archive.
If the extraction takes longer than `timeout` seconds, the temporary path
is removed, and an exception is raised.
"""
content_type = content_type or content_type_from_file(path)
if content_type == "application/zip":
extractor = ZipExtractor(timeout=timeout)
else:
extractor = TarExtractor(timeout=timeout)
try:
ctx = extractor.from_path(path, extract_dir=extract_dir, content_type=content_type)
content_type = extractor.content_type
yield Extraction(ctx.tmp_dir, content_type)
finally:
if extractor.created_tmp_dir:
fs.remove(extractor.tmp_dir, chmod=True) | [
"def",
"extract",
"(",
"path",
",",
"timeout",
"=",
"None",
",",
"extract_dir",
"=",
"None",
",",
"content_type",
"=",
"None",
")",
":",
"content_type",
"=",
"content_type",
"or",
"content_type_from_file",
"(",
"path",
")",
"if",
"content_type",
"==",
"\"app... | Extract path into a temporary directory in `extract_dir`.
Yields an object containing the temporary path and the content type of the
original archive.
If the extraction takes longer than `timeout` seconds, the temporary path
is removed, and an exception is raised. | [
"Extract",
"path",
"into",
"a",
"temporary",
"directory",
"in",
"extract_dir",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/archives.py#L96-L118 |
226,028 | RedHatInsights/insights-core | examples/rules/sample_script.py | report | def report(rel):
"""Fires if the machine is running Fedora."""
if "Fedora" in rel.product:
return make_pass("IS_FEDORA", product=rel.product)
else:
return make_fail("IS_NOT_FEDORA", product=rel.product) | python | def report(rel):
"""Fires if the machine is running Fedora."""
if "Fedora" in rel.product:
return make_pass("IS_FEDORA", product=rel.product)
else:
return make_fail("IS_NOT_FEDORA", product=rel.product) | [
"def",
"report",
"(",
"rel",
")",
":",
"if",
"\"Fedora\"",
"in",
"rel",
".",
"product",
":",
"return",
"make_pass",
"(",
"\"IS_FEDORA\"",
",",
"product",
"=",
"rel",
".",
"product",
")",
"else",
":",
"return",
"make_fail",
"(",
"\"IS_NOT_FEDORA\"",
",",
... | Fires if the machine is running Fedora. | [
"Fires",
"if",
"the",
"machine",
"is",
"running",
"Fedora",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/examples/rules/sample_script.py#L24-L30 |
226,029 | RedHatInsights/insights-core | insights/parsers/crontab.py | _make_cron_re | def _make_cron_re():
"""
Make the regular expression that matches a crontab 'cron' line.
Each field has a set of allowed values, and can then be in a range, and be
listed with dashes. A range can be stepped with the '/' modifier, and
ranges can be in a list. A field can also be '*', or '*' divided in steps.
The best way to do this is to have a template for a single field that
encapsulates the syntax of that field, regardless of what that field
matches. We then fill in the actual template's value with the pattern
that matches that field. Each field is named, so we can pull them out as
a dictionary later.
"""
range_ = r"{val}(?:-{val}(?:/\d+)?)?"
template = r"(?P<{name}>" + "(?:\*(?:/\d+)?|{r}(?:,{r})*)".format(r=range_) + ")\s+"
return (
r'^\s*' +
template.format(name='minute', val=r'(?:\d|[012345]\d)') +
template.format(name='hour', val=r'(?:\d|[01]\d|2[0123])') +
template.format(name='day_of_month', val=r'(?:0?[1-9]|[12]\d|3[01])') +
template.format(name='month', val=r'(?:0?[1-9]|1[012]|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)') +
template.format(name='day_of_week', val=r'(?:[0-7]|mon|tue|wed|thur|fri|sat|sun)') +
r'(?P<command>\S.*)$'
) | python | def _make_cron_re():
"""
Make the regular expression that matches a crontab 'cron' line.
Each field has a set of allowed values, and can then be in a range, and be
listed with dashes. A range can be stepped with the '/' modifier, and
ranges can be in a list. A field can also be '*', or '*' divided in steps.
The best way to do this is to have a template for a single field that
encapsulates the syntax of that field, regardless of what that field
matches. We then fill in the actual template's value with the pattern
that matches that field. Each field is named, so we can pull them out as
a dictionary later.
"""
range_ = r"{val}(?:-{val}(?:/\d+)?)?"
template = r"(?P<{name}>" + "(?:\*(?:/\d+)?|{r}(?:,{r})*)".format(r=range_) + ")\s+"
return (
r'^\s*' +
template.format(name='minute', val=r'(?:\d|[012345]\d)') +
template.format(name='hour', val=r'(?:\d|[01]\d|2[0123])') +
template.format(name='day_of_month', val=r'(?:0?[1-9]|[12]\d|3[01])') +
template.format(name='month', val=r'(?:0?[1-9]|1[012]|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)') +
template.format(name='day_of_week', val=r'(?:[0-7]|mon|tue|wed|thur|fri|sat|sun)') +
r'(?P<command>\S.*)$'
) | [
"def",
"_make_cron_re",
"(",
")",
":",
"range_",
"=",
"r\"{val}(?:-{val}(?:/\\d+)?)?\"",
"template",
"=",
"r\"(?P<{name}>\"",
"+",
"\"(?:\\*(?:/\\d+)?|{r}(?:,{r})*)\"",
".",
"format",
"(",
"r",
"=",
"range_",
")",
"+",
"\")\\s+\"",
"return",
"(",
"r'^\\s*'",
"+",
... | Make the regular expression that matches a crontab 'cron' line.
Each field has a set of allowed values, and can then be in a range, and be
listed with dashes. A range can be stepped with the '/' modifier, and
ranges can be in a list. A field can also be '*', or '*' divided in steps.
The best way to do this is to have a template for a single field that
encapsulates the syntax of that field, regardless of what that field
matches. We then fill in the actual template's value with the pattern
that matches that field. Each field is named, so we can pull them out as
a dictionary later. | [
"Make",
"the",
"regular",
"expression",
"that",
"matches",
"a",
"crontab",
"cron",
"line",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/crontab.py#L8-L32 |
226,030 | RedHatInsights/insights-core | insights/client/auto_config.py | verify_connectivity | def verify_connectivity(config):
"""
Verify connectivity to satellite server
"""
logger.debug("Verifying Connectivity")
ic = InsightsConnection(config)
try:
branch_info = ic.get_branch_info()
except requests.ConnectionError as e:
logger.debug(e)
logger.debug("Failed to connect to satellite")
return False
except LookupError as e:
logger.debug(e)
logger.debug("Failed to parse response from satellite")
return False
try:
remote_leaf = branch_info['remote_leaf']
return remote_leaf
except LookupError as e:
logger.debug(e)
logger.debug("Failed to find accurate branch_info")
return False | python | def verify_connectivity(config):
"""
Verify connectivity to satellite server
"""
logger.debug("Verifying Connectivity")
ic = InsightsConnection(config)
try:
branch_info = ic.get_branch_info()
except requests.ConnectionError as e:
logger.debug(e)
logger.debug("Failed to connect to satellite")
return False
except LookupError as e:
logger.debug(e)
logger.debug("Failed to parse response from satellite")
return False
try:
remote_leaf = branch_info['remote_leaf']
return remote_leaf
except LookupError as e:
logger.debug(e)
logger.debug("Failed to find accurate branch_info")
return False | [
"def",
"verify_connectivity",
"(",
"config",
")",
":",
"logger",
".",
"debug",
"(",
"\"Verifying Connectivity\"",
")",
"ic",
"=",
"InsightsConnection",
"(",
"config",
")",
"try",
":",
"branch_info",
"=",
"ic",
".",
"get_branch_info",
"(",
")",
"except",
"reque... | Verify connectivity to satellite server | [
"Verify",
"connectivity",
"to",
"satellite",
"server"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/auto_config.py#L27-L50 |
226,031 | RedHatInsights/insights-core | insights/client/auto_config.py | set_auto_configuration | def set_auto_configuration(config, hostname, ca_cert, proxy, is_satellite):
"""
Set config based on discovered data
"""
logger.debug("Attempting to auto configure!")
logger.debug("Attempting to auto configure hostname: %s", hostname)
logger.debug("Attempting to auto configure CA cert: %s", ca_cert)
logger.debug("Attempting to auto configure proxy: %s", proxy)
saved_base_url = config.base_url
if ca_cert is not None:
saved_cert_verify = config.cert_verify
config.cert_verify = ca_cert
if proxy is not None:
saved_proxy = config.proxy
config.proxy = proxy
if is_satellite:
# satellite
config.base_url = hostname + '/r/insights'
if not config.legacy_upload:
config.base_url += '/platform'
logger.debug('Auto-configured base_url: %s', config.base_url)
else:
# connected directly to RHSM
if config.legacy_upload:
config.base_url = hostname + '/r/insights'
else:
config.base_url = hostname + '/api'
logger.debug('Auto-configured base_url: %s', config.base_url)
logger.debug('Not connected to Satellite, skipping branch_info')
# direct connection to RHSM, skip verify_connectivity
return
if not verify_connectivity(config):
logger.warn("Could not auto configure, falling back to static config")
logger.warn("See %s for additional information",
constants.default_log_file)
config.base_url = saved_base_url
if proxy is not None:
if saved_proxy is not None and saved_proxy.lower() == 'none':
saved_proxy = None
config.proxy = saved_proxy
if ca_cert is not None:
config.cert_verify = saved_cert_verify | python | def set_auto_configuration(config, hostname, ca_cert, proxy, is_satellite):
"""
Set config based on discovered data
"""
logger.debug("Attempting to auto configure!")
logger.debug("Attempting to auto configure hostname: %s", hostname)
logger.debug("Attempting to auto configure CA cert: %s", ca_cert)
logger.debug("Attempting to auto configure proxy: %s", proxy)
saved_base_url = config.base_url
if ca_cert is not None:
saved_cert_verify = config.cert_verify
config.cert_verify = ca_cert
if proxy is not None:
saved_proxy = config.proxy
config.proxy = proxy
if is_satellite:
# satellite
config.base_url = hostname + '/r/insights'
if not config.legacy_upload:
config.base_url += '/platform'
logger.debug('Auto-configured base_url: %s', config.base_url)
else:
# connected directly to RHSM
if config.legacy_upload:
config.base_url = hostname + '/r/insights'
else:
config.base_url = hostname + '/api'
logger.debug('Auto-configured base_url: %s', config.base_url)
logger.debug('Not connected to Satellite, skipping branch_info')
# direct connection to RHSM, skip verify_connectivity
return
if not verify_connectivity(config):
logger.warn("Could not auto configure, falling back to static config")
logger.warn("See %s for additional information",
constants.default_log_file)
config.base_url = saved_base_url
if proxy is not None:
if saved_proxy is not None and saved_proxy.lower() == 'none':
saved_proxy = None
config.proxy = saved_proxy
if ca_cert is not None:
config.cert_verify = saved_cert_verify | [
"def",
"set_auto_configuration",
"(",
"config",
",",
"hostname",
",",
"ca_cert",
",",
"proxy",
",",
"is_satellite",
")",
":",
"logger",
".",
"debug",
"(",
"\"Attempting to auto configure!\"",
")",
"logger",
".",
"debug",
"(",
"\"Attempting to auto configure hostname: ... | Set config based on discovered data | [
"Set",
"config",
"based",
"on",
"discovered",
"data"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/auto_config.py#L53-L95 |
226,032 | RedHatInsights/insights-core | insights/client/auto_config.py | _try_satellite6_configuration | def _try_satellite6_configuration(config):
"""
Try to autoconfigure for Satellite 6
"""
try:
rhsm_config = _importInitConfig()
logger.debug('Trying to autoconfigure...')
cert = open(rhsmCertificate.certpath(), 'r').read()
key = open(rhsmCertificate.keypath(), 'r').read()
rhsm = rhsmCertificate(key, cert)
is_satellite = False
# This will throw an exception if we are not registered
logger.debug('Checking if system is subscription-manager registered')
rhsm.getConsumerId()
logger.debug('System is subscription-manager registered')
rhsm_hostname = rhsm_config.get('server', 'hostname')
rhsm_hostport = rhsm_config.get('server', 'port')
rhsm_proxy_hostname = rhsm_config.get('server', 'proxy_hostname').strip()
rhsm_proxy_port = rhsm_config.get('server', 'proxy_port').strip()
rhsm_proxy_user = rhsm_config.get('server', 'proxy_user').strip()
rhsm_proxy_pass = rhsm_config.get('server', 'proxy_password').strip()
proxy = None
if rhsm_proxy_hostname != "":
logger.debug("Found rhsm_proxy_hostname %s", rhsm_proxy_hostname)
proxy = "http://"
if rhsm_proxy_user != "" and rhsm_proxy_pass != "":
logger.debug("Found user and password for rhsm_proxy")
proxy = proxy + rhsm_proxy_user + ":" + rhsm_proxy_pass + "@"
proxy = proxy + rhsm_proxy_hostname + ':' + rhsm_proxy_port
logger.debug("RHSM Proxy: %s", proxy)
logger.debug("Found %sHost: %s, Port: %s",
('' if _is_rhn_or_rhsm(rhsm_hostname)
else 'Satellite 6 Server '),
rhsm_hostname, rhsm_hostport)
rhsm_ca = rhsm_config.get('rhsm', 'repo_ca_cert')
logger.debug("Found CA: %s", rhsm_ca)
logger.debug("Setting authmethod to CERT")
config.authmethod = 'CERT'
# Directly connected to Red Hat, use cert auth directly with the api
if _is_rhn_or_rhsm(rhsm_hostname):
# URL changes. my favorite
if config.legacy_upload:
logger.debug("Connected to Red Hat Directly, using cert-api")
rhsm_hostname = 'cert-api.access.redhat.com'
else:
logger.debug("Connected to Red Hat Directly, using cloud.redhat.com")
rhsm_hostname = 'cloud.redhat.com'
rhsm_ca = None
else:
# Set the host path
# 'rhsm_hostname' should really be named ~ 'rhsm_host_base_url'
rhsm_hostname = rhsm_hostname + ':' + rhsm_hostport + '/redhat_access'
is_satellite = True
logger.debug("Trying to set auto_configuration")
set_auto_configuration(config, rhsm_hostname, rhsm_ca, proxy, is_satellite)
return True
except Exception as e:
logger.debug(e)
logger.debug('System is NOT subscription-manager registered')
return False | python | def _try_satellite6_configuration(config):
"""
Try to autoconfigure for Satellite 6
"""
try:
rhsm_config = _importInitConfig()
logger.debug('Trying to autoconfigure...')
cert = open(rhsmCertificate.certpath(), 'r').read()
key = open(rhsmCertificate.keypath(), 'r').read()
rhsm = rhsmCertificate(key, cert)
is_satellite = False
# This will throw an exception if we are not registered
logger.debug('Checking if system is subscription-manager registered')
rhsm.getConsumerId()
logger.debug('System is subscription-manager registered')
rhsm_hostname = rhsm_config.get('server', 'hostname')
rhsm_hostport = rhsm_config.get('server', 'port')
rhsm_proxy_hostname = rhsm_config.get('server', 'proxy_hostname').strip()
rhsm_proxy_port = rhsm_config.get('server', 'proxy_port').strip()
rhsm_proxy_user = rhsm_config.get('server', 'proxy_user').strip()
rhsm_proxy_pass = rhsm_config.get('server', 'proxy_password').strip()
proxy = None
if rhsm_proxy_hostname != "":
logger.debug("Found rhsm_proxy_hostname %s", rhsm_proxy_hostname)
proxy = "http://"
if rhsm_proxy_user != "" and rhsm_proxy_pass != "":
logger.debug("Found user and password for rhsm_proxy")
proxy = proxy + rhsm_proxy_user + ":" + rhsm_proxy_pass + "@"
proxy = proxy + rhsm_proxy_hostname + ':' + rhsm_proxy_port
logger.debug("RHSM Proxy: %s", proxy)
logger.debug("Found %sHost: %s, Port: %s",
('' if _is_rhn_or_rhsm(rhsm_hostname)
else 'Satellite 6 Server '),
rhsm_hostname, rhsm_hostport)
rhsm_ca = rhsm_config.get('rhsm', 'repo_ca_cert')
logger.debug("Found CA: %s", rhsm_ca)
logger.debug("Setting authmethod to CERT")
config.authmethod = 'CERT'
# Directly connected to Red Hat, use cert auth directly with the api
if _is_rhn_or_rhsm(rhsm_hostname):
# URL changes. my favorite
if config.legacy_upload:
logger.debug("Connected to Red Hat Directly, using cert-api")
rhsm_hostname = 'cert-api.access.redhat.com'
else:
logger.debug("Connected to Red Hat Directly, using cloud.redhat.com")
rhsm_hostname = 'cloud.redhat.com'
rhsm_ca = None
else:
# Set the host path
# 'rhsm_hostname' should really be named ~ 'rhsm_host_base_url'
rhsm_hostname = rhsm_hostname + ':' + rhsm_hostport + '/redhat_access'
is_satellite = True
logger.debug("Trying to set auto_configuration")
set_auto_configuration(config, rhsm_hostname, rhsm_ca, proxy, is_satellite)
return True
except Exception as e:
logger.debug(e)
logger.debug('System is NOT subscription-manager registered')
return False | [
"def",
"_try_satellite6_configuration",
"(",
"config",
")",
":",
"try",
":",
"rhsm_config",
"=",
"_importInitConfig",
"(",
")",
"logger",
".",
"debug",
"(",
"'Trying to autoconfigure...'",
")",
"cert",
"=",
"open",
"(",
"rhsmCertificate",
".",
"certpath",
"(",
"... | Try to autoconfigure for Satellite 6 | [
"Try",
"to",
"autoconfigure",
"for",
"Satellite",
"6"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/auto_config.py#L103-L169 |
226,033 | RedHatInsights/insights-core | insights/client/auto_config.py | _try_satellite5_configuration | def _try_satellite5_configuration(config):
"""
Attempt to determine Satellite 5 Configuration
"""
logger.debug("Trying Satellite 5 auto_config")
rhn_config = '/etc/sysconfig/rhn/up2date'
systemid = '/etc/sysconfig/rhn/systemid'
if os.path.isfile(rhn_config):
if os.path.isfile(systemid):
config.systemid = _read_systemid_file(systemid)
else:
logger.debug("Could not find Satellite 5 systemid file.")
return False
logger.debug("Found Satellite 5 Config")
rhn_conf_file = open(rhn_config, 'r')
hostname = None
for line in rhn_conf_file:
if line.startswith('serverURL='):
url = urlparse(line.split('=')[1])
hostname = url.netloc + '/redhat_access'
logger.debug("Found hostname %s", hostname)
if line.startswith('sslCACert='):
rhn_ca = line.strip().split('=')[1]
# Auto discover proxy stuff
if line.startswith('enableProxy='):
proxy_enabled = line.strip().split('=')[1]
if line.startswith('httpProxy='):
proxy_host_port = line.strip().split('=')[1]
if line.startswith('proxyUser='):
proxy_user = line.strip().split('=')[1]
if line.startswith('proxyPassword='):
proxy_password = line.strip().split('=')[1]
if hostname:
proxy = None
if proxy_enabled == "1":
proxy = "http://"
if proxy_user != "" and proxy_password != "":
logger.debug("Found user and password for rhn_proxy")
proxy = proxy + proxy_user + ':' + proxy_password
proxy = proxy + "@" + proxy_host_port
else:
proxy = proxy + proxy_host_port
logger.debug("RHN Proxy: %s", proxy)
set_auto_configuration(config, hostname, rhn_ca, proxy)
else:
logger.debug("Could not find hostname")
return False
return True
else:
logger.debug("Could not find rhn config")
return False | python | def _try_satellite5_configuration(config):
"""
Attempt to determine Satellite 5 Configuration
"""
logger.debug("Trying Satellite 5 auto_config")
rhn_config = '/etc/sysconfig/rhn/up2date'
systemid = '/etc/sysconfig/rhn/systemid'
if os.path.isfile(rhn_config):
if os.path.isfile(systemid):
config.systemid = _read_systemid_file(systemid)
else:
logger.debug("Could not find Satellite 5 systemid file.")
return False
logger.debug("Found Satellite 5 Config")
rhn_conf_file = open(rhn_config, 'r')
hostname = None
for line in rhn_conf_file:
if line.startswith('serverURL='):
url = urlparse(line.split('=')[1])
hostname = url.netloc + '/redhat_access'
logger.debug("Found hostname %s", hostname)
if line.startswith('sslCACert='):
rhn_ca = line.strip().split('=')[1]
# Auto discover proxy stuff
if line.startswith('enableProxy='):
proxy_enabled = line.strip().split('=')[1]
if line.startswith('httpProxy='):
proxy_host_port = line.strip().split('=')[1]
if line.startswith('proxyUser='):
proxy_user = line.strip().split('=')[1]
if line.startswith('proxyPassword='):
proxy_password = line.strip().split('=')[1]
if hostname:
proxy = None
if proxy_enabled == "1":
proxy = "http://"
if proxy_user != "" and proxy_password != "":
logger.debug("Found user and password for rhn_proxy")
proxy = proxy + proxy_user + ':' + proxy_password
proxy = proxy + "@" + proxy_host_port
else:
proxy = proxy + proxy_host_port
logger.debug("RHN Proxy: %s", proxy)
set_auto_configuration(config, hostname, rhn_ca, proxy)
else:
logger.debug("Could not find hostname")
return False
return True
else:
logger.debug("Could not find rhn config")
return False | [
"def",
"_try_satellite5_configuration",
"(",
"config",
")",
":",
"logger",
".",
"debug",
"(",
"\"Trying Satellite 5 auto_config\"",
")",
"rhn_config",
"=",
"'/etc/sysconfig/rhn/up2date'",
"systemid",
"=",
"'/etc/sysconfig/rhn/systemid'",
"if",
"os",
".",
"path",
".",
"i... | Attempt to determine Satellite 5 Configuration | [
"Attempt",
"to",
"determine",
"Satellite",
"5",
"Configuration"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/auto_config.py#L178-L231 |
226,034 | RedHatInsights/insights-core | insights/parsers/iptables.py | IPTablesConfiguration.get_chain | def get_chain(self, name, table="filter"):
"""
Get the list of rules for a particular chain. Chain order is kept intact.
Args:
name (str): chain name, e.g. ``
table (str): table name, defaults to ``filter``
Returns:
list: rules
"""
return [r for r in self.rules if r["table"] == table and r["chain"] == name] | python | def get_chain(self, name, table="filter"):
"""
Get the list of rules for a particular chain. Chain order is kept intact.
Args:
name (str): chain name, e.g. ``
table (str): table name, defaults to ``filter``
Returns:
list: rules
"""
return [r for r in self.rules if r["table"] == table and r["chain"] == name] | [
"def",
"get_chain",
"(",
"self",
",",
"name",
",",
"table",
"=",
"\"filter\"",
")",
":",
"return",
"[",
"r",
"for",
"r",
"in",
"self",
".",
"rules",
"if",
"r",
"[",
"\"table\"",
"]",
"==",
"table",
"and",
"r",
"[",
"\"chain\"",
"]",
"==",
"name",
... | Get the list of rules for a particular chain. Chain order is kept intact.
Args:
name (str): chain name, e.g. ``
table (str): table name, defaults to ``filter``
Returns:
list: rules | [
"Get",
"the",
"list",
"of",
"rules",
"for",
"a",
"particular",
"chain",
".",
"Chain",
"order",
"is",
"kept",
"intact",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/iptables.py#L127-L138 |
226,035 | RedHatInsights/insights-core | insights/parsers/iptables.py | IPTablesConfiguration.table_chains | def table_chains(self, table="filter"):
"""
Get a dict where the keys are all the chains for the given table
and each value is the set of rules defined for the given chain.
Args:
table (str): table name, defaults to ``filter``
Returns:
dict: chains with set of defined rules
"""
return dict((c["name"], self.get_chain(c["name"], table)) for c in self.get_table(table)) | python | def table_chains(self, table="filter"):
"""
Get a dict where the keys are all the chains for the given table
and each value is the set of rules defined for the given chain.
Args:
table (str): table name, defaults to ``filter``
Returns:
dict: chains with set of defined rules
"""
return dict((c["name"], self.get_chain(c["name"], table)) for c in self.get_table(table)) | [
"def",
"table_chains",
"(",
"self",
",",
"table",
"=",
"\"filter\"",
")",
":",
"return",
"dict",
"(",
"(",
"c",
"[",
"\"name\"",
"]",
",",
"self",
".",
"get_chain",
"(",
"c",
"[",
"\"name\"",
"]",
",",
"table",
")",
")",
"for",
"c",
"in",
"self",
... | Get a dict where the keys are all the chains for the given table
and each value is the set of rules defined for the given chain.
Args:
table (str): table name, defaults to ``filter``
Returns:
dict: chains with set of defined rules | [
"Get",
"a",
"dict",
"where",
"the",
"keys",
"are",
"all",
"the",
"chains",
"for",
"the",
"given",
"table",
"and",
"each",
"value",
"is",
"the",
"set",
"of",
"rules",
"defined",
"for",
"the",
"given",
"chain",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/iptables.py#L152-L163 |
226,036 | RedHatInsights/insights-core | insights/client/__init__.py | InsightsClient.verify | def verify(self, egg_path, gpg_key=constants.pub_gpg_path):
"""
Verifies the GPG signature of the egg. The signature is assumed to
be in the same directory as the egg and named the same as the egg
except with an additional ".asc" extension.
returns (dict): {'gpg': if the egg checks out,
'stderr': error message if present,
'stdout': stdout,
'rc': return code}
"""
# check if the provided files (egg and gpg) actually exist
if egg_path and not os.path.isfile(egg_path):
the_message = "Provided egg path %s does not exist, cannot verify." % (egg_path)
logger.debug(the_message)
return {'gpg': False,
'stderr': the_message,
'stdout': the_message,
'rc': 1,
'message': the_message}
if self.config.gpg and gpg_key and not os.path.isfile(gpg_key):
the_message = ("Running in GPG mode but cannot find "
"file %s to verify against." % (gpg_key))
logger.debug(the_message)
return {'gpg': False,
'stderr': the_message,
'stdout': the_message,
'rc': 1,
'message': the_message}
# if we are running in no_gpg or not gpg mode then return true
if not self.config.gpg:
return {'gpg': True,
'stderr': None,
'stdout': None,
'rc': 0}
# if a valid egg path and gpg were received do the verification
if egg_path and gpg_key:
cmd_template = '/usr/bin/gpg --verify --keyring %s %s %s'
cmd = cmd_template % (gpg_key, egg_path + '.asc', egg_path)
logger.debug(cmd)
process = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
rc = process.returncode
logger.debug("GPG return code: %s" % rc)
return {'gpg': True if rc == 0 else False,
'stderr': stderr,
'stdout': stdout,
'rc': rc}
else:
return {'gpg': False,
'stderr': 'Must specify a valid core and gpg key.',
'stdout': 'Must specify a valid core and gpg key.',
'rc': 1} | python | def verify(self, egg_path, gpg_key=constants.pub_gpg_path):
"""
Verifies the GPG signature of the egg. The signature is assumed to
be in the same directory as the egg and named the same as the egg
except with an additional ".asc" extension.
returns (dict): {'gpg': if the egg checks out,
'stderr': error message if present,
'stdout': stdout,
'rc': return code}
"""
# check if the provided files (egg and gpg) actually exist
if egg_path and not os.path.isfile(egg_path):
the_message = "Provided egg path %s does not exist, cannot verify." % (egg_path)
logger.debug(the_message)
return {'gpg': False,
'stderr': the_message,
'stdout': the_message,
'rc': 1,
'message': the_message}
if self.config.gpg and gpg_key and not os.path.isfile(gpg_key):
the_message = ("Running in GPG mode but cannot find "
"file %s to verify against." % (gpg_key))
logger.debug(the_message)
return {'gpg': False,
'stderr': the_message,
'stdout': the_message,
'rc': 1,
'message': the_message}
# if we are running in no_gpg or not gpg mode then return true
if not self.config.gpg:
return {'gpg': True,
'stderr': None,
'stdout': None,
'rc': 0}
# if a valid egg path and gpg were received do the verification
if egg_path and gpg_key:
cmd_template = '/usr/bin/gpg --verify --keyring %s %s %s'
cmd = cmd_template % (gpg_key, egg_path + '.asc', egg_path)
logger.debug(cmd)
process = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
rc = process.returncode
logger.debug("GPG return code: %s" % rc)
return {'gpg': True if rc == 0 else False,
'stderr': stderr,
'stdout': stdout,
'rc': rc}
else:
return {'gpg': False,
'stderr': 'Must specify a valid core and gpg key.',
'stdout': 'Must specify a valid core and gpg key.',
'rc': 1} | [
"def",
"verify",
"(",
"self",
",",
"egg_path",
",",
"gpg_key",
"=",
"constants",
".",
"pub_gpg_path",
")",
":",
"# check if the provided files (egg and gpg) actually exist",
"if",
"egg_path",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"egg_path",
")",
... | Verifies the GPG signature of the egg. The signature is assumed to
be in the same directory as the egg and named the same as the egg
except with an additional ".asc" extension.
returns (dict): {'gpg': if the egg checks out,
'stderr': error message if present,
'stdout': stdout,
'rc': return code} | [
"Verifies",
"the",
"GPG",
"signature",
"of",
"the",
"egg",
".",
"The",
"signature",
"is",
"assumed",
"to",
"be",
"in",
"the",
"same",
"directory",
"as",
"the",
"egg",
"and",
"named",
"the",
"same",
"as",
"the",
"egg",
"except",
"with",
"an",
"additional"... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/__init__.py#L213-L267 |
226,037 | RedHatInsights/insights-core | insights/client/__init__.py | InsightsClient.get_diagnosis | def get_diagnosis(self, remediation_id=None):
'''
returns JSON of diagnosis data on success, None on failure
Optional arg remediation_id to get a particular remediation set.
'''
if self.config.offline:
logger.error('Cannot get diagnosis in offline mode.')
return None
return self.connection.get_diagnosis(remediation_id) | python | def get_diagnosis(self, remediation_id=None):
'''
returns JSON of diagnosis data on success, None on failure
Optional arg remediation_id to get a particular remediation set.
'''
if self.config.offline:
logger.error('Cannot get diagnosis in offline mode.')
return None
return self.connection.get_diagnosis(remediation_id) | [
"def",
"get_diagnosis",
"(",
"self",
",",
"remediation_id",
"=",
"None",
")",
":",
"if",
"self",
".",
"config",
".",
"offline",
":",
"logger",
".",
"error",
"(",
"'Cannot get diagnosis in offline mode.'",
")",
"return",
"None",
"return",
"self",
".",
"connecti... | returns JSON of diagnosis data on success, None on failure
Optional arg remediation_id to get a particular remediation set. | [
"returns",
"JSON",
"of",
"diagnosis",
"data",
"on",
"success",
"None",
"on",
"failure",
"Optional",
"arg",
"remediation_id",
"to",
"get",
"a",
"particular",
"remediation",
"set",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/__init__.py#L455-L463 |
226,038 | RedHatInsights/insights-core | insights/client/__init__.py | InsightsClient.delete_cached_branch_info | def delete_cached_branch_info(self):
'''
Deletes cached branch_info file
'''
if os.path.isfile(constants.cached_branch_info):
logger.debug('Deleting cached branch_info file...')
os.remove(constants.cached_branch_info)
else:
logger.debug('Cached branch_info file does not exist.') | python | def delete_cached_branch_info(self):
'''
Deletes cached branch_info file
'''
if os.path.isfile(constants.cached_branch_info):
logger.debug('Deleting cached branch_info file...')
os.remove(constants.cached_branch_info)
else:
logger.debug('Cached branch_info file does not exist.') | [
"def",
"delete_cached_branch_info",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"constants",
".",
"cached_branch_info",
")",
":",
"logger",
".",
"debug",
"(",
"'Deleting cached branch_info file...'",
")",
"os",
".",
"remove",
"(",
"cons... | Deletes cached branch_info file | [
"Deletes",
"cached",
"branch_info",
"file"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/__init__.py#L465-L473 |
226,039 | RedHatInsights/insights-core | insights/client/__init__.py | InsightsClient.clear_local_registration | def clear_local_registration(self):
'''
Deletes dotfiles and machine-id for fresh registration
'''
delete_registered_file()
delete_unregistered_file()
write_to_disk(constants.machine_id_file, delete=True)
logger.debug('Re-register set, forcing registration.')
logger.debug('New machine-id: %s', generate_machine_id(new=True)) | python | def clear_local_registration(self):
'''
Deletes dotfiles and machine-id for fresh registration
'''
delete_registered_file()
delete_unregistered_file()
write_to_disk(constants.machine_id_file, delete=True)
logger.debug('Re-register set, forcing registration.')
logger.debug('New machine-id: %s', generate_machine_id(new=True)) | [
"def",
"clear_local_registration",
"(",
"self",
")",
":",
"delete_registered_file",
"(",
")",
"delete_unregistered_file",
"(",
")",
"write_to_disk",
"(",
"constants",
".",
"machine_id_file",
",",
"delete",
"=",
"True",
")",
"logger",
".",
"debug",
"(",
"'Re-regist... | Deletes dotfiles and machine-id for fresh registration | [
"Deletes",
"dotfiles",
"and",
"machine",
"-",
"id",
"for",
"fresh",
"registration"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/__init__.py#L478-L486 |
226,040 | RedHatInsights/insights-core | insights/contrib/pyparsing.py | col | def col (loc,strg):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
s = strg
return 1 if loc<len(s) and s[loc] == '\n' else loc - s.rfind("\n", 0, loc) | python | def col (loc,strg):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
s = strg
return 1 if loc<len(s) and s[loc] == '\n' else loc - s.rfind("\n", 0, loc) | [
"def",
"col",
"(",
"loc",
",",
"strg",
")",
":",
"s",
"=",
"strg",
"return",
"1",
"if",
"loc",
"<",
"len",
"(",
"s",
")",
"and",
"s",
"[",
"loc",
"]",
"==",
"'\\n'",
"else",
"loc",
"-",
"s",
".",
"rfind",
"(",
"\"\\n\"",
",",
"0",
",",
"loc... | Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string. | [
"Returns",
"current",
"column",
"within",
"a",
"string",
"counting",
"newlines",
"as",
"line",
"separators",
".",
"The",
"first",
"column",
"is",
"number",
"1",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/pyparsing.py#L716-L727 |
226,041 | RedHatInsights/insights-core | insights/contrib/pyparsing.py | upcaseTokens | def upcaseTokens(s,l,t):
"""Helper parse action to convert tokens to upper case."""
return [ tt.upper() for tt in map(_ustr,t) ] | python | def upcaseTokens(s,l,t):
"""Helper parse action to convert tokens to upper case."""
return [ tt.upper() for tt in map(_ustr,t) ] | [
"def",
"upcaseTokens",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"return",
"[",
"tt",
".",
"upper",
"(",
")",
"for",
"tt",
"in",
"map",
"(",
"_ustr",
",",
"t",
")",
"]"
] | Helper parse action to convert tokens to upper case. | [
"Helper",
"parse",
"action",
"to",
"convert",
"tokens",
"to",
"upper",
"case",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/pyparsing.py#L3592-L3594 |
226,042 | RedHatInsights/insights-core | insights/contrib/pyparsing.py | downcaseTokens | def downcaseTokens(s,l,t):
"""Helper parse action to convert tokens to lower case."""
return [ tt.lower() for tt in map(_ustr,t) ] | python | def downcaseTokens(s,l,t):
"""Helper parse action to convert tokens to lower case."""
return [ tt.lower() for tt in map(_ustr,t) ] | [
"def",
"downcaseTokens",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"return",
"[",
"tt",
".",
"lower",
"(",
")",
"for",
"tt",
"in",
"map",
"(",
"_ustr",
",",
"t",
")",
"]"
] | Helper parse action to convert tokens to lower case. | [
"Helper",
"parse",
"action",
"to",
"convert",
"tokens",
"to",
"lower",
"case",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/pyparsing.py#L3596-L3598 |
226,043 | RedHatInsights/insights-core | insights/contrib/pyparsing.py | infixNotation | def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ):
"""Helper method for constructing grammars of expressions made up of
operators working in a precedence hierarchy. Operators may be unary or
binary, left- or right-associative. Parse actions can also be attached
to operator expressions.
Parameters:
- baseExpr - expression representing the most basic element for the nested
- opList - list of tuples, one for each operator precedence level in the
expression grammar; each tuple is of the form
(opExpr, numTerms, rightLeftAssoc, parseAction), where:
- opExpr is the pyparsing expression for the operator;
may also be a string, which will be converted to a Literal;
if numTerms is 3, opExpr is a tuple of two expressions, for the
two operators separating the 3 terms
- numTerms is the number of terms for this operator (must
be 1, 2, or 3)
- rightLeftAssoc is the indicator whether the operator is
right or left associative, using the pyparsing-defined
constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}.
- parseAction is the parse action to be associated with
expressions matching this operator expression (the
parse action tuple member may be omitted)
- lpar - expression for matching left-parentheses (default=Suppress('('))
- rpar - expression for matching right-parentheses (default=Suppress(')'))
"""
ret = Forward()
lastExpr = baseExpr | ( lpar + ret + rpar )
for i,operDef in enumerate(opList):
opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
termName = "%s term" % opExpr if arity < 3 else "%s%s term" % opExpr
if arity == 3:
if opExpr is None or len(opExpr) != 2:
raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions")
opExpr1, opExpr2 = opExpr
thisExpr = Forward().setName(termName)
if rightLeftAssoc == opAssoc.LEFT:
if arity == 1:
matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) )
elif arity == 2:
if opExpr is not None:
matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
else:
matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) )
elif arity == 3:
matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \
Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr )
else:
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
elif rightLeftAssoc == opAssoc.RIGHT:
if arity == 1:
# try to avoid LR with this extra test
if not isinstance(opExpr, Optional):
opExpr = Optional(opExpr)
matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr )
elif arity == 2:
if opExpr is not None:
matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
else:
matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) )
elif arity == 3:
matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \
Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr )
else:
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
else:
raise ValueError("operator must indicate right or left associativity")
if pa:
matchExpr.setParseAction( pa )
thisExpr <<= ( matchExpr.setName(termName) | lastExpr )
lastExpr = thisExpr
ret <<= lastExpr
return ret | python | def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ):
"""Helper method for constructing grammars of expressions made up of
operators working in a precedence hierarchy. Operators may be unary or
binary, left- or right-associative. Parse actions can also be attached
to operator expressions.
Parameters:
- baseExpr - expression representing the most basic element for the nested
- opList - list of tuples, one for each operator precedence level in the
expression grammar; each tuple is of the form
(opExpr, numTerms, rightLeftAssoc, parseAction), where:
- opExpr is the pyparsing expression for the operator;
may also be a string, which will be converted to a Literal;
if numTerms is 3, opExpr is a tuple of two expressions, for the
two operators separating the 3 terms
- numTerms is the number of terms for this operator (must
be 1, 2, or 3)
- rightLeftAssoc is the indicator whether the operator is
right or left associative, using the pyparsing-defined
constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}.
- parseAction is the parse action to be associated with
expressions matching this operator expression (the
parse action tuple member may be omitted)
- lpar - expression for matching left-parentheses (default=Suppress('('))
- rpar - expression for matching right-parentheses (default=Suppress(')'))
"""
ret = Forward()
lastExpr = baseExpr | ( lpar + ret + rpar )
for i,operDef in enumerate(opList):
opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
termName = "%s term" % opExpr if arity < 3 else "%s%s term" % opExpr
if arity == 3:
if opExpr is None or len(opExpr) != 2:
raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions")
opExpr1, opExpr2 = opExpr
thisExpr = Forward().setName(termName)
if rightLeftAssoc == opAssoc.LEFT:
if arity == 1:
matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) )
elif arity == 2:
if opExpr is not None:
matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
else:
matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) )
elif arity == 3:
matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \
Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr )
else:
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
elif rightLeftAssoc == opAssoc.RIGHT:
if arity == 1:
# try to avoid LR with this extra test
if not isinstance(opExpr, Optional):
opExpr = Optional(opExpr)
matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr )
elif arity == 2:
if opExpr is not None:
matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
else:
matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) )
elif arity == 3:
matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \
Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr )
else:
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
else:
raise ValueError("operator must indicate right or left associativity")
if pa:
matchExpr.setParseAction( pa )
thisExpr <<= ( matchExpr.setName(termName) | lastExpr )
lastExpr = thisExpr
ret <<= lastExpr
return ret | [
"def",
"infixNotation",
"(",
"baseExpr",
",",
"opList",
",",
"lpar",
"=",
"Suppress",
"(",
"'('",
")",
",",
"rpar",
"=",
"Suppress",
"(",
"')'",
")",
")",
":",
"ret",
"=",
"Forward",
"(",
")",
"lastExpr",
"=",
"baseExpr",
"|",
"(",
"lpar",
"+",
"re... | Helper method for constructing grammars of expressions made up of
operators working in a precedence hierarchy. Operators may be unary or
binary, left- or right-associative. Parse actions can also be attached
to operator expressions.
Parameters:
- baseExpr - expression representing the most basic element for the nested
- opList - list of tuples, one for each operator precedence level in the
expression grammar; each tuple is of the form
(opExpr, numTerms, rightLeftAssoc, parseAction), where:
- opExpr is the pyparsing expression for the operator;
may also be a string, which will be converted to a Literal;
if numTerms is 3, opExpr is a tuple of two expressions, for the
two operators separating the 3 terms
- numTerms is the number of terms for this operator (must
be 1, 2, or 3)
- rightLeftAssoc is the indicator whether the operator is
right or left associative, using the pyparsing-defined
constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}.
- parseAction is the parse action to be associated with
expressions matching this operator expression (the
parse action tuple member may be omitted)
- lpar - expression for matching left-parentheses (default=Suppress('('))
- rpar - expression for matching right-parentheses (default=Suppress(')')) | [
"Helper",
"method",
"for",
"constructing",
"grammars",
"of",
"expressions",
"made",
"up",
"of",
"operators",
"working",
"in",
"a",
"precedence",
"hierarchy",
".",
"Operators",
"may",
"be",
"unary",
"or",
"binary",
"left",
"-",
"or",
"right",
"-",
"associative"... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/pyparsing.py#L3683-L3755 |
226,044 | RedHatInsights/insights-core | examples/cluster_rules/ntp_compare.py | report | def report(shas, meta):
"""
Cluster rule to compare ntp.conf files across a cluster
``shas`` is a Pandas DataFrame for the facts for each host
by the fact ``ntp_sha256``. See
https://pandas.pydata.org/pandas-docs/stable/api.html#dataframe
for information on available attributes and methods.
``meta`` is a dictionary that contains the information from the
cluster topology file provided by the ``-i`` switch. The dictionary
keys are the sections, and the values are a list of the host
information provided in the toplolgy file.
Arguments:
shas (pandas.DataFrame): Includes facts from ``ntp_sha256``
fact with column "sha" and one row per host in the cluster.
meta (dict): Keys are the sections in the topology file and
values are a list of the values in the section.
"""
num_members = meta.num_members
uniq = shas.sha.unique()
if len(shas) != num_members or len(uniq) != 1:
return make_fail("DISTINCT_NTP_CONFS", confs=len(uniq), nodes=num_members)
return make_pass("MATCHING_NTP_CONFS", nodes=meta['nodes'], servers=meta['servers']) | python | def report(shas, meta):
"""
Cluster rule to compare ntp.conf files across a cluster
``shas`` is a Pandas DataFrame for the facts for each host
by the fact ``ntp_sha256``. See
https://pandas.pydata.org/pandas-docs/stable/api.html#dataframe
for information on available attributes and methods.
``meta`` is a dictionary that contains the information from the
cluster topology file provided by the ``-i`` switch. The dictionary
keys are the sections, and the values are a list of the host
information provided in the toplolgy file.
Arguments:
shas (pandas.DataFrame): Includes facts from ``ntp_sha256``
fact with column "sha" and one row per host in the cluster.
meta (dict): Keys are the sections in the topology file and
values are a list of the values in the section.
"""
num_members = meta.num_members
uniq = shas.sha.unique()
if len(shas) != num_members or len(uniq) != 1:
return make_fail("DISTINCT_NTP_CONFS", confs=len(uniq), nodes=num_members)
return make_pass("MATCHING_NTP_CONFS", nodes=meta['nodes'], servers=meta['servers']) | [
"def",
"report",
"(",
"shas",
",",
"meta",
")",
":",
"num_members",
"=",
"meta",
".",
"num_members",
"uniq",
"=",
"shas",
".",
"sha",
".",
"unique",
"(",
")",
"if",
"len",
"(",
"shas",
")",
"!=",
"num_members",
"or",
"len",
"(",
"uniq",
")",
"!=",
... | Cluster rule to compare ntp.conf files across a cluster
``shas`` is a Pandas DataFrame for the facts for each host
by the fact ``ntp_sha256``. See
https://pandas.pydata.org/pandas-docs/stable/api.html#dataframe
for information on available attributes and methods.
``meta`` is a dictionary that contains the information from the
cluster topology file provided by the ``-i`` switch. The dictionary
keys are the sections, and the values are a list of the host
information provided in the toplolgy file.
Arguments:
shas (pandas.DataFrame): Includes facts from ``ntp_sha256``
fact with column "sha" and one row per host in the cluster.
meta (dict): Keys are the sections in the topology file and
values are a list of the values in the section. | [
"Cluster",
"rule",
"to",
"compare",
"ntp",
".",
"conf",
"files",
"across",
"a",
"cluster"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/examples/cluster_rules/ntp_compare.py#L50-L75 |
226,045 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner._create_ip_report | def _create_ip_report(self):
'''
this will take the obfuscated ip and hostname databases and output csv files
'''
try:
ip_report_name = os.path.join(self.report_dir, "%s-ip.csv" % self.session)
self.logger.con_out('Creating IP Report - %s', ip_report_name)
ip_report = open(ip_report_name, 'wt')
ip_report.write('Obfuscated IP,Original IP\n')
for k,v in self.ip_db.items():
ip_report.write('%s,%s\n' %(self._int2ip(k),self._int2ip(v)))
ip_report.close()
self.logger.info('Completed IP Report')
self.ip_report = ip_report_name
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception('CreateReport Error: Error Creating IP Report') | python | def _create_ip_report(self):
'''
this will take the obfuscated ip and hostname databases and output csv files
'''
try:
ip_report_name = os.path.join(self.report_dir, "%s-ip.csv" % self.session)
self.logger.con_out('Creating IP Report - %s', ip_report_name)
ip_report = open(ip_report_name, 'wt')
ip_report.write('Obfuscated IP,Original IP\n')
for k,v in self.ip_db.items():
ip_report.write('%s,%s\n' %(self._int2ip(k),self._int2ip(v)))
ip_report.close()
self.logger.info('Completed IP Report')
self.ip_report = ip_report_name
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception('CreateReport Error: Error Creating IP Report') | [
"def",
"_create_ip_report",
"(",
"self",
")",
":",
"try",
":",
"ip_report_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"report_dir",
",",
"\"%s-ip.csv\"",
"%",
"self",
".",
"session",
")",
"self",
".",
"logger",
".",
"con_out",
"(",
"'... | this will take the obfuscated ip and hostname databases and output csv files | [
"this",
"will",
"take",
"the",
"obfuscated",
"ip",
"and",
"hostname",
"databases",
"and",
"output",
"csv",
"files"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L214-L231 |
226,046 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner._create_archive | def _create_archive(self):
'''This will create a tar.gz compressed archive of the scrubbed directory'''
try:
self.archive_path = os.path.join(self.report_dir, "%s.tar.gz" % self.session)
self.logger.con_out('Creating SOSCleaner Archive - %s', self.archive_path)
t = tarfile.open(self.archive_path, 'w:gz')
for dirpath, dirnames, filenames in os.walk(self.dir_path):
for f in filenames:
f_full = os.path.join(dirpath, f)
f_archive = f_full.replace(self.report_dir,'')
self.logger.debug('adding %s to %s archive', f_archive, self.archive_path)
t.add(f_full, arcname=f_archive)
except Exception as e: #pragma: no cover
self.logger.exception(e)
raise Exception('CreateArchiveError: Unable to create Archive')
self._clean_up()
self.logger.info('Archiving Complete')
self.logger.con_out('SOSCleaner Complete')
if not self.quiet: # pragma: no cover
t.add(self.logfile, arcname=self.logfile.replace(self.report_dir,''))
t.close() | python | def _create_archive(self):
'''This will create a tar.gz compressed archive of the scrubbed directory'''
try:
self.archive_path = os.path.join(self.report_dir, "%s.tar.gz" % self.session)
self.logger.con_out('Creating SOSCleaner Archive - %s', self.archive_path)
t = tarfile.open(self.archive_path, 'w:gz')
for dirpath, dirnames, filenames in os.walk(self.dir_path):
for f in filenames:
f_full = os.path.join(dirpath, f)
f_archive = f_full.replace(self.report_dir,'')
self.logger.debug('adding %s to %s archive', f_archive, self.archive_path)
t.add(f_full, arcname=f_archive)
except Exception as e: #pragma: no cover
self.logger.exception(e)
raise Exception('CreateArchiveError: Unable to create Archive')
self._clean_up()
self.logger.info('Archiving Complete')
self.logger.con_out('SOSCleaner Complete')
if not self.quiet: # pragma: no cover
t.add(self.logfile, arcname=self.logfile.replace(self.report_dir,''))
t.close() | [
"def",
"_create_archive",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"archive_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"report_dir",
",",
"\"%s.tar.gz\"",
"%",
"self",
".",
"session",
")",
"self",
".",
"logger",
".",
"con_out"... | This will create a tar.gz compressed archive of the scrubbed directory | [
"This",
"will",
"create",
"a",
"tar",
".",
"gz",
"compressed",
"archive",
"of",
"the",
"scrubbed",
"directory"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L313-L334 |
226,047 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner._clean_up | def _clean_up(self):
'''This will clean up origin directories, etc.'''
self.logger.info('Beginning Clean Up Process')
try:
if self.origin_path:
self.logger.info('Removing Origin Directory - %s', self.origin_path)
shutil.rmtree(self.origin_path)
self.logger.info('Removing Working Directory - %s', self.dir_path)
shutil.rmtree(self.dir_path)
self.logger.info('Clean Up Process Complete')
except Exception as e: #pragma: no cover
self.logger.exception(e) | python | def _clean_up(self):
'''This will clean up origin directories, etc.'''
self.logger.info('Beginning Clean Up Process')
try:
if self.origin_path:
self.logger.info('Removing Origin Directory - %s', self.origin_path)
shutil.rmtree(self.origin_path)
self.logger.info('Removing Working Directory - %s', self.dir_path)
shutil.rmtree(self.dir_path)
self.logger.info('Clean Up Process Complete')
except Exception as e: #pragma: no cover
self.logger.exception(e) | [
"def",
"_clean_up",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Beginning Clean Up Process'",
")",
"try",
":",
"if",
"self",
".",
"origin_path",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Removing Origin Directory - %s'",
",",
"sel... | This will clean up origin directories, etc. | [
"This",
"will",
"clean",
"up",
"origin",
"directories",
"etc",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L336-L347 |
226,048 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner._hn2db | def _hn2db(self, hn):
'''
This will add a hostname for a hostname for an included domain or return an existing entry
'''
db = self.hn_db
hn_found = False
for k,v in db.items():
if v == hn: #the hostname is in the database
ret_hn = k
hn_found = True
if hn_found:
return ret_hn
else:
self.hostname_count += 1 #we have a new hostname, so we increment the counter to get the host ID number
o_domain = self.root_domain
for od,d in self.dn_db.items():
if d in hn:
o_domain = od
new_hn = "host%s.%s" % (self.hostname_count, o_domain)
self.hn_db[new_hn] = hn
return new_hn | python | def _hn2db(self, hn):
'''
This will add a hostname for a hostname for an included domain or return an existing entry
'''
db = self.hn_db
hn_found = False
for k,v in db.items():
if v == hn: #the hostname is in the database
ret_hn = k
hn_found = True
if hn_found:
return ret_hn
else:
self.hostname_count += 1 #we have a new hostname, so we increment the counter to get the host ID number
o_domain = self.root_domain
for od,d in self.dn_db.items():
if d in hn:
o_domain = od
new_hn = "host%s.%s" % (self.hostname_count, o_domain)
self.hn_db[new_hn] = hn
return new_hn | [
"def",
"_hn2db",
"(",
"self",
",",
"hn",
")",
":",
"db",
"=",
"self",
".",
"hn_db",
"hn_found",
"=",
"False",
"for",
"k",
",",
"v",
"in",
"db",
".",
"items",
"(",
")",
":",
"if",
"v",
"==",
"hn",
":",
"#the hostname is in the database",
"ret_hn",
"... | This will add a hostname for a hostname for an included domain or return an existing entry | [
"This",
"will",
"add",
"a",
"hostname",
"for",
"a",
"hostname",
"for",
"an",
"included",
"domain",
"or",
"return",
"an",
"existing",
"entry"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L510-L531 |
226,049 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner._file_list | def _file_list(self, folder):
'''returns a list of file names in an sosreport directory'''
rtn = []
walk = self._walk_report(folder)
for key,val in walk.items():
for v in val:
x=os.path.join(key,v)
rtn.append(x)
self.file_count = len(rtn) #a count of the files we'll have in the final cleaned sosreport, for reporting
return rtn | python | def _file_list(self, folder):
'''returns a list of file names in an sosreport directory'''
rtn = []
walk = self._walk_report(folder)
for key,val in walk.items():
for v in val:
x=os.path.join(key,v)
rtn.append(x)
self.file_count = len(rtn) #a count of the files we'll have in the final cleaned sosreport, for reporting
return rtn | [
"def",
"_file_list",
"(",
"self",
",",
"folder",
")",
":",
"rtn",
"=",
"[",
"]",
"walk",
"=",
"self",
".",
"_walk_report",
"(",
"folder",
")",
"for",
"key",
",",
"val",
"in",
"walk",
".",
"items",
"(",
")",
":",
"for",
"v",
"in",
"val",
":",
"x... | returns a list of file names in an sosreport directory | [
"returns",
"a",
"list",
"of",
"file",
"names",
"in",
"an",
"sosreport",
"directory"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L549-L559 |
226,050 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner._clean_line | def _clean_line(self, l):
'''this will return a line with obfuscations for all possible variables, hostname, ip, etc.'''
new_line = self._sub_ip(l) # IP substitution
new_line = self._sub_hostname(new_line) # Hostname substitution
new_line = self._sub_keywords(new_line) # Keyword Substitution
return new_line | python | def _clean_line(self, l):
'''this will return a line with obfuscations for all possible variables, hostname, ip, etc.'''
new_line = self._sub_ip(l) # IP substitution
new_line = self._sub_hostname(new_line) # Hostname substitution
new_line = self._sub_keywords(new_line) # Keyword Substitution
return new_line | [
"def",
"_clean_line",
"(",
"self",
",",
"l",
")",
":",
"new_line",
"=",
"self",
".",
"_sub_ip",
"(",
"l",
")",
"# IP substitution",
"new_line",
"=",
"self",
".",
"_sub_hostname",
"(",
"new_line",
")",
"# Hostname substitution",
"new_line",
"=",
"self",
".",
... | this will return a line with obfuscations for all possible variables, hostname, ip, etc. | [
"this",
"will",
"return",
"a",
"line",
"with",
"obfuscations",
"for",
"all",
"possible",
"variables",
"hostname",
"ip",
"etc",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L561-L568 |
226,051 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner._clean_file | def _clean_file(self, f):
'''this will take a given file path, scrub it accordingly, and save a new copy of the file
in the same location'''
if os.path.exists(f) and not os.path.islink(f):
tmp_file = tempfile.TemporaryFile(mode='w+b')
try:
fh = open(f, 'r')
data = fh.readlines()
fh.close()
if len(data) > 0: #if the file isn't empty:
for l in data:
new_l = self._clean_line(l)
tmp_file.write(new_l.encode('utf-8'))
tmp_file.seek(0)
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception("CleanFile Error: Cannot Open File For Reading - %s" % f)
try:
if len(data) > 0:
new_fh = open(f, 'wb')
for line in tmp_file:
new_fh.write(line)
new_fh.close()
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception("CleanFile Error: Cannot Write to New File - %s" % f)
finally:
tmp_file.close() | python | def _clean_file(self, f):
'''this will take a given file path, scrub it accordingly, and save a new copy of the file
in the same location'''
if os.path.exists(f) and not os.path.islink(f):
tmp_file = tempfile.TemporaryFile(mode='w+b')
try:
fh = open(f, 'r')
data = fh.readlines()
fh.close()
if len(data) > 0: #if the file isn't empty:
for l in data:
new_l = self._clean_line(l)
tmp_file.write(new_l.encode('utf-8'))
tmp_file.seek(0)
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception("CleanFile Error: Cannot Open File For Reading - %s" % f)
try:
if len(data) > 0:
new_fh = open(f, 'wb')
for line in tmp_file:
new_fh.write(line)
new_fh.close()
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception("CleanFile Error: Cannot Write to New File - %s" % f)
finally:
tmp_file.close() | [
"def",
"_clean_file",
"(",
"self",
",",
"f",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"f",
")",
"and",
"not",
"os",
".",
"path",
".",
"islink",
"(",
"f",
")",
":",
"tmp_file",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
"mode",
"=",... | this will take a given file path, scrub it accordingly, and save a new copy of the file
in the same location | [
"this",
"will",
"take",
"a",
"given",
"file",
"path",
"scrub",
"it",
"accordingly",
"and",
"save",
"a",
"new",
"copy",
"of",
"the",
"file",
"in",
"the",
"same",
"location"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L570-L601 |
226,052 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner._add_extra_files | def _add_extra_files(self, files):
'''if extra files are to be analyzed with an sosreport, this will add them to the origin path to be analyzed'''
try:
for f in files:
self.logger.con_out("adding additional file for analysis: %s" % f)
fname = os.path.basename(f)
f_new = os.path.join(self.dir_path, fname)
shutil.copyfile(f,f_new)
except IOError as e:
self.logger.con_out("ExtraFileError: %s is not readable or does not exist. Skipping File" % f)
self.logger.exception(e)
pass
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception("ExtraFileError: Unable to Process Extra File - %s" % f) | python | def _add_extra_files(self, files):
'''if extra files are to be analyzed with an sosreport, this will add them to the origin path to be analyzed'''
try:
for f in files:
self.logger.con_out("adding additional file for analysis: %s" % f)
fname = os.path.basename(f)
f_new = os.path.join(self.dir_path, fname)
shutil.copyfile(f,f_new)
except IOError as e:
self.logger.con_out("ExtraFileError: %s is not readable or does not exist. Skipping File" % f)
self.logger.exception(e)
pass
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception("ExtraFileError: Unable to Process Extra File - %s" % f) | [
"def",
"_add_extra_files",
"(",
"self",
",",
"files",
")",
":",
"try",
":",
"for",
"f",
"in",
"files",
":",
"self",
".",
"logger",
".",
"con_out",
"(",
"\"adding additional file for analysis: %s\"",
"%",
"f",
")",
"fname",
"=",
"os",
".",
"path",
".",
"b... | if extra files are to be analyzed with an sosreport, this will add them to the origin path to be analyzed | [
"if",
"extra",
"files",
"are",
"to",
"be",
"analyzed",
"with",
"an",
"sosreport",
"this",
"will",
"add",
"them",
"to",
"the",
"origin",
"path",
"to",
"be",
"analyzed"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L603-L618 |
226,053 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner._clean_files_only | def _clean_files_only(self, files):
''' if a user only wants to process one or more specific files, instead of a full sosreport '''
try:
if not (os.path.exists(self.origin_path)):
self.logger.info("Creating Origin Path - %s" % self.origin_path)
os.makedirs(self.origin_path) # create the origin_path directory
if not (os.path.exists(self.dir_path)):
self.logger.info("Creating Directory Path - %s" % self.dir_path)
os.makedirs(self.dir_path) # create the dir_path directory
self._add_extra_files(files)
except OSError as e: # pragma: no cover
if e.errno == errno.EEXIST:
pass
else: # pragma: no cover
self.logger.exception(e)
raise e
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception("CleanFilesOnlyError: unable to process") | python | def _clean_files_only(self, files):
''' if a user only wants to process one or more specific files, instead of a full sosreport '''
try:
if not (os.path.exists(self.origin_path)):
self.logger.info("Creating Origin Path - %s" % self.origin_path)
os.makedirs(self.origin_path) # create the origin_path directory
if not (os.path.exists(self.dir_path)):
self.logger.info("Creating Directory Path - %s" % self.dir_path)
os.makedirs(self.dir_path) # create the dir_path directory
self._add_extra_files(files)
except OSError as e: # pragma: no cover
if e.errno == errno.EEXIST:
pass
else: # pragma: no cover
self.logger.exception(e)
raise e
except Exception as e: # pragma: no cover
self.logger.exception(e)
raise Exception("CleanFilesOnlyError: unable to process") | [
"def",
"_clean_files_only",
"(",
"self",
",",
"files",
")",
":",
"try",
":",
"if",
"not",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"origin_path",
")",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Creating Origin Path - %s\"",
"... | if a user only wants to process one or more specific files, instead of a full sosreport | [
"if",
"a",
"user",
"only",
"wants",
"to",
"process",
"one",
"or",
"more",
"specific",
"files",
"instead",
"of",
"a",
"full",
"sosreport"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L620-L640 |
226,054 | RedHatInsights/insights-core | insights/contrib/soscleaner.py | SOSCleaner.clean_report | def clean_report(self, options, sosreport): # pragma: no cover
'''this is the primary function, to put everything together and analyze an sosreport'''
if options.report_dir: # override the default location for artifacts (/tmp)
if os.path.isdir(options.report_dir):
self.report_dir = options.report_dir
self.origin_path, self.dir_path, self.session, self.logfile, self.uuid = self._prep_environment()
self._start_logging(self.logfile)
self._get_disclaimer()
if options.domains:
self.domains = options.domains
if options.keywords:
self.keywords = options.keywords
self._keywords2db()
if not sosreport:
if not options.files:
raise Exception("Error: You must supply either an sosreport and/or files to process")
self.logger.con_out("No sosreport supplied. Only processing specific files")
self._clean_files_only(options.files)
else: # we DO have an sosreport to analyze
self.report = self._extract_sosreport(sosreport)
self._make_dest_env() # create the working directory
if options.hostname_path:
self.hostname, self.domainname = self._get_hostname(options.hostname_path)
else:
self.hostname, self.domainname = self._get_hostname()
if options.files:
self._add_extra_files(options.files)
if self.hostname: # if we have a hostname that's not a None type
self.hn_db['host0'] = self.hostname # we'll prime the hostname pump to clear out a ton of useless logic later
self._process_hosts_file() # we'll take a dig through the hosts file and make sure it is as scrubbed as possible
self._domains2db()
files = self._file_list(self.dir_path)
self.logger.con_out("IP Obfuscation Start Address - %s", self.start_ip)
self.logger.con_out("*** SOSCleaner Processing ***")
self.logger.info("Working Directory - %s", self.dir_path)
for f in files:
self.logger.debug("Cleaning %s", f)
self._clean_file(f)
self.logger.con_out("*** SOSCleaner Statistics ***")
self.logger.con_out("IP Addresses Obfuscated - %s", len(self.ip_db))
self.logger.con_out("Hostnames Obfuscated - %s" , len(self.hn_db))
self.logger.con_out("Domains Obfuscated - %s" , len(self.dn_db))
self.logger.con_out("Total Files Analyzed - %s", self.file_count)
self.logger.con_out("*** SOSCleaner Artifacts ***")
self._create_reports()
self._create_archive()
return_data = [self.archive_path, self.logfile, self.ip_report]
if self.hostname:
return_data.append(self.hn_report)
if len(self.dn_db) >= 1:
return_data.append(self.dn_report)
return return_data | python | def clean_report(self, options, sosreport): # pragma: no cover
'''this is the primary function, to put everything together and analyze an sosreport'''
if options.report_dir: # override the default location for artifacts (/tmp)
if os.path.isdir(options.report_dir):
self.report_dir = options.report_dir
self.origin_path, self.dir_path, self.session, self.logfile, self.uuid = self._prep_environment()
self._start_logging(self.logfile)
self._get_disclaimer()
if options.domains:
self.domains = options.domains
if options.keywords:
self.keywords = options.keywords
self._keywords2db()
if not sosreport:
if not options.files:
raise Exception("Error: You must supply either an sosreport and/or files to process")
self.logger.con_out("No sosreport supplied. Only processing specific files")
self._clean_files_only(options.files)
else: # we DO have an sosreport to analyze
self.report = self._extract_sosreport(sosreport)
self._make_dest_env() # create the working directory
if options.hostname_path:
self.hostname, self.domainname = self._get_hostname(options.hostname_path)
else:
self.hostname, self.domainname = self._get_hostname()
if options.files:
self._add_extra_files(options.files)
if self.hostname: # if we have a hostname that's not a None type
self.hn_db['host0'] = self.hostname # we'll prime the hostname pump to clear out a ton of useless logic later
self._process_hosts_file() # we'll take a dig through the hosts file and make sure it is as scrubbed as possible
self._domains2db()
files = self._file_list(self.dir_path)
self.logger.con_out("IP Obfuscation Start Address - %s", self.start_ip)
self.logger.con_out("*** SOSCleaner Processing ***")
self.logger.info("Working Directory - %s", self.dir_path)
for f in files:
self.logger.debug("Cleaning %s", f)
self._clean_file(f)
self.logger.con_out("*** SOSCleaner Statistics ***")
self.logger.con_out("IP Addresses Obfuscated - %s", len(self.ip_db))
self.logger.con_out("Hostnames Obfuscated - %s" , len(self.hn_db))
self.logger.con_out("Domains Obfuscated - %s" , len(self.dn_db))
self.logger.con_out("Total Files Analyzed - %s", self.file_count)
self.logger.con_out("*** SOSCleaner Artifacts ***")
self._create_reports()
self._create_archive()
return_data = [self.archive_path, self.logfile, self.ip_report]
if self.hostname:
return_data.append(self.hn_report)
if len(self.dn_db) >= 1:
return_data.append(self.dn_report)
return return_data | [
"def",
"clean_report",
"(",
"self",
",",
"options",
",",
"sosreport",
")",
":",
"# pragma: no cover",
"if",
"options",
".",
"report_dir",
":",
"# override the default location for artifacts (/tmp)",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"options",
".",
"repo... | this is the primary function, to put everything together and analyze an sosreport | [
"this",
"is",
"the",
"primary",
"function",
"to",
"put",
"everything",
"together",
"and",
"analyze",
"an",
"sosreport"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/soscleaner.py#L642-L702 |
226,055 | RedHatInsights/insights-core | insights/parsers/docker_list.py | DockerList.parse_content | def parse_content(self, content):
"""
Parse the lines given into a list of dictionaries for each row. This
is stored in the ``rows`` attribute.
If the ``key_field`` property is set, use this to key a ``data``
dictionary attribute.
"""
self.rows = []
if len(content) < 2:
self.no_data = True
return
# Parse header, remembering column numbers for data capture. We use
# a finditer to get the positions, and we find by field rather than
# splitting on three or more spaces because of this.
headers = []
field_re = re.compile(r'\w+(\s\w+)*')
for match in field_re.finditer(content[0]):
headers.append({'name': match.group(), 'start': match.start()})
# Parse the rest of the line. Each field starts at the column
# given by the header and ends with at least three spaces.
for line in content[1:]:
# I think the dictionary comprehension version of this is too
# complicated for words :-)
row = {}
for header in headers:
value = line[header['start']:].split(' ', 1)[0]
if value == '':
value = None
row[header['name']] = value
self.rows.append(row)
# If we have a key_field set, construct a data dictionary on it.
# Note that duplicates will be overwritten, but we ignore '<none>'.
if self.key_field and self.key_field in self.rows[0]:
self.data = {}
for row in self.rows:
k = row[self.key_field]
if k is not None and k != '<none>':
self.data[k] = row | python | def parse_content(self, content):
"""
Parse the lines given into a list of dictionaries for each row. This
is stored in the ``rows`` attribute.
If the ``key_field`` property is set, use this to key a ``data``
dictionary attribute.
"""
self.rows = []
if len(content) < 2:
self.no_data = True
return
# Parse header, remembering column numbers for data capture. We use
# a finditer to get the positions, and we find by field rather than
# splitting on three or more spaces because of this.
headers = []
field_re = re.compile(r'\w+(\s\w+)*')
for match in field_re.finditer(content[0]):
headers.append({'name': match.group(), 'start': match.start()})
# Parse the rest of the line. Each field starts at the column
# given by the header and ends with at least three spaces.
for line in content[1:]:
# I think the dictionary comprehension version of this is too
# complicated for words :-)
row = {}
for header in headers:
value = line[header['start']:].split(' ', 1)[0]
if value == '':
value = None
row[header['name']] = value
self.rows.append(row)
# If we have a key_field set, construct a data dictionary on it.
# Note that duplicates will be overwritten, but we ignore '<none>'.
if self.key_field and self.key_field in self.rows[0]:
self.data = {}
for row in self.rows:
k = row[self.key_field]
if k is not None and k != '<none>':
self.data[k] = row | [
"def",
"parse_content",
"(",
"self",
",",
"content",
")",
":",
"self",
".",
"rows",
"=",
"[",
"]",
"if",
"len",
"(",
"content",
")",
"<",
"2",
":",
"self",
".",
"no_data",
"=",
"True",
"return",
"# Parse header, remembering column numbers for data capture. We... | Parse the lines given into a list of dictionaries for each row. This
is stored in the ``rows`` attribute.
If the ``key_field`` property is set, use this to key a ``data``
dictionary attribute. | [
"Parse",
"the",
"lines",
"given",
"into",
"a",
"list",
"of",
"dictionaries",
"for",
"each",
"row",
".",
"This",
"is",
"stored",
"in",
"the",
"rows",
"attribute",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/docker_list.py#L78-L119 |
226,056 | RedHatInsights/insights-core | insights/contrib/ipaddress.py | _IPAddressBase._ip_int_from_prefix | def _ip_int_from_prefix(self, prefixlen=None):
"""Turn the prefix length netmask into a int for comparison.
Args:
prefixlen: An integer, the prefix length.
Returns:
An integer.
"""
if prefixlen is None:
prefixlen = self._prefixlen
return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) | python | def _ip_int_from_prefix(self, prefixlen=None):
"""Turn the prefix length netmask into a int for comparison.
Args:
prefixlen: An integer, the prefix length.
Returns:
An integer.
"""
if prefixlen is None:
prefixlen = self._prefixlen
return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) | [
"def",
"_ip_int_from_prefix",
"(",
"self",
",",
"prefixlen",
"=",
"None",
")",
":",
"if",
"prefixlen",
"is",
"None",
":",
"prefixlen",
"=",
"self",
".",
"_prefixlen",
"return",
"self",
".",
"_ALL_ONES",
"^",
"(",
"self",
".",
"_ALL_ONES",
">>",
"prefixlen"... | Turn the prefix length netmask into a int for comparison.
Args:
prefixlen: An integer, the prefix length.
Returns:
An integer. | [
"Turn",
"the",
"prefix",
"length",
"netmask",
"into",
"a",
"int",
"for",
"comparison",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/ipaddress.py#L530-L542 |
226,057 | RedHatInsights/insights-core | insights/contrib/ipaddress.py | _IPAddressBase._ip_string_from_prefix | def _ip_string_from_prefix(self, prefixlen=None):
"""Turn a prefix length into a dotted decimal string.
Args:
prefixlen: An integer, the netmask prefix length.
Returns:
A string, the dotted decimal netmask string.
"""
if not prefixlen:
prefixlen = self._prefixlen
return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen)) | python | def _ip_string_from_prefix(self, prefixlen=None):
"""Turn a prefix length into a dotted decimal string.
Args:
prefixlen: An integer, the netmask prefix length.
Returns:
A string, the dotted decimal netmask string.
"""
if not prefixlen:
prefixlen = self._prefixlen
return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen)) | [
"def",
"_ip_string_from_prefix",
"(",
"self",
",",
"prefixlen",
"=",
"None",
")",
":",
"if",
"not",
"prefixlen",
":",
"prefixlen",
"=",
"self",
".",
"_prefixlen",
"return",
"self",
".",
"_string_from_ip_int",
"(",
"self",
".",
"_ip_int_from_prefix",
"(",
"pref... | Turn a prefix length into a dotted decimal string.
Args:
prefixlen: An integer, the netmask prefix length.
Returns:
A string, the dotted decimal netmask string. | [
"Turn",
"a",
"prefix",
"length",
"into",
"a",
"dotted",
"decimal",
"string",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/ipaddress.py#L557-L569 |
226,058 | RedHatInsights/insights-core | insights/core/context.py | ExecutionContext.check_output | def check_output(self, cmd, timeout=None, keep_rc=False, env=None):
""" Subclasses can override to provide special
environment setup, command prefixes, etc.
"""
return subproc.call(cmd, timeout=timeout or self.timeout,
keep_rc=keep_rc, env=env) | python | def check_output(self, cmd, timeout=None, keep_rc=False, env=None):
""" Subclasses can override to provide special
environment setup, command prefixes, etc.
"""
return subproc.call(cmd, timeout=timeout or self.timeout,
keep_rc=keep_rc, env=env) | [
"def",
"check_output",
"(",
"self",
",",
"cmd",
",",
"timeout",
"=",
"None",
",",
"keep_rc",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"return",
"subproc",
".",
"call",
"(",
"cmd",
",",
"timeout",
"=",
"timeout",
"or",
"self",
".",
"timeout",
... | Subclasses can override to provide special
environment setup, command prefixes, etc. | [
"Subclasses",
"can",
"override",
"to",
"provide",
"special",
"environment",
"setup",
"command",
"prefixes",
"etc",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/context.py#L132-L137 |
226,059 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.create_archive_dir | def create_archive_dir(self):
"""
Create the archive dir
"""
archive_dir = os.path.join(self.tmp_dir, self.archive_name)
os.makedirs(archive_dir, 0o700)
return archive_dir | python | def create_archive_dir(self):
"""
Create the archive dir
"""
archive_dir = os.path.join(self.tmp_dir, self.archive_name)
os.makedirs(archive_dir, 0o700)
return archive_dir | [
"def",
"create_archive_dir",
"(",
"self",
")",
":",
"archive_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"tmp_dir",
",",
"self",
".",
"archive_name",
")",
"os",
".",
"makedirs",
"(",
"archive_dir",
",",
"0o700",
")",
"return",
"archive_d... | Create the archive dir | [
"Create",
"the",
"archive",
"dir"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L41-L47 |
226,060 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.create_command_dir | def create_command_dir(self):
"""
Create the "sos_commands" dir
"""
cmd_dir = os.path.join(self.archive_dir, "insights_commands")
os.makedirs(cmd_dir, 0o700)
return cmd_dir | python | def create_command_dir(self):
"""
Create the "sos_commands" dir
"""
cmd_dir = os.path.join(self.archive_dir, "insights_commands")
os.makedirs(cmd_dir, 0o700)
return cmd_dir | [
"def",
"create_command_dir",
"(",
"self",
")",
":",
"cmd_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"archive_dir",
",",
"\"insights_commands\"",
")",
"os",
".",
"makedirs",
"(",
"cmd_dir",
",",
"0o700",
")",
"return",
"cmd_dir"
] | Create the "sos_commands" dir | [
"Create",
"the",
"sos_commands",
"dir"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L49-L55 |
226,061 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.get_full_archive_path | def get_full_archive_path(self, path):
"""
Returns the full archive path
"""
return os.path.join(self.archive_dir, path.lstrip('/')) | python | def get_full_archive_path(self, path):
"""
Returns the full archive path
"""
return os.path.join(self.archive_dir, path.lstrip('/')) | [
"def",
"get_full_archive_path",
"(",
"self",
",",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"archive_dir",
",",
"path",
".",
"lstrip",
"(",
"'/'",
")",
")"
] | Returns the full archive path | [
"Returns",
"the",
"full",
"archive",
"path"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L57-L61 |
226,062 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive._copy_file | def _copy_file(self, path):
"""
Copy just a single file
"""
full_path = self.get_full_archive_path(path)
# Try to make the dir, eat exception if it fails
try:
os.makedirs(os.path.dirname(full_path))
except OSError:
pass
logger.debug("Copying %s to %s", path, full_path)
shutil.copyfile(path, full_path)
return path | python | def _copy_file(self, path):
"""
Copy just a single file
"""
full_path = self.get_full_archive_path(path)
# Try to make the dir, eat exception if it fails
try:
os.makedirs(os.path.dirname(full_path))
except OSError:
pass
logger.debug("Copying %s to %s", path, full_path)
shutil.copyfile(path, full_path)
return path | [
"def",
"_copy_file",
"(",
"self",
",",
"path",
")",
":",
"full_path",
"=",
"self",
".",
"get_full_archive_path",
"(",
"path",
")",
"# Try to make the dir, eat exception if it fails",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(... | Copy just a single file | [
"Copy",
"just",
"a",
"single",
"file"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L63-L75 |
226,063 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.copy_file | def copy_file(self, path):
"""
Copy a single file or regex, creating the necessary directories
"""
if "*" in path:
paths = _expand_paths(path)
if paths:
for path in paths:
self._copy_file(path)
else:
if os.path.isfile(path):
return self._copy_file(path)
else:
logger.debug("File %s does not exist", path)
return False | python | def copy_file(self, path):
"""
Copy a single file or regex, creating the necessary directories
"""
if "*" in path:
paths = _expand_paths(path)
if paths:
for path in paths:
self._copy_file(path)
else:
if os.path.isfile(path):
return self._copy_file(path)
else:
logger.debug("File %s does not exist", path)
return False | [
"def",
"copy_file",
"(",
"self",
",",
"path",
")",
":",
"if",
"\"*\"",
"in",
"path",
":",
"paths",
"=",
"_expand_paths",
"(",
"path",
")",
"if",
"paths",
":",
"for",
"path",
"in",
"paths",
":",
"self",
".",
"_copy_file",
"(",
"path",
")",
"else",
"... | Copy a single file or regex, creating the necessary directories | [
"Copy",
"a",
"single",
"file",
"or",
"regex",
"creating",
"the",
"necessary",
"directories"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L77-L91 |
226,064 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.copy_dir | def copy_dir(self, path):
"""
Recursively copy directory
"""
for directory in path:
if os.path.isdir(path):
full_path = os.path.join(self.archive_dir, directory.lstrip('/'))
logger.debug("Copying %s to %s", directory, full_path)
shutil.copytree(directory, full_path)
else:
logger.debug("Not a directory: %s", directory)
return path | python | def copy_dir(self, path):
"""
Recursively copy directory
"""
for directory in path:
if os.path.isdir(path):
full_path = os.path.join(self.archive_dir, directory.lstrip('/'))
logger.debug("Copying %s to %s", directory, full_path)
shutil.copytree(directory, full_path)
else:
logger.debug("Not a directory: %s", directory)
return path | [
"def",
"copy_dir",
"(",
"self",
",",
"path",
")",
":",
"for",
"directory",
"in",
"path",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"archive_dir",
",",
"d... | Recursively copy directory | [
"Recursively",
"copy",
"directory"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L93-L104 |
226,065 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.create_tar_file | def create_tar_file(self, full_archive=False):
"""
Create tar file to be compressed
"""
tar_file_name = os.path.join(self.archive_tmp_dir, self.archive_name)
ext = "" if self.compressor == "none" else ".%s" % self.compressor
tar_file_name = tar_file_name + ".tar" + ext
logger.debug("Tar File: " + tar_file_name)
subprocess.call(shlex.split("tar c%sfS %s -C %s ." % (
self.get_compression_flag(self.compressor),
tar_file_name,
# for the docker "uber archive,"use archive_dir
# rather than tmp_dir for all the files we tar,
# because all the individual archives are in there
self.tmp_dir if not full_archive else self.archive_dir)),
stderr=subprocess.PIPE)
self.delete_archive_dir()
logger.debug("Tar File Size: %s", str(os.path.getsize(tar_file_name)))
return tar_file_name | python | def create_tar_file(self, full_archive=False):
"""
Create tar file to be compressed
"""
tar_file_name = os.path.join(self.archive_tmp_dir, self.archive_name)
ext = "" if self.compressor == "none" else ".%s" % self.compressor
tar_file_name = tar_file_name + ".tar" + ext
logger.debug("Tar File: " + tar_file_name)
subprocess.call(shlex.split("tar c%sfS %s -C %s ." % (
self.get_compression_flag(self.compressor),
tar_file_name,
# for the docker "uber archive,"use archive_dir
# rather than tmp_dir for all the files we tar,
# because all the individual archives are in there
self.tmp_dir if not full_archive else self.archive_dir)),
stderr=subprocess.PIPE)
self.delete_archive_dir()
logger.debug("Tar File Size: %s", str(os.path.getsize(tar_file_name)))
return tar_file_name | [
"def",
"create_tar_file",
"(",
"self",
",",
"full_archive",
"=",
"False",
")",
":",
"tar_file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"archive_tmp_dir",
",",
"self",
".",
"archive_name",
")",
"ext",
"=",
"\"\"",
"if",
"self",
".",
... | Create tar file to be compressed | [
"Create",
"tar",
"file",
"to",
"be",
"compressed"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L114-L132 |
226,066 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.delete_tmp_dir | def delete_tmp_dir(self):
"""
Delete the entire tmp dir
"""
logger.debug("Deleting: " + self.tmp_dir)
shutil.rmtree(self.tmp_dir, True) | python | def delete_tmp_dir(self):
"""
Delete the entire tmp dir
"""
logger.debug("Deleting: " + self.tmp_dir)
shutil.rmtree(self.tmp_dir, True) | [
"def",
"delete_tmp_dir",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Deleting: \"",
"+",
"self",
".",
"tmp_dir",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"tmp_dir",
",",
"True",
")"
] | Delete the entire tmp dir | [
"Delete",
"the",
"entire",
"tmp",
"dir"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L134-L139 |
226,067 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.delete_archive_dir | def delete_archive_dir(self):
"""
Delete the entire archive dir
"""
logger.debug("Deleting: " + self.archive_dir)
shutil.rmtree(self.archive_dir, True) | python | def delete_archive_dir(self):
"""
Delete the entire archive dir
"""
logger.debug("Deleting: " + self.archive_dir)
shutil.rmtree(self.archive_dir, True) | [
"def",
"delete_archive_dir",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Deleting: \"",
"+",
"self",
".",
"archive_dir",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"archive_dir",
",",
"True",
")"
] | Delete the entire archive dir | [
"Delete",
"the",
"entire",
"archive",
"dir"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L141-L146 |
226,068 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.delete_archive_file | def delete_archive_file(self):
"""
Delete the directory containing the constructed archive
"""
logger.debug("Deleting %s", self.archive_tmp_dir)
shutil.rmtree(self.archive_tmp_dir, True) | python | def delete_archive_file(self):
"""
Delete the directory containing the constructed archive
"""
logger.debug("Deleting %s", self.archive_tmp_dir)
shutil.rmtree(self.archive_tmp_dir, True) | [
"def",
"delete_archive_file",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Deleting %s\"",
",",
"self",
".",
"archive_tmp_dir",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"archive_tmp_dir",
",",
"True",
")"
] | Delete the directory containing the constructed archive | [
"Delete",
"the",
"directory",
"containing",
"the",
"constructed",
"archive"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L148-L153 |
226,069 | RedHatInsights/insights-core | insights/client/archive.py | InsightsArchive.add_metadata_to_archive | def add_metadata_to_archive(self, metadata, meta_path):
'''
Add metadata to archive
'''
archive_path = self.get_full_archive_path(meta_path.lstrip('/'))
write_data_to_file(metadata, archive_path) | python | def add_metadata_to_archive(self, metadata, meta_path):
'''
Add metadata to archive
'''
archive_path = self.get_full_archive_path(meta_path.lstrip('/'))
write_data_to_file(metadata, archive_path) | [
"def",
"add_metadata_to_archive",
"(",
"self",
",",
"metadata",
",",
"meta_path",
")",
":",
"archive_path",
"=",
"self",
".",
"get_full_archive_path",
"(",
"meta_path",
".",
"lstrip",
"(",
"'/'",
")",
")",
"write_data_to_file",
"(",
"metadata",
",",
"archive_pat... | Add metadata to archive | [
"Add",
"metadata",
"to",
"archive"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L168-L173 |
226,070 | RedHatInsights/insights-core | insights/core/remote_resource.py | RemoteResource.get | def get(self, url, params={}, headers={}, auth=(), certificate_path=None):
"""
Returns the response payload from the request to the given URL.
Args:
url (str): The URL for the WEB API that the request is being made too.
params (dict): Dictionary containing the query string parameters.
headers (dict): HTTP Headers that may be needed for the request.
auth (tuple): User ID and password for Basic Auth
certificate_path (str): Path to the ssl certificate.
Returns:
response: (HttpResponse): Response object from requests.get api request
"""
certificate_path = certificate_path if certificate_path else False
return self.session.get(url, params=params, headers=headers, verify=certificate_path, auth=auth,
timeout=self.timeout) | python | def get(self, url, params={}, headers={}, auth=(), certificate_path=None):
"""
Returns the response payload from the request to the given URL.
Args:
url (str): The URL for the WEB API that the request is being made too.
params (dict): Dictionary containing the query string parameters.
headers (dict): HTTP Headers that may be needed for the request.
auth (tuple): User ID and password for Basic Auth
certificate_path (str): Path to the ssl certificate.
Returns:
response: (HttpResponse): Response object from requests.get api request
"""
certificate_path = certificate_path if certificate_path else False
return self.session.get(url, params=params, headers=headers, verify=certificate_path, auth=auth,
timeout=self.timeout) | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"{",
"}",
",",
"headers",
"=",
"{",
"}",
",",
"auth",
"=",
"(",
")",
",",
"certificate_path",
"=",
"None",
")",
":",
"certificate_path",
"=",
"certificate_path",
"if",
"certificate_path",
"else... | Returns the response payload from the request to the given URL.
Args:
url (str): The URL for the WEB API that the request is being made too.
params (dict): Dictionary containing the query string parameters.
headers (dict): HTTP Headers that may be needed for the request.
auth (tuple): User ID and password for Basic Auth
certificate_path (str): Path to the ssl certificate.
Returns:
response: (HttpResponse): Response object from requests.get api request | [
"Returns",
"the",
"response",
"payload",
"from",
"the",
"request",
"to",
"the",
"given",
"URL",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/remote_resource.py#L34-L51 |
226,071 | RedHatInsights/insights-core | insights/core/remote_resource.py | DefaultHeuristic.update_headers | def update_headers(self, response):
"""
Returns the updated caching headers.
Args:
response (HttpResponse): The response from the remote service
Returns:
response:(HttpResponse.Headers): Http caching headers
"""
if 'expires' in response.headers and 'cache-control' in response.headers:
self.msg = self.server_cache_headers
return response.headers
else:
self.msg = self.default_cache_vars
date = parsedate(response.headers['date'])
expires = datetime(*date[:6]) + timedelta(0, self.expire_after)
response.headers.update({'expires': formatdate(calendar.timegm(expires.timetuple())),
'cache-control': 'public'})
return response.headers | python | def update_headers(self, response):
"""
Returns the updated caching headers.
Args:
response (HttpResponse): The response from the remote service
Returns:
response:(HttpResponse.Headers): Http caching headers
"""
if 'expires' in response.headers and 'cache-control' in response.headers:
self.msg = self.server_cache_headers
return response.headers
else:
self.msg = self.default_cache_vars
date = parsedate(response.headers['date'])
expires = datetime(*date[:6]) + timedelta(0, self.expire_after)
response.headers.update({'expires': formatdate(calendar.timegm(expires.timetuple())),
'cache-control': 'public'})
return response.headers | [
"def",
"update_headers",
"(",
"self",
",",
"response",
")",
":",
"if",
"'expires'",
"in",
"response",
".",
"headers",
"and",
"'cache-control'",
"in",
"response",
".",
"headers",
":",
"self",
".",
"msg",
"=",
"self",
".",
"server_cache_headers",
"return",
"re... | Returns the updated caching headers.
Args:
response (HttpResponse): The response from the remote service
Returns:
response:(HttpResponse.Headers): Http caching headers | [
"Returns",
"the",
"updated",
"caching",
"headers",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/remote_resource.py#L119-L138 |
226,072 | RedHatInsights/insights-core | insights/combiners/hostname.py | hostname | def hostname(hn, ft, si):
"""Check hostname, facter and systemid to get the fqdn, hostname and domain.
Prefer hostname to facter and systemid.
Returns:
insights.combiners.hostname.Hostname: A named tuple with `fqdn`,
`hostname` and `domain` components.
Raises:
Exception: If no hostname can be found in any of the three parsers.
"""
if not hn or not hn.fqdn:
hn = ft
if hn and hn.fqdn:
fqdn = hn.fqdn
hostname = hn.hostname if hn.hostname else fqdn.split(".")[0]
domain = hn.domain if hn.domain else ".".join(fqdn.split(".")[1:])
return Hostname(fqdn, hostname, domain)
else:
fqdn = si.get("profile_name") if si else None
if fqdn:
hostname = fqdn.split(".")[0]
domain = ".".join(fqdn.split(".")[1:])
return Hostname(fqdn, hostname, domain)
raise Exception("Unable to get hostname.") | python | def hostname(hn, ft, si):
"""Check hostname, facter and systemid to get the fqdn, hostname and domain.
Prefer hostname to facter and systemid.
Returns:
insights.combiners.hostname.Hostname: A named tuple with `fqdn`,
`hostname` and `domain` components.
Raises:
Exception: If no hostname can be found in any of the three parsers.
"""
if not hn or not hn.fqdn:
hn = ft
if hn and hn.fqdn:
fqdn = hn.fqdn
hostname = hn.hostname if hn.hostname else fqdn.split(".")[0]
domain = hn.domain if hn.domain else ".".join(fqdn.split(".")[1:])
return Hostname(fqdn, hostname, domain)
else:
fqdn = si.get("profile_name") if si else None
if fqdn:
hostname = fqdn.split(".")[0]
domain = ".".join(fqdn.split(".")[1:])
return Hostname(fqdn, hostname, domain)
raise Exception("Unable to get hostname.") | [
"def",
"hostname",
"(",
"hn",
",",
"ft",
",",
"si",
")",
":",
"if",
"not",
"hn",
"or",
"not",
"hn",
".",
"fqdn",
":",
"hn",
"=",
"ft",
"if",
"hn",
"and",
"hn",
".",
"fqdn",
":",
"fqdn",
"=",
"hn",
".",
"fqdn",
"hostname",
"=",
"hn",
".",
"h... | Check hostname, facter and systemid to get the fqdn, hostname and domain.
Prefer hostname to facter and systemid.
Returns:
insights.combiners.hostname.Hostname: A named tuple with `fqdn`,
`hostname` and `domain` components.
Raises:
Exception: If no hostname can be found in any of the three parsers. | [
"Check",
"hostname",
"facter",
"and",
"systemid",
"to",
"get",
"the",
"fqdn",
"hostname",
"and",
"domain",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/combiners/hostname.py#L44-L72 |
226,073 | RedHatInsights/insights-core | insights/configtree/iniconfig.py | parse_doc | def parse_doc(f, ctx=None, overwrite=False):
""" Accepts an open file or a list of lines. """
lg = LineGetter(f, comment_marker=("#", ";"), strip=False)
cfg = ConfigParser(ctx).parse_doc(lg)
set_defaults(cfg)
if overwrite:
squash(cfg)
return cfg | python | def parse_doc(f, ctx=None, overwrite=False):
""" Accepts an open file or a list of lines. """
lg = LineGetter(f, comment_marker=("#", ";"), strip=False)
cfg = ConfigParser(ctx).parse_doc(lg)
set_defaults(cfg)
if overwrite:
squash(cfg)
return cfg | [
"def",
"parse_doc",
"(",
"f",
",",
"ctx",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"lg",
"=",
"LineGetter",
"(",
"f",
",",
"comment_marker",
"=",
"(",
"\"#\"",
",",
"\";\"",
")",
",",
"strip",
"=",
"False",
")",
"cfg",
"=",
"ConfigPar... | Accepts an open file or a list of lines. | [
"Accepts",
"an",
"open",
"file",
"or",
"a",
"list",
"of",
"lines",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/configtree/iniconfig.py#L82-L89 |
226,074 | RedHatInsights/insights-core | insights/parsers/uname.py | pad_release | def pad_release(release_to_pad, num_sections=4):
'''
Pad out package and kernel release versions so that
``LooseVersion`` comparisons will be correct.
Release versions with less than num_sections will
be padded in front of the last section with zeros.
For example ::
pad_release("390.el6", 4)
will return ``390.0.0.el6`` and ::
pad_release("390.11.el6", 4)
will return ``390.11.0.el6``.
If the number of sections of the release to be padded is
greater than num_sections, a ``ValueError`` will be raised.
'''
parts = release_to_pad.split('.')
if len(parts) > num_sections:
raise ValueError("Too many sections encountered ({found} > {num} in release string {rel}".format(
found=len(parts), num=num_sections, rel=release_to_pad
))
pad_count = num_sections - len(parts)
return ".".join(parts[:-1] + ['0'] * pad_count + parts[-1:]) | python | def pad_release(release_to_pad, num_sections=4):
'''
Pad out package and kernel release versions so that
``LooseVersion`` comparisons will be correct.
Release versions with less than num_sections will
be padded in front of the last section with zeros.
For example ::
pad_release("390.el6", 4)
will return ``390.0.0.el6`` and ::
pad_release("390.11.el6", 4)
will return ``390.11.0.el6``.
If the number of sections of the release to be padded is
greater than num_sections, a ``ValueError`` will be raised.
'''
parts = release_to_pad.split('.')
if len(parts) > num_sections:
raise ValueError("Too many sections encountered ({found} > {num} in release string {rel}".format(
found=len(parts), num=num_sections, rel=release_to_pad
))
pad_count = num_sections - len(parts)
return ".".join(parts[:-1] + ['0'] * pad_count + parts[-1:]) | [
"def",
"pad_release",
"(",
"release_to_pad",
",",
"num_sections",
"=",
"4",
")",
":",
"parts",
"=",
"release_to_pad",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
">",
"num_sections",
":",
"raise",
"ValueError",
"(",
"\"Too many sections en... | Pad out package and kernel release versions so that
``LooseVersion`` comparisons will be correct.
Release versions with less than num_sections will
be padded in front of the last section with zeros.
For example ::
pad_release("390.el6", 4)
will return ``390.0.0.el6`` and ::
pad_release("390.11.el6", 4)
will return ``390.11.0.el6``.
If the number of sections of the release to be padded is
greater than num_sections, a ``ValueError`` will be raised. | [
"Pad",
"out",
"package",
"and",
"kernel",
"release",
"versions",
"so",
"that",
"LooseVersion",
"comparisons",
"will",
"be",
"correct",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/uname.py#L537-L566 |
226,075 | RedHatInsights/insights-core | insights/parsers/alternatives.py | AlternativesOutput.parse_content | def parse_content(self, content):
"""
Parse the output of the ``alternatives`` command.
"""
self.program = None
self.status = None
self.link = None
self.best = None
self.paths = []
current_path = None
# Set up instance variable
for line in content:
words = line.split(None)
if ' - status is' in line:
# alternatives only displays one program, so finding
# this line again is an error.
if self.program:
raise ParseException(
"Program line for {newprog} found in output for {oldprog}".format(
newprog=words[0], oldprog=self.program
)
)
# Set up new program data
self.program = words[0]
self.status = words[4][:-1] # remove trailing .
self.alternatives = []
current_path = {}
elif not self.program:
# Lines before 'status is' line are ignored
continue
elif line.startswith(' link currently points to ') and len(words) == 5:
# line: ' link currently points to /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.111-1.b15.el7_2.x86_64/jre/bin/java'
self.link = words[4]
elif ' - priority ' in line and len(words) == 4 and words[3].isdigit():
# line: /usr/lib/jvm/jre-1.6.0-ibm.x86_64/bin/java - priority 16091
# New path - save current path if set
self.paths.append({
'path': words[0],
'priority': int(words[3]),
'slave': {},
})
current_path = self.paths[-1]
elif line.startswith(' slave ') and len(words) == 3 and current_path:
# line: ' slave ControlPanel: /usr/lib/jvm/jre-1.6.0-ibm.x86_64/bin/ControlPanel'
current_path['slave'][words[1][:-1]] = words[2] # remove final : from program
elif line.startswith("Current `best' version is ") and len(words) == 5:
# line: 'Current `best' version is /usr/lib/jvm/jre-1.6.0-ibm.x86_64/bin/java.'
self.best = words[4][:-1] | python | def parse_content(self, content):
"""
Parse the output of the ``alternatives`` command.
"""
self.program = None
self.status = None
self.link = None
self.best = None
self.paths = []
current_path = None
# Set up instance variable
for line in content:
words = line.split(None)
if ' - status is' in line:
# alternatives only displays one program, so finding
# this line again is an error.
if self.program:
raise ParseException(
"Program line for {newprog} found in output for {oldprog}".format(
newprog=words[0], oldprog=self.program
)
)
# Set up new program data
self.program = words[0]
self.status = words[4][:-1] # remove trailing .
self.alternatives = []
current_path = {}
elif not self.program:
# Lines before 'status is' line are ignored
continue
elif line.startswith(' link currently points to ') and len(words) == 5:
# line: ' link currently points to /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.111-1.b15.el7_2.x86_64/jre/bin/java'
self.link = words[4]
elif ' - priority ' in line and len(words) == 4 and words[3].isdigit():
# line: /usr/lib/jvm/jre-1.6.0-ibm.x86_64/bin/java - priority 16091
# New path - save current path if set
self.paths.append({
'path': words[0],
'priority': int(words[3]),
'slave': {},
})
current_path = self.paths[-1]
elif line.startswith(' slave ') and len(words) == 3 and current_path:
# line: ' slave ControlPanel: /usr/lib/jvm/jre-1.6.0-ibm.x86_64/bin/ControlPanel'
current_path['slave'][words[1][:-1]] = words[2] # remove final : from program
elif line.startswith("Current `best' version is ") and len(words) == 5:
# line: 'Current `best' version is /usr/lib/jvm/jre-1.6.0-ibm.x86_64/bin/java.'
self.best = words[4][:-1] | [
"def",
"parse_content",
"(",
"self",
",",
"content",
")",
":",
"self",
".",
"program",
"=",
"None",
"self",
".",
"status",
"=",
"None",
"self",
".",
"link",
"=",
"None",
"self",
".",
"best",
"=",
"None",
"self",
".",
"paths",
"=",
"[",
"]",
"curren... | Parse the output of the ``alternatives`` command. | [
"Parse",
"the",
"output",
"of",
"the",
"alternatives",
"command",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/alternatives.py#L79-L127 |
226,076 | RedHatInsights/insights-core | insights/core/__init__.py | CommandParser.validate_lines | def validate_lines(results, bad_lines):
"""
If `results` contains a single line and that line is included
in the `bad_lines` list, this function returns `False`. If no bad
line is found the function returns `True`
Parameters:
results(str): The results string of the output from the command
defined by the command spec.
Returns:
(Boolean): True for no bad lines or False for bad line found.
"""
if results and len(results) == 1:
first = results[0]
if any(l in first.lower() for l in bad_lines):
return False
return True | python | def validate_lines(results, bad_lines):
"""
If `results` contains a single line and that line is included
in the `bad_lines` list, this function returns `False`. If no bad
line is found the function returns `True`
Parameters:
results(str): The results string of the output from the command
defined by the command spec.
Returns:
(Boolean): True for no bad lines or False for bad line found.
"""
if results and len(results) == 1:
first = results[0]
if any(l in first.lower() for l in bad_lines):
return False
return True | [
"def",
"validate_lines",
"(",
"results",
",",
"bad_lines",
")",
":",
"if",
"results",
"and",
"len",
"(",
"results",
")",
"==",
"1",
":",
"first",
"=",
"results",
"[",
"0",
"]",
"if",
"any",
"(",
"l",
"in",
"first",
".",
"lower",
"(",
")",
"for",
... | If `results` contains a single line and that line is included
in the `bad_lines` list, this function returns `False`. If no bad
line is found the function returns `True`
Parameters:
results(str): The results string of the output from the command
defined by the command spec.
Returns:
(Boolean): True for no bad lines or False for bad line found. | [
"If",
"results",
"contains",
"a",
"single",
"line",
"and",
"that",
"line",
"is",
"included",
"in",
"the",
"bad_lines",
"list",
"this",
"function",
"returns",
"False",
".",
"If",
"no",
"bad",
"line",
"is",
"found",
"the",
"function",
"returns",
"True"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L528-L546 |
226,077 | RedHatInsights/insights-core | insights/core/__init__.py | Scannable._scan | def _scan(cls, result_key, scanner):
"""
Registers a `scanner` which is a function that will be called once per
logical line in a document. A scanners job is to evaluate the content
of the line and set a so-called `result_key` on the class to be
retrieved later by a rule.
"""
if result_key in cls.scanner_keys:
raise ValueError("'%s' is already a registered scanner key" % result_key)
cls.scanners.append(scanner)
cls.scanner_keys.add(result_key) | python | def _scan(cls, result_key, scanner):
"""
Registers a `scanner` which is a function that will be called once per
logical line in a document. A scanners job is to evaluate the content
of the line and set a so-called `result_key` on the class to be
retrieved later by a rule.
"""
if result_key in cls.scanner_keys:
raise ValueError("'%s' is already a registered scanner key" % result_key)
cls.scanners.append(scanner)
cls.scanner_keys.add(result_key) | [
"def",
"_scan",
"(",
"cls",
",",
"result_key",
",",
"scanner",
")",
":",
"if",
"result_key",
"in",
"cls",
".",
"scanner_keys",
":",
"raise",
"ValueError",
"(",
"\"'%s' is already a registered scanner key\"",
"%",
"result_key",
")",
"cls",
".",
"scanners",
".",
... | Registers a `scanner` which is a function that will be called once per
logical line in a document. A scanners job is to evaluate the content
of the line and set a so-called `result_key` on the class to be
retrieved later by a rule. | [
"Registers",
"a",
"scanner",
"which",
"is",
"a",
"function",
"that",
"will",
"be",
"called",
"once",
"per",
"logical",
"line",
"in",
"a",
"document",
".",
"A",
"scanners",
"job",
"is",
"to",
"evaluate",
"the",
"content",
"of",
"the",
"line",
"and",
"set"... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L790-L802 |
226,078 | RedHatInsights/insights-core | insights/core/__init__.py | Scannable.any | def any(cls, result_key, func):
"""
Sets the `result_key` to the output of `func` if `func` ever returns
truthy
"""
def scanner(self, obj):
current_value = getattr(self, result_key, None)
setattr(self, result_key, current_value or func(obj))
cls._scan(result_key, scanner) | python | def any(cls, result_key, func):
"""
Sets the `result_key` to the output of `func` if `func` ever returns
truthy
"""
def scanner(self, obj):
current_value = getattr(self, result_key, None)
setattr(self, result_key, current_value or func(obj))
cls._scan(result_key, scanner) | [
"def",
"any",
"(",
"cls",
",",
"result_key",
",",
"func",
")",
":",
"def",
"scanner",
"(",
"self",
",",
"obj",
")",
":",
"current_value",
"=",
"getattr",
"(",
"self",
",",
"result_key",
",",
"None",
")",
"setattr",
"(",
"self",
",",
"result_key",
","... | Sets the `result_key` to the output of `func` if `func` ever returns
truthy | [
"Sets",
"the",
"result_key",
"to",
"the",
"output",
"of",
"func",
"if",
"func",
"ever",
"returns",
"truthy"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L805-L814 |
226,079 | RedHatInsights/insights-core | insights/core/__init__.py | LogFileOutput.parse_content | def parse_content(self, content):
"""
Use all the defined scanners to search the log file, setting the
properties defined in the scanner.
"""
self.lines = content
for scanner in self.scanners:
scanner(self) | python | def parse_content(self, content):
"""
Use all the defined scanners to search the log file, setting the
properties defined in the scanner.
"""
self.lines = content
for scanner in self.scanners:
scanner(self) | [
"def",
"parse_content",
"(",
"self",
",",
"content",
")",
":",
"self",
".",
"lines",
"=",
"content",
"for",
"scanner",
"in",
"self",
".",
"scanners",
":",
"scanner",
"(",
"self",
")"
] | Use all the defined scanners to search the log file, setting the
properties defined in the scanner. | [
"Use",
"all",
"the",
"defined",
"scanners",
"to",
"search",
"the",
"log",
"file",
"setting",
"the",
"properties",
"defined",
"in",
"the",
"scanner",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L902-L909 |
226,080 | RedHatInsights/insights-core | insights/core/__init__.py | LogFileOutput._valid_search | def _valid_search(self, s):
"""
Check this given `s`, it must be a string or a list of strings.
Otherwise, a TypeError will be raised.
"""
if isinstance(s, six.string_types):
return lambda l: s in l
elif (isinstance(s, list) and len(s) > 0 and
all(isinstance(w, six.string_types) for w in s)):
return lambda l: all(w in l for w in s)
elif s is not None:
raise TypeError('Search items must be given as a string or a list of strings') | python | def _valid_search(self, s):
"""
Check this given `s`, it must be a string or a list of strings.
Otherwise, a TypeError will be raised.
"""
if isinstance(s, six.string_types):
return lambda l: s in l
elif (isinstance(s, list) and len(s) > 0 and
all(isinstance(w, six.string_types) for w in s)):
return lambda l: all(w in l for w in s)
elif s is not None:
raise TypeError('Search items must be given as a string or a list of strings') | [
"def",
"_valid_search",
"(",
"self",
",",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
":",
"return",
"lambda",
"l",
":",
"s",
"in",
"l",
"elif",
"(",
"isinstance",
"(",
"s",
",",
"list",
")",
"and",
"len",
"... | Check this given `s`, it must be a string or a list of strings.
Otherwise, a TypeError will be raised. | [
"Check",
"this",
"given",
"s",
"it",
"must",
"be",
"a",
"string",
"or",
"a",
"list",
"of",
"strings",
".",
"Otherwise",
"a",
"TypeError",
"will",
"be",
"raised",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L925-L936 |
226,081 | RedHatInsights/insights-core | insights/core/__init__.py | LogFileOutput.get | def get(self, s):
"""
Returns all lines that contain `s` anywhere and wrap them in a list of
dictionaries. `s` can be either a single string or a string list. For
list, all keywords in the list must be found in each line.
Parameters:
s(str or list): one or more strings to search for.
Returns:
(list): list of dictionaries corresponding to the parsed lines
contain the `s`.
"""
ret = []
search_by_expression = self._valid_search(s)
for l in self.lines:
if search_by_expression(l):
ret.append(self._parse_line(l))
return ret | python | def get(self, s):
"""
Returns all lines that contain `s` anywhere and wrap them in a list of
dictionaries. `s` can be either a single string or a string list. For
list, all keywords in the list must be found in each line.
Parameters:
s(str or list): one or more strings to search for.
Returns:
(list): list of dictionaries corresponding to the parsed lines
contain the `s`.
"""
ret = []
search_by_expression = self._valid_search(s)
for l in self.lines:
if search_by_expression(l):
ret.append(self._parse_line(l))
return ret | [
"def",
"get",
"(",
"self",
",",
"s",
")",
":",
"ret",
"=",
"[",
"]",
"search_by_expression",
"=",
"self",
".",
"_valid_search",
"(",
"s",
")",
"for",
"l",
"in",
"self",
".",
"lines",
":",
"if",
"search_by_expression",
"(",
"l",
")",
":",
"ret",
"."... | Returns all lines that contain `s` anywhere and wrap them in a list of
dictionaries. `s` can be either a single string or a string list. For
list, all keywords in the list must be found in each line.
Parameters:
s(str or list): one or more strings to search for.
Returns:
(list): list of dictionaries corresponding to the parsed lines
contain the `s`. | [
"Returns",
"all",
"lines",
"that",
"contain",
"s",
"anywhere",
"and",
"wrap",
"them",
"in",
"a",
"list",
"of",
"dictionaries",
".",
"s",
"can",
"be",
"either",
"a",
"single",
"string",
"or",
"a",
"string",
"list",
".",
"For",
"list",
"all",
"keywords",
... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L938-L956 |
226,082 | RedHatInsights/insights-core | insights/core/__init__.py | LogFileOutput.scan | def scan(cls, result_key, func):
"""
Define computed fields based on a string to "grep for". This is
preferred to utilizing raw log lines in plugins because computed fields
will be serialized, whereas raw log lines will not.
"""
if result_key in cls.scanner_keys:
raise ValueError("'%s' is already a registered scanner key" % result_key)
def scanner(self):
result = func(self)
setattr(self, result_key, result)
cls.scanners.append(scanner)
cls.scanner_keys.add(result_key) | python | def scan(cls, result_key, func):
"""
Define computed fields based on a string to "grep for". This is
preferred to utilizing raw log lines in plugins because computed fields
will be serialized, whereas raw log lines will not.
"""
if result_key in cls.scanner_keys:
raise ValueError("'%s' is already a registered scanner key" % result_key)
def scanner(self):
result = func(self)
setattr(self, result_key, result)
cls.scanners.append(scanner)
cls.scanner_keys.add(result_key) | [
"def",
"scan",
"(",
"cls",
",",
"result_key",
",",
"func",
")",
":",
"if",
"result_key",
"in",
"cls",
".",
"scanner_keys",
":",
"raise",
"ValueError",
"(",
"\"'%s' is already a registered scanner key\"",
"%",
"result_key",
")",
"def",
"scanner",
"(",
"self",
"... | Define computed fields based on a string to "grep for". This is
preferred to utilizing raw log lines in plugins because computed fields
will be serialized, whereas raw log lines will not. | [
"Define",
"computed",
"fields",
"based",
"on",
"a",
"string",
"to",
"grep",
"for",
".",
"This",
"is",
"preferred",
"to",
"utilizing",
"raw",
"log",
"lines",
"in",
"plugins",
"because",
"computed",
"fields",
"will",
"be",
"serialized",
"whereas",
"raw",
"log"... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L959-L974 |
226,083 | RedHatInsights/insights-core | insights/core/__init__.py | LogFileOutput.keep_scan | def keep_scan(cls, result_key, token):
"""
Define a property that is set to the list of lines that contain the
given token. Uses the get method of the log file.
"""
def _scan(self):
return self.get(token)
cls.scan(result_key, _scan) | python | def keep_scan(cls, result_key, token):
"""
Define a property that is set to the list of lines that contain the
given token. Uses the get method of the log file.
"""
def _scan(self):
return self.get(token)
cls.scan(result_key, _scan) | [
"def",
"keep_scan",
"(",
"cls",
",",
"result_key",
",",
"token",
")",
":",
"def",
"_scan",
"(",
"self",
")",
":",
"return",
"self",
".",
"get",
"(",
"token",
")",
"cls",
".",
"scan",
"(",
"result_key",
",",
"_scan",
")"
] | Define a property that is set to the list of lines that contain the
given token. Uses the get method of the log file. | [
"Define",
"a",
"property",
"that",
"is",
"set",
"to",
"the",
"list",
"of",
"lines",
"that",
"contain",
"the",
"given",
"token",
".",
"Uses",
"the",
"get",
"method",
"of",
"the",
"log",
"file",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L988-L996 |
226,084 | RedHatInsights/insights-core | insights/core/__init__.py | IniConfigFile.parse_content | def parse_content(self, content, allow_no_value=False):
"""Parses content of the config file.
In child class overload and call super to set flag
``allow_no_values`` and allow keys with no value in
config file::
def parse_content(self, content):
super(YourClass, self).parse_content(content,
allow_no_values=True)
"""
super(IniConfigFile, self).parse_content(content)
config = RawConfigParser(allow_no_value=allow_no_value)
fp = io.StringIO(u"\n".join(content))
config.readfp(fp, filename=self.file_name)
self.data = config | python | def parse_content(self, content, allow_no_value=False):
"""Parses content of the config file.
In child class overload and call super to set flag
``allow_no_values`` and allow keys with no value in
config file::
def parse_content(self, content):
super(YourClass, self).parse_content(content,
allow_no_values=True)
"""
super(IniConfigFile, self).parse_content(content)
config = RawConfigParser(allow_no_value=allow_no_value)
fp = io.StringIO(u"\n".join(content))
config.readfp(fp, filename=self.file_name)
self.data = config | [
"def",
"parse_content",
"(",
"self",
",",
"content",
",",
"allow_no_value",
"=",
"False",
")",
":",
"super",
"(",
"IniConfigFile",
",",
"self",
")",
".",
"parse_content",
"(",
"content",
")",
"config",
"=",
"RawConfigParser",
"(",
"allow_no_value",
"=",
"all... | Parses content of the config file.
In child class overload and call super to set flag
``allow_no_values`` and allow keys with no value in
config file::
def parse_content(self, content):
super(YourClass, self).parse_content(content,
allow_no_values=True) | [
"Parses",
"content",
"of",
"the",
"config",
"file",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L1315-L1330 |
226,085 | RedHatInsights/insights-core | insights/core/__init__.py | FileListing.path_entry | def path_entry(self, path):
"""
The parsed data given a path, which is separated into its directory
and entry name.
"""
if path[0] != '/':
return None
path_parts = path.split('/')
# Note that here the first element will be '' because it's before the
# first separator. That's OK, the join puts it back together.
directory = '/'.join(path_parts[:-1])
name = path_parts[-1]
if directory not in self.listings:
return None
if name not in self.listings[directory]['entries']:
return None
return self.listings[directory]['entries'][name] | python | def path_entry(self, path):
"""
The parsed data given a path, which is separated into its directory
and entry name.
"""
if path[0] != '/':
return None
path_parts = path.split('/')
# Note that here the first element will be '' because it's before the
# first separator. That's OK, the join puts it back together.
directory = '/'.join(path_parts[:-1])
name = path_parts[-1]
if directory not in self.listings:
return None
if name not in self.listings[directory]['entries']:
return None
return self.listings[directory]['entries'][name] | [
"def",
"path_entry",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"[",
"0",
"]",
"!=",
"'/'",
":",
"return",
"None",
"path_parts",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"# Note that here the first element will be '' because it's before the",
"# first ... | The parsed data given a path, which is separated into its directory
and entry name. | [
"The",
"parsed",
"data",
"given",
"a",
"path",
"which",
"is",
"separated",
"into",
"its",
"directory",
"and",
"entry",
"name",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/__init__.py#L1525-L1541 |
226,086 | RedHatInsights/insights-core | insights/client/util.py | image_by_name | def image_by_name(img_name, images=None):
"""
Returns a list of image data for images which match img_name. Will
optionally take a list of images from a docker.Client.images
query to avoid multiple docker queries.
"""
i_reg, i_rep, i_tag = _decompose(img_name)
# Correct for bash-style matching expressions.
if not i_reg:
i_reg = '*'
if not i_tag:
i_tag = '*'
# If the images were not passed in, go get them.
if images is None:
c = docker.Client(**kwargs_from_env())
images = c.images(all=False)
valid_images = []
for i in images:
for t in i['RepoTags']:
reg, rep, tag = _decompose(t)
if matches(reg, i_reg) \
and matches(rep, i_rep) \
and matches(tag, i_tag):
valid_images.append(i)
break
# Some repo after decompose end up with the img_name
# at the end. i.e. rhel7/rsyslog
if rep.endswith(img_name):
valid_images.append(i)
break
return valid_images | python | def image_by_name(img_name, images=None):
"""
Returns a list of image data for images which match img_name. Will
optionally take a list of images from a docker.Client.images
query to avoid multiple docker queries.
"""
i_reg, i_rep, i_tag = _decompose(img_name)
# Correct for bash-style matching expressions.
if not i_reg:
i_reg = '*'
if not i_tag:
i_tag = '*'
# If the images were not passed in, go get them.
if images is None:
c = docker.Client(**kwargs_from_env())
images = c.images(all=False)
valid_images = []
for i in images:
for t in i['RepoTags']:
reg, rep, tag = _decompose(t)
if matches(reg, i_reg) \
and matches(rep, i_rep) \
and matches(tag, i_tag):
valid_images.append(i)
break
# Some repo after decompose end up with the img_name
# at the end. i.e. rhel7/rsyslog
if rep.endswith(img_name):
valid_images.append(i)
break
return valid_images | [
"def",
"image_by_name",
"(",
"img_name",
",",
"images",
"=",
"None",
")",
":",
"i_reg",
",",
"i_rep",
",",
"i_tag",
"=",
"_decompose",
"(",
"img_name",
")",
"# Correct for bash-style matching expressions.",
"if",
"not",
"i_reg",
":",
"i_reg",
"=",
"'*'",
"if",... | Returns a list of image data for images which match img_name. Will
optionally take a list of images from a docker.Client.images
query to avoid multiple docker queries. | [
"Returns",
"a",
"list",
"of",
"image",
"data",
"for",
"images",
"which",
"match",
"img_name",
".",
"Will",
"optionally",
"take",
"a",
"list",
"of",
"images",
"from",
"a",
"docker",
".",
"Client",
".",
"images",
"query",
"to",
"avoid",
"multiple",
"docker",... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/util.py#L31-L64 |
226,087 | RedHatInsights/insights-core | insights/client/util.py | subp | def subp(cmd):
"""
Run a command as a subprocess.
Return a triple of return code, standard out, standard err.
"""
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate()
return ReturnTuple(proc.returncode, stdout=out, stderr=err) | python | def subp(cmd):
"""
Run a command as a subprocess.
Return a triple of return code, standard out, standard err.
"""
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate()
return ReturnTuple(proc.returncode, stdout=out, stderr=err) | [
"def",
"subp",
"(",
"cmd",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"out",
",",
"err",
"=",
"proc",
".",
"communicate",
"(",
")... | Run a command as a subprocess.
Return a triple of return code, standard out, standard err. | [
"Run",
"a",
"command",
"as",
"a",
"subprocess",
".",
"Return",
"a",
"triple",
"of",
"return",
"code",
"standard",
"out",
"standard",
"err",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/util.py#L67-L75 |
226,088 | RedHatInsights/insights-core | insights/client/util.py | print_scan_summary | def print_scan_summary(json_data, names=None):
'''
Print a summary of the data returned from a
CVE scan.
'''
max_col_width = 50
min_width = 15
def _max_width(data):
max_name = 0
for name in data:
max_name = len(data[name]) if len(data[name]) > max_name \
else max_name
# If the max name length is less that max_width
if max_name < min_width:
max_name = min_width
# If the man name is greater than the max col leng
# we wish to use
if max_name > max_col_width:
max_name = max_col_width
return max_name
clean = True
if len(names) > 0:
max_width = _max_width(names)
else:
max_width = min_width
template = "{0:" + str(max_width) + "} {1:5} {2:5} {3:5} {4:5}"
sevs = ['critical', 'important', 'moderate', 'low']
writeOut(template.format("Container/Image", "Cri", "Imp", "Med", "Low"))
writeOut(template.format("-" * max_width, "---", "---", "---", "---"))
res_summary = json_data['results_summary']
for image in res_summary.keys():
image_res = res_summary[image]
if 'msg' in image_res.keys():
tmp_tuple = (image_res['msg'], "", "", "", "")
else:
if len(names) < 1:
image_name = image[:max_width]
else:
image_name = names[image][-max_width:]
if len(image_name) == max_col_width:
image_name = '...' + image_name[-(len(image_name) - 3):]
tmp_tuple = tuple([image_name] +
[str(image_res[sev]) for sev in sevs])
sev_results = [image_res[sev] for sev in
sevs if image_res[sev] > 0]
if len(sev_results) > 0:
clean = False
writeOut(template.format(*tmp_tuple))
writeOut("")
return clean | python | def print_scan_summary(json_data, names=None):
'''
Print a summary of the data returned from a
CVE scan.
'''
max_col_width = 50
min_width = 15
def _max_width(data):
max_name = 0
for name in data:
max_name = len(data[name]) if len(data[name]) > max_name \
else max_name
# If the max name length is less that max_width
if max_name < min_width:
max_name = min_width
# If the man name is greater than the max col leng
# we wish to use
if max_name > max_col_width:
max_name = max_col_width
return max_name
clean = True
if len(names) > 0:
max_width = _max_width(names)
else:
max_width = min_width
template = "{0:" + str(max_width) + "} {1:5} {2:5} {3:5} {4:5}"
sevs = ['critical', 'important', 'moderate', 'low']
writeOut(template.format("Container/Image", "Cri", "Imp", "Med", "Low"))
writeOut(template.format("-" * max_width, "---", "---", "---", "---"))
res_summary = json_data['results_summary']
for image in res_summary.keys():
image_res = res_summary[image]
if 'msg' in image_res.keys():
tmp_tuple = (image_res['msg'], "", "", "", "")
else:
if len(names) < 1:
image_name = image[:max_width]
else:
image_name = names[image][-max_width:]
if len(image_name) == max_col_width:
image_name = '...' + image_name[-(len(image_name) - 3):]
tmp_tuple = tuple([image_name] +
[str(image_res[sev]) for sev in sevs])
sev_results = [image_res[sev] for sev in
sevs if image_res[sev] > 0]
if len(sev_results) > 0:
clean = False
writeOut(template.format(*tmp_tuple))
writeOut("")
return clean | [
"def",
"print_scan_summary",
"(",
"json_data",
",",
"names",
"=",
"None",
")",
":",
"max_col_width",
"=",
"50",
"min_width",
"=",
"15",
"def",
"_max_width",
"(",
"data",
")",
":",
"max_name",
"=",
"0",
"for",
"name",
"in",
"data",
":",
"max_name",
"=",
... | Print a summary of the data returned from a
CVE scan. | [
"Print",
"a",
"summary",
"of",
"the",
"data",
"returned",
"from",
"a",
"CVE",
"scan",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/util.py#L98-L153 |
226,089 | RedHatInsights/insights-core | insights/client/util.py | print_detail_scan_summary | def print_detail_scan_summary(json_data, names=None):
'''
Print a detailed summary of the data returned from
a CVE scan.
'''
clean = True
sevs = ['Critical', 'Important', 'Moderate', 'Low']
cve_summary = json_data['host_results']
image_template = " {0:10}: {1}"
cve_template = " {0:10}: {1}"
for image in cve_summary.keys():
image_res = cve_summary[image]
writeOut("")
writeOut(image[:12])
if not image_res['isRHEL']:
writeOut(image_template.format("Result",
"Not based on Red Hat"
"Enterprise Linux"))
continue
else:
writeOut(image_template.format("OS", image_res['os'].rstrip()))
scan_results = image_res['cve_summary']['scan_results']
for sev in sevs:
if sev in scan_results:
clean = False
writeOut(image_template.format(sev,
str(scan_results[sev]['num'])))
for cve in scan_results[sev]['cves']:
writeOut(cve_template.format("CVE", cve['cve_title']))
writeOut(cve_template.format("CVE URL",
cve['cve_ref_url']))
writeOut(cve_template.format("RHSA ID",
cve['rhsa_ref_id']))
writeOut(cve_template.format("RHSA URL",
cve['rhsa_ref_url']))
writeOut("")
return clean | python | def print_detail_scan_summary(json_data, names=None):
'''
Print a detailed summary of the data returned from
a CVE scan.
'''
clean = True
sevs = ['Critical', 'Important', 'Moderate', 'Low']
cve_summary = json_data['host_results']
image_template = " {0:10}: {1}"
cve_template = " {0:10}: {1}"
for image in cve_summary.keys():
image_res = cve_summary[image]
writeOut("")
writeOut(image[:12])
if not image_res['isRHEL']:
writeOut(image_template.format("Result",
"Not based on Red Hat"
"Enterprise Linux"))
continue
else:
writeOut(image_template.format("OS", image_res['os'].rstrip()))
scan_results = image_res['cve_summary']['scan_results']
for sev in sevs:
if sev in scan_results:
clean = False
writeOut(image_template.format(sev,
str(scan_results[sev]['num'])))
for cve in scan_results[sev]['cves']:
writeOut(cve_template.format("CVE", cve['cve_title']))
writeOut(cve_template.format("CVE URL",
cve['cve_ref_url']))
writeOut(cve_template.format("RHSA ID",
cve['rhsa_ref_id']))
writeOut(cve_template.format("RHSA URL",
cve['rhsa_ref_url']))
writeOut("")
return clean | [
"def",
"print_detail_scan_summary",
"(",
"json_data",
",",
"names",
"=",
"None",
")",
":",
"clean",
"=",
"True",
"sevs",
"=",
"[",
"'Critical'",
",",
"'Important'",
",",
"'Moderate'",
",",
"'Low'",
"]",
"cve_summary",
"=",
"json_data",
"[",
"'host_results'",
... | Print a detailed summary of the data returned from
a CVE scan. | [
"Print",
"a",
"detailed",
"summary",
"of",
"the",
"data",
"returned",
"from",
"a",
"CVE",
"scan",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/util.py#L156-L193 |
226,090 | RedHatInsights/insights-core | insights/util/subproc.py | call | def call(cmd,
timeout=None,
signum=signal.SIGKILL,
keep_rc=False,
encoding="utf-8",
env=os.environ):
"""
Execute a cmd or list of commands with an optional timeout in seconds.
If `timeout` is supplied and expires, the process is killed with
SIGKILL (kill -9) and an exception is raised. Otherwise, the command
output is returned.
Parameters
----------
cmd: str or [[str]]
The command(s) to execute
timeout: int
Seconds before kill is issued to the process
signum: int
The signal number to issue to the process on timeout
keep_rc: bool
Whether to return the exit code along with the output
encoding: str
unicode decoding scheme to use. Default is "utf-8"
env: dict
The environment in which to execute commands. Default is os.environ
Returns
-------
str
Content of stdout of cmd on success.
Raises
------
CalledProcessError
Raised when cmd fails
"""
if not isinstance(cmd, list):
cmd = [cmd]
p = Pipeline(*cmd, timeout=timeout, signum=signum, env=env)
res = p(keep_rc=keep_rc)
if keep_rc:
rc, output = res
output = output.decode(encoding, 'ignore')
return rc, output
return res.decode(encoding, "ignore") | python | def call(cmd,
timeout=None,
signum=signal.SIGKILL,
keep_rc=False,
encoding="utf-8",
env=os.environ):
"""
Execute a cmd or list of commands with an optional timeout in seconds.
If `timeout` is supplied and expires, the process is killed with
SIGKILL (kill -9) and an exception is raised. Otherwise, the command
output is returned.
Parameters
----------
cmd: str or [[str]]
The command(s) to execute
timeout: int
Seconds before kill is issued to the process
signum: int
The signal number to issue to the process on timeout
keep_rc: bool
Whether to return the exit code along with the output
encoding: str
unicode decoding scheme to use. Default is "utf-8"
env: dict
The environment in which to execute commands. Default is os.environ
Returns
-------
str
Content of stdout of cmd on success.
Raises
------
CalledProcessError
Raised when cmd fails
"""
if not isinstance(cmd, list):
cmd = [cmd]
p = Pipeline(*cmd, timeout=timeout, signum=signum, env=env)
res = p(keep_rc=keep_rc)
if keep_rc:
rc, output = res
output = output.decode(encoding, 'ignore')
return rc, output
return res.decode(encoding, "ignore") | [
"def",
"call",
"(",
"cmd",
",",
"timeout",
"=",
"None",
",",
"signum",
"=",
"signal",
".",
"SIGKILL",
",",
"keep_rc",
"=",
"False",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"env",
"=",
"os",
".",
"environ",
")",
":",
"if",
"not",
"isinstance",
"(",
... | Execute a cmd or list of commands with an optional timeout in seconds.
If `timeout` is supplied and expires, the process is killed with
SIGKILL (kill -9) and an exception is raised. Otherwise, the command
output is returned.
Parameters
----------
cmd: str or [[str]]
The command(s) to execute
timeout: int
Seconds before kill is issued to the process
signum: int
The signal number to issue to the process on timeout
keep_rc: bool
Whether to return the exit code along with the output
encoding: str
unicode decoding scheme to use. Default is "utf-8"
env: dict
The environment in which to execute commands. Default is os.environ
Returns
-------
str
Content of stdout of cmd on success.
Raises
------
CalledProcessError
Raised when cmd fails | [
"Execute",
"a",
"cmd",
"or",
"list",
"of",
"commands",
"with",
"an",
"optional",
"timeout",
"in",
"seconds",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/subproc.py#L165-L214 |
226,091 | RedHatInsights/insights-core | insights/util/subproc.py | Pipeline.write | def write(self, output, mode="w", keep_rc=False):
"""
Executes the pipeline and writes the results to the supplied output.
If output is a filename and the file didn't already exist before trying
to write, the file will be removed if an exception is raised.
Args:
output (str or file like object): will create a new file of this
name or overwrite an existing file. If output is already a file
like object, it is used.
mode (str): mode to use when creating or opening the provided file
name if it is a string. Ignored if output is a file like object.
Returns:
The final output of the pipeline.
Raises:
CalledProcessError if any return code in the pipeline is nonzero.
"""
if isinstance(output, six.string_types):
already_exists = os.path.exists(output)
try:
with open(output, mode) as f:
p = self._build_pipes(f)
rc = p.wait()
if keep_rc:
return rc
if rc:
raise CalledProcessError(rc, self.cmds[0], "")
except BaseException as be:
if not already_exists and os.path.exists(output):
os.remove(output)
six.reraise(be.__class__, be, sys.exc_info()[2])
else:
p = self._build_pipes(output)
rc = p.wait()
if keep_rc:
return rc
if rc:
raise CalledProcessError(rc, self.cmds[0], "") | python | def write(self, output, mode="w", keep_rc=False):
"""
Executes the pipeline and writes the results to the supplied output.
If output is a filename and the file didn't already exist before trying
to write, the file will be removed if an exception is raised.
Args:
output (str or file like object): will create a new file of this
name or overwrite an existing file. If output is already a file
like object, it is used.
mode (str): mode to use when creating or opening the provided file
name if it is a string. Ignored if output is a file like object.
Returns:
The final output of the pipeline.
Raises:
CalledProcessError if any return code in the pipeline is nonzero.
"""
if isinstance(output, six.string_types):
already_exists = os.path.exists(output)
try:
with open(output, mode) as f:
p = self._build_pipes(f)
rc = p.wait()
if keep_rc:
return rc
if rc:
raise CalledProcessError(rc, self.cmds[0], "")
except BaseException as be:
if not already_exists and os.path.exists(output):
os.remove(output)
six.reraise(be.__class__, be, sys.exc_info()[2])
else:
p = self._build_pipes(output)
rc = p.wait()
if keep_rc:
return rc
if rc:
raise CalledProcessError(rc, self.cmds[0], "") | [
"def",
"write",
"(",
"self",
",",
"output",
",",
"mode",
"=",
"\"w\"",
",",
"keep_rc",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"output",
",",
"six",
".",
"string_types",
")",
":",
"already_exists",
"=",
"os",
".",
"path",
".",
"exists",
"(",... | Executes the pipeline and writes the results to the supplied output.
If output is a filename and the file didn't already exist before trying
to write, the file will be removed if an exception is raised.
Args:
output (str or file like object): will create a new file of this
name or overwrite an existing file. If output is already a file
like object, it is used.
mode (str): mode to use when creating or opening the provided file
name if it is a string. Ignored if output is a file like object.
Returns:
The final output of the pipeline.
Raises:
CalledProcessError if any return code in the pipeline is nonzero. | [
"Executes",
"the",
"pipeline",
"and",
"writes",
"the",
"results",
"to",
"the",
"supplied",
"output",
".",
"If",
"output",
"is",
"a",
"filename",
"and",
"the",
"file",
"didn",
"t",
"already",
"exist",
"before",
"trying",
"to",
"write",
"the",
"file",
"will"... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/subproc.py#L124-L162 |
226,092 | RedHatInsights/insights-core | insights/core/plugins.py | Response.validate_kwargs | def validate_kwargs(self, kwargs):
"""
Validates expected subclass attributes and constructor keyword
arguments.
"""
if not self.response_type:
msg = "response_type must be set on the Response subclass."
raise ValidationException(msg)
if (self.key_name and self.key_name in kwargs) or "type" in kwargs:
name = self.__class__.__name__
msg = "%s is an invalid argument for %s" % (self.key_name, name)
raise ValidationException(msg) | python | def validate_kwargs(self, kwargs):
"""
Validates expected subclass attributes and constructor keyword
arguments.
"""
if not self.response_type:
msg = "response_type must be set on the Response subclass."
raise ValidationException(msg)
if (self.key_name and self.key_name in kwargs) or "type" in kwargs:
name = self.__class__.__name__
msg = "%s is an invalid argument for %s" % (self.key_name, name)
raise ValidationException(msg) | [
"def",
"validate_kwargs",
"(",
"self",
",",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"response_type",
":",
"msg",
"=",
"\"response_type must be set on the Response subclass.\"",
"raise",
"ValidationException",
"(",
"msg",
")",
"if",
"(",
"self",
".",
"key_nam... | Validates expected subclass attributes and constructor keyword
arguments. | [
"Validates",
"expected",
"subclass",
"attributes",
"and",
"constructor",
"keyword",
"arguments",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/plugins.py#L390-L402 |
226,093 | RedHatInsights/insights-core | insights/core/plugins.py | Response.validate_key | def validate_key(self, key):
""" Called if the key_name class attribute is not None. """
if not key:
name = self.__class__.__name__
msg = "%s response missing %s" % (name, self.key_name)
raise ValidationException(msg, self)
elif not isinstance(key, str):
msg = "Response contains invalid %s type" % self.key_name
raise ValidationException(msg, type(key)) | python | def validate_key(self, key):
""" Called if the key_name class attribute is not None. """
if not key:
name = self.__class__.__name__
msg = "%s response missing %s" % (name, self.key_name)
raise ValidationException(msg, self)
elif not isinstance(key, str):
msg = "Response contains invalid %s type" % self.key_name
raise ValidationException(msg, type(key)) | [
"def",
"validate_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"key",
":",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
"msg",
"=",
"\"%s response missing %s\"",
"%",
"(",
"name",
",",
"self",
".",
"key_name",
")",
"raise",
"Validation... | Called if the key_name class attribute is not None. | [
"Called",
"if",
"the",
"key_name",
"class",
"attribute",
"is",
"not",
"None",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/plugins.py#L404-L412 |
226,094 | RedHatInsights/insights-core | insights/core/plugins.py | Response.adjust_for_length | def adjust_for_length(self, key, r, kwargs):
"""
Converts the response to a string and compares its length to a max
length specified in settings. If the response is too long, an error is
logged, and an abbreviated response is returned instead.
"""
length = len(str(kwargs))
if length > settings.defaults["max_detail_length"]:
self._log_length_error(key, length)
r["max_detail_length_error"] = length
return r
return kwargs | python | def adjust_for_length(self, key, r, kwargs):
"""
Converts the response to a string and compares its length to a max
length specified in settings. If the response is too long, an error is
logged, and an abbreviated response is returned instead.
"""
length = len(str(kwargs))
if length > settings.defaults["max_detail_length"]:
self._log_length_error(key, length)
r["max_detail_length_error"] = length
return r
return kwargs | [
"def",
"adjust_for_length",
"(",
"self",
",",
"key",
",",
"r",
",",
"kwargs",
")",
":",
"length",
"=",
"len",
"(",
"str",
"(",
"kwargs",
")",
")",
"if",
"length",
">",
"settings",
".",
"defaults",
"[",
"\"max_detail_length\"",
"]",
":",
"self",
".",
... | Converts the response to a string and compares its length to a max
length specified in settings. If the response is too long, an error is
logged, and an abbreviated response is returned instead. | [
"Converts",
"the",
"response",
"to",
"a",
"string",
"and",
"compares",
"its",
"length",
"to",
"a",
"max",
"length",
"specified",
"in",
"settings",
".",
"If",
"the",
"response",
"is",
"too",
"long",
"an",
"error",
"is",
"logged",
"and",
"an",
"abbreviated",... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/plugins.py#L414-L425 |
226,095 | RedHatInsights/insights-core | insights/core/plugins.py | Response._log_length_error | def _log_length_error(self, key, length):
""" Helper function for logging a response length error. """
extra = {
"max_detail_length": settings.defaults["max_detail_length"],
"len": length
}
if self.key_name:
extra[self.key_name] = key
msg = "Length of data in %s is too long." % self.__class__.__name__
log.error(msg, extra=extra) | python | def _log_length_error(self, key, length):
""" Helper function for logging a response length error. """
extra = {
"max_detail_length": settings.defaults["max_detail_length"],
"len": length
}
if self.key_name:
extra[self.key_name] = key
msg = "Length of data in %s is too long." % self.__class__.__name__
log.error(msg, extra=extra) | [
"def",
"_log_length_error",
"(",
"self",
",",
"key",
",",
"length",
")",
":",
"extra",
"=",
"{",
"\"max_detail_length\"",
":",
"settings",
".",
"defaults",
"[",
"\"max_detail_length\"",
"]",
",",
"\"len\"",
":",
"length",
"}",
"if",
"self",
".",
"key_name",
... | Helper function for logging a response length error. | [
"Helper",
"function",
"for",
"logging",
"a",
"response",
"length",
"error",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/plugins.py#L427-L436 |
226,096 | RedHatInsights/insights-core | insights/parsers/oracle.py | _parse_oracle | def _parse_oracle(lines):
"""
Performs the actual file parsing, returning a dict of the config values
in a given Oracle DB config file.
Despite their differences, the two filetypes are similar enough to
allow idential parsing.
"""
config = {}
for line in get_active_lines(lines):
# Check for NULL in line to begin control char removal
if '\00' in line:
line = cleanup.sub('', line)
if '=' in line:
(key, value) = line.split('=', 1)
key = key.strip(whitespace + '"\'').lower()
if ',' in line:
value = [s.strip(whitespace + '"\'').lower() for s in value.split(',')]
else:
value = value.strip(whitespace + '"\'').lower()
config[key] = value
return config | python | def _parse_oracle(lines):
"""
Performs the actual file parsing, returning a dict of the config values
in a given Oracle DB config file.
Despite their differences, the two filetypes are similar enough to
allow idential parsing.
"""
config = {}
for line in get_active_lines(lines):
# Check for NULL in line to begin control char removal
if '\00' in line:
line = cleanup.sub('', line)
if '=' in line:
(key, value) = line.split('=', 1)
key = key.strip(whitespace + '"\'').lower()
if ',' in line:
value = [s.strip(whitespace + '"\'').lower() for s in value.split(',')]
else:
value = value.strip(whitespace + '"\'').lower()
config[key] = value
return config | [
"def",
"_parse_oracle",
"(",
"lines",
")",
":",
"config",
"=",
"{",
"}",
"for",
"line",
"in",
"get_active_lines",
"(",
"lines",
")",
":",
"# Check for NULL in line to begin control char removal",
"if",
"'\\00'",
"in",
"line",
":",
"line",
"=",
"cleanup",
".",
... | Performs the actual file parsing, returning a dict of the config values
in a given Oracle DB config file.
Despite their differences, the two filetypes are similar enough to
allow idential parsing. | [
"Performs",
"the",
"actual",
"file",
"parsing",
"returning",
"a",
"dict",
"of",
"the",
"config",
"values",
"in",
"a",
"given",
"Oracle",
"DB",
"config",
"file",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/oracle.py#L18-L41 |
226,097 | RedHatInsights/insights-core | insights/parsers/mdstat.py | apply_upstring | def apply_upstring(upstring, component_list):
"""Update the dictionaries resulting from ``parse_array_start`` with
the "up" key based on the upstring returned from ``parse_upstring``.
The function assumes that the upstring and component_list parameters
passed in are from the same device array stanza of a
``/proc/mdstat`` file.
The function modifies component_list in place, adding or updating
the value of the "up" key to True if there is a corresponding ``U``
in the upstring string, or to False if there is a corresponding
``_``.
If there the number of rows in component_list does not match the
number of characters in upstring, an ``AssertionError`` is raised.
Parameters
----------
upstring : str
String sequence of ``U``s and ``_``s as determined by the
``parse_upstring`` method
component_list : list
List of dictionaries output from the ``parse_array_start`` method.
"""
assert len(upstring) == len(component_list)
def add_up_key(comp_dict, up_indicator):
assert up_indicator == 'U' or up_indicator == "_"
comp_dict['up'] = up_indicator == 'U'
for comp_dict, up_indicator in zip(component_list, upstring):
add_up_key(comp_dict, up_indicator) | python | def apply_upstring(upstring, component_list):
"""Update the dictionaries resulting from ``parse_array_start`` with
the "up" key based on the upstring returned from ``parse_upstring``.
The function assumes that the upstring and component_list parameters
passed in are from the same device array stanza of a
``/proc/mdstat`` file.
The function modifies component_list in place, adding or updating
the value of the "up" key to True if there is a corresponding ``U``
in the upstring string, or to False if there is a corresponding
``_``.
If there the number of rows in component_list does not match the
number of characters in upstring, an ``AssertionError`` is raised.
Parameters
----------
upstring : str
String sequence of ``U``s and ``_``s as determined by the
``parse_upstring`` method
component_list : list
List of dictionaries output from the ``parse_array_start`` method.
"""
assert len(upstring) == len(component_list)
def add_up_key(comp_dict, up_indicator):
assert up_indicator == 'U' or up_indicator == "_"
comp_dict['up'] = up_indicator == 'U'
for comp_dict, up_indicator in zip(component_list, upstring):
add_up_key(comp_dict, up_indicator) | [
"def",
"apply_upstring",
"(",
"upstring",
",",
"component_list",
")",
":",
"assert",
"len",
"(",
"upstring",
")",
"==",
"len",
"(",
"component_list",
")",
"def",
"add_up_key",
"(",
"comp_dict",
",",
"up_indicator",
")",
":",
"assert",
"up_indicator",
"==",
"... | Update the dictionaries resulting from ``parse_array_start`` with
the "up" key based on the upstring returned from ``parse_upstring``.
The function assumes that the upstring and component_list parameters
passed in are from the same device array stanza of a
``/proc/mdstat`` file.
The function modifies component_list in place, adding or updating
the value of the "up" key to True if there is a corresponding ``U``
in the upstring string, or to False if there is a corresponding
``_``.
If there the number of rows in component_list does not match the
number of characters in upstring, an ``AssertionError`` is raised.
Parameters
----------
upstring : str
String sequence of ``U``s and ``_``s as determined by the
``parse_upstring`` method
component_list : list
List of dictionaries output from the ``parse_array_start`` method. | [
"Update",
"the",
"dictionaries",
"resulting",
"from",
"parse_array_start",
"with",
"the",
"up",
"key",
"based",
"on",
"the",
"upstring",
"returned",
"from",
"parse_upstring",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/mdstat.py#L344-L377 |
226,098 | RedHatInsights/insights-core | insights/util/fs.py | remove | def remove(path, chmod=False):
"""Remove a file or directory located on the filesystem at path.
If chmod is True, chmod -R 755 is executed on the path
before rm -rf path is called.
Parameters
----------
path : str
file system path to an existing file or directory
chmod : bool
If True, chmod -R 755 is executed on path before
it's removed.
Raises
------
CalledProcessError
If any part of the removal process fails.
"""
if not os.path.exists(path):
return
if chmod:
cmd = "chmod -R 755 %s" % path
subproc.call(cmd)
cmd = 'rm -rf "{p}"'.format(p=path)
subproc.call(cmd) | python | def remove(path, chmod=False):
"""Remove a file or directory located on the filesystem at path.
If chmod is True, chmod -R 755 is executed on the path
before rm -rf path is called.
Parameters
----------
path : str
file system path to an existing file or directory
chmod : bool
If True, chmod -R 755 is executed on path before
it's removed.
Raises
------
CalledProcessError
If any part of the removal process fails.
"""
if not os.path.exists(path):
return
if chmod:
cmd = "chmod -R 755 %s" % path
subproc.call(cmd)
cmd = 'rm -rf "{p}"'.format(p=path)
subproc.call(cmd) | [
"def",
"remove",
"(",
"path",
",",
"chmod",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"if",
"chmod",
":",
"cmd",
"=",
"\"chmod -R 755 %s\"",
"%",
"path",
"subproc",
".",
"call",
"(",
"cm... | Remove a file or directory located on the filesystem at path.
If chmod is True, chmod -R 755 is executed on the path
before rm -rf path is called.
Parameters
----------
path : str
file system path to an existing file or directory
chmod : bool
If True, chmod -R 755 is executed on path before
it's removed.
Raises
------
CalledProcessError
If any part of the removal process fails. | [
"Remove",
"a",
"file",
"or",
"directory",
"located",
"on",
"the",
"filesystem",
"at",
"path",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/fs.py#L41-L69 |
226,099 | RedHatInsights/insights-core | insights/util/fs.py | ensure_path | def ensure_path(path, mode=0o777):
"""Ensure that path exists in a multiprocessing safe way.
If the path does not exist, recursively create it and its parent
directories using the provided mode. If the path already exists,
do nothing. The umask is cleared to enable the mode to be set,
and then reset to the original value after the mode is set.
Parameters
----------
path : str
file system path to a non-existent directory
that should be created.
mode : int
octal representation of the mode to use when creating
the directory.
Raises
------
OSError
If os.makedirs raises an OSError for any reason
other than if the directory already exists.
"""
if path:
try:
umask = os.umask(000)
os.makedirs(path, mode)
os.umask(umask)
except OSError as e:
if e.errno != errno.EEXIST:
raise | python | def ensure_path(path, mode=0o777):
"""Ensure that path exists in a multiprocessing safe way.
If the path does not exist, recursively create it and its parent
directories using the provided mode. If the path already exists,
do nothing. The umask is cleared to enable the mode to be set,
and then reset to the original value after the mode is set.
Parameters
----------
path : str
file system path to a non-existent directory
that should be created.
mode : int
octal representation of the mode to use when creating
the directory.
Raises
------
OSError
If os.makedirs raises an OSError for any reason
other than if the directory already exists.
"""
if path:
try:
umask = os.umask(000)
os.makedirs(path, mode)
os.umask(umask)
except OSError as e:
if e.errno != errno.EEXIST:
raise | [
"def",
"ensure_path",
"(",
"path",
",",
"mode",
"=",
"0o777",
")",
":",
"if",
"path",
":",
"try",
":",
"umask",
"=",
"os",
".",
"umask",
"(",
"000",
")",
"os",
".",
"makedirs",
"(",
"path",
",",
"mode",
")",
"os",
".",
"umask",
"(",
"umask",
")... | Ensure that path exists in a multiprocessing safe way.
If the path does not exist, recursively create it and its parent
directories using the provided mode. If the path already exists,
do nothing. The umask is cleared to enable the mode to be set,
and then reset to the original value after the mode is set.
Parameters
----------
path : str
file system path to a non-existent directory
that should be created.
mode : int
octal representation of the mode to use when creating
the directory.
Raises
------
OSError
If os.makedirs raises an OSError for any reason
other than if the directory already exists. | [
"Ensure",
"that",
"path",
"exists",
"in",
"a",
"multiprocessing",
"safe",
"way",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/fs.py#L72-L103 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.