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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
239,500 | sosreport/sos | sos/__init__.py | SoSOptions.__str | def __str(self, quote=False, sep=" ", prefix="", suffix=""):
"""Format a SoSOptions object as a human or machine readable string.
:param quote: quote option values
:param sep: list separator string
:param prefix: arbitrary prefix string
:param suffix: arbitrary suffix string
:param literal: print values as Python literals
"""
args = prefix
arg_fmt = "=%s"
for arg in _arg_names:
args += arg + arg_fmt + sep
args.strip(sep)
vals = [getattr(self, arg) for arg in _arg_names]
if not quote:
# Convert Python source notation for sequences into plain strings
vals = [",".join(v) if _is_seq(v) else v for v in vals]
else:
def is_string(val):
return isinstance(val, six.string_types)
# Only quote strings if quote=False
vals = ["'%s'" % v if is_string(v) else v for v in vals]
return (args % tuple(vals)).strip(sep) + suffix | python | def __str(self, quote=False, sep=" ", prefix="", suffix=""):
args = prefix
arg_fmt = "=%s"
for arg in _arg_names:
args += arg + arg_fmt + sep
args.strip(sep)
vals = [getattr(self, arg) for arg in _arg_names]
if not quote:
# Convert Python source notation for sequences into plain strings
vals = [",".join(v) if _is_seq(v) else v for v in vals]
else:
def is_string(val):
return isinstance(val, six.string_types)
# Only quote strings if quote=False
vals = ["'%s'" % v if is_string(v) else v for v in vals]
return (args % tuple(vals)).strip(sep) + suffix | [
"def",
"__str",
"(",
"self",
",",
"quote",
"=",
"False",
",",
"sep",
"=",
"\" \"",
",",
"prefix",
"=",
"\"\"",
",",
"suffix",
"=",
"\"\"",
")",
":",
"args",
"=",
"prefix",
"arg_fmt",
"=",
"\"=%s\"",
"for",
"arg",
"in",
"_arg_names",
":",
"args",
"+... | Format a SoSOptions object as a human or machine readable string.
:param quote: quote option values
:param sep: list separator string
:param prefix: arbitrary prefix string
:param suffix: arbitrary suffix string
:param literal: print values as Python literals | [
"Format",
"a",
"SoSOptions",
"object",
"as",
"a",
"human",
"or",
"machine",
"readable",
"string",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L111-L136 |
239,501 | sosreport/sos | sos/__init__.py | SoSOptions.from_args | def from_args(cls, args):
"""Initialise a new SoSOptions object from a ``Namespace``
obtained by parsing command line arguments.
:param args: parsed command line arguments
:returns: an initialised SoSOptions object
:returntype: SoSOptions
"""
opts = SoSOptions()
opts._merge_opts(args, True)
return opts | python | def from_args(cls, args):
opts = SoSOptions()
opts._merge_opts(args, True)
return opts | [
"def",
"from_args",
"(",
"cls",
",",
"args",
")",
":",
"opts",
"=",
"SoSOptions",
"(",
")",
"opts",
".",
"_merge_opts",
"(",
"args",
",",
"True",
")",
"return",
"opts"
] | Initialise a new SoSOptions object from a ``Namespace``
obtained by parsing command line arguments.
:param args: parsed command line arguments
:returns: an initialised SoSOptions object
:returntype: SoSOptions | [
"Initialise",
"a",
"new",
"SoSOptions",
"object",
"from",
"a",
"Namespace",
"obtained",
"by",
"parsing",
"command",
"line",
"arguments",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L201-L211 |
239,502 | sosreport/sos | sos/__init__.py | SoSOptions.merge | def merge(self, src, skip_default=True):
"""Merge another set of ``SoSOptions`` into this object.
Merge two ``SoSOptions`` objects by setting unset or default
values to their value in the ``src`` object.
:param src: the ``SoSOptions`` object to copy from
:param is_default: ``True`` if new default values are to be set.
"""
for arg in _arg_names:
if not hasattr(src, arg):
continue
if getattr(src, arg) is not None or not skip_default:
self._merge_opt(arg, src, False) | python | def merge(self, src, skip_default=True):
for arg in _arg_names:
if not hasattr(src, arg):
continue
if getattr(src, arg) is not None or not skip_default:
self._merge_opt(arg, src, False) | [
"def",
"merge",
"(",
"self",
",",
"src",
",",
"skip_default",
"=",
"True",
")",
":",
"for",
"arg",
"in",
"_arg_names",
":",
"if",
"not",
"hasattr",
"(",
"src",
",",
"arg",
")",
":",
"continue",
"if",
"getattr",
"(",
"src",
",",
"arg",
")",
"is",
... | Merge another set of ``SoSOptions`` into this object.
Merge two ``SoSOptions`` objects by setting unset or default
values to their value in the ``src`` object.
:param src: the ``SoSOptions`` object to copy from
:param is_default: ``True`` if new default values are to be set. | [
"Merge",
"another",
"set",
"of",
"SoSOptions",
"into",
"this",
"object",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L272-L285 |
239,503 | sosreport/sos | sos/__init__.py | SoSOptions.dict | def dict(self):
"""Return this ``SoSOptions`` option values as a dictionary of
argument name to value mappings.
:returns: a name:value dictionary of option values.
"""
odict = {}
for arg in _arg_names:
value = getattr(self, arg)
# Do not attempt to store preset option values in presets
if arg in ('add_preset', 'del_preset', 'desc', 'note'):
value = None
odict[arg] = value
return odict | python | def dict(self):
odict = {}
for arg in _arg_names:
value = getattr(self, arg)
# Do not attempt to store preset option values in presets
if arg in ('add_preset', 'del_preset', 'desc', 'note'):
value = None
odict[arg] = value
return odict | [
"def",
"dict",
"(",
"self",
")",
":",
"odict",
"=",
"{",
"}",
"for",
"arg",
"in",
"_arg_names",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"arg",
")",
"# Do not attempt to store preset option values in presets",
"if",
"arg",
"in",
"(",
"'add_preset'",
"... | Return this ``SoSOptions`` option values as a dictionary of
argument name to value mappings.
:returns: a name:value dictionary of option values. | [
"Return",
"this",
"SoSOptions",
"option",
"values",
"as",
"a",
"dictionary",
"of",
"argument",
"name",
"to",
"value",
"mappings",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L287-L300 |
239,504 | sosreport/sos | sos/__init__.py | SoSOptions.to_args | def to_args(self):
"""Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]``
"""
def has_value(name, value):
""" Test for non-null option values.
"""
null_values = ("False", "None", "[]", '""', "''", "0")
if not value or value in null_values:
return False
if name in _arg_defaults:
if str(value) == str(_arg_defaults[name]):
return False
return True
def filter_opt(name, value):
""" Filter out preset and null-valued options.
"""
if name in ("add_preset", "del_preset", "desc", "note"):
return False
return has_value(name, value)
def argify(name, value):
""" Convert sos option notation to command line arguments.
"""
# Handle --verbosity specially
if name.startswith("verbosity"):
arg = "-" + int(value) * "v"
return arg
name = name.replace("_", "-")
value = ",".join(value) if _is_seq(value) else value
if value is not True:
opt = "%s %s" % (name, value)
else:
opt = name
arg = "--" + opt if len(opt) > 1 else "-" + opt
return arg
opt_items = sorted(self.dict().items(), key=lambda x: x[0])
return [argify(n, v) for (n, v) in opt_items if filter_opt(n, v)] | python | def to_args(self):
def has_value(name, value):
""" Test for non-null option values.
"""
null_values = ("False", "None", "[]", '""', "''", "0")
if not value or value in null_values:
return False
if name in _arg_defaults:
if str(value) == str(_arg_defaults[name]):
return False
return True
def filter_opt(name, value):
""" Filter out preset and null-valued options.
"""
if name in ("add_preset", "del_preset", "desc", "note"):
return False
return has_value(name, value)
def argify(name, value):
""" Convert sos option notation to command line arguments.
"""
# Handle --verbosity specially
if name.startswith("verbosity"):
arg = "-" + int(value) * "v"
return arg
name = name.replace("_", "-")
value = ",".join(value) if _is_seq(value) else value
if value is not True:
opt = "%s %s" % (name, value)
else:
opt = name
arg = "--" + opt if len(opt) > 1 else "-" + opt
return arg
opt_items = sorted(self.dict().items(), key=lambda x: x[0])
return [argify(n, v) for (n, v) in opt_items if filter_opt(n, v)] | [
"def",
"to_args",
"(",
"self",
")",
":",
"def",
"has_value",
"(",
"name",
",",
"value",
")",
":",
"\"\"\" Test for non-null option values.\n \"\"\"",
"null_values",
"=",
"(",
"\"False\"",
",",
"\"None\"",
",",
"\"[]\"",
",",
"'\"\"'",
",",
"\"''\"",
"... | Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]`` | [
"Return",
"command",
"arguments",
"for",
"this",
"object",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L302-L350 |
239,505 | sosreport/sos | sos/plugins/autofs.py | Autofs.checkdebug | def checkdebug(self):
""" testing if autofs debug has been enabled anywhere
"""
# Global debugging
opt = self.file_grep(r"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)",
*self.files)
for opt1 in opt:
for opt2 in opt1.split(" "):
if opt2 in ("--debug", "debug"):
return True
return False | python | def checkdebug(self):
# Global debugging
opt = self.file_grep(r"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)",
*self.files)
for opt1 in opt:
for opt2 in opt1.split(" "):
if opt2 in ("--debug", "debug"):
return True
return False | [
"def",
"checkdebug",
"(",
"self",
")",
":",
"# Global debugging",
"opt",
"=",
"self",
".",
"file_grep",
"(",
"r\"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)\"",
",",
"*",
"self",
".",
"files",
")",
"for",
"opt1",
"in",
"opt",
":",
"for",
"opt2",
"in",
"opt1",
".",... | testing if autofs debug has been enabled anywhere | [
"testing",
"if",
"autofs",
"debug",
"has",
"been",
"enabled",
"anywhere"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/autofs.py#L24-L34 |
239,506 | sosreport/sos | sos/plugins/autofs.py | Autofs.getdaemondebug | def getdaemondebug(self):
""" capture daemon debug output
"""
debugout = self.file_grep(r"^(daemon.*)\s+(\/var\/log\/.*)",
*self.files)
for i in debugout:
return i[1] | python | def getdaemondebug(self):
debugout = self.file_grep(r"^(daemon.*)\s+(\/var\/log\/.*)",
*self.files)
for i in debugout:
return i[1] | [
"def",
"getdaemondebug",
"(",
"self",
")",
":",
"debugout",
"=",
"self",
".",
"file_grep",
"(",
"r\"^(daemon.*)\\s+(\\/var\\/log\\/.*)\"",
",",
"*",
"self",
".",
"files",
")",
"for",
"i",
"in",
"debugout",
":",
"return",
"i",
"[",
"1",
"]"
] | capture daemon debug output | [
"capture",
"daemon",
"debug",
"output"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/autofs.py#L36-L42 |
239,507 | sosreport/sos | sos/plugins/jars.py | Jars.is_jar | def is_jar(path):
"""Check whether given file is a JAR file.
JARs are ZIP files which usually include a manifest
at the canonical location 'META-INF/MANIFEST.MF'.
"""
if os.path.isfile(path) and zipfile.is_zipfile(path):
try:
with zipfile.ZipFile(path) as f:
if "META-INF/MANIFEST.MF" in f.namelist():
return True
except (IOError, zipfile.BadZipfile):
pass
return False | python | def is_jar(path):
if os.path.isfile(path) and zipfile.is_zipfile(path):
try:
with zipfile.ZipFile(path) as f:
if "META-INF/MANIFEST.MF" in f.namelist():
return True
except (IOError, zipfile.BadZipfile):
pass
return False | [
"def",
"is_jar",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"and",
"zipfile",
".",
"is_zipfile",
"(",
"path",
")",
":",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"as",
"f",
":",
"if",
... | Check whether given file is a JAR file.
JARs are ZIP files which usually include a manifest
at the canonical location 'META-INF/MANIFEST.MF'. | [
"Check",
"whether",
"given",
"file",
"is",
"a",
"JAR",
"file",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/jars.py#L84-L97 |
239,508 | sosreport/sos | sos/plugins/jars.py | Jars.get_maven_id | def get_maven_id(jar_path):
"""Extract Maven coordinates from a given JAR file, if possible.
JARs build by Maven (most popular Java build system) contain
'pom.properties' file. We can extract Maven coordinates
from there.
"""
props = {}
try:
with zipfile.ZipFile(jar_path) as f:
r = re.compile("META-INF/maven/[^/]+/[^/]+/pom.properties$")
result = [x for x in f.namelist() if r.match(x)]
if len(result) != 1:
return None
with f.open(result[0]) as props_f:
for line in props_f.readlines():
line = line.strip()
if not line.startswith(b"#"):
try:
(key, value) = line.split(b"=")
key = key.decode('utf8').strip()
value = value.decode('utf8').strip()
props[key] = value
except ValueError:
return None
except IOError:
pass
return props | python | def get_maven_id(jar_path):
props = {}
try:
with zipfile.ZipFile(jar_path) as f:
r = re.compile("META-INF/maven/[^/]+/[^/]+/pom.properties$")
result = [x for x in f.namelist() if r.match(x)]
if len(result) != 1:
return None
with f.open(result[0]) as props_f:
for line in props_f.readlines():
line = line.strip()
if not line.startswith(b"#"):
try:
(key, value) = line.split(b"=")
key = key.decode('utf8').strip()
value = value.decode('utf8').strip()
props[key] = value
except ValueError:
return None
except IOError:
pass
return props | [
"def",
"get_maven_id",
"(",
"jar_path",
")",
":",
"props",
"=",
"{",
"}",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"jar_path",
")",
"as",
"f",
":",
"r",
"=",
"re",
".",
"compile",
"(",
"\"META-INF/maven/[^/]+/[^/]+/pom.properties$\"",
")",
"resu... | Extract Maven coordinates from a given JAR file, if possible.
JARs build by Maven (most popular Java build system) contain
'pom.properties' file. We can extract Maven coordinates
from there. | [
"Extract",
"Maven",
"coordinates",
"from",
"a",
"given",
"JAR",
"file",
"if",
"possible",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/jars.py#L100-L127 |
239,509 | sosreport/sos | sos/plugins/jars.py | Jars.get_jar_id | def get_jar_id(jar_path):
"""Compute JAR id.
Returns sha1 hash of a given JAR file.
"""
jar_id = ""
try:
with open(jar_path, mode="rb") as f:
m = hashlib.sha1()
for buf in iter(partial(f.read, 4096), b''):
m.update(buf)
jar_id = m.hexdigest()
except IOError:
pass
return jar_id | python | def get_jar_id(jar_path):
jar_id = ""
try:
with open(jar_path, mode="rb") as f:
m = hashlib.sha1()
for buf in iter(partial(f.read, 4096), b''):
m.update(buf)
jar_id = m.hexdigest()
except IOError:
pass
return jar_id | [
"def",
"get_jar_id",
"(",
"jar_path",
")",
":",
"jar_id",
"=",
"\"\"",
"try",
":",
"with",
"open",
"(",
"jar_path",
",",
"mode",
"=",
"\"rb\"",
")",
"as",
"f",
":",
"m",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"for",
"buf",
"in",
"iter",
"(",
"par... | Compute JAR id.
Returns sha1 hash of a given JAR file. | [
"Compute",
"JAR",
"id",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/jars.py#L130-L144 |
239,510 | sosreport/sos | sos/plugins/qpid.py | Qpid.setup | def setup(self):
""" performs data collection for qpid broker """
options = ""
amqps_prefix = "" # set amqps:// when SSL is used
if self.get_option("ssl"):
amqps_prefix = "amqps://"
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key"]:
if self.get_option(option):
amqps_prefix = "amqps://"
options = (options + " --%s=" % (option) +
self.get_option(option))
if self.get_option("port"):
options = (options + " -b " + amqps_prefix +
"localhost:%s" % (self.get_option("port")))
self.add_cmd_output([
"qpid-stat -g" + options, # applies since 0.18 version
"qpid-stat -b" + options, # applies to pre-0.18 versions
"qpid-stat -c" + options,
"qpid-stat -e" + options,
"qpid-stat -q" + options,
"qpid-stat -u" + options,
"qpid-stat -m" + options, # applies since 0.18 version
"qpid-config exchanges" + options,
"qpid-config queues" + options,
"qpid-config exchanges -b" + options, # applies to pre-0.18 vers.
"qpid-config queues -b" + options, # applies to pre-0.18 versions
"qpid-config exchanges -r" + options, # applies since 0.18 version
"qpid-config queues -r" + options, # applies since 0.18 version
"qpid-route link list" + options,
"qpid-route route list" + options,
"qpid-cluster" + options, # applies to pre-0.22 versions
"qpid-ha query" + options, # applies since 0.22 version
"ls -lanR /var/lib/qpidd"
])
self.add_copy_spec([
"/etc/qpidd.conf", # applies to pre-0.22 versions
"/etc/qpid/qpidd.conf", # applies since 0.22 version
"/var/lib/qpid/syslog",
"/etc/ais/openais.conf",
"/var/log/cumin.log",
"/var/log/mint.log",
"/etc/sasl2/qpidd.conf",
"/etc/qpid/qpidc.conf",
"/etc/sesame/sesame.conf",
"/etc/cumin/cumin.conf",
"/etc/corosync/corosync.conf",
"/var/lib/sesame",
"/var/log/qpidd.log",
"/var/log/sesame",
"/var/log/cumin"
]) | python | def setup(self):
options = ""
amqps_prefix = "" # set amqps:// when SSL is used
if self.get_option("ssl"):
amqps_prefix = "amqps://"
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key"]:
if self.get_option(option):
amqps_prefix = "amqps://"
options = (options + " --%s=" % (option) +
self.get_option(option))
if self.get_option("port"):
options = (options + " -b " + amqps_prefix +
"localhost:%s" % (self.get_option("port")))
self.add_cmd_output([
"qpid-stat -g" + options, # applies since 0.18 version
"qpid-stat -b" + options, # applies to pre-0.18 versions
"qpid-stat -c" + options,
"qpid-stat -e" + options,
"qpid-stat -q" + options,
"qpid-stat -u" + options,
"qpid-stat -m" + options, # applies since 0.18 version
"qpid-config exchanges" + options,
"qpid-config queues" + options,
"qpid-config exchanges -b" + options, # applies to pre-0.18 vers.
"qpid-config queues -b" + options, # applies to pre-0.18 versions
"qpid-config exchanges -r" + options, # applies since 0.18 version
"qpid-config queues -r" + options, # applies since 0.18 version
"qpid-route link list" + options,
"qpid-route route list" + options,
"qpid-cluster" + options, # applies to pre-0.22 versions
"qpid-ha query" + options, # applies since 0.22 version
"ls -lanR /var/lib/qpidd"
])
self.add_copy_spec([
"/etc/qpidd.conf", # applies to pre-0.22 versions
"/etc/qpid/qpidd.conf", # applies since 0.22 version
"/var/lib/qpid/syslog",
"/etc/ais/openais.conf",
"/var/log/cumin.log",
"/var/log/mint.log",
"/etc/sasl2/qpidd.conf",
"/etc/qpid/qpidc.conf",
"/etc/sesame/sesame.conf",
"/etc/cumin/cumin.conf",
"/etc/corosync/corosync.conf",
"/var/lib/sesame",
"/var/log/qpidd.log",
"/var/log/sesame",
"/var/log/cumin"
]) | [
"def",
"setup",
"(",
"self",
")",
":",
"options",
"=",
"\"\"",
"amqps_prefix",
"=",
"\"\"",
"# set amqps:// when SSL is used",
"if",
"self",
".",
"get_option",
"(",
"\"ssl\"",
")",
":",
"amqps_prefix",
"=",
"\"amqps://\"",
"# for either present option, add --option=va... | performs data collection for qpid broker | [
"performs",
"data",
"collection",
"for",
"qpid",
"broker"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/qpid.py#L27-L80 |
239,511 | sosreport/sos | sos/sosreport.py | SoSReport._exception | def _exception(etype, eval_, etrace):
""" Wrap exception in debugger if not in tty """
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(etype, eval_, etrace)
else:
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, eval_, etrace, limit=2,
file=sys.stdout)
six.print_()
# ...then start the debugger in post-mortem mode.
pdb.pm() | python | def _exception(etype, eval_, etrace):
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(etype, eval_, etrace)
else:
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, eval_, etrace, limit=2,
file=sys.stdout)
six.print_()
# ...then start the debugger in post-mortem mode.
pdb.pm() | [
"def",
"_exception",
"(",
"etype",
",",
"eval_",
",",
"etrace",
")",
":",
"if",
"hasattr",
"(",
"sys",
",",
"'ps1'",
")",
"or",
"not",
"sys",
".",
"stderr",
".",
"isatty",
"(",
")",
":",
"# we are in interactive mode or we don't have a tty-like",
"# device, so... | Wrap exception in debugger if not in tty | [
"Wrap",
"exception",
"in",
"debugger",
"if",
"not",
"in",
"tty"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L404-L416 |
239,512 | sosreport/sos | sos/sosreport.py | SoSReport.add_preset | def add_preset(self, name, desc="", note=""):
"""Add a new command line preset for the current options with the
specified name.
:param name: the name of the new preset
:returns: True on success or False otherwise
"""
policy = self.policy
if policy.find_preset(name):
self.ui_log.error("A preset named '%s' already exists" % name)
return False
desc = desc or self.opts.desc
note = note or self.opts.note
try:
policy.add_preset(name=name, desc=desc, note=note, opts=self.opts)
except Exception as e:
self.ui_log.error("Could not add preset: %s" % e)
return False
# Filter --add-preset <name> from arguments list
arg_index = self._args.index("--add-preset")
args = self._args[0:arg_index] + self._args[arg_index + 2:]
self.ui_log.info("Added preset '%s' with options %s\n" %
(name, " ".join(args)))
return True | python | def add_preset(self, name, desc="", note=""):
policy = self.policy
if policy.find_preset(name):
self.ui_log.error("A preset named '%s' already exists" % name)
return False
desc = desc or self.opts.desc
note = note or self.opts.note
try:
policy.add_preset(name=name, desc=desc, note=note, opts=self.opts)
except Exception as e:
self.ui_log.error("Could not add preset: %s" % e)
return False
# Filter --add-preset <name> from arguments list
arg_index = self._args.index("--add-preset")
args = self._args[0:arg_index] + self._args[arg_index + 2:]
self.ui_log.info("Added preset '%s' with options %s\n" %
(name, " ".join(args)))
return True | [
"def",
"add_preset",
"(",
"self",
",",
"name",
",",
"desc",
"=",
"\"\"",
",",
"note",
"=",
"\"\"",
")",
":",
"policy",
"=",
"self",
".",
"policy",
"if",
"policy",
".",
"find_preset",
"(",
"name",
")",
":",
"self",
".",
"ui_log",
".",
"error",
"(",
... | Add a new command line preset for the current options with the
specified name.
:param name: the name of the new preset
:returns: True on success or False otherwise | [
"Add",
"a",
"new",
"command",
"line",
"preset",
"for",
"the",
"current",
"options",
"with",
"the",
"specified",
"name",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L802-L829 |
239,513 | sosreport/sos | sos/sosreport.py | SoSReport.del_preset | def del_preset(self, name):
"""Delete a named command line preset.
:param name: the name of the preset to delete
:returns: True on success or False otherwise
"""
policy = self.policy
if not policy.find_preset(name):
self.ui_log.error("Preset '%s' not found" % name)
return False
try:
policy.del_preset(name=name)
except Exception as e:
self.ui_log.error(str(e) + "\n")
return False
self.ui_log.info("Deleted preset '%s'\n" % name)
return True | python | def del_preset(self, name):
policy = self.policy
if not policy.find_preset(name):
self.ui_log.error("Preset '%s' not found" % name)
return False
try:
policy.del_preset(name=name)
except Exception as e:
self.ui_log.error(str(e) + "\n")
return False
self.ui_log.info("Deleted preset '%s'\n" % name)
return True | [
"def",
"del_preset",
"(",
"self",
",",
"name",
")",
":",
"policy",
"=",
"self",
".",
"policy",
"if",
"not",
"policy",
".",
"find_preset",
"(",
"name",
")",
":",
"self",
".",
"ui_log",
".",
"error",
"(",
"\"Preset '%s' not found\"",
"%",
"name",
")",
"r... | Delete a named command line preset.
:param name: the name of the preset to delete
:returns: True on success or False otherwise | [
"Delete",
"a",
"named",
"command",
"line",
"preset",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L831-L849 |
239,514 | sosreport/sos | sos/sosreport.py | SoSReport.version | def version(self):
"""Fetch version information from all plugins and store in the report
version file"""
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
self.archive.add_string(content="\n".join(versions),
dest='version.txt') | python | def version(self):
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
self.archive.add_string(content="\n".join(versions),
dest='version.txt') | [
"def",
"version",
"(",
"self",
")",
":",
"versions",
"=",
"[",
"]",
"versions",
".",
"append",
"(",
"\"sosreport: %s\"",
"%",
"__version__",
")",
"for",
"plugname",
",",
"plug",
"in",
"self",
".",
"loaded_plugins",
":",
"versions",
".",
"append",
"(",
"\... | Fetch version information from all plugins and store in the report
version file | [
"Fetch",
"version",
"information",
"from",
"all",
"plugins",
"and",
"store",
"in",
"the",
"report",
"version",
"file"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L949-L960 |
239,515 | sosreport/sos | sos/plugins/navicli.py | Navicli.get_navicli_SP_info | def get_navicli_SP_info(self, SP_address):
""" EMC Navisphere Host Agent NAVICLI specific
information - CLARiiON - commands
"""
self.add_cmd_output([
"navicli -h %s getall" % SP_address,
"navicli -h %s getsptime -spa" % SP_address,
"navicli -h %s getsptime -spb" % SP_address,
"navicli -h %s getlog" % SP_address,
"navicli -h %s getdisk" % SP_address,
"navicli -h %s getcache" % SP_address,
"navicli -h %s getlun" % SP_address,
"navicli -h %s getlun -rg -type -default -owner -crus "
"-capacity" % SP_address,
"navicli -h %s lunmapinfo" % SP_address,
"navicli -h %s getcrus" % SP_address,
"navicli -h %s port -list -all" % SP_address,
"navicli -h %s storagegroup -list" % SP_address,
"navicli -h %s spportspeed -get" % SP_address
]) | python | def get_navicli_SP_info(self, SP_address):
self.add_cmd_output([
"navicli -h %s getall" % SP_address,
"navicli -h %s getsptime -spa" % SP_address,
"navicli -h %s getsptime -spb" % SP_address,
"navicli -h %s getlog" % SP_address,
"navicli -h %s getdisk" % SP_address,
"navicli -h %s getcache" % SP_address,
"navicli -h %s getlun" % SP_address,
"navicli -h %s getlun -rg -type -default -owner -crus "
"-capacity" % SP_address,
"navicli -h %s lunmapinfo" % SP_address,
"navicli -h %s getcrus" % SP_address,
"navicli -h %s port -list -all" % SP_address,
"navicli -h %s storagegroup -list" % SP_address,
"navicli -h %s spportspeed -get" % SP_address
]) | [
"def",
"get_navicli_SP_info",
"(",
"self",
",",
"SP_address",
")",
":",
"self",
".",
"add_cmd_output",
"(",
"[",
"\"navicli -h %s getall\"",
"%",
"SP_address",
",",
"\"navicli -h %s getsptime -spa\"",
"%",
"SP_address",
",",
"\"navicli -h %s getsptime -spb\"",
"%",
"SP_... | EMC Navisphere Host Agent NAVICLI specific
information - CLARiiON - commands | [
"EMC",
"Navisphere",
"Host",
"Agent",
"NAVICLI",
"specific",
"information",
"-",
"CLARiiON",
"-",
"commands"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/navicli.py#L41-L60 |
239,516 | sosreport/sos | sos/plugins/origin.py | OpenShiftOrigin.is_static_etcd | def is_static_etcd(self):
'''Determine if we are on a node running etcd'''
return os.path.exists(os.path.join(self.static_pod_dir, "etcd.yaml")) | python | def is_static_etcd(self):
'''Determine if we are on a node running etcd'''
return os.path.exists(os.path.join(self.static_pod_dir, "etcd.yaml")) | [
"def",
"is_static_etcd",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"static_pod_dir",
",",
"\"etcd.yaml\"",
")",
")"
] | Determine if we are on a node running etcd | [
"Determine",
"if",
"we",
"are",
"on",
"a",
"node",
"running",
"etcd"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/origin.py#L78-L80 |
239,517 | sosreport/sos | sos/plugins/networking.py | Networking.get_ip_netns | def get_ip_netns(self, ip_netns_file):
"""Returns a list for which items are namespaces in the output of
ip netns stored in the ip_netns_file.
"""
out = []
try:
ip_netns_out = open(ip_netns_file).read()
except IOError:
return out
for line in ip_netns_out.splitlines():
# If there's no namespaces, no need to continue
if line.startswith("Object \"netns\" is unknown") \
or line.isspace() \
or line[:1].isspace():
return out
out.append(line.partition(' ')[0])
return out | python | def get_ip_netns(self, ip_netns_file):
out = []
try:
ip_netns_out = open(ip_netns_file).read()
except IOError:
return out
for line in ip_netns_out.splitlines():
# If there's no namespaces, no need to continue
if line.startswith("Object \"netns\" is unknown") \
or line.isspace() \
or line[:1].isspace():
return out
out.append(line.partition(' ')[0])
return out | [
"def",
"get_ip_netns",
"(",
"self",
",",
"ip_netns_file",
")",
":",
"out",
"=",
"[",
"]",
"try",
":",
"ip_netns_out",
"=",
"open",
"(",
"ip_netns_file",
")",
".",
"read",
"(",
")",
"except",
"IOError",
":",
"return",
"out",
"for",
"line",
"in",
"ip_net... | Returns a list for which items are namespaces in the output of
ip netns stored in the ip_netns_file. | [
"Returns",
"a",
"list",
"for",
"which",
"items",
"are",
"namespaces",
"in",
"the",
"output",
"of",
"ip",
"netns",
"stored",
"in",
"the",
"ip_netns_file",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/networking.py#L28-L44 |
239,518 | sosreport/sos | sos/plugins/networking.py | Networking.collect_iptable | def collect_iptable(self, tablename):
""" When running the iptables command, it unfortunately auto-loads
the modules before trying to get output. Some people explicitly
don't want this, so check if the modules are loaded before running
the command. If they aren't loaded, there can't possibly be any
relevant rules in that table """
modname = "iptable_"+tablename
if self.check_ext_prog("grep -q %s /proc/modules" % modname):
cmd = "iptables -t "+tablename+" -nvL"
self.add_cmd_output(cmd) | python | def collect_iptable(self, tablename):
modname = "iptable_"+tablename
if self.check_ext_prog("grep -q %s /proc/modules" % modname):
cmd = "iptables -t "+tablename+" -nvL"
self.add_cmd_output(cmd) | [
"def",
"collect_iptable",
"(",
"self",
",",
"tablename",
")",
":",
"modname",
"=",
"\"iptable_\"",
"+",
"tablename",
"if",
"self",
".",
"check_ext_prog",
"(",
"\"grep -q %s /proc/modules\"",
"%",
"modname",
")",
":",
"cmd",
"=",
"\"iptables -t \"",
"+",
"tablena... | When running the iptables command, it unfortunately auto-loads
the modules before trying to get output. Some people explicitly
don't want this, so check if the modules are loaded before running
the command. If they aren't loaded, there can't possibly be any
relevant rules in that table | [
"When",
"running",
"the",
"iptables",
"command",
"it",
"unfortunately",
"auto",
"-",
"loads",
"the",
"modules",
"before",
"trying",
"to",
"get",
"output",
".",
"Some",
"people",
"explicitly",
"don",
"t",
"want",
"this",
"so",
"check",
"if",
"the",
"modules",... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/networking.py#L46-L56 |
239,519 | sosreport/sos | sos/plugins/networking.py | Networking.collect_ip6table | def collect_ip6table(self, tablename):
""" Same as function above, but for ipv6 """
modname = "ip6table_"+tablename
if self.check_ext_prog("grep -q %s /proc/modules" % modname):
cmd = "ip6tables -t "+tablename+" -nvL"
self.add_cmd_output(cmd) | python | def collect_ip6table(self, tablename):
modname = "ip6table_"+tablename
if self.check_ext_prog("grep -q %s /proc/modules" % modname):
cmd = "ip6tables -t "+tablename+" -nvL"
self.add_cmd_output(cmd) | [
"def",
"collect_ip6table",
"(",
"self",
",",
"tablename",
")",
":",
"modname",
"=",
"\"ip6table_\"",
"+",
"tablename",
"if",
"self",
".",
"check_ext_prog",
"(",
"\"grep -q %s /proc/modules\"",
"%",
"modname",
")",
":",
"cmd",
"=",
"\"ip6tables -t \"",
"+",
"tabl... | Same as function above, but for ipv6 | [
"Same",
"as",
"function",
"above",
"but",
"for",
"ipv6"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/networking.py#L58-L64 |
239,520 | sosreport/sos | sos/plugins/ovirt.py | Ovirt.postproc | def postproc(self):
"""
Obfuscate sensitive keys.
"""
self.do_file_sub(
"/etc/ovirt-engine/engine-config/engine-config.properties",
r"Password.type=(.*)",
r"Password.type=********"
)
self.do_file_sub(
"/etc/rhevm/rhevm-config/rhevm-config.properties",
r"Password.type=(.*)",
r"Password.type=********"
)
engine_files = (
'ovirt-engine.xml',
'ovirt-engine_history/current/ovirt-engine.v1.xml',
'ovirt-engine_history/ovirt-engine.boot.xml',
'ovirt-engine_history/ovirt-engine.initial.xml',
'ovirt-engine_history/ovirt-engine.last.xml',
)
for filename in engine_files:
self.do_file_sub(
"/var/tmp/ovirt-engine/config/%s" % filename,
r"<password>(.*)</password>",
r"<password>********</password>"
)
self.do_file_sub(
"/etc/ovirt-engine/redhatsupportplugin.conf",
r"proxyPassword=(.*)",
r"proxyPassword=********"
)
passwd_files = [
"logcollector.conf",
"imageuploader.conf",
"isouploader.conf"
]
for conf_file in passwd_files:
conf_path = os.path.join("/etc/ovirt-engine", conf_file)
self.do_file_sub(
conf_path,
r"passwd=(.*)",
r"passwd=********"
)
self.do_file_sub(
conf_path,
r"pg-pass=(.*)",
r"pg-pass=********"
)
sensitive_keys = self.DEFAULT_SENSITIVE_KEYS
# Handle --alloptions case which set this to True.
keys_opt = self.get_option('sensitive_keys')
if keys_opt and keys_opt is not True:
sensitive_keys = keys_opt
key_list = [x for x in sensitive_keys.split(':') if x]
for key in key_list:
self.do_path_regex_sub(
self.DB_PASS_FILES,
r'{key}=(.*)'.format(key=key),
r'{key}=********'.format(key=key)
)
# Answer files contain passwords
for key in (
'OVESETUP_CONFIG/adminPassword',
'OVESETUP_CONFIG/remoteEngineHostRootPassword',
'OVESETUP_DWH_DB/password',
'OVESETUP_DB/password',
'OVESETUP_REPORTS_CONFIG/adminPassword',
'OVESETUP_REPORTS_DB/password',
):
self.do_path_regex_sub(
r'/var/lib/ovirt-engine/setup/answers/.*',
r'{key}=(.*)'.format(key=key),
r'{key}=********'.format(key=key)
)
# aaa profiles contain passwords
protect_keys = [
"vars.password",
"pool.default.auth.simple.password",
"pool.default.ssl.truststore.password",
"config.datasource.dbpassword"
]
regexp = r"((?m)^\s*#*(%s)\s*=\s*)(.*)" % "|".join(protect_keys)
self.do_path_regex_sub(r"/etc/ovirt-engine/aaa/.*\.properties", regexp,
r"\1*********") | python | def postproc(self):
self.do_file_sub(
"/etc/ovirt-engine/engine-config/engine-config.properties",
r"Password.type=(.*)",
r"Password.type=********"
)
self.do_file_sub(
"/etc/rhevm/rhevm-config/rhevm-config.properties",
r"Password.type=(.*)",
r"Password.type=********"
)
engine_files = (
'ovirt-engine.xml',
'ovirt-engine_history/current/ovirt-engine.v1.xml',
'ovirt-engine_history/ovirt-engine.boot.xml',
'ovirt-engine_history/ovirt-engine.initial.xml',
'ovirt-engine_history/ovirt-engine.last.xml',
)
for filename in engine_files:
self.do_file_sub(
"/var/tmp/ovirt-engine/config/%s" % filename,
r"<password>(.*)</password>",
r"<password>********</password>"
)
self.do_file_sub(
"/etc/ovirt-engine/redhatsupportplugin.conf",
r"proxyPassword=(.*)",
r"proxyPassword=********"
)
passwd_files = [
"logcollector.conf",
"imageuploader.conf",
"isouploader.conf"
]
for conf_file in passwd_files:
conf_path = os.path.join("/etc/ovirt-engine", conf_file)
self.do_file_sub(
conf_path,
r"passwd=(.*)",
r"passwd=********"
)
self.do_file_sub(
conf_path,
r"pg-pass=(.*)",
r"pg-pass=********"
)
sensitive_keys = self.DEFAULT_SENSITIVE_KEYS
# Handle --alloptions case which set this to True.
keys_opt = self.get_option('sensitive_keys')
if keys_opt and keys_opt is not True:
sensitive_keys = keys_opt
key_list = [x for x in sensitive_keys.split(':') if x]
for key in key_list:
self.do_path_regex_sub(
self.DB_PASS_FILES,
r'{key}=(.*)'.format(key=key),
r'{key}=********'.format(key=key)
)
# Answer files contain passwords
for key in (
'OVESETUP_CONFIG/adminPassword',
'OVESETUP_CONFIG/remoteEngineHostRootPassword',
'OVESETUP_DWH_DB/password',
'OVESETUP_DB/password',
'OVESETUP_REPORTS_CONFIG/adminPassword',
'OVESETUP_REPORTS_DB/password',
):
self.do_path_regex_sub(
r'/var/lib/ovirt-engine/setup/answers/.*',
r'{key}=(.*)'.format(key=key),
r'{key}=********'.format(key=key)
)
# aaa profiles contain passwords
protect_keys = [
"vars.password",
"pool.default.auth.simple.password",
"pool.default.ssl.truststore.password",
"config.datasource.dbpassword"
]
regexp = r"((?m)^\s*#*(%s)\s*=\s*)(.*)" % "|".join(protect_keys)
self.do_path_regex_sub(r"/etc/ovirt-engine/aaa/.*\.properties", regexp,
r"\1*********") | [
"def",
"postproc",
"(",
"self",
")",
":",
"self",
".",
"do_file_sub",
"(",
"\"/etc/ovirt-engine/engine-config/engine-config.properties\"",
",",
"r\"Password.type=(.*)\"",
",",
"r\"Password.type=********\"",
")",
"self",
".",
"do_file_sub",
"(",
"\"/etc/rhevm/rhevm-config/rhev... | Obfuscate sensitive keys. | [
"Obfuscate",
"sensitive",
"keys",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/ovirt.py#L135-L226 |
239,521 | sosreport/sos | sos/plugins/watchdog.py | Watchdog.get_log_dir | def get_log_dir(self, conf_file):
"""Get watchdog log directory.
Get watchdog log directory path configured in ``conf_file``.
:returns: The watchdog log directory path.
:returntype: str.
:raises: IOError if ``conf_file`` is not readable.
"""
log_dir = None
with open(conf_file, 'r') as conf_f:
for line in conf_f:
line = line.split('#')[0].strip()
try:
(key, value) = line.split('=', 1)
if key.strip() == 'log-dir':
log_dir = value.strip()
except ValueError:
pass
return log_dir | python | def get_log_dir(self, conf_file):
log_dir = None
with open(conf_file, 'r') as conf_f:
for line in conf_f:
line = line.split('#')[0].strip()
try:
(key, value) = line.split('=', 1)
if key.strip() == 'log-dir':
log_dir = value.strip()
except ValueError:
pass
return log_dir | [
"def",
"get_log_dir",
"(",
"self",
",",
"conf_file",
")",
":",
"log_dir",
"=",
"None",
"with",
"open",
"(",
"conf_file",
",",
"'r'",
")",
"as",
"conf_f",
":",
"for",
"line",
"in",
"conf_f",
":",
"line",
"=",
"line",
".",
"split",
"(",
"'#'",
")",
"... | Get watchdog log directory.
Get watchdog log directory path configured in ``conf_file``.
:returns: The watchdog log directory path.
:returntype: str.
:raises: IOError if ``conf_file`` is not readable. | [
"Get",
"watchdog",
"log",
"directory",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/watchdog.py#L27-L49 |
239,522 | sosreport/sos | sos/plugins/watchdog.py | Watchdog.setup | def setup(self):
"""Collect watchdog information.
Collect configuration files, custom executables for test-binary
and repair-binary, and stdout/stderr logs.
"""
conf_file = self.get_option('conf_file')
log_dir = '/var/log/watchdog'
# Get service configuration and sysconfig files
self.add_copy_spec([
conf_file,
'/etc/sysconfig/watchdog',
])
# Get custom executables
self.add_copy_spec([
'/etc/watchdog.d',
'/usr/libexec/watchdog/scripts',
])
# Get logs
try:
res = self.get_log_dir(conf_file)
if res:
log_dir = res
except IOError as ex:
self._log_warn("Could not read %s: %s" % (conf_file, ex))
if self.get_option('all_logs'):
log_files = glob(os.path.join(log_dir, '*'))
else:
log_files = (glob(os.path.join(log_dir, '*.stdout')) +
glob(os.path.join(log_dir, '*.stderr')))
self.add_copy_spec(log_files)
# Get output of "wdctl <device>" for each /dev/watchdog*
for dev in glob('/dev/watchdog*'):
self.add_cmd_output("wdctl %s" % dev) | python | def setup(self):
conf_file = self.get_option('conf_file')
log_dir = '/var/log/watchdog'
# Get service configuration and sysconfig files
self.add_copy_spec([
conf_file,
'/etc/sysconfig/watchdog',
])
# Get custom executables
self.add_copy_spec([
'/etc/watchdog.d',
'/usr/libexec/watchdog/scripts',
])
# Get logs
try:
res = self.get_log_dir(conf_file)
if res:
log_dir = res
except IOError as ex:
self._log_warn("Could not read %s: %s" % (conf_file, ex))
if self.get_option('all_logs'):
log_files = glob(os.path.join(log_dir, '*'))
else:
log_files = (glob(os.path.join(log_dir, '*.stdout')) +
glob(os.path.join(log_dir, '*.stderr')))
self.add_copy_spec(log_files)
# Get output of "wdctl <device>" for each /dev/watchdog*
for dev in glob('/dev/watchdog*'):
self.add_cmd_output("wdctl %s" % dev) | [
"def",
"setup",
"(",
"self",
")",
":",
"conf_file",
"=",
"self",
".",
"get_option",
"(",
"'conf_file'",
")",
"log_dir",
"=",
"'/var/log/watchdog'",
"# Get service configuration and sysconfig files",
"self",
".",
"add_copy_spec",
"(",
"[",
"conf_file",
",",
"'/etc/sy... | Collect watchdog information.
Collect configuration files, custom executables for test-binary
and repair-binary, and stdout/stderr logs. | [
"Collect",
"watchdog",
"information",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/watchdog.py#L51-L90 |
239,523 | sosreport/sos | sos/plugins/gluster.py | Gluster.get_volume_names | def get_volume_names(self, volume_file):
"""Return a dictionary for which key are volume names according to the
output of gluster volume info stored in volume_file.
"""
out = []
fp = open(volume_file, 'r')
for line in fp.readlines():
if not line.startswith("Volume Name:"):
continue
volname = line[12:-1]
out.append(volname)
fp.close()
return out | python | def get_volume_names(self, volume_file):
out = []
fp = open(volume_file, 'r')
for line in fp.readlines():
if not line.startswith("Volume Name:"):
continue
volname = line[12:-1]
out.append(volname)
fp.close()
return out | [
"def",
"get_volume_names",
"(",
"self",
",",
"volume_file",
")",
":",
"out",
"=",
"[",
"]",
"fp",
"=",
"open",
"(",
"volume_file",
",",
"'r'",
")",
"for",
"line",
"in",
"fp",
".",
"readlines",
"(",
")",
":",
"if",
"not",
"line",
".",
"startswith",
... | Return a dictionary for which key are volume names according to the
output of gluster volume info stored in volume_file. | [
"Return",
"a",
"dictionary",
"for",
"which",
"key",
"are",
"volume",
"names",
"according",
"to",
"the",
"output",
"of",
"gluster",
"volume",
"info",
"stored",
"in",
"volume_file",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/gluster.py#L29-L41 |
239,524 | sosreport/sos | sos/policies/ubuntu.py | UbuntuPolicy.dist_version | def dist_version(self):
""" Returns the version stated in DISTRIB_RELEASE
"""
try:
with open('/etc/lsb-release', 'r') as fp:
lines = fp.readlines()
for line in lines:
if "DISTRIB_RELEASE" in line:
return line.split("=")[1].strip()
return False
except IOError:
return False | python | def dist_version(self):
try:
with open('/etc/lsb-release', 'r') as fp:
lines = fp.readlines()
for line in lines:
if "DISTRIB_RELEASE" in line:
return line.split("=")[1].strip()
return False
except IOError:
return False | [
"def",
"dist_version",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"'/etc/lsb-release'",
",",
"'r'",
")",
"as",
"fp",
":",
"lines",
"=",
"fp",
".",
"readlines",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"\"DISTRIB_RELEASE\"",
"in",... | Returns the version stated in DISTRIB_RELEASE | [
"Returns",
"the",
"version",
"stated",
"in",
"DISTRIB_RELEASE"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/ubuntu.py#L26-L37 |
239,525 | sosreport/sos | sos/archive.py | FileCacheArchive._make_leading_paths | def _make_leading_paths(self, src, mode=0o700):
"""Create leading path components
The standard python `os.makedirs` is insufficient for our
needs: it will only create directories, and ignores the fact
that some path components may be symbolic links.
:param src: The source path in the host file system for which
leading components should be created, or the path
to an sos_* virtual directory inside the archive.
Host paths must be absolute (initial '/'), and
sos_* directory paths must be a path relative to
the root of the archive.
:param mode: An optional mode to be used when creating path
components.
:returns: A rewritten destination path in the case that one
or more symbolic links in intermediate components
of the path have altered the path destination.
"""
self.log_debug("Making leading paths for %s" % src)
root = self._archive_root
dest = src
def in_archive(path):
"""Test whether path ``path`` is inside the archive.
"""
return path.startswith(os.path.join(root, ""))
if not src.startswith("/"):
# Sos archive path (sos_commands, sos_logs etc.)
src_dir = src
else:
# Host file path
src_dir = src if os.path.isdir(src) else os.path.split(src)[0]
# Build a list of path components in root-to-leaf order.
path = src_dir
path_comps = []
while path != '/' and path != '':
head, tail = os.path.split(path)
path_comps.append(tail)
path = head
path_comps.reverse()
abs_path = root
src_path = "/"
# Check and create components as needed
for comp in path_comps:
abs_path = os.path.join(abs_path, comp)
# Do not create components that are above the archive root.
if not in_archive(abs_path):
continue
src_path = os.path.join(src_path, comp)
if not os.path.exists(abs_path):
self.log_debug("Making path %s" % abs_path)
if os.path.islink(src_path) and os.path.isdir(src_path):
target = os.readlink(src_path)
# The directory containing the source in the host fs,
# adjusted for the current level of path creation.
target_dir = os.path.split(src_path)[0]
# The source path of the target in the host fs to be
# recursively copied.
target_src = os.path.join(target_dir, target)
# Recursively create leading components of target
dest = self._make_leading_paths(target_src, mode=mode)
dest = os.path.normpath(dest)
self.log_debug("Making symlink '%s' -> '%s'" %
(abs_path, target))
os.symlink(target, abs_path)
else:
self.log_debug("Making directory %s" % abs_path)
os.mkdir(abs_path, mode)
dest = src_path
return dest | python | def _make_leading_paths(self, src, mode=0o700):
self.log_debug("Making leading paths for %s" % src)
root = self._archive_root
dest = src
def in_archive(path):
"""Test whether path ``path`` is inside the archive.
"""
return path.startswith(os.path.join(root, ""))
if not src.startswith("/"):
# Sos archive path (sos_commands, sos_logs etc.)
src_dir = src
else:
# Host file path
src_dir = src if os.path.isdir(src) else os.path.split(src)[0]
# Build a list of path components in root-to-leaf order.
path = src_dir
path_comps = []
while path != '/' and path != '':
head, tail = os.path.split(path)
path_comps.append(tail)
path = head
path_comps.reverse()
abs_path = root
src_path = "/"
# Check and create components as needed
for comp in path_comps:
abs_path = os.path.join(abs_path, comp)
# Do not create components that are above the archive root.
if not in_archive(abs_path):
continue
src_path = os.path.join(src_path, comp)
if not os.path.exists(abs_path):
self.log_debug("Making path %s" % abs_path)
if os.path.islink(src_path) and os.path.isdir(src_path):
target = os.readlink(src_path)
# The directory containing the source in the host fs,
# adjusted for the current level of path creation.
target_dir = os.path.split(src_path)[0]
# The source path of the target in the host fs to be
# recursively copied.
target_src = os.path.join(target_dir, target)
# Recursively create leading components of target
dest = self._make_leading_paths(target_src, mode=mode)
dest = os.path.normpath(dest)
self.log_debug("Making symlink '%s' -> '%s'" %
(abs_path, target))
os.symlink(target, abs_path)
else:
self.log_debug("Making directory %s" % abs_path)
os.mkdir(abs_path, mode)
dest = src_path
return dest | [
"def",
"_make_leading_paths",
"(",
"self",
",",
"src",
",",
"mode",
"=",
"0o700",
")",
":",
"self",
".",
"log_debug",
"(",
"\"Making leading paths for %s\"",
"%",
"src",
")",
"root",
"=",
"self",
".",
"_archive_root",
"dest",
"=",
"src",
"def",
"in_archive",... | Create leading path components
The standard python `os.makedirs` is insufficient for our
needs: it will only create directories, and ignores the fact
that some path components may be symbolic links.
:param src: The source path in the host file system for which
leading components should be created, or the path
to an sos_* virtual directory inside the archive.
Host paths must be absolute (initial '/'), and
sos_* directory paths must be a path relative to
the root of the archive.
:param mode: An optional mode to be used when creating path
components.
:returns: A rewritten destination path in the case that one
or more symbolic links in intermediate components
of the path have altered the path destination. | [
"Create",
"leading",
"path",
"components"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L159-L243 |
239,526 | sosreport/sos | sos/archive.py | FileCacheArchive._check_path | def _check_path(self, src, path_type, dest=None, force=False):
"""Check a new destination path in the archive.
Since it is possible for multiple plugins to collect the same
paths, and since plugins can now run concurrently, it is possible
for two threads to race in archive methods: historically the
archive class only needed to test for the actual presence of a
path, since it was impossible for another `Archive` client to
enter the class while another method invocation was being
dispatched.
Deal with this by implementing a locking scheme for operations
that modify the path structure of the archive, and by testing
explicitly for conflicts with any existing content at the
specified destination path.
It is not an error to attempt to create a path that already
exists in the archive so long as the type of the object to be
added matches the type of object already found at the path.
It is an error to attempt to re-create an existing path with
a different path type (for example, creating a symbolic link
at a path already occupied by a regular file).
:param src: the source path to be copied to the archive
:param path_type: the type of object to be copied
:param dest: an optional destination path
:param force: force file creation even if the path exists
:returns: An absolute destination path if the path should be
copied now or `None` otherwise
"""
dest = dest or self.dest_path(src)
if path_type == P_DIR:
dest_dir = dest
else:
dest_dir = os.path.split(dest)[0]
if not dest_dir:
return dest
# Check containing directory presence and path type
if os.path.exists(dest_dir) and not os.path.isdir(dest_dir):
raise ValueError("path '%s' exists and is not a directory" %
dest_dir)
elif not os.path.exists(dest_dir):
src_dir = src if path_type == P_DIR else os.path.split(src)[0]
self._make_leading_paths(src_dir)
def is_special(mode):
return any([
stat.S_ISBLK(mode),
stat.S_ISCHR(mode),
stat.S_ISFIFO(mode),
stat.S_ISSOCK(mode)
])
if force:
return dest
# Check destination path presence and type
if os.path.exists(dest):
# Use lstat: we care about the current object, not the referent.
st = os.lstat(dest)
ve_msg = "path '%s' exists and is not a %s"
if path_type == P_FILE and not stat.S_ISREG(st.st_mode):
raise ValueError(ve_msg % (dest, "regular file"))
if path_type == P_LINK and not stat.S_ISLNK(st.st_mode):
raise ValueError(ve_msg % (dest, "symbolic link"))
if path_type == P_NODE and not is_special(st.st_mode):
raise ValueError(ve_msg % (dest, "special file"))
if path_type == P_DIR and not stat.S_ISDIR(st.st_mode):
raise ValueError(ve_msg % (dest, "directory"))
# Path has already been copied: skip
return None
return dest | python | def _check_path(self, src, path_type, dest=None, force=False):
dest = dest or self.dest_path(src)
if path_type == P_DIR:
dest_dir = dest
else:
dest_dir = os.path.split(dest)[0]
if not dest_dir:
return dest
# Check containing directory presence and path type
if os.path.exists(dest_dir) and not os.path.isdir(dest_dir):
raise ValueError("path '%s' exists and is not a directory" %
dest_dir)
elif not os.path.exists(dest_dir):
src_dir = src if path_type == P_DIR else os.path.split(src)[0]
self._make_leading_paths(src_dir)
def is_special(mode):
return any([
stat.S_ISBLK(mode),
stat.S_ISCHR(mode),
stat.S_ISFIFO(mode),
stat.S_ISSOCK(mode)
])
if force:
return dest
# Check destination path presence and type
if os.path.exists(dest):
# Use lstat: we care about the current object, not the referent.
st = os.lstat(dest)
ve_msg = "path '%s' exists and is not a %s"
if path_type == P_FILE and not stat.S_ISREG(st.st_mode):
raise ValueError(ve_msg % (dest, "regular file"))
if path_type == P_LINK and not stat.S_ISLNK(st.st_mode):
raise ValueError(ve_msg % (dest, "symbolic link"))
if path_type == P_NODE and not is_special(st.st_mode):
raise ValueError(ve_msg % (dest, "special file"))
if path_type == P_DIR and not stat.S_ISDIR(st.st_mode):
raise ValueError(ve_msg % (dest, "directory"))
# Path has already been copied: skip
return None
return dest | [
"def",
"_check_path",
"(",
"self",
",",
"src",
",",
"path_type",
",",
"dest",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"dest",
"=",
"dest",
"or",
"self",
".",
"dest_path",
"(",
"src",
")",
"if",
"path_type",
"==",
"P_DIR",
":",
"dest_dir",
... | Check a new destination path in the archive.
Since it is possible for multiple plugins to collect the same
paths, and since plugins can now run concurrently, it is possible
for two threads to race in archive methods: historically the
archive class only needed to test for the actual presence of a
path, since it was impossible for another `Archive` client to
enter the class while another method invocation was being
dispatched.
Deal with this by implementing a locking scheme for operations
that modify the path structure of the archive, and by testing
explicitly for conflicts with any existing content at the
specified destination path.
It is not an error to attempt to create a path that already
exists in the archive so long as the type of the object to be
added matches the type of object already found at the path.
It is an error to attempt to re-create an existing path with
a different path type (for example, creating a symbolic link
at a path already occupied by a regular file).
:param src: the source path to be copied to the archive
:param path_type: the type of object to be copied
:param dest: an optional destination path
:param force: force file creation even if the path exists
:returns: An absolute destination path if the path should be
copied now or `None` otherwise | [
"Check",
"a",
"new",
"destination",
"path",
"in",
"the",
"archive",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L245-L318 |
239,527 | sosreport/sos | sos/archive.py | FileCacheArchive.makedirs | def makedirs(self, path, mode=0o700):
"""Create path, including leading components.
Used by sos.sosreport to set up sos_* directories.
"""
os.makedirs(os.path.join(self._archive_root, path), mode=mode)
self.log_debug("created directory at '%s' in FileCacheArchive '%s'"
% (path, self._archive_root)) | python | def makedirs(self, path, mode=0o700):
os.makedirs(os.path.join(self._archive_root, path), mode=mode)
self.log_debug("created directory at '%s' in FileCacheArchive '%s'"
% (path, self._archive_root)) | [
"def",
"makedirs",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"0o700",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_archive_root",
",",
"path",
")",
",",
"mode",
"=",
"mode",
")",
"self",
".",
"log_de... | Create path, including leading components.
Used by sos.sosreport to set up sos_* directories. | [
"Create",
"path",
"including",
"leading",
"components",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L510-L517 |
239,528 | sosreport/sos | sos/archive.py | FileCacheArchive._encrypt | def _encrypt(self, archive):
"""Encrypts the compressed archive using GPG.
If encryption fails for any reason, it should be logged by sos but not
cause execution to stop. The assumption is that the unencrypted archive
would still be of use to the user, and/or that the end user has another
means of securing the archive.
Returns the name of the encrypted archive, or raises an exception to
signal that encryption failed and the unencrypted archive name should
be used.
"""
arc_name = archive.replace("sosreport-", "secured-sosreport-")
arc_name += ".gpg"
enc_cmd = "gpg --batch -o %s " % arc_name
env = None
if self.enc_opts["key"]:
# need to assume a trusted key here to be able to encrypt the
# archive non-interactively
enc_cmd += "--trust-model always -e -r %s " % self.enc_opts["key"]
enc_cmd += archive
if self.enc_opts["password"]:
# prevent change of gpg options using a long password, but also
# prevent the addition of quote characters to the passphrase
passwd = "%s" % self.enc_opts["password"].replace('\'"', '')
env = {"sos_gpg": passwd}
enc_cmd += "-c --passphrase-fd 0 "
enc_cmd = "/bin/bash -c \"echo $sos_gpg | %s\"" % enc_cmd
enc_cmd += archive
r = sos_get_command_output(enc_cmd, timeout=0, env=env)
if r["status"] == 0:
return arc_name
elif r["status"] == 2:
if self.enc_opts["key"]:
msg = "Specified key not in keyring"
else:
msg = "Could not read passphrase"
else:
# TODO: report the actual error from gpg. Currently, we cannot as
# sos_get_command_output() does not capture stderr
msg = "gpg exited with code %s" % r["status"]
raise Exception(msg) | python | def _encrypt(self, archive):
arc_name = archive.replace("sosreport-", "secured-sosreport-")
arc_name += ".gpg"
enc_cmd = "gpg --batch -o %s " % arc_name
env = None
if self.enc_opts["key"]:
# need to assume a trusted key here to be able to encrypt the
# archive non-interactively
enc_cmd += "--trust-model always -e -r %s " % self.enc_opts["key"]
enc_cmd += archive
if self.enc_opts["password"]:
# prevent change of gpg options using a long password, but also
# prevent the addition of quote characters to the passphrase
passwd = "%s" % self.enc_opts["password"].replace('\'"', '')
env = {"sos_gpg": passwd}
enc_cmd += "-c --passphrase-fd 0 "
enc_cmd = "/bin/bash -c \"echo $sos_gpg | %s\"" % enc_cmd
enc_cmd += archive
r = sos_get_command_output(enc_cmd, timeout=0, env=env)
if r["status"] == 0:
return arc_name
elif r["status"] == 2:
if self.enc_opts["key"]:
msg = "Specified key not in keyring"
else:
msg = "Could not read passphrase"
else:
# TODO: report the actual error from gpg. Currently, we cannot as
# sos_get_command_output() does not capture stderr
msg = "gpg exited with code %s" % r["status"]
raise Exception(msg) | [
"def",
"_encrypt",
"(",
"self",
",",
"archive",
")",
":",
"arc_name",
"=",
"archive",
".",
"replace",
"(",
"\"sosreport-\"",
",",
"\"secured-sosreport-\"",
")",
"arc_name",
"+=",
"\".gpg\"",
"enc_cmd",
"=",
"\"gpg --batch -o %s \"",
"%",
"arc_name",
"env",
"=",
... | Encrypts the compressed archive using GPG.
If encryption fails for any reason, it should be logged by sos but not
cause execution to stop. The assumption is that the unencrypted archive
would still be of use to the user, and/or that the end user has another
means of securing the archive.
Returns the name of the encrypted archive, or raises an exception to
signal that encryption failed and the unencrypted archive name should
be used. | [
"Encrypts",
"the",
"compressed",
"archive",
"using",
"GPG",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/archive.py#L552-L593 |
239,529 | sosreport/sos | sos/utilities.py | tail | def tail(filename, number_of_bytes):
"""Returns the last number_of_bytes of filename"""
with open(filename, "rb") as f:
if os.stat(filename).st_size > number_of_bytes:
f.seek(-number_of_bytes, 2)
return f.read() | python | def tail(filename, number_of_bytes):
with open(filename, "rb") as f:
if os.stat(filename).st_size > number_of_bytes:
f.seek(-number_of_bytes, 2)
return f.read() | [
"def",
"tail",
"(",
"filename",
",",
"number_of_bytes",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"f",
":",
"if",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_size",
">",
"number_of_bytes",
":",
"f",
".",
"seek",
"(",
... | Returns the last number_of_bytes of filename | [
"Returns",
"the",
"last",
"number_of_bytes",
"of",
"filename"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L29-L34 |
239,530 | sosreport/sos | sos/utilities.py | fileobj | def fileobj(path_or_file, mode='r'):
"""Returns a file-like object that can be used as a context manager"""
if isinstance(path_or_file, six.string_types):
try:
return open(path_or_file, mode)
except IOError:
log = logging.getLogger('sos')
log.debug("fileobj: %s could not be opened" % path_or_file)
return closing(six.StringIO())
else:
return closing(path_or_file) | python | def fileobj(path_or_file, mode='r'):
if isinstance(path_or_file, six.string_types):
try:
return open(path_or_file, mode)
except IOError:
log = logging.getLogger('sos')
log.debug("fileobj: %s could not be opened" % path_or_file)
return closing(six.StringIO())
else:
return closing(path_or_file) | [
"def",
"fileobj",
"(",
"path_or_file",
",",
"mode",
"=",
"'r'",
")",
":",
"if",
"isinstance",
"(",
"path_or_file",
",",
"six",
".",
"string_types",
")",
":",
"try",
":",
"return",
"open",
"(",
"path_or_file",
",",
"mode",
")",
"except",
"IOError",
":",
... | Returns a file-like object that can be used as a context manager | [
"Returns",
"a",
"file",
"-",
"like",
"object",
"that",
"can",
"be",
"used",
"as",
"a",
"context",
"manager"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L37-L47 |
239,531 | sosreport/sos | sos/utilities.py | convert_bytes | def convert_bytes(bytes_, K=1 << 10, M=1 << 20, G=1 << 30, T=1 << 40):
"""Converts a number of bytes to a shorter, more human friendly format"""
fn = float(bytes_)
if bytes_ >= T:
return '%.1fT' % (fn / T)
elif bytes_ >= G:
return '%.1fG' % (fn / G)
elif bytes_ >= M:
return '%.1fM' % (fn / M)
elif bytes_ >= K:
return '%.1fK' % (fn / K)
else:
return '%d' % bytes_ | python | def convert_bytes(bytes_, K=1 << 10, M=1 << 20, G=1 << 30, T=1 << 40):
fn = float(bytes_)
if bytes_ >= T:
return '%.1fT' % (fn / T)
elif bytes_ >= G:
return '%.1fG' % (fn / G)
elif bytes_ >= M:
return '%.1fM' % (fn / M)
elif bytes_ >= K:
return '%.1fK' % (fn / K)
else:
return '%d' % bytes_ | [
"def",
"convert_bytes",
"(",
"bytes_",
",",
"K",
"=",
"1",
"<<",
"10",
",",
"M",
"=",
"1",
"<<",
"20",
",",
"G",
"=",
"1",
"<<",
"30",
",",
"T",
"=",
"1",
"<<",
"40",
")",
":",
"fn",
"=",
"float",
"(",
"bytes_",
")",
"if",
"bytes_",
">=",
... | Converts a number of bytes to a shorter, more human friendly format | [
"Converts",
"a",
"number",
"of",
"bytes",
"to",
"a",
"shorter",
"more",
"human",
"friendly",
"format"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L50-L62 |
239,532 | sosreport/sos | sos/utilities.py | grep | def grep(pattern, *files_or_paths):
"""Returns lines matched in fnames, where fnames can either be pathnames to
files to grep through or open file objects to grep through line by line"""
matches = []
for fop in files_or_paths:
with fileobj(fop) as fo:
matches.extend((line for line in fo if re.match(pattern, line)))
return matches | python | def grep(pattern, *files_or_paths):
matches = []
for fop in files_or_paths:
with fileobj(fop) as fo:
matches.extend((line for line in fo if re.match(pattern, line)))
return matches | [
"def",
"grep",
"(",
"pattern",
",",
"*",
"files_or_paths",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"fop",
"in",
"files_or_paths",
":",
"with",
"fileobj",
"(",
"fop",
")",
"as",
"fo",
":",
"matches",
".",
"extend",
"(",
"(",
"line",
"for",
"line",
... | Returns lines matched in fnames, where fnames can either be pathnames to
files to grep through or open file objects to grep through line by line | [
"Returns",
"lines",
"matched",
"in",
"fnames",
"where",
"fnames",
"can",
"either",
"be",
"pathnames",
"to",
"files",
"to",
"grep",
"through",
"or",
"open",
"file",
"objects",
"to",
"grep",
"through",
"line",
"by",
"line"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L87-L96 |
239,533 | sosreport/sos | sos/utilities.py | is_executable | def is_executable(command):
"""Returns if a command matches an executable on the PATH"""
paths = os.environ.get("PATH", "").split(os.path.pathsep)
candidates = [command] + [os.path.join(p, command) for p in paths]
return any(os.access(path, os.X_OK) for path in candidates) | python | def is_executable(command):
paths = os.environ.get("PATH", "").split(os.path.pathsep)
candidates = [command] + [os.path.join(p, command) for p in paths]
return any(os.access(path, os.X_OK) for path in candidates) | [
"def",
"is_executable",
"(",
"command",
")",
":",
"paths",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"PATH\"",
",",
"\"\"",
")",
".",
"split",
"(",
"os",
".",
"path",
".",
"pathsep",
")",
"candidates",
"=",
"[",
"command",
"]",
"+",
"[",
"os",
... | Returns if a command matches an executable on the PATH | [
"Returns",
"if",
"a",
"command",
"matches",
"an",
"executable",
"on",
"the",
"PATH"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L99-L104 |
239,534 | sosreport/sos | sos/utilities.py | sos_get_command_output | def sos_get_command_output(command, timeout=300, stderr=False,
chroot=None, chdir=None, env=None,
binary=False, sizelimit=None, poller=None):
"""Execute a command and return a dictionary of status and output,
optionally changing root or current working directory before
executing command.
"""
# Change root or cwd for child only. Exceptions in the prexec_fn
# closure are caught in the parent (chroot and chdir are bound from
# the enclosing scope).
def _child_prep_fn():
if (chroot):
os.chroot(chroot)
if (chdir):
os.chdir(chdir)
cmd_env = os.environ.copy()
# ensure consistent locale for collected command output
cmd_env['LC_ALL'] = 'C'
# optionally add an environment change for the command
if env:
for key, value in env.items():
if value:
cmd_env[key] = value
else:
cmd_env.pop(key, None)
# use /usr/bin/timeout to implement a timeout
if timeout and is_executable("timeout"):
command = "timeout %ds %s" % (timeout, command)
# shlex.split() reacts badly to unicode on older python runtimes.
if not six.PY3:
command = command.encode('utf-8', 'ignore')
args = shlex.split(command)
# Expand arguments that are wildcard paths.
expanded_args = []
for arg in args:
expanded_arg = glob.glob(arg)
if expanded_arg:
expanded_args.extend(expanded_arg)
else:
expanded_args.append(arg)
try:
p = Popen(expanded_args, shell=False, stdout=PIPE,
stderr=STDOUT if stderr else PIPE,
bufsize=-1, env=cmd_env, close_fds=True,
preexec_fn=_child_prep_fn)
reader = AsyncReader(p.stdout, sizelimit, binary)
if poller:
while reader.running:
if poller():
p.terminate()
raise SoSTimeoutError
stdout = reader.get_contents()
while p.poll() is None:
pass
except OSError as e:
if e.errno == errno.ENOENT:
return {'status': 127, 'output': ""}
else:
raise e
if p.returncode == 126 or p.returncode == 127:
stdout = six.binary_type(b"")
return {
'status': p.returncode,
'output': stdout
} | python | def sos_get_command_output(command, timeout=300, stderr=False,
chroot=None, chdir=None, env=None,
binary=False, sizelimit=None, poller=None):
# Change root or cwd for child only. Exceptions in the prexec_fn
# closure are caught in the parent (chroot and chdir are bound from
# the enclosing scope).
def _child_prep_fn():
if (chroot):
os.chroot(chroot)
if (chdir):
os.chdir(chdir)
cmd_env = os.environ.copy()
# ensure consistent locale for collected command output
cmd_env['LC_ALL'] = 'C'
# optionally add an environment change for the command
if env:
for key, value in env.items():
if value:
cmd_env[key] = value
else:
cmd_env.pop(key, None)
# use /usr/bin/timeout to implement a timeout
if timeout and is_executable("timeout"):
command = "timeout %ds %s" % (timeout, command)
# shlex.split() reacts badly to unicode on older python runtimes.
if not six.PY3:
command = command.encode('utf-8', 'ignore')
args = shlex.split(command)
# Expand arguments that are wildcard paths.
expanded_args = []
for arg in args:
expanded_arg = glob.glob(arg)
if expanded_arg:
expanded_args.extend(expanded_arg)
else:
expanded_args.append(arg)
try:
p = Popen(expanded_args, shell=False, stdout=PIPE,
stderr=STDOUT if stderr else PIPE,
bufsize=-1, env=cmd_env, close_fds=True,
preexec_fn=_child_prep_fn)
reader = AsyncReader(p.stdout, sizelimit, binary)
if poller:
while reader.running:
if poller():
p.terminate()
raise SoSTimeoutError
stdout = reader.get_contents()
while p.poll() is None:
pass
except OSError as e:
if e.errno == errno.ENOENT:
return {'status': 127, 'output': ""}
else:
raise e
if p.returncode == 126 or p.returncode == 127:
stdout = six.binary_type(b"")
return {
'status': p.returncode,
'output': stdout
} | [
"def",
"sos_get_command_output",
"(",
"command",
",",
"timeout",
"=",
"300",
",",
"stderr",
"=",
"False",
",",
"chroot",
"=",
"None",
",",
"chdir",
"=",
"None",
",",
"env",
"=",
"None",
",",
"binary",
"=",
"False",
",",
"sizelimit",
"=",
"None",
",",
... | Execute a command and return a dictionary of status and output,
optionally changing root or current working directory before
executing command. | [
"Execute",
"a",
"command",
"and",
"return",
"a",
"dictionary",
"of",
"status",
"and",
"output",
"optionally",
"changing",
"root",
"or",
"current",
"working",
"directory",
"before",
"executing",
"command",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L107-L177 |
239,535 | sosreport/sos | sos/utilities.py | import_module | def import_module(module_fqname, superclasses=None):
"""Imports the module module_fqname and returns a list of defined classes
from that module. If superclasses is defined then the classes returned will
be subclasses of the specified superclass or superclasses. If superclasses
is plural it must be a tuple of classes."""
module_name = module_fqname.rpartition(".")[-1]
module = __import__(module_fqname, globals(), locals(), [module_name])
modules = [class_ for cname, class_ in
inspect.getmembers(module, inspect.isclass)
if class_.__module__ == module_fqname]
if superclasses:
modules = [m for m in modules if issubclass(m, superclasses)]
return modules | python | def import_module(module_fqname, superclasses=None):
module_name = module_fqname.rpartition(".")[-1]
module = __import__(module_fqname, globals(), locals(), [module_name])
modules = [class_ for cname, class_ in
inspect.getmembers(module, inspect.isclass)
if class_.__module__ == module_fqname]
if superclasses:
modules = [m for m in modules if issubclass(m, superclasses)]
return modules | [
"def",
"import_module",
"(",
"module_fqname",
",",
"superclasses",
"=",
"None",
")",
":",
"module_name",
"=",
"module_fqname",
".",
"rpartition",
"(",
"\".\"",
")",
"[",
"-",
"1",
"]",
"module",
"=",
"__import__",
"(",
"module_fqname",
",",
"globals",
"(",
... | Imports the module module_fqname and returns a list of defined classes
from that module. If superclasses is defined then the classes returned will
be subclasses of the specified superclass or superclasses. If superclasses
is plural it must be a tuple of classes. | [
"Imports",
"the",
"module",
"module_fqname",
"and",
"returns",
"a",
"list",
"of",
"defined",
"classes",
"from",
"that",
"module",
".",
"If",
"superclasses",
"is",
"defined",
"then",
"the",
"classes",
"returned",
"will",
"be",
"subclasses",
"of",
"the",
"specif... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L180-L193 |
239,536 | sosreport/sos | sos/utilities.py | shell_out | def shell_out(cmd, timeout=30, chroot=None, runat=None):
"""Shell out to an external command and return the output or the empty
string in case of error.
"""
return sos_get_command_output(cmd, timeout=timeout,
chroot=chroot, chdir=runat)['output'] | python | def shell_out(cmd, timeout=30, chroot=None, runat=None):
return sos_get_command_output(cmd, timeout=timeout,
chroot=chroot, chdir=runat)['output'] | [
"def",
"shell_out",
"(",
"cmd",
",",
"timeout",
"=",
"30",
",",
"chroot",
"=",
"None",
",",
"runat",
"=",
"None",
")",
":",
"return",
"sos_get_command_output",
"(",
"cmd",
",",
"timeout",
"=",
"timeout",
",",
"chroot",
"=",
"chroot",
",",
"chdir",
"=",... | Shell out to an external command and return the output or the empty
string in case of error. | [
"Shell",
"out",
"to",
"an",
"external",
"command",
"and",
"return",
"the",
"output",
"or",
"the",
"empty",
"string",
"in",
"case",
"of",
"error",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L196-L201 |
239,537 | sosreport/sos | sos/utilities.py | AsyncReader.get_contents | def get_contents(self):
'''Returns the contents of the deque as a string'''
# block until command completes or timesout (separate from the plugin
# hitting a timeout)
while self.running:
pass
if not self.binary:
return ''.join(ln.decode('utf-8', 'ignore') for ln in self.deque)
else:
return b''.join(ln for ln in self.deque) | python | def get_contents(self):
'''Returns the contents of the deque as a string'''
# block until command completes or timesout (separate from the plugin
# hitting a timeout)
while self.running:
pass
if not self.binary:
return ''.join(ln.decode('utf-8', 'ignore') for ln in self.deque)
else:
return b''.join(ln for ln in self.deque) | [
"def",
"get_contents",
"(",
"self",
")",
":",
"# block until command completes or timesout (separate from the plugin",
"# hitting a timeout)",
"while",
"self",
".",
"running",
":",
"pass",
"if",
"not",
"self",
".",
"binary",
":",
"return",
"''",
".",
"join",
"(",
"l... | Returns the contents of the deque as a string | [
"Returns",
"the",
"contents",
"of",
"the",
"deque",
"as",
"a",
"string"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L246-L255 |
239,538 | sosreport/sos | sos/utilities.py | ImporterHelper._plugin_name | def _plugin_name(self, path):
"Returns the plugin module name given the path"
base = os.path.basename(path)
name, ext = os.path.splitext(base)
return name | python | def _plugin_name(self, path):
"Returns the plugin module name given the path"
base = os.path.basename(path)
name, ext = os.path.splitext(base)
return name | [
"def",
"_plugin_name",
"(",
"self",
",",
"path",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"base",
")",
"return",
"name"
] | Returns the plugin module name given the path | [
"Returns",
"the",
"plugin",
"module",
"name",
"given",
"the",
"path"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L270-L274 |
239,539 | sosreport/sos | sos/utilities.py | ImporterHelper.get_modules | def get_modules(self):
"""Returns the list of importable modules in the configured python
package. """
plugins = []
for path in self.package.__path__:
if os.path.isdir(path):
plugins.extend(self._find_plugins_in_dir(path))
return plugins | python | def get_modules(self):
plugins = []
for path in self.package.__path__:
if os.path.isdir(path):
plugins.extend(self._find_plugins_in_dir(path))
return plugins | [
"def",
"get_modules",
"(",
"self",
")",
":",
"plugins",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"package",
".",
"__path__",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"plugins",
".",
"extend",
"(",
"self",
".",
"_... | Returns the list of importable modules in the configured python
package. | [
"Returns",
"the",
"list",
"of",
"importable",
"modules",
"in",
"the",
"configured",
"python",
"package",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/utilities.py#L292-L300 |
239,540 | sosreport/sos | sos/policies/redhat.py | RedHatPolicy.check_usrmove | def check_usrmove(self, pkgs):
"""Test whether the running system implements UsrMove.
If the 'filesystem' package is present, it will check that the
version is greater than 3. If the package is not present the
'/bin' and '/sbin' paths are checked and UsrMove is assumed
if both are symbolic links.
:param pkgs: a packages dictionary
"""
if 'filesystem' not in pkgs:
return os.path.islink('/bin') and os.path.islink('/sbin')
else:
filesys_version = pkgs['filesystem']['version']
return True if filesys_version[0] == '3' else False | python | def check_usrmove(self, pkgs):
if 'filesystem' not in pkgs:
return os.path.islink('/bin') and os.path.islink('/sbin')
else:
filesys_version = pkgs['filesystem']['version']
return True if filesys_version[0] == '3' else False | [
"def",
"check_usrmove",
"(",
"self",
",",
"pkgs",
")",
":",
"if",
"'filesystem'",
"not",
"in",
"pkgs",
":",
"return",
"os",
".",
"path",
".",
"islink",
"(",
"'/bin'",
")",
"and",
"os",
".",
"path",
".",
"islink",
"(",
"'/sbin'",
")",
"else",
":",
"... | Test whether the running system implements UsrMove.
If the 'filesystem' package is present, it will check that the
version is greater than 3. If the package is not present the
'/bin' and '/sbin' paths are checked and UsrMove is assumed
if both are symbolic links.
:param pkgs: a packages dictionary | [
"Test",
"whether",
"the",
"running",
"system",
"implements",
"UsrMove",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L100-L114 |
239,541 | sosreport/sos | sos/policies/redhat.py | RedHatPolicy.mangle_package_path | def mangle_package_path(self, files):
"""Mangle paths for post-UsrMove systems.
If the system implements UsrMove, all files will be in
'/usr/[s]bin'. This method substitutes all the /[s]bin
references in the 'files' list with '/usr/[s]bin'.
:param files: the list of package managed files
"""
paths = []
def transform_path(path):
# Some packages actually own paths in /bin: in this case,
# duplicate the path as both the / and /usr version.
skip_paths = ["/bin/rpm", "/bin/mailx"]
if path in skip_paths:
return (path, os.path.join("/usr", path[1:]))
return (re.sub(r'(^)(/s?bin)', r'\1/usr\2', path),)
if self.usrmove:
for f in files:
paths.extend(transform_path(f))
return paths
else:
return files | python | def mangle_package_path(self, files):
paths = []
def transform_path(path):
# Some packages actually own paths in /bin: in this case,
# duplicate the path as both the / and /usr version.
skip_paths = ["/bin/rpm", "/bin/mailx"]
if path in skip_paths:
return (path, os.path.join("/usr", path[1:]))
return (re.sub(r'(^)(/s?bin)', r'\1/usr\2', path),)
if self.usrmove:
for f in files:
paths.extend(transform_path(f))
return paths
else:
return files | [
"def",
"mangle_package_path",
"(",
"self",
",",
"files",
")",
":",
"paths",
"=",
"[",
"]",
"def",
"transform_path",
"(",
"path",
")",
":",
"# Some packages actually own paths in /bin: in this case,",
"# duplicate the path as both the / and /usr version.",
"skip_paths",
"=",... | Mangle paths for post-UsrMove systems.
If the system implements UsrMove, all files will be in
'/usr/[s]bin'. This method substitutes all the /[s]bin
references in the 'files' list with '/usr/[s]bin'.
:param files: the list of package managed files | [
"Mangle",
"paths",
"for",
"post",
"-",
"UsrMove",
"systems",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L116-L140 |
239,542 | sosreport/sos | sos/policies/redhat.py | RedHatPolicy._container_init | def _container_init(self):
"""Check if sos is running in a container and perform container
specific initialisation based on ENV_HOST_SYSROOT.
"""
if ENV_CONTAINER in os.environ:
if os.environ[ENV_CONTAINER] in ['docker', 'oci']:
self._in_container = True
if ENV_HOST_SYSROOT in os.environ:
self._host_sysroot = os.environ[ENV_HOST_SYSROOT]
use_sysroot = self._in_container and self._host_sysroot != '/'
if use_sysroot:
host_tmp_dir = os.path.abspath(self._host_sysroot + self._tmp_dir)
self._tmp_dir = host_tmp_dir
return self._host_sysroot if use_sysroot else None | python | def _container_init(self):
if ENV_CONTAINER in os.environ:
if os.environ[ENV_CONTAINER] in ['docker', 'oci']:
self._in_container = True
if ENV_HOST_SYSROOT in os.environ:
self._host_sysroot = os.environ[ENV_HOST_SYSROOT]
use_sysroot = self._in_container and self._host_sysroot != '/'
if use_sysroot:
host_tmp_dir = os.path.abspath(self._host_sysroot + self._tmp_dir)
self._tmp_dir = host_tmp_dir
return self._host_sysroot if use_sysroot else None | [
"def",
"_container_init",
"(",
"self",
")",
":",
"if",
"ENV_CONTAINER",
"in",
"os",
".",
"environ",
":",
"if",
"os",
".",
"environ",
"[",
"ENV_CONTAINER",
"]",
"in",
"[",
"'docker'",
",",
"'oci'",
"]",
":",
"self",
".",
"_in_container",
"=",
"True",
"i... | Check if sos is running in a container and perform container
specific initialisation based on ENV_HOST_SYSROOT. | [
"Check",
"if",
"sos",
"is",
"running",
"in",
"a",
"container",
"and",
"perform",
"container",
"specific",
"initialisation",
"based",
"on",
"ENV_HOST_SYSROOT",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L142-L155 |
239,543 | sosreport/sos | sos/policies/redhat.py | RHELPolicy.check | def check(cls):
"""Test to see if the running host is a RHEL installation.
Checks for the presence of the "Red Hat Enterprise Linux"
release string at the beginning of the NAME field in the
`/etc/os-release` file and returns ``True`` if it is
found, and ``False`` otherwise.
:returns: ``True`` if the host is running RHEL or ``False``
otherwise.
"""
if not os.path.exists(OS_RELEASE):
return False
with open(OS_RELEASE, "r") as f:
for line in f:
if line.startswith("NAME"):
(name, value) = line.split("=")
value = value.strip("\"'")
if value.startswith(cls.distro):
return True
return False | python | def check(cls):
if not os.path.exists(OS_RELEASE):
return False
with open(OS_RELEASE, "r") as f:
for line in f:
if line.startswith("NAME"):
(name, value) = line.split("=")
value = value.strip("\"'")
if value.startswith(cls.distro):
return True
return False | [
"def",
"check",
"(",
"cls",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"OS_RELEASE",
")",
":",
"return",
"False",
"with",
"open",
"(",
"OS_RELEASE",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"line"... | Test to see if the running host is a RHEL installation.
Checks for the presence of the "Red Hat Enterprise Linux"
release string at the beginning of the NAME field in the
`/etc/os-release` file and returns ``True`` if it is
found, and ``False`` otherwise.
:returns: ``True`` if the host is running RHEL or ``False``
otherwise. | [
"Test",
"to",
"see",
"if",
"the",
"running",
"host",
"is",
"a",
"RHEL",
"installation",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/redhat.py#L274-L295 |
239,544 | sosreport/sos | sos/plugins/lustre.py | Lustre.get_params | def get_params(self, name, param_list):
'''Use lctl get_param to collect a selection of parameters into a
file.
'''
self.add_cmd_output("lctl get_param %s" % " ".join(param_list),
suggest_filename="params-%s" % name,
stderr=False) | python | def get_params(self, name, param_list):
'''Use lctl get_param to collect a selection of parameters into a
file.
'''
self.add_cmd_output("lctl get_param %s" % " ".join(param_list),
suggest_filename="params-%s" % name,
stderr=False) | [
"def",
"get_params",
"(",
"self",
",",
"name",
",",
"param_list",
")",
":",
"self",
".",
"add_cmd_output",
"(",
"\"lctl get_param %s\"",
"%",
"\" \"",
".",
"join",
"(",
"param_list",
")",
",",
"suggest_filename",
"=",
"\"params-%s\"",
"%",
"name",
",",
"stde... | Use lctl get_param to collect a selection of parameters into a
file. | [
"Use",
"lctl",
"get_param",
"to",
"collect",
"a",
"selection",
"of",
"parameters",
"into",
"a",
"file",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/lustre.py#L19-L26 |
239,545 | sosreport/sos | sos/plugins/qpid_dispatch.py | QpidDispatch.setup | def setup(self):
""" performs data collection for qpid dispatch router """
options = ""
if self.get_option("port"):
options = (options + " -b " + gethostname() +
":%s" % (self.get_option("port")))
# gethostname() is due to DISPATCH-156
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key", "ssl-trustfile"]:
if self.get_option(option):
options = (options + " --%s=" % (option) +
self.get_option(option))
self.add_cmd_output([
"qdstat -a" + options, # Show Router Addresses
"qdstat -n" + options, # Show Router Nodes
"qdstat -c" + options, # Show Connections
"qdstat -m" + options # Show Broker Memory Stats
])
self.add_copy_spec([
"/etc/qpid-dispatch/qdrouterd.conf"
]) | python | def setup(self):
options = ""
if self.get_option("port"):
options = (options + " -b " + gethostname() +
":%s" % (self.get_option("port")))
# gethostname() is due to DISPATCH-156
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key", "ssl-trustfile"]:
if self.get_option(option):
options = (options + " --%s=" % (option) +
self.get_option(option))
self.add_cmd_output([
"qdstat -a" + options, # Show Router Addresses
"qdstat -n" + options, # Show Router Nodes
"qdstat -c" + options, # Show Connections
"qdstat -m" + options # Show Broker Memory Stats
])
self.add_copy_spec([
"/etc/qpid-dispatch/qdrouterd.conf"
]) | [
"def",
"setup",
"(",
"self",
")",
":",
"options",
"=",
"\"\"",
"if",
"self",
".",
"get_option",
"(",
"\"port\"",
")",
":",
"options",
"=",
"(",
"options",
"+",
"\" -b \"",
"+",
"gethostname",
"(",
")",
"+",
"\":%s\"",
"%",
"(",
"self",
".",
"get_opti... | performs data collection for qpid dispatch router | [
"performs",
"data",
"collection",
"for",
"qpid",
"dispatch",
"router"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/qpid_dispatch.py#L30-L53 |
239,546 | sosreport/sos | sos/plugins/__init__.py | SoSPredicate.__str | def __str(self, quote=False, prefix="", suffix=""):
"""Return a string representation of this SoSPredicate with
optional prefix, suffix and value quoting.
"""
quotes = '"%s"'
pstr = "dry_run=%s, " % self._dry_run
kmods = self._kmods
kmods = [quotes % k for k in kmods] if quote else kmods
pstr += "kmods=[%s], " % (",".join(kmods))
services = self._services
services = [quotes % s for s in services] if quote else services
pstr += "services=[%s]" % (",".join(services))
return prefix + pstr + suffix | python | def __str(self, quote=False, prefix="", suffix=""):
quotes = '"%s"'
pstr = "dry_run=%s, " % self._dry_run
kmods = self._kmods
kmods = [quotes % k for k in kmods] if quote else kmods
pstr += "kmods=[%s], " % (",".join(kmods))
services = self._services
services = [quotes % s for s in services] if quote else services
pstr += "services=[%s]" % (",".join(services))
return prefix + pstr + suffix | [
"def",
"__str",
"(",
"self",
",",
"quote",
"=",
"False",
",",
"prefix",
"=",
"\"\"",
",",
"suffix",
"=",
"\"\"",
")",
":",
"quotes",
"=",
"'\"%s\"'",
"pstr",
"=",
"\"dry_run=%s, \"",
"%",
"self",
".",
"_dry_run",
"kmods",
"=",
"self",
".",
"_kmods",
... | Return a string representation of this SoSPredicate with
optional prefix, suffix and value quoting. | [
"Return",
"a",
"string",
"representation",
"of",
"this",
"SoSPredicate",
"with",
"optional",
"prefix",
"suffix",
"and",
"value",
"quoting",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L117-L132 |
239,547 | sosreport/sos | sos/plugins/__init__.py | Plugin.do_file_sub | def do_file_sub(self, srcpath, regexp, subst):
'''Apply a regexp substitution to a file archived by sosreport.
srcpath is the path in the archive where the file can be found. regexp
can be a regexp string or a compiled re object. subst is a string to
replace each occurance of regexp in the content of srcpath.
This function returns the number of replacements made.
'''
try:
path = self._get_dest_for_srcpath(srcpath)
self._log_debug("substituting scrpath '%s'" % srcpath)
self._log_debug("substituting '%s' for '%s' in '%s'"
% (subst, regexp, path))
if not path:
return 0
readable = self.archive.open_file(path)
content = readable.read()
if not isinstance(content, six.string_types):
content = content.decode('utf8', 'ignore')
result, replacements = re.subn(regexp, subst, content)
if replacements:
self.archive.add_string(result, srcpath)
else:
replacements = 0
except (OSError, IOError) as e:
# if trying to regexp a nonexisting file, dont log it as an
# error to stdout
if e.errno == errno.ENOENT:
msg = "file '%s' not collected, substitution skipped"
self._log_debug(msg % path)
else:
msg = "regex substitution failed for '%s' with: '%s'"
self._log_error(msg % (path, e))
replacements = 0
return replacements | python | def do_file_sub(self, srcpath, regexp, subst):
'''Apply a regexp substitution to a file archived by sosreport.
srcpath is the path in the archive where the file can be found. regexp
can be a regexp string or a compiled re object. subst is a string to
replace each occurance of regexp in the content of srcpath.
This function returns the number of replacements made.
'''
try:
path = self._get_dest_for_srcpath(srcpath)
self._log_debug("substituting scrpath '%s'" % srcpath)
self._log_debug("substituting '%s' for '%s' in '%s'"
% (subst, regexp, path))
if not path:
return 0
readable = self.archive.open_file(path)
content = readable.read()
if not isinstance(content, six.string_types):
content = content.decode('utf8', 'ignore')
result, replacements = re.subn(regexp, subst, content)
if replacements:
self.archive.add_string(result, srcpath)
else:
replacements = 0
except (OSError, IOError) as e:
# if trying to regexp a nonexisting file, dont log it as an
# error to stdout
if e.errno == errno.ENOENT:
msg = "file '%s' not collected, substitution skipped"
self._log_debug(msg % path)
else:
msg = "regex substitution failed for '%s' with: '%s'"
self._log_error(msg % (path, e))
replacements = 0
return replacements | [
"def",
"do_file_sub",
"(",
"self",
",",
"srcpath",
",",
"regexp",
",",
"subst",
")",
":",
"try",
":",
"path",
"=",
"self",
".",
"_get_dest_for_srcpath",
"(",
"srcpath",
")",
"self",
".",
"_log_debug",
"(",
"\"substituting scrpath '%s'\"",
"%",
"srcpath",
")"... | Apply a regexp substitution to a file archived by sosreport.
srcpath is the path in the archive where the file can be found. regexp
can be a regexp string or a compiled re object. subst is a string to
replace each occurance of regexp in the content of srcpath.
This function returns the number of replacements made. | [
"Apply",
"a",
"regexp",
"substitution",
"to",
"a",
"file",
"archived",
"by",
"sosreport",
".",
"srcpath",
"is",
"the",
"path",
"in",
"the",
"archive",
"where",
"the",
"file",
"can",
"be",
"found",
".",
"regexp",
"can",
"be",
"a",
"regexp",
"string",
"or"... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L482-L516 |
239,548 | sosreport/sos | sos/plugins/__init__.py | Plugin.do_path_regex_sub | def do_path_regex_sub(self, pathexp, regexp, subst):
'''Apply a regexp substituation to a set of files archived by
sos. The set of files to be substituted is generated by matching
collected file pathnames against pathexp which may be a regular
expression string or compiled re object. The portion of the file
to be replaced is specified via regexp and the replacement string
is passed in subst.'''
if not hasattr(pathexp, "match"):
pathexp = re.compile(pathexp)
match = pathexp.match
file_list = [f for f in self.copied_files if match(f['srcpath'])]
for file in file_list:
self.do_file_sub(file['srcpath'], regexp, subst) | python | def do_path_regex_sub(self, pathexp, regexp, subst):
'''Apply a regexp substituation to a set of files archived by
sos. The set of files to be substituted is generated by matching
collected file pathnames against pathexp which may be a regular
expression string or compiled re object. The portion of the file
to be replaced is specified via regexp and the replacement string
is passed in subst.'''
if not hasattr(pathexp, "match"):
pathexp = re.compile(pathexp)
match = pathexp.match
file_list = [f for f in self.copied_files if match(f['srcpath'])]
for file in file_list:
self.do_file_sub(file['srcpath'], regexp, subst) | [
"def",
"do_path_regex_sub",
"(",
"self",
",",
"pathexp",
",",
"regexp",
",",
"subst",
")",
":",
"if",
"not",
"hasattr",
"(",
"pathexp",
",",
"\"match\"",
")",
":",
"pathexp",
"=",
"re",
".",
"compile",
"(",
"pathexp",
")",
"match",
"=",
"pathexp",
".",... | Apply a regexp substituation to a set of files archived by
sos. The set of files to be substituted is generated by matching
collected file pathnames against pathexp which may be a regular
expression string or compiled re object. The portion of the file
to be replaced is specified via regexp and the replacement string
is passed in subst. | [
"Apply",
"a",
"regexp",
"substituation",
"to",
"a",
"set",
"of",
"files",
"archived",
"by",
"sos",
".",
"The",
"set",
"of",
"files",
"to",
"be",
"substituted",
"is",
"generated",
"by",
"matching",
"collected",
"file",
"pathnames",
"against",
"pathexp",
"whic... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L518-L530 |
239,549 | sosreport/sos | sos/plugins/__init__.py | Plugin._do_copy_path | def _do_copy_path(self, srcpath, dest=None):
'''Copy file or directory to the destination tree. If a directory, then
everything below it is recursively copied. A list of copied files are
saved for use later in preparing a report.
'''
if self._is_forbidden_path(srcpath):
self._log_debug("skipping forbidden path '%s'" % srcpath)
return ''
if not dest:
dest = srcpath
if self.use_sysroot():
dest = self.strip_sysroot(dest)
try:
st = os.lstat(srcpath)
except (OSError, IOError):
self._log_info("failed to stat '%s'" % srcpath)
return
if stat.S_ISLNK(st.st_mode):
self._copy_symlink(srcpath)
return
else:
if stat.S_ISDIR(st.st_mode) and os.access(srcpath, os.R_OK):
self._copy_dir(srcpath)
return
# handle special nodes (block, char, fifo, socket)
if not (stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)):
ntype = _node_type(st)
self._log_debug("creating %s node at archive:'%s'"
% (ntype, dest))
self._copy_node(srcpath, st)
return
# if we get here, it's definitely a regular file (not a symlink or dir)
self._log_debug("copying path '%s' to archive:'%s'" % (srcpath, dest))
# if not readable(srcpath)
if not st.st_mode & 0o444:
# FIXME: reflect permissions in archive
self.archive.add_string("", dest)
else:
self.archive.add_file(srcpath, dest)
self.copied_files.append({
'srcpath': srcpath,
'dstpath': dest,
'symlink': "no"
}) | python | def _do_copy_path(self, srcpath, dest=None):
'''Copy file or directory to the destination tree. If a directory, then
everything below it is recursively copied. A list of copied files are
saved for use later in preparing a report.
'''
if self._is_forbidden_path(srcpath):
self._log_debug("skipping forbidden path '%s'" % srcpath)
return ''
if not dest:
dest = srcpath
if self.use_sysroot():
dest = self.strip_sysroot(dest)
try:
st = os.lstat(srcpath)
except (OSError, IOError):
self._log_info("failed to stat '%s'" % srcpath)
return
if stat.S_ISLNK(st.st_mode):
self._copy_symlink(srcpath)
return
else:
if stat.S_ISDIR(st.st_mode) and os.access(srcpath, os.R_OK):
self._copy_dir(srcpath)
return
# handle special nodes (block, char, fifo, socket)
if not (stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)):
ntype = _node_type(st)
self._log_debug("creating %s node at archive:'%s'"
% (ntype, dest))
self._copy_node(srcpath, st)
return
# if we get here, it's definitely a regular file (not a symlink or dir)
self._log_debug("copying path '%s' to archive:'%s'" % (srcpath, dest))
# if not readable(srcpath)
if not st.st_mode & 0o444:
# FIXME: reflect permissions in archive
self.archive.add_string("", dest)
else:
self.archive.add_file(srcpath, dest)
self.copied_files.append({
'srcpath': srcpath,
'dstpath': dest,
'symlink': "no"
}) | [
"def",
"_do_copy_path",
"(",
"self",
",",
"srcpath",
",",
"dest",
"=",
"None",
")",
":",
"if",
"self",
".",
"_is_forbidden_path",
"(",
"srcpath",
")",
":",
"self",
".",
"_log_debug",
"(",
"\"skipping forbidden path '%s'\"",
"%",
"srcpath",
")",
"return",
"''... | Copy file or directory to the destination tree. If a directory, then
everything below it is recursively copied. A list of copied files are
saved for use later in preparing a report. | [
"Copy",
"file",
"or",
"directory",
"to",
"the",
"destination",
"tree",
".",
"If",
"a",
"directory",
"then",
"everything",
"below",
"it",
"is",
"recursively",
"copied",
".",
"A",
"list",
"of",
"copied",
"files",
"are",
"saved",
"for",
"use",
"later",
"in",
... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L627-L678 |
239,550 | sosreport/sos | sos/plugins/__init__.py | Plugin.set_option | def set_option(self, optionname, value):
"""Set the named option to value. Ensure the original type
of the option value is preserved.
"""
for name, parms in zip(self.opt_names, self.opt_parms):
if name == optionname:
# FIXME: ensure that the resulting type of the set option
# matches that of the default value. This prevents a string
# option from being coerced to int simply because it holds
# a numeric value (e.g. a password).
# See PR #1526 and Issue #1597
defaulttype = type(parms['enabled'])
if defaulttype != type(value) and defaulttype != type(None):
value = (defaulttype)(value)
parms['enabled'] = value
return True
else:
return False | python | def set_option(self, optionname, value):
for name, parms in zip(self.opt_names, self.opt_parms):
if name == optionname:
# FIXME: ensure that the resulting type of the set option
# matches that of the default value. This prevents a string
# option from being coerced to int simply because it holds
# a numeric value (e.g. a password).
# See PR #1526 and Issue #1597
defaulttype = type(parms['enabled'])
if defaulttype != type(value) and defaulttype != type(None):
value = (defaulttype)(value)
parms['enabled'] = value
return True
else:
return False | [
"def",
"set_option",
"(",
"self",
",",
"optionname",
",",
"value",
")",
":",
"for",
"name",
",",
"parms",
"in",
"zip",
"(",
"self",
".",
"opt_names",
",",
"self",
".",
"opt_parms",
")",
":",
"if",
"name",
"==",
"optionname",
":",
"# FIXME: ensure that th... | Set the named option to value. Ensure the original type
of the option value is preserved. | [
"Set",
"the",
"named",
"option",
"to",
"value",
".",
"Ensure",
"the",
"original",
"type",
"of",
"the",
"option",
"value",
"is",
"preserved",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L699-L716 |
239,551 | sosreport/sos | sos/plugins/__init__.py | Plugin.get_option | def get_option(self, optionname, default=0):
"""Returns the first value that matches 'optionname' in parameters
passed in via the command line or set via set_option or via the
global_plugin_options dictionary, in that order.
optionaname may be iterable, in which case the first option that
matches any of the option names is returned.
"""
global_options = ('verify', 'all_logs', 'log_size', 'plugin_timeout')
if optionname in global_options:
return getattr(self.commons['cmdlineopts'], optionname)
for name, parms in zip(self.opt_names, self.opt_parms):
if name == optionname:
val = parms['enabled']
if val is not None:
return val
return default | python | def get_option(self, optionname, default=0):
global_options = ('verify', 'all_logs', 'log_size', 'plugin_timeout')
if optionname in global_options:
return getattr(self.commons['cmdlineopts'], optionname)
for name, parms in zip(self.opt_names, self.opt_parms):
if name == optionname:
val = parms['enabled']
if val is not None:
return val
return default | [
"def",
"get_option",
"(",
"self",
",",
"optionname",
",",
"default",
"=",
"0",
")",
":",
"global_options",
"=",
"(",
"'verify'",
",",
"'all_logs'",
",",
"'log_size'",
",",
"'plugin_timeout'",
")",
"if",
"optionname",
"in",
"global_options",
":",
"return",
"g... | Returns the first value that matches 'optionname' in parameters
passed in via the command line or set via set_option or via the
global_plugin_options dictionary, in that order.
optionaname may be iterable, in which case the first option that
matches any of the option names is returned. | [
"Returns",
"the",
"first",
"value",
"that",
"matches",
"optionname",
"in",
"parameters",
"passed",
"in",
"via",
"the",
"command",
"line",
"or",
"set",
"via",
"set_option",
"or",
"via",
"the",
"global_plugin_options",
"dictionary",
"in",
"that",
"order",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L718-L738 |
239,552 | sosreport/sos | sos/plugins/__init__.py | Plugin.get_option_as_list | def get_option_as_list(self, optionname, delimiter=",", default=None):
'''Will try to return the option as a list separated by the
delimiter.
'''
option = self.get_option(optionname)
try:
opt_list = [opt.strip() for opt in option.split(delimiter)]
return list(filter(None, opt_list))
except Exception:
return default | python | def get_option_as_list(self, optionname, delimiter=",", default=None):
'''Will try to return the option as a list separated by the
delimiter.
'''
option = self.get_option(optionname)
try:
opt_list = [opt.strip() for opt in option.split(delimiter)]
return list(filter(None, opt_list))
except Exception:
return default | [
"def",
"get_option_as_list",
"(",
"self",
",",
"optionname",
",",
"delimiter",
"=",
"\",\"",
",",
"default",
"=",
"None",
")",
":",
"option",
"=",
"self",
".",
"get_option",
"(",
"optionname",
")",
"try",
":",
"opt_list",
"=",
"[",
"opt",
".",
"strip",
... | Will try to return the option as a list separated by the
delimiter. | [
"Will",
"try",
"to",
"return",
"the",
"option",
"as",
"a",
"list",
"separated",
"by",
"the",
"delimiter",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L740-L749 |
239,553 | sosreport/sos | sos/plugins/__init__.py | Plugin.add_copy_spec | def add_copy_spec(self, copyspecs, sizelimit=None, tailit=True, pred=None):
"""Add a file or glob but limit it to sizelimit megabytes. If fname is
a single file the file will be tailed to meet sizelimit. If the first
file in a glob is too large it will be tailed to meet the sizelimit.
"""
if not self.test_predicate(pred=pred):
self._log_info("skipped copy spec '%s' due to predicate (%s)" %
(copyspecs, self.get_predicate(pred=pred)))
return
if sizelimit is None:
sizelimit = self.get_option("log_size")
if self.get_option('all_logs'):
sizelimit = None
if sizelimit:
sizelimit *= 1024 * 1024 # in MB
if not copyspecs:
return False
if isinstance(copyspecs, six.string_types):
copyspecs = [copyspecs]
for copyspec in copyspecs:
if not (copyspec and len(copyspec)):
return False
if self.use_sysroot():
copyspec = self.join_sysroot(copyspec)
files = self._expand_copy_spec(copyspec)
if len(files) == 0:
continue
# Files hould be sorted in most-recently-modified order, so that
# we collect the newest data first before reaching the limit.
def getmtime(path):
try:
return os.path.getmtime(path)
except OSError:
return 0
files.sort(key=getmtime, reverse=True)
current_size = 0
limit_reached = False
_file = None
for _file in files:
if self._is_forbidden_path(_file):
self._log_debug("skipping forbidden path '%s'" % _file)
continue
try:
current_size += os.stat(_file)[stat.ST_SIZE]
except OSError:
self._log_info("failed to stat '%s'" % _file)
if sizelimit and current_size > sizelimit:
limit_reached = True
break
self._add_copy_paths([_file])
if limit_reached and tailit and not _file_is_compressed(_file):
file_name = _file
if file_name[0] == os.sep:
file_name = file_name.lstrip(os.sep)
strfile = file_name.replace(os.path.sep, ".") + ".tailed"
self.add_string_as_file(tail(_file, sizelimit), strfile)
rel_path = os.path.relpath('/', os.path.dirname(_file))
link_path = os.path.join(rel_path, 'sos_strings',
self.name(), strfile)
self.archive.add_link(link_path, _file) | python | def add_copy_spec(self, copyspecs, sizelimit=None, tailit=True, pred=None):
if not self.test_predicate(pred=pred):
self._log_info("skipped copy spec '%s' due to predicate (%s)" %
(copyspecs, self.get_predicate(pred=pred)))
return
if sizelimit is None:
sizelimit = self.get_option("log_size")
if self.get_option('all_logs'):
sizelimit = None
if sizelimit:
sizelimit *= 1024 * 1024 # in MB
if not copyspecs:
return False
if isinstance(copyspecs, six.string_types):
copyspecs = [copyspecs]
for copyspec in copyspecs:
if not (copyspec and len(copyspec)):
return False
if self.use_sysroot():
copyspec = self.join_sysroot(copyspec)
files = self._expand_copy_spec(copyspec)
if len(files) == 0:
continue
# Files hould be sorted in most-recently-modified order, so that
# we collect the newest data first before reaching the limit.
def getmtime(path):
try:
return os.path.getmtime(path)
except OSError:
return 0
files.sort(key=getmtime, reverse=True)
current_size = 0
limit_reached = False
_file = None
for _file in files:
if self._is_forbidden_path(_file):
self._log_debug("skipping forbidden path '%s'" % _file)
continue
try:
current_size += os.stat(_file)[stat.ST_SIZE]
except OSError:
self._log_info("failed to stat '%s'" % _file)
if sizelimit and current_size > sizelimit:
limit_reached = True
break
self._add_copy_paths([_file])
if limit_reached and tailit and not _file_is_compressed(_file):
file_name = _file
if file_name[0] == os.sep:
file_name = file_name.lstrip(os.sep)
strfile = file_name.replace(os.path.sep, ".") + ".tailed"
self.add_string_as_file(tail(_file, sizelimit), strfile)
rel_path = os.path.relpath('/', os.path.dirname(_file))
link_path = os.path.join(rel_path, 'sos_strings',
self.name(), strfile)
self.archive.add_link(link_path, _file) | [
"def",
"add_copy_spec",
"(",
"self",
",",
"copyspecs",
",",
"sizelimit",
"=",
"None",
",",
"tailit",
"=",
"True",
",",
"pred",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"test_predicate",
"(",
"pred",
"=",
"pred",
")",
":",
"self",
".",
"_log_i... | Add a file or glob but limit it to sizelimit megabytes. If fname is
a single file the file will be tailed to meet sizelimit. If the first
file in a glob is too large it will be tailed to meet the sizelimit. | [
"Add",
"a",
"file",
"or",
"glob",
"but",
"limit",
"it",
"to",
"sizelimit",
"megabytes",
".",
"If",
"fname",
"is",
"a",
"single",
"file",
"the",
"file",
"will",
"be",
"tailed",
"to",
"meet",
"sizelimit",
".",
"If",
"the",
"first",
"file",
"in",
"a",
"... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L754-L827 |
239,554 | sosreport/sos | sos/plugins/__init__.py | Plugin.call_ext_prog | def call_ext_prog(self, prog, timeout=300, stderr=True,
chroot=True, runat=None):
"""Execute a command independantly of the output gathering part of
sosreport.
"""
return self.get_command_output(prog, timeout=timeout, stderr=stderr,
chroot=chroot, runat=runat) | python | def call_ext_prog(self, prog, timeout=300, stderr=True,
chroot=True, runat=None):
return self.get_command_output(prog, timeout=timeout, stderr=stderr,
chroot=chroot, runat=runat) | [
"def",
"call_ext_prog",
"(",
"self",
",",
"prog",
",",
"timeout",
"=",
"300",
",",
"stderr",
"=",
"True",
",",
"chroot",
"=",
"True",
",",
"runat",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_command_output",
"(",
"prog",
",",
"timeout",
"=",
... | Execute a command independantly of the output gathering part of
sosreport. | [
"Execute",
"a",
"command",
"independantly",
"of",
"the",
"output",
"gathering",
"part",
"of",
"sosreport",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L862-L868 |
239,555 | sosreport/sos | sos/plugins/__init__.py | Plugin._add_cmd_output | def _add_cmd_output(self, cmd, suggest_filename=None,
root_symlink=None, timeout=300, stderr=True,
chroot=True, runat=None, env=None, binary=False,
sizelimit=None, pred=None):
"""Internal helper to add a single command to the collection list."""
cmdt = (
cmd, suggest_filename,
root_symlink, timeout, stderr,
chroot, runat, env, binary, sizelimit
)
_tuplefmt = ("('%s', '%s', '%s', %s, '%s', '%s', '%s', '%s', '%s', "
"'%s')")
_logstr = "packed command tuple: " + _tuplefmt
self._log_debug(_logstr % cmdt)
if self.test_predicate(cmd=True, pred=pred):
self.collect_cmds.append(cmdt)
self._log_info("added cmd output '%s'" % cmd)
else:
self._log_info("skipped cmd output '%s' due to predicate (%s)" %
(cmd, self.get_predicate(cmd=True, pred=pred))) | python | def _add_cmd_output(self, cmd, suggest_filename=None,
root_symlink=None, timeout=300, stderr=True,
chroot=True, runat=None, env=None, binary=False,
sizelimit=None, pred=None):
cmdt = (
cmd, suggest_filename,
root_symlink, timeout, stderr,
chroot, runat, env, binary, sizelimit
)
_tuplefmt = ("('%s', '%s', '%s', %s, '%s', '%s', '%s', '%s', '%s', "
"'%s')")
_logstr = "packed command tuple: " + _tuplefmt
self._log_debug(_logstr % cmdt)
if self.test_predicate(cmd=True, pred=pred):
self.collect_cmds.append(cmdt)
self._log_info("added cmd output '%s'" % cmd)
else:
self._log_info("skipped cmd output '%s' due to predicate (%s)" %
(cmd, self.get_predicate(cmd=True, pred=pred))) | [
"def",
"_add_cmd_output",
"(",
"self",
",",
"cmd",
",",
"suggest_filename",
"=",
"None",
",",
"root_symlink",
"=",
"None",
",",
"timeout",
"=",
"300",
",",
"stderr",
"=",
"True",
",",
"chroot",
"=",
"True",
",",
"runat",
"=",
"None",
",",
"env",
"=",
... | Internal helper to add a single command to the collection list. | [
"Internal",
"helper",
"to",
"add",
"a",
"single",
"command",
"to",
"the",
"collection",
"list",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L877-L896 |
239,556 | sosreport/sos | sos/plugins/__init__.py | Plugin.add_cmd_output | def add_cmd_output(self, cmds, suggest_filename=None,
root_symlink=None, timeout=300, stderr=True,
chroot=True, runat=None, env=None, binary=False,
sizelimit=None, pred=None):
"""Run a program or a list of programs and collect the output"""
if isinstance(cmds, six.string_types):
cmds = [cmds]
if len(cmds) > 1 and (suggest_filename or root_symlink):
self._log_warn("ambiguous filename or symlink for command list")
if sizelimit is None:
sizelimit = self.get_option("log_size")
for cmd in cmds:
self._add_cmd_output(cmd, suggest_filename=suggest_filename,
root_symlink=root_symlink, timeout=timeout,
stderr=stderr, chroot=chroot, runat=runat,
env=env, binary=binary, sizelimit=sizelimit,
pred=pred) | python | def add_cmd_output(self, cmds, suggest_filename=None,
root_symlink=None, timeout=300, stderr=True,
chroot=True, runat=None, env=None, binary=False,
sizelimit=None, pred=None):
if isinstance(cmds, six.string_types):
cmds = [cmds]
if len(cmds) > 1 and (suggest_filename or root_symlink):
self._log_warn("ambiguous filename or symlink for command list")
if sizelimit is None:
sizelimit = self.get_option("log_size")
for cmd in cmds:
self._add_cmd_output(cmd, suggest_filename=suggest_filename,
root_symlink=root_symlink, timeout=timeout,
stderr=stderr, chroot=chroot, runat=runat,
env=env, binary=binary, sizelimit=sizelimit,
pred=pred) | [
"def",
"add_cmd_output",
"(",
"self",
",",
"cmds",
",",
"suggest_filename",
"=",
"None",
",",
"root_symlink",
"=",
"None",
",",
"timeout",
"=",
"300",
",",
"stderr",
"=",
"True",
",",
"chroot",
"=",
"True",
",",
"runat",
"=",
"None",
",",
"env",
"=",
... | Run a program or a list of programs and collect the output | [
"Run",
"a",
"program",
"or",
"a",
"list",
"of",
"programs",
"and",
"collect",
"the",
"output"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L898-L914 |
239,557 | sosreport/sos | sos/plugins/__init__.py | Plugin.get_cmd_output_path | def get_cmd_output_path(self, name=None, make=True):
"""Return a path into which this module should store collected
command output
"""
cmd_output_path = os.path.join(self.archive.get_tmp_dir(),
'sos_commands', self.name())
if name:
cmd_output_path = os.path.join(cmd_output_path, name)
if make:
os.makedirs(cmd_output_path)
return cmd_output_path | python | def get_cmd_output_path(self, name=None, make=True):
cmd_output_path = os.path.join(self.archive.get_tmp_dir(),
'sos_commands', self.name())
if name:
cmd_output_path = os.path.join(cmd_output_path, name)
if make:
os.makedirs(cmd_output_path)
return cmd_output_path | [
"def",
"get_cmd_output_path",
"(",
"self",
",",
"name",
"=",
"None",
",",
"make",
"=",
"True",
")",
":",
"cmd_output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"archive",
".",
"get_tmp_dir",
"(",
")",
",",
"'sos_commands'",
",",
"sel... | Return a path into which this module should store collected
command output | [
"Return",
"a",
"path",
"into",
"which",
"this",
"module",
"should",
"store",
"collected",
"command",
"output"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L916-L927 |
239,558 | sosreport/sos | sos/plugins/__init__.py | Plugin._make_command_filename | def _make_command_filename(self, exe):
"""The internal function to build up a filename based on a command."""
outfn = os.path.join(self.commons['cmddir'], self.name(),
self._mangle_command(exe))
# check for collisions
if os.path.exists(outfn):
inc = 2
while True:
newfn = "%s_%d" % (outfn, inc)
if not os.path.exists(newfn):
outfn = newfn
break
inc += 1
return outfn | python | def _make_command_filename(self, exe):
outfn = os.path.join(self.commons['cmddir'], self.name(),
self._mangle_command(exe))
# check for collisions
if os.path.exists(outfn):
inc = 2
while True:
newfn = "%s_%d" % (outfn, inc)
if not os.path.exists(newfn):
outfn = newfn
break
inc += 1
return outfn | [
"def",
"_make_command_filename",
"(",
"self",
",",
"exe",
")",
":",
"outfn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"commons",
"[",
"'cmddir'",
"]",
",",
"self",
".",
"name",
"(",
")",
",",
"self",
".",
"_mangle_command",
"(",
"exe",
... | The internal function to build up a filename based on a command. | [
"The",
"internal",
"function",
"to",
"build",
"up",
"a",
"filename",
"based",
"on",
"a",
"command",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L940-L956 |
239,559 | sosreport/sos | sos/plugins/__init__.py | Plugin.add_string_as_file | def add_string_as_file(self, content, filename, pred=None):
"""Add a string to the archive as a file named `filename`"""
# Generate summary string for logging
summary = content.splitlines()[0] if content else ''
if not isinstance(summary, six.string_types):
summary = content.decode('utf8', 'ignore')
if not self.test_predicate(cmd=False, pred=pred):
self._log_info("skipped string ...'%s' due to predicate (%s)" %
(summary, self.get_predicate(pred=pred)))
return
self.copy_strings.append((content, filename))
self._log_debug("added string ...'%s' as '%s'" % (summary, filename)) | python | def add_string_as_file(self, content, filename, pred=None):
# Generate summary string for logging
summary = content.splitlines()[0] if content else ''
if not isinstance(summary, six.string_types):
summary = content.decode('utf8', 'ignore')
if not self.test_predicate(cmd=False, pred=pred):
self._log_info("skipped string ...'%s' due to predicate (%s)" %
(summary, self.get_predicate(pred=pred)))
return
self.copy_strings.append((content, filename))
self._log_debug("added string ...'%s' as '%s'" % (summary, filename)) | [
"def",
"add_string_as_file",
"(",
"self",
",",
"content",
",",
"filename",
",",
"pred",
"=",
"None",
")",
":",
"# Generate summary string for logging",
"summary",
"=",
"content",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"if",
"content",
"else",
"''",
"if"... | Add a string to the archive as a file named `filename` | [
"Add",
"a",
"string",
"to",
"the",
"archive",
"as",
"a",
"file",
"named",
"filename"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L958-L972 |
239,560 | sosreport/sos | sos/plugins/__init__.py | Plugin.add_journal | def add_journal(self, units=None, boot=None, since=None, until=None,
lines=None, allfields=False, output=None, timeout=None,
identifier=None, catalog=None, sizelimit=None, pred=None):
"""Collect journald logs from one of more units.
:param units: A string, or list of strings specifying the
systemd units for which journal entries will be
collected.
:param boot: A string selecting a boot index using the
journalctl syntax. The special values 'this' and
'last' are also accepted.
:param since: A string representation of the start time for
journal messages.
:param until: A string representation of the end time for
journal messages.
:param lines: The maximum number of lines to be collected.
:param allfields: A bool. Include all journal fields
regardless of size or non-printable
characters.
:param output: A journalctl output control string, for
example "verbose".
:param timeout: An optional timeout in seconds.
:param identifier: An optional message identifier.
:param catalog: Bool. If True, augment lines with descriptions
from the system catalog.
:param sizelimit: Limit to the size of output returned in MB.
Defaults to the value of --log-size.
"""
journal_cmd = "journalctl --no-pager "
unit_opt = " --unit %s"
boot_opt = " --boot %s"
since_opt = " --since %s"
until_opt = " --until %s"
lines_opt = " --lines %s"
output_opt = " --output %s"
identifier_opt = " --identifier %s"
catalog_opt = " --catalog"
journal_size = 100
all_logs = self.get_option("all_logs")
log_size = sizelimit or self.get_option("log_size")
log_size = max(log_size, journal_size) if not all_logs else 0
if isinstance(units, six.string_types):
units = [units]
if units:
for unit in units:
journal_cmd += unit_opt % unit
if identifier:
journal_cmd += identifier_opt % identifier
if catalog:
journal_cmd += catalog_opt
if allfields:
journal_cmd += " --all"
if boot:
if boot == "this":
boot = ""
if boot == "last":
boot = "-1"
journal_cmd += boot_opt % boot
if since:
journal_cmd += since_opt % since
if until:
journal_cmd += until_opt % until
if lines:
journal_cmd += lines_opt % lines
if output:
journal_cmd += output_opt % output
self._log_debug("collecting journal: %s" % journal_cmd)
self._add_cmd_output(journal_cmd, timeout=timeout,
sizelimit=log_size, pred=pred) | python | def add_journal(self, units=None, boot=None, since=None, until=None,
lines=None, allfields=False, output=None, timeout=None,
identifier=None, catalog=None, sizelimit=None, pred=None):
journal_cmd = "journalctl --no-pager "
unit_opt = " --unit %s"
boot_opt = " --boot %s"
since_opt = " --since %s"
until_opt = " --until %s"
lines_opt = " --lines %s"
output_opt = " --output %s"
identifier_opt = " --identifier %s"
catalog_opt = " --catalog"
journal_size = 100
all_logs = self.get_option("all_logs")
log_size = sizelimit or self.get_option("log_size")
log_size = max(log_size, journal_size) if not all_logs else 0
if isinstance(units, six.string_types):
units = [units]
if units:
for unit in units:
journal_cmd += unit_opt % unit
if identifier:
journal_cmd += identifier_opt % identifier
if catalog:
journal_cmd += catalog_opt
if allfields:
journal_cmd += " --all"
if boot:
if boot == "this":
boot = ""
if boot == "last":
boot = "-1"
journal_cmd += boot_opt % boot
if since:
journal_cmd += since_opt % since
if until:
journal_cmd += until_opt % until
if lines:
journal_cmd += lines_opt % lines
if output:
journal_cmd += output_opt % output
self._log_debug("collecting journal: %s" % journal_cmd)
self._add_cmd_output(journal_cmd, timeout=timeout,
sizelimit=log_size, pred=pred) | [
"def",
"add_journal",
"(",
"self",
",",
"units",
"=",
"None",
",",
"boot",
"=",
"None",
",",
"since",
"=",
"None",
",",
"until",
"=",
"None",
",",
"lines",
"=",
"None",
",",
"allfields",
"=",
"False",
",",
"output",
"=",
"None",
",",
"timeout",
"="... | Collect journald logs from one of more units.
:param units: A string, or list of strings specifying the
systemd units for which journal entries will be
collected.
:param boot: A string selecting a boot index using the
journalctl syntax. The special values 'this' and
'last' are also accepted.
:param since: A string representation of the start time for
journal messages.
:param until: A string representation of the end time for
journal messages.
:param lines: The maximum number of lines to be collected.
:param allfields: A bool. Include all journal fields
regardless of size or non-printable
characters.
:param output: A journalctl output control string, for
example "verbose".
:param timeout: An optional timeout in seconds.
:param identifier: An optional message identifier.
:param catalog: Bool. If True, augment lines with descriptions
from the system catalog.
:param sizelimit: Limit to the size of output returned in MB.
Defaults to the value of --log-size. | [
"Collect",
"journald",
"logs",
"from",
"one",
"of",
"more",
"units",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1046-L1133 |
239,561 | sosreport/sos | sos/plugins/__init__.py | Plugin.add_udev_info | def add_udev_info(self, device, attrs=False):
"""Collect udevadm info output for a given device
:param device: A string or list of strings of device names or sysfs
paths. E.G. either '/sys/class/scsi_host/host0' or
'/dev/sda' is valid.
:param attrs: If True, run udevadm with the --attribute-walk option.
"""
udev_cmd = 'udevadm info'
if attrs:
udev_cmd += ' -a'
if isinstance(device, six.string_types):
device = [device]
for dev in device:
self._log_debug("collecting udev info for: %s" % dev)
self._add_cmd_output('%s %s' % (udev_cmd, dev)) | python | def add_udev_info(self, device, attrs=False):
udev_cmd = 'udevadm info'
if attrs:
udev_cmd += ' -a'
if isinstance(device, six.string_types):
device = [device]
for dev in device:
self._log_debug("collecting udev info for: %s" % dev)
self._add_cmd_output('%s %s' % (udev_cmd, dev)) | [
"def",
"add_udev_info",
"(",
"self",
",",
"device",
",",
"attrs",
"=",
"False",
")",
":",
"udev_cmd",
"=",
"'udevadm info'",
"if",
"attrs",
":",
"udev_cmd",
"+=",
"' -a'",
"if",
"isinstance",
"(",
"device",
",",
"six",
".",
"string_types",
")",
":",
"dev... | Collect udevadm info output for a given device
:param device: A string or list of strings of device names or sysfs
paths. E.G. either '/sys/class/scsi_host/host0' or
'/dev/sda' is valid.
:param attrs: If True, run udevadm with the --attribute-walk option. | [
"Collect",
"udevadm",
"info",
"output",
"for",
"a",
"given",
"device"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1135-L1152 |
239,562 | sosreport/sos | sos/plugins/__init__.py | Plugin.collect | def collect(self):
"""Collect the data for a plugin."""
start = time()
self._collect_copy_specs()
self._collect_cmd_output()
self._collect_strings()
fields = (self.name(), time() - start)
self._log_debug("collected plugin '%s' in %s" % fields) | python | def collect(self):
start = time()
self._collect_copy_specs()
self._collect_cmd_output()
self._collect_strings()
fields = (self.name(), time() - start)
self._log_debug("collected plugin '%s' in %s" % fields) | [
"def",
"collect",
"(",
"self",
")",
":",
"start",
"=",
"time",
"(",
")",
"self",
".",
"_collect_copy_specs",
"(",
")",
"self",
".",
"_collect_cmd_output",
"(",
")",
"self",
".",
"_collect_strings",
"(",
")",
"fields",
"=",
"(",
"self",
".",
"name",
"("... | Collect the data for a plugin. | [
"Collect",
"the",
"data",
"for",
"a",
"plugin",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1202-L1209 |
239,563 | sosreport/sos | sos/plugins/__init__.py | Plugin.get_description | def get_description(self):
""" This function will return the description for the plugin"""
try:
if hasattr(self, '__doc__') and self.__doc__:
return self.__doc__.strip()
return super(self.__class__, self).__doc__.strip()
except Exception:
return "<no description available>" | python | def get_description(self):
try:
if hasattr(self, '__doc__') and self.__doc__:
return self.__doc__.strip()
return super(self.__class__, self).__doc__.strip()
except Exception:
return "<no description available>" | [
"def",
"get_description",
"(",
"self",
")",
":",
"try",
":",
"if",
"hasattr",
"(",
"self",
",",
"'__doc__'",
")",
"and",
"self",
".",
"__doc__",
":",
"return",
"self",
".",
"__doc__",
".",
"strip",
"(",
")",
"return",
"super",
"(",
"self",
".",
"__cl... | This function will return the description for the plugin | [
"This",
"function",
"will",
"return",
"the",
"description",
"for",
"the",
"plugin"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1211-L1218 |
239,564 | sosreport/sos | sos/plugins/__init__.py | Plugin.check_enabled | def check_enabled(self):
"""This method will be used to verify that a plugin should execute
given the condition of the underlying environment.
The default implementation will return True if none of class.files,
class.packages, nor class.commands is specified. If any of these is
specified the plugin will check for the existence of any of the
corresponding paths, packages or commands and return True if any
are present.
For SCLPlugin subclasses, it will check whether the plugin can be run
for any of installed SCLs. If so, it will store names of these SCLs
on the plugin class in addition to returning True.
For plugins with more complex enablement checks this method may be
overridden.
"""
# some files or packages have been specified for this package
if any([self.files, self.packages, self.commands, self.kernel_mods,
self.services]):
if isinstance(self.files, six.string_types):
self.files = [self.files]
if isinstance(self.packages, six.string_types):
self.packages = [self.packages]
if isinstance(self.commands, six.string_types):
self.commands = [self.commands]
if isinstance(self.kernel_mods, six.string_types):
self.kernel_mods = [self.kernel_mods]
if isinstance(self.services, six.string_types):
self.services = [self.services]
if isinstance(self, SCLPlugin):
# save SCLs that match files or packages
type(self)._scls_matched = []
for scl in self._get_scls():
files = [f % {"scl_name": scl} for f in self.files]
packages = [p % {"scl_name": scl} for p in self.packages]
commands = [c % {"scl_name": scl} for c in self.commands]
services = [s % {"scl_name": scl} for s in self.services]
if self._check_plugin_triggers(files,
packages,
commands,
services):
type(self)._scls_matched.append(scl)
return len(type(self)._scls_matched) > 0
return self._check_plugin_triggers(self.files,
self.packages,
self.commands,
self.services)
if isinstance(self, SCLPlugin):
# if files and packages weren't specified, we take all SCLs
type(self)._scls_matched = self._get_scls()
return True | python | def check_enabled(self):
# some files or packages have been specified for this package
if any([self.files, self.packages, self.commands, self.kernel_mods,
self.services]):
if isinstance(self.files, six.string_types):
self.files = [self.files]
if isinstance(self.packages, six.string_types):
self.packages = [self.packages]
if isinstance(self.commands, six.string_types):
self.commands = [self.commands]
if isinstance(self.kernel_mods, six.string_types):
self.kernel_mods = [self.kernel_mods]
if isinstance(self.services, six.string_types):
self.services = [self.services]
if isinstance(self, SCLPlugin):
# save SCLs that match files or packages
type(self)._scls_matched = []
for scl in self._get_scls():
files = [f % {"scl_name": scl} for f in self.files]
packages = [p % {"scl_name": scl} for p in self.packages]
commands = [c % {"scl_name": scl} for c in self.commands]
services = [s % {"scl_name": scl} for s in self.services]
if self._check_plugin_triggers(files,
packages,
commands,
services):
type(self)._scls_matched.append(scl)
return len(type(self)._scls_matched) > 0
return self._check_plugin_triggers(self.files,
self.packages,
self.commands,
self.services)
if isinstance(self, SCLPlugin):
# if files and packages weren't specified, we take all SCLs
type(self)._scls_matched = self._get_scls()
return True | [
"def",
"check_enabled",
"(",
"self",
")",
":",
"# some files or packages have been specified for this package",
"if",
"any",
"(",
"[",
"self",
".",
"files",
",",
"self",
".",
"packages",
",",
"self",
".",
"commands",
",",
"self",
".",
"kernel_mods",
",",
"self",... | This method will be used to verify that a plugin should execute
given the condition of the underlying environment.
The default implementation will return True if none of class.files,
class.packages, nor class.commands is specified. If any of these is
specified the plugin will check for the existence of any of the
corresponding paths, packages or commands and return True if any
are present.
For SCLPlugin subclasses, it will check whether the plugin can be run
for any of installed SCLs. If so, it will store names of these SCLs
on the plugin class in addition to returning True.
For plugins with more complex enablement checks this method may be
overridden. | [
"This",
"method",
"will",
"be",
"used",
"to",
"verify",
"that",
"a",
"plugin",
"should",
"execute",
"given",
"the",
"condition",
"of",
"the",
"underlying",
"environment",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1220-L1279 |
239,565 | sosreport/sos | sos/plugins/__init__.py | Plugin.report | def report(self):
""" Present all information that was gathered in an html file that
allows browsing the results.
"""
# make this prettier
html = u'<hr/><a name="%s"></a>\n' % self.name()
# Intro
html = html + "<h2> Plugin <em>" + self.name() + "</em></h2>\n"
# Files
if len(self.copied_files):
html = html + "<p>Files copied:<br><ul>\n"
for afile in self.copied_files:
html = html + '<li><a href="%s">%s</a>' % \
(u'..' + _to_u(afile['dstpath']), _to_u(afile['srcpath']))
if afile['symlink'] == "yes":
html = html + " (symlink to %s)" % _to_u(afile['pointsto'])
html = html + '</li>\n'
html = html + "</ul></p>\n"
# Command Output
if len(self.executed_commands):
html = html + "<p>Commands Executed:<br><ul>\n"
# convert file name to relative path from our root
# don't use relpath - these are HTML paths not OS paths.
for cmd in self.executed_commands:
if cmd["file"] and len(cmd["file"]):
cmd_rel_path = u"../" + _to_u(self.commons['cmddir']) \
+ "/" + _to_u(cmd['file'])
html = html + '<li><a href="%s">%s</a></li>\n' % \
(cmd_rel_path, _to_u(cmd['exe']))
else:
html = html + '<li>%s</li>\n' % (_to_u(cmd['exe']))
html = html + "</ul></p>\n"
# Alerts
if len(self.alerts):
html = html + "<p>Alerts:<br><ul>\n"
for alert in self.alerts:
html = html + '<li>%s</li>\n' % _to_u(alert)
html = html + "</ul></p>\n"
# Custom Text
if self.custom_text != "":
html = html + "<p>Additional Information:<br>\n"
html = html + _to_u(self.custom_text) + "</p>\n"
if six.PY2:
return html.encode('utf8')
else:
return html | python | def report(self):
# make this prettier
html = u'<hr/><a name="%s"></a>\n' % self.name()
# Intro
html = html + "<h2> Plugin <em>" + self.name() + "</em></h2>\n"
# Files
if len(self.copied_files):
html = html + "<p>Files copied:<br><ul>\n"
for afile in self.copied_files:
html = html + '<li><a href="%s">%s</a>' % \
(u'..' + _to_u(afile['dstpath']), _to_u(afile['srcpath']))
if afile['symlink'] == "yes":
html = html + " (symlink to %s)" % _to_u(afile['pointsto'])
html = html + '</li>\n'
html = html + "</ul></p>\n"
# Command Output
if len(self.executed_commands):
html = html + "<p>Commands Executed:<br><ul>\n"
# convert file name to relative path from our root
# don't use relpath - these are HTML paths not OS paths.
for cmd in self.executed_commands:
if cmd["file"] and len(cmd["file"]):
cmd_rel_path = u"../" + _to_u(self.commons['cmddir']) \
+ "/" + _to_u(cmd['file'])
html = html + '<li><a href="%s">%s</a></li>\n' % \
(cmd_rel_path, _to_u(cmd['exe']))
else:
html = html + '<li>%s</li>\n' % (_to_u(cmd['exe']))
html = html + "</ul></p>\n"
# Alerts
if len(self.alerts):
html = html + "<p>Alerts:<br><ul>\n"
for alert in self.alerts:
html = html + '<li>%s</li>\n' % _to_u(alert)
html = html + "</ul></p>\n"
# Custom Text
if self.custom_text != "":
html = html + "<p>Additional Information:<br>\n"
html = html + _to_u(self.custom_text) + "</p>\n"
if six.PY2:
return html.encode('utf8')
else:
return html | [
"def",
"report",
"(",
"self",
")",
":",
"# make this prettier",
"html",
"=",
"u'<hr/><a name=\"%s\"></a>\\n'",
"%",
"self",
".",
"name",
"(",
")",
"# Intro",
"html",
"=",
"html",
"+",
"\"<h2> Plugin <em>\"",
"+",
"self",
".",
"name",
"(",
")",
"+",
"\"</em><... | Present all information that was gathered in an html file that
allows browsing the results. | [
"Present",
"all",
"information",
"that",
"was",
"gathered",
"in",
"an",
"html",
"file",
"that",
"allows",
"browsing",
"the",
"results",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1323-L1374 |
239,566 | sosreport/sos | sos/plugins/__init__.py | Plugin.get_process_pids | def get_process_pids(self, process):
"""Returns PIDs of all processes with process name.
If the process doesn't exist, returns an empty list"""
pids = []
cmd_line_glob = "/proc/[0-9]*/cmdline"
cmd_line_paths = glob.glob(cmd_line_glob)
for path in cmd_line_paths:
try:
with open(path, 'r') as f:
cmd_line = f.read().strip()
if process in cmd_line:
pids.append(path.split("/")[2])
except IOError as e:
continue
return pids | python | def get_process_pids(self, process):
pids = []
cmd_line_glob = "/proc/[0-9]*/cmdline"
cmd_line_paths = glob.glob(cmd_line_glob)
for path in cmd_line_paths:
try:
with open(path, 'r') as f:
cmd_line = f.read().strip()
if process in cmd_line:
pids.append(path.split("/")[2])
except IOError as e:
continue
return pids | [
"def",
"get_process_pids",
"(",
"self",
",",
"process",
")",
":",
"pids",
"=",
"[",
"]",
"cmd_line_glob",
"=",
"\"/proc/[0-9]*/cmdline\"",
"cmd_line_paths",
"=",
"glob",
".",
"glob",
"(",
"cmd_line_glob",
")",
"for",
"path",
"in",
"cmd_line_paths",
":",
"try",... | Returns PIDs of all processes with process name.
If the process doesn't exist, returns an empty list | [
"Returns",
"PIDs",
"of",
"all",
"processes",
"with",
"process",
"name",
".",
"If",
"the",
"process",
"doesn",
"t",
"exist",
"returns",
"an",
"empty",
"list"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1392-L1406 |
239,567 | sosreport/sos | sos/plugins/__init__.py | SCLPlugin.convert_cmd_scl | def convert_cmd_scl(self, scl, cmd):
"""wrapping command in "scl enable" call and adds proper PATH
"""
# load default SCL prefix to PATH
prefix = self.policy.get_default_scl_prefix()
# read prefix from /etc/scl/prefixes/${scl} and strip trailing '\n'
try:
prefix = open('/etc/scl/prefixes/%s' % scl, 'r').read()\
.rstrip('\n')
except Exception as e:
self._log_error("Failed to find prefix for SCL %s, using %s"
% (scl, prefix))
# expand PATH by equivalent prefixes under the SCL tree
path = os.environ["PATH"]
for p in path.split(':'):
path = '%s/%s%s:%s' % (prefix, scl, p, path)
scl_cmd = "scl enable %s \"PATH=%s %s\"" % (scl, path, cmd)
return scl_cmd | python | def convert_cmd_scl(self, scl, cmd):
# load default SCL prefix to PATH
prefix = self.policy.get_default_scl_prefix()
# read prefix from /etc/scl/prefixes/${scl} and strip trailing '\n'
try:
prefix = open('/etc/scl/prefixes/%s' % scl, 'r').read()\
.rstrip('\n')
except Exception as e:
self._log_error("Failed to find prefix for SCL %s, using %s"
% (scl, prefix))
# expand PATH by equivalent prefixes under the SCL tree
path = os.environ["PATH"]
for p in path.split(':'):
path = '%s/%s%s:%s' % (prefix, scl, p, path)
scl_cmd = "scl enable %s \"PATH=%s %s\"" % (scl, path, cmd)
return scl_cmd | [
"def",
"convert_cmd_scl",
"(",
"self",
",",
"scl",
",",
"cmd",
")",
":",
"# load default SCL prefix to PATH",
"prefix",
"=",
"self",
".",
"policy",
".",
"get_default_scl_prefix",
"(",
")",
"# read prefix from /etc/scl/prefixes/${scl} and strip trailing '\\n'",
"try",
":",... | wrapping command in "scl enable" call and adds proper PATH | [
"wrapping",
"command",
"in",
"scl",
"enable",
"call",
"and",
"adds",
"proper",
"PATH"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1448-L1467 |
239,568 | sosreport/sos | sos/plugins/__init__.py | SCLPlugin.add_cmd_output_scl | def add_cmd_output_scl(self, scl, cmds, **kwargs):
"""Same as add_cmd_output, except that it wraps command in
"scl enable" call and sets proper PATH.
"""
if isinstance(cmds, six.string_types):
cmds = [cmds]
scl_cmds = []
for cmd in cmds:
scl_cmds.append(self.convert_cmd_scl(scl, cmd))
self.add_cmd_output(scl_cmds, **kwargs) | python | def add_cmd_output_scl(self, scl, cmds, **kwargs):
if isinstance(cmds, six.string_types):
cmds = [cmds]
scl_cmds = []
for cmd in cmds:
scl_cmds.append(self.convert_cmd_scl(scl, cmd))
self.add_cmd_output(scl_cmds, **kwargs) | [
"def",
"add_cmd_output_scl",
"(",
"self",
",",
"scl",
",",
"cmds",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"cmds",
",",
"six",
".",
"string_types",
")",
":",
"cmds",
"=",
"[",
"cmds",
"]",
"scl_cmds",
"=",
"[",
"]",
"for",
"cmd"... | Same as add_cmd_output, except that it wraps command in
"scl enable" call and sets proper PATH. | [
"Same",
"as",
"add_cmd_output",
"except",
"that",
"it",
"wraps",
"command",
"in",
"scl",
"enable",
"call",
"and",
"sets",
"proper",
"PATH",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1469-L1478 |
239,569 | sosreport/sos | sos/plugins/__init__.py | SCLPlugin.add_copy_spec_scl | def add_copy_spec_scl(self, scl, copyspecs):
"""Same as add_copy_spec, except that it prepends path to SCL root
to "copyspecs".
"""
if isinstance(copyspecs, six.string_types):
copyspecs = [copyspecs]
scl_copyspecs = []
for copyspec in copyspecs:
scl_copyspecs.append(self.convert_copyspec_scl(scl, copyspec))
self.add_copy_spec(scl_copyspecs) | python | def add_copy_spec_scl(self, scl, copyspecs):
if isinstance(copyspecs, six.string_types):
copyspecs = [copyspecs]
scl_copyspecs = []
for copyspec in copyspecs:
scl_copyspecs.append(self.convert_copyspec_scl(scl, copyspec))
self.add_copy_spec(scl_copyspecs) | [
"def",
"add_copy_spec_scl",
"(",
"self",
",",
"scl",
",",
"copyspecs",
")",
":",
"if",
"isinstance",
"(",
"copyspecs",
",",
"six",
".",
"string_types",
")",
":",
"copyspecs",
"=",
"[",
"copyspecs",
"]",
"scl_copyspecs",
"=",
"[",
"]",
"for",
"copyspec",
... | Same as add_copy_spec, except that it prepends path to SCL root
to "copyspecs". | [
"Same",
"as",
"add_copy_spec",
"except",
"that",
"it",
"prepends",
"path",
"to",
"SCL",
"root",
"to",
"copyspecs",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1492-L1501 |
239,570 | sosreport/sos | sos/plugins/__init__.py | SCLPlugin.add_copy_spec_limit_scl | def add_copy_spec_limit_scl(self, scl, copyspec, **kwargs):
"""Same as add_copy_spec_limit, except that it prepends path to SCL
root to "copyspec".
"""
self.add_copy_spec_limit(
self.convert_copyspec_scl(scl, copyspec),
**kwargs
) | python | def add_copy_spec_limit_scl(self, scl, copyspec, **kwargs):
self.add_copy_spec_limit(
self.convert_copyspec_scl(scl, copyspec),
**kwargs
) | [
"def",
"add_copy_spec_limit_scl",
"(",
"self",
",",
"scl",
",",
"copyspec",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"add_copy_spec_limit",
"(",
"self",
".",
"convert_copyspec_scl",
"(",
"scl",
",",
"copyspec",
")",
",",
"*",
"*",
"kwargs",
")"
] | Same as add_copy_spec_limit, except that it prepends path to SCL
root to "copyspec". | [
"Same",
"as",
"add_copy_spec_limit",
"except",
"that",
"it",
"prepends",
"path",
"to",
"SCL",
"root",
"to",
"copyspec",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1503-L1510 |
239,571 | sosreport/sos | sos/plugins/veritas.py | Veritas.setup | def setup(self):
""" interface with vrtsexplorer to capture veritas related data """
r = self.call_ext_prog(self.get_option("script"))
if r['status'] == 0:
tarfile = ""
for line in r['output']:
line = line.strip()
tarfile = self.do_regex_find_all(r"ftp (.*tar.gz)", line)
if len(tarfile) == 1:
self.add_copy_spec(tarfile[0]) | python | def setup(self):
r = self.call_ext_prog(self.get_option("script"))
if r['status'] == 0:
tarfile = ""
for line in r['output']:
line = line.strip()
tarfile = self.do_regex_find_all(r"ftp (.*tar.gz)", line)
if len(tarfile) == 1:
self.add_copy_spec(tarfile[0]) | [
"def",
"setup",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"call_ext_prog",
"(",
"self",
".",
"get_option",
"(",
"\"script\"",
")",
")",
"if",
"r",
"[",
"'status'",
"]",
"==",
"0",
":",
"tarfile",
"=",
"\"\"",
"for",
"line",
"in",
"r",
"[",
"'... | interface with vrtsexplorer to capture veritas related data | [
"interface",
"with",
"vrtsexplorer",
"to",
"capture",
"veritas",
"related",
"data"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/veritas.py#L28-L37 |
239,572 | sosreport/sos | sos/plugins/openstack_ansible.py | OpenStackAnsible.postproc | def postproc(self):
"""Remove sensitive keys and passwords from YAML files."""
secrets_files = [
"/etc/openstack_deploy/user_secrets.yml",
"/etc/rpc_deploy/user_secrets.yml"
]
regexp = r"(?m)^\s*#*([\w_]*:\s*).*"
for secrets_file in secrets_files:
self.do_path_regex_sub(
secrets_file,
regexp,
r"\1*********") | python | def postproc(self):
secrets_files = [
"/etc/openstack_deploy/user_secrets.yml",
"/etc/rpc_deploy/user_secrets.yml"
]
regexp = r"(?m)^\s*#*([\w_]*:\s*).*"
for secrets_file in secrets_files:
self.do_path_regex_sub(
secrets_file,
regexp,
r"\1*********") | [
"def",
"postproc",
"(",
"self",
")",
":",
"secrets_files",
"=",
"[",
"\"/etc/openstack_deploy/user_secrets.yml\"",
",",
"\"/etc/rpc_deploy/user_secrets.yml\"",
"]",
"regexp",
"=",
"r\"(?m)^\\s*#*([\\w_]*:\\s*).*\"",
"for",
"secrets_file",
"in",
"secrets_files",
":",
"self",... | Remove sensitive keys and passwords from YAML files. | [
"Remove",
"sensitive",
"keys",
"and",
"passwords",
"from",
"YAML",
"files",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/openstack_ansible.py#L30-L41 |
239,573 | timothycrosley/isort | isort/main.py | ISortCommand.finalize_options | def finalize_options(self) -> None:
"Get options from config files."
self.arguments = {} # type: Dict[str, Any]
computed_settings = from_path(os.getcwd())
for key, value in computed_settings.items():
self.arguments[key] = value | python | def finalize_options(self) -> None:
"Get options from config files."
self.arguments = {} # type: Dict[str, Any]
computed_settings = from_path(os.getcwd())
for key, value in computed_settings.items():
self.arguments[key] = value | [
"def",
"finalize_options",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"arguments",
"=",
"{",
"}",
"# type: Dict[str, Any]",
"computed_settings",
"=",
"from_path",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"for",
"key",
",",
"value",
"in",
"computed_s... | Get options from config files. | [
"Get",
"options",
"from",
"config",
"files",
"."
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/main.py#L131-L136 |
239,574 | timothycrosley/isort | isort/main.py | ISortCommand.distribution_files | def distribution_files(self) -> Iterator[str]:
"""Find distribution packages."""
# This is verbatim from flake8
if self.distribution.packages:
package_dirs = self.distribution.package_dir or {}
for package in self.distribution.packages:
pkg_dir = package
if package in package_dirs:
pkg_dir = package_dirs[package]
elif '' in package_dirs:
pkg_dir = package_dirs[''] + os.path.sep + pkg_dir
yield pkg_dir.replace('.', os.path.sep)
if self.distribution.py_modules:
for filename in self.distribution.py_modules:
yield "%s.py" % filename
# Don't miss the setup.py file itself
yield "setup.py" | python | def distribution_files(self) -> Iterator[str]:
# This is verbatim from flake8
if self.distribution.packages:
package_dirs = self.distribution.package_dir or {}
for package in self.distribution.packages:
pkg_dir = package
if package in package_dirs:
pkg_dir = package_dirs[package]
elif '' in package_dirs:
pkg_dir = package_dirs[''] + os.path.sep + pkg_dir
yield pkg_dir.replace('.', os.path.sep)
if self.distribution.py_modules:
for filename in self.distribution.py_modules:
yield "%s.py" % filename
# Don't miss the setup.py file itself
yield "setup.py" | [
"def",
"distribution_files",
"(",
"self",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"# This is verbatim from flake8",
"if",
"self",
".",
"distribution",
".",
"packages",
":",
"package_dirs",
"=",
"self",
".",
"distribution",
".",
"package_dir",
"or",
"{",
"... | Find distribution packages. | [
"Find",
"distribution",
"packages",
"."
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/main.py#L138-L155 |
239,575 | timothycrosley/isort | isort/utils.py | chdir | def chdir(path: str) -> Iterator[None]:
"""Context manager for changing dir and restoring previous workdir after exit.
"""
curdir = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(curdir) | python | def chdir(path: str) -> Iterator[None]:
curdir = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(curdir) | [
"def",
"chdir",
"(",
"path",
":",
"str",
")",
"->",
"Iterator",
"[",
"None",
"]",
":",
"curdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"path",
")",
"try",
":",
"yield",
"finally",
":",
"os",
".",
"chdir",
"(",
"curdir",
"... | Context manager for changing dir and restoring previous workdir after exit. | [
"Context",
"manager",
"for",
"changing",
"dir",
"and",
"restoring",
"previous",
"workdir",
"after",
"exit",
"."
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/utils.py#L23-L31 |
239,576 | timothycrosley/isort | isort/utils.py | union | def union(a: Iterable[Any], b: Iterable[Any]) -> List[Any]:
""" Return a list of items that are in `a` or `b`
"""
u = [] # type: List[Any]
for item in a:
if item not in u:
u.append(item)
for item in b:
if item not in u:
u.append(item)
return u | python | def union(a: Iterable[Any], b: Iterable[Any]) -> List[Any]:
u = [] # type: List[Any]
for item in a:
if item not in u:
u.append(item)
for item in b:
if item not in u:
u.append(item)
return u | [
"def",
"union",
"(",
"a",
":",
"Iterable",
"[",
"Any",
"]",
",",
"b",
":",
"Iterable",
"[",
"Any",
"]",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"u",
"=",
"[",
"]",
"# type: List[Any]",
"for",
"item",
"in",
"a",
":",
"if",
"item",
"not",
"in",
... | Return a list of items that are in `a` or `b` | [
"Return",
"a",
"list",
"of",
"items",
"that",
"are",
"in",
"a",
"or",
"b"
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/utils.py#L34-L44 |
239,577 | timothycrosley/isort | isort/utils.py | difference | def difference(a: Iterable[Any], b: Container[Any]) -> List[Any]:
""" Return a list of items from `a` that are not in `b`.
"""
d = []
for item in a:
if item not in b:
d.append(item)
return d | python | def difference(a: Iterable[Any], b: Container[Any]) -> List[Any]:
d = []
for item in a:
if item not in b:
d.append(item)
return d | [
"def",
"difference",
"(",
"a",
":",
"Iterable",
"[",
"Any",
"]",
",",
"b",
":",
"Container",
"[",
"Any",
"]",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"d",
"=",
"[",
"]",
"for",
"item",
"in",
"a",
":",
"if",
"item",
"not",
"in",
"b",
":",
"... | Return a list of items from `a` that are not in `b`. | [
"Return",
"a",
"list",
"of",
"items",
"from",
"a",
"that",
"are",
"not",
"in",
"b",
"."
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/utils.py#L47-L54 |
239,578 | timothycrosley/isort | kate_plugin/isort_plugin.py | sort_kate_imports | def sort_kate_imports(add_imports=(), remove_imports=()):
"""Sorts imports within Kate while maintaining cursor position and selection, even if length of file changes."""
document = kate.activeDocument()
view = document.activeView()
position = view.cursorPosition()
selection = view.selectionRange()
sorter = SortImports(file_contents=document.text(), add_imports=add_imports, remove_imports=remove_imports,
settings_path=os.path.dirname(os.path.abspath(str(document.url().path()))))
document.setText(sorter.output)
position.setLine(position.line() + sorter.length_change)
if selection:
start = selection.start()
start.setLine(start.line() + sorter.length_change)
end = selection.end()
end.setLine(end.line() + sorter.length_change)
selection.setRange(start, end)
view.setSelection(selection)
view.setCursorPosition(position) | python | def sort_kate_imports(add_imports=(), remove_imports=()):
document = kate.activeDocument()
view = document.activeView()
position = view.cursorPosition()
selection = view.selectionRange()
sorter = SortImports(file_contents=document.text(), add_imports=add_imports, remove_imports=remove_imports,
settings_path=os.path.dirname(os.path.abspath(str(document.url().path()))))
document.setText(sorter.output)
position.setLine(position.line() + sorter.length_change)
if selection:
start = selection.start()
start.setLine(start.line() + sorter.length_change)
end = selection.end()
end.setLine(end.line() + sorter.length_change)
selection.setRange(start, end)
view.setSelection(selection)
view.setCursorPosition(position) | [
"def",
"sort_kate_imports",
"(",
"add_imports",
"=",
"(",
")",
",",
"remove_imports",
"=",
"(",
")",
")",
":",
"document",
"=",
"kate",
".",
"activeDocument",
"(",
")",
"view",
"=",
"document",
".",
"activeView",
"(",
")",
"position",
"=",
"view",
".",
... | Sorts imports within Kate while maintaining cursor position and selection, even if length of file changes. | [
"Sorts",
"imports",
"within",
"Kate",
"while",
"maintaining",
"cursor",
"position",
"and",
"selection",
"even",
"if",
"length",
"of",
"file",
"changes",
"."
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/kate_plugin/isort_plugin.py#L37-L54 |
239,579 | timothycrosley/isort | isort/isort.py | _SortImports._get_line | def _get_line(self) -> str:
"""Returns the current line from the file while incrementing the index."""
line = self.in_lines[self.index]
self.index += 1
return line | python | def _get_line(self) -> str:
line = self.in_lines[self.index]
self.index += 1
return line | [
"def",
"_get_line",
"(",
"self",
")",
"->",
"str",
":",
"line",
"=",
"self",
".",
"in_lines",
"[",
"self",
".",
"index",
"]",
"self",
".",
"index",
"+=",
"1",
"return",
"line"
] | Returns the current line from the file while incrementing the index. | [
"Returns",
"the",
"current",
"line",
"from",
"the",
"file",
"while",
"incrementing",
"the",
"index",
"."
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/isort.py#L139-L143 |
239,580 | timothycrosley/isort | isort/isort.py | _SortImports._add_comments | def _add_comments(
self,
comments: Optional[Sequence[str]],
original_string: str = ""
) -> str:
"""
Returns a string with comments added if ignore_comments is not set.
"""
if self.config['ignore_comments']:
return self._strip_comments(original_string)[0]
if not comments:
return original_string
else:
return "{0}{1} {2}".format(self._strip_comments(original_string)[0],
self.config['comment_prefix'],
"; ".join(comments)) | python | def _add_comments(
self,
comments: Optional[Sequence[str]],
original_string: str = ""
) -> str:
if self.config['ignore_comments']:
return self._strip_comments(original_string)[0]
if not comments:
return original_string
else:
return "{0}{1} {2}".format(self._strip_comments(original_string)[0],
self.config['comment_prefix'],
"; ".join(comments)) | [
"def",
"_add_comments",
"(",
"self",
",",
"comments",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
",",
"original_string",
":",
"str",
"=",
"\"\"",
")",
"->",
"str",
":",
"if",
"self",
".",
"config",
"[",
"'ignore_comments'",
"]",
":",
"retu... | Returns a string with comments added if ignore_comments is not set. | [
"Returns",
"a",
"string",
"with",
"comments",
"added",
"if",
"ignore_comments",
"is",
"not",
"set",
"."
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/isort.py#L194-L210 |
239,581 | timothycrosley/isort | isort/isort.py | _SortImports._wrap | def _wrap(self, line: str) -> str:
"""
Returns an import wrapped to the specified line-length, if possible.
"""
wrap_mode = self.config['multi_line_output']
if len(line) > self.config['line_length'] and wrap_mode != WrapModes.NOQA:
line_without_comment = line
comment = None
if '#' in line:
line_without_comment, comment = line.split('#', 1)
for splitter in ("import ", ".", "as "):
exp = r"\b" + re.escape(splitter) + r"\b"
if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(splitter):
line_parts = re.split(exp, line_without_comment)
if comment:
line_parts[-1] = '{0}#{1}'.format(line_parts[-1], comment)
next_line = []
while (len(line) + 2) > (self.config['wrap_length'] or self.config['line_length']) and line_parts:
next_line.append(line_parts.pop())
line = splitter.join(line_parts)
if not line:
line = next_line.pop()
cont_line = self._wrap(self.config['indent'] + splitter.join(next_line).lstrip())
if self.config['use_parentheses']:
output = "{0}{1}({2}{3}{4}{5})".format(
line, splitter, self.line_separator, cont_line,
"," if self.config['include_trailing_comma'] else "",
self.line_separator if wrap_mode in {WrapModes.VERTICAL_HANGING_INDENT,
WrapModes.VERTICAL_GRID_GROUPED}
else "")
lines = output.split(self.line_separator)
if self.config['comment_prefix'] in lines[-1] and lines[-1].endswith(')'):
line, comment = lines[-1].split(self.config['comment_prefix'], 1)
lines[-1] = line + ')' + self.config['comment_prefix'] + comment[:-1]
return self.line_separator.join(lines)
return "{0}{1}\\{2}{3}".format(line, splitter, self.line_separator, cont_line)
elif len(line) > self.config['line_length'] and wrap_mode == settings.WrapModes.NOQA:
if "# NOQA" not in line:
return "{0}{1} NOQA".format(line, self.config['comment_prefix'])
return line | python | def _wrap(self, line: str) -> str:
wrap_mode = self.config['multi_line_output']
if len(line) > self.config['line_length'] and wrap_mode != WrapModes.NOQA:
line_without_comment = line
comment = None
if '#' in line:
line_without_comment, comment = line.split('#', 1)
for splitter in ("import ", ".", "as "):
exp = r"\b" + re.escape(splitter) + r"\b"
if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(splitter):
line_parts = re.split(exp, line_without_comment)
if comment:
line_parts[-1] = '{0}#{1}'.format(line_parts[-1], comment)
next_line = []
while (len(line) + 2) > (self.config['wrap_length'] or self.config['line_length']) and line_parts:
next_line.append(line_parts.pop())
line = splitter.join(line_parts)
if not line:
line = next_line.pop()
cont_line = self._wrap(self.config['indent'] + splitter.join(next_line).lstrip())
if self.config['use_parentheses']:
output = "{0}{1}({2}{3}{4}{5})".format(
line, splitter, self.line_separator, cont_line,
"," if self.config['include_trailing_comma'] else "",
self.line_separator if wrap_mode in {WrapModes.VERTICAL_HANGING_INDENT,
WrapModes.VERTICAL_GRID_GROUPED}
else "")
lines = output.split(self.line_separator)
if self.config['comment_prefix'] in lines[-1] and lines[-1].endswith(')'):
line, comment = lines[-1].split(self.config['comment_prefix'], 1)
lines[-1] = line + ')' + self.config['comment_prefix'] + comment[:-1]
return self.line_separator.join(lines)
return "{0}{1}\\{2}{3}".format(line, splitter, self.line_separator, cont_line)
elif len(line) > self.config['line_length'] and wrap_mode == settings.WrapModes.NOQA:
if "# NOQA" not in line:
return "{0}{1} NOQA".format(line, self.config['comment_prefix'])
return line | [
"def",
"_wrap",
"(",
"self",
",",
"line",
":",
"str",
")",
"->",
"str",
":",
"wrap_mode",
"=",
"self",
".",
"config",
"[",
"'multi_line_output'",
"]",
"if",
"len",
"(",
"line",
")",
">",
"self",
".",
"config",
"[",
"'line_length'",
"]",
"and",
"wrap_... | Returns an import wrapped to the specified line-length, if possible. | [
"Returns",
"an",
"import",
"wrapped",
"to",
"the",
"specified",
"line",
"-",
"length",
"if",
"possible",
"."
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/isort.py#L212-L253 |
239,582 | timothycrosley/isort | isort/finders.py | KnownPatternFinder._parse_known_pattern | def _parse_known_pattern(self, pattern: str) -> List[str]:
"""
Expand pattern if identified as a directory and return found sub packages
"""
if pattern.endswith(os.path.sep):
patterns = [
filename
for filename in os.listdir(pattern)
if os.path.isdir(os.path.join(pattern, filename))
]
else:
patterns = [pattern]
return patterns | python | def _parse_known_pattern(self, pattern: str) -> List[str]:
if pattern.endswith(os.path.sep):
patterns = [
filename
for filename in os.listdir(pattern)
if os.path.isdir(os.path.join(pattern, filename))
]
else:
patterns = [pattern]
return patterns | [
"def",
"_parse_known_pattern",
"(",
"self",
",",
"pattern",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"pattern",
".",
"endswith",
"(",
"os",
".",
"path",
".",
"sep",
")",
":",
"patterns",
"=",
"[",
"filename",
"for",
"filename",
"in"... | Expand pattern if identified as a directory and return found sub packages | [
"Expand",
"pattern",
"if",
"identified",
"as",
"a",
"directory",
"and",
"return",
"found",
"sub",
"packages"
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L86-L99 |
239,583 | timothycrosley/isort | isort/finders.py | ReqsBaseFinder._load_mapping | def _load_mapping() -> Optional[Dict[str, str]]:
"""Return list of mappings `package_name -> module_name`
Example:
django-haystack -> haystack
"""
if not pipreqs:
return None
path = os.path.dirname(inspect.getfile(pipreqs))
path = os.path.join(path, 'mapping')
with open(path) as f:
# pypi_name: import_name
mappings = {} # type: Dict[str, str]
for line in f:
import_name, _, pypi_name = line.strip().partition(":")
mappings[pypi_name] = import_name
return mappings | python | def _load_mapping() -> Optional[Dict[str, str]]:
if not pipreqs:
return None
path = os.path.dirname(inspect.getfile(pipreqs))
path = os.path.join(path, 'mapping')
with open(path) as f:
# pypi_name: import_name
mappings = {} # type: Dict[str, str]
for line in f:
import_name, _, pypi_name = line.strip().partition(":")
mappings[pypi_name] = import_name
return mappings | [
"def",
"_load_mapping",
"(",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"if",
"not",
"pipreqs",
":",
"return",
"None",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"inspect",
".",
"getfile",
"(",
"pipreqs",
"... | Return list of mappings `package_name -> module_name`
Example:
django-haystack -> haystack | [
"Return",
"list",
"of",
"mappings",
"package_name",
"-",
">",
"module_name"
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L200-L216 |
239,584 | timothycrosley/isort | isort/finders.py | ReqsBaseFinder._load_names | def _load_names(self) -> List[str]:
"""Return list of thirdparty modules from requirements
"""
names = []
for path in self._get_files():
for name in self._get_names(path):
names.append(self._normalize_name(name))
return names | python | def _load_names(self) -> List[str]:
names = []
for path in self._get_files():
for name in self._get_names(path):
names.append(self._normalize_name(name))
return names | [
"def",
"_load_names",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"names",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"_get_files",
"(",
")",
":",
"for",
"name",
"in",
"self",
".",
"_get_names",
"(",
"path",
")",
":",
"names",
"."... | Return list of thirdparty modules from requirements | [
"Return",
"list",
"of",
"thirdparty",
"modules",
"from",
"requirements"
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L219-L226 |
239,585 | timothycrosley/isort | isort/finders.py | ReqsBaseFinder._get_files | def _get_files(self) -> Iterator[str]:
"""Return paths to all requirements files
"""
path = os.path.abspath(self.path)
if os.path.isfile(path):
path = os.path.dirname(path)
for path in self._get_parents(path):
for file_path in self._get_files_from_dir(path):
yield file_path | python | def _get_files(self) -> Iterator[str]:
path = os.path.abspath(self.path)
if os.path.isfile(path):
path = os.path.dirname(path)
for path in self._get_parents(path):
for file_path in self._get_files_from_dir(path):
yield file_path | [
"def",
"_get_files",
"(",
"self",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"path",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",... | Return paths to all requirements files | [
"Return",
"paths",
"to",
"all",
"requirements",
"files"
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L236-L245 |
239,586 | timothycrosley/isort | isort/finders.py | ReqsBaseFinder._normalize_name | def _normalize_name(self, name: str) -> str:
"""Convert package name to module name
Examples:
Django -> django
django-haystack -> django_haystack
Flask-RESTFul -> flask_restful
"""
if self.mapping:
name = self.mapping.get(name, name)
return name.lower().replace('-', '_') | python | def _normalize_name(self, name: str) -> str:
if self.mapping:
name = self.mapping.get(name, name)
return name.lower().replace('-', '_') | [
"def",
"_normalize_name",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"str",
":",
"if",
"self",
".",
"mapping",
":",
"name",
"=",
"self",
".",
"mapping",
".",
"get",
"(",
"name",
",",
"name",
")",
"return",
"name",
".",
"lower",
"(",
")",
".... | Convert package name to module name
Examples:
Django -> django
django-haystack -> django_haystack
Flask-RESTFul -> flask_restful | [
"Convert",
"package",
"name",
"to",
"module",
"name"
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L247-L257 |
239,587 | timothycrosley/isort | isort/finders.py | RequirementsFinder._get_names | def _get_names(self, path: str) -> Iterator[str]:
"""Load required packages from path to requirements file
"""
for i in RequirementsFinder._get_names_cached(path):
yield i | python | def _get_names(self, path: str) -> Iterator[str]:
for i in RequirementsFinder._get_names_cached(path):
yield i | [
"def",
"_get_names",
"(",
"self",
",",
"path",
":",
"str",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"for",
"i",
"in",
"RequirementsFinder",
".",
"_get_names_cached",
"(",
"path",
")",
":",
"yield",
"i"
] | Load required packages from path to requirements file | [
"Load",
"required",
"packages",
"from",
"path",
"to",
"requirements",
"file"
] | 493c02a1a000fe782cec56f1f43262bacb316381 | https://github.com/timothycrosley/isort/blob/493c02a1a000fe782cec56f1f43262bacb316381/isort/finders.py#L310-L314 |
239,588 | graphql-python/graphql-ws | graphql_ws/django_channels.py | GraphQLSubscriptionConsumer.receive | def receive(self, content, **kwargs):
"""
Called when a message is received with either text or bytes
filled out.
"""
self.connection_context = DjangoChannelConnectionContext(self.message)
self.subscription_server = DjangoChannelSubscriptionServer(graphene_settings.SCHEMA)
self.subscription_server.on_open(self.connection_context)
self.subscription_server.handle(content, self.connection_context) | python | def receive(self, content, **kwargs):
self.connection_context = DjangoChannelConnectionContext(self.message)
self.subscription_server = DjangoChannelSubscriptionServer(graphene_settings.SCHEMA)
self.subscription_server.on_open(self.connection_context)
self.subscription_server.handle(content, self.connection_context) | [
"def",
"receive",
"(",
"self",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"connection_context",
"=",
"DjangoChannelConnectionContext",
"(",
"self",
".",
"message",
")",
"self",
".",
"subscription_server",
"=",
"DjangoChannelSubscriptionServer"... | Called when a message is received with either text or bytes
filled out. | [
"Called",
"when",
"a",
"message",
"is",
"received",
"with",
"either",
"text",
"or",
"bytes",
"filled",
"out",
"."
] | 523dd1516d8709149a475602042d6a3c5eab5a3d | https://github.com/graphql-python/graphql-ws/blob/523dd1516d8709149a475602042d6a3c5eab5a3d/graphql_ws/django_channels.py#L106-L114 |
239,589 | autokey/autokey | lib/autokey/qtui/settings/general.py | GeneralSettings.save | def save(self):
"""Called by the parent settings dialog when the user clicks on the Save button.
Stores the current settings in the ConfigManager."""
logger.debug("User requested to save settings. New settings: " + self._settings_str())
cm.ConfigManager.SETTINGS[cm.PROMPT_TO_SAVE] = not self.autosave_checkbox.isChecked()
cm.ConfigManager.SETTINGS[cm.SHOW_TRAY_ICON] = self.show_tray_checkbox.isChecked()
# cm.ConfigManager.SETTINGS[cm.MENU_TAKES_FOCUS] = self.allow_kb_nav_checkbox.isChecked()
cm.ConfigManager.SETTINGS[cm.SORT_BY_USAGE_COUNT] = self.sort_by_usage_checkbox.isChecked()
cm.ConfigManager.SETTINGS[cm.UNDO_USING_BACKSPACE] = self.enable_undo_checkbox.isChecked()
cm.ConfigManager.SETTINGS[cm.NOTIFICATION_ICON] = self.system_tray_icon_theme_combobox.currentData(Qt.UserRole)
# TODO: After saving the notification icon, apply it to the currently running instance.
self._save_autostart_settings() | python | def save(self):
logger.debug("User requested to save settings. New settings: " + self._settings_str())
cm.ConfigManager.SETTINGS[cm.PROMPT_TO_SAVE] = not self.autosave_checkbox.isChecked()
cm.ConfigManager.SETTINGS[cm.SHOW_TRAY_ICON] = self.show_tray_checkbox.isChecked()
# cm.ConfigManager.SETTINGS[cm.MENU_TAKES_FOCUS] = self.allow_kb_nav_checkbox.isChecked()
cm.ConfigManager.SETTINGS[cm.SORT_BY_USAGE_COUNT] = self.sort_by_usage_checkbox.isChecked()
cm.ConfigManager.SETTINGS[cm.UNDO_USING_BACKSPACE] = self.enable_undo_checkbox.isChecked()
cm.ConfigManager.SETTINGS[cm.NOTIFICATION_ICON] = self.system_tray_icon_theme_combobox.currentData(Qt.UserRole)
# TODO: After saving the notification icon, apply it to the currently running instance.
self._save_autostart_settings() | [
"def",
"save",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"User requested to save settings. New settings: \"",
"+",
"self",
".",
"_settings_str",
"(",
")",
")",
"cm",
".",
"ConfigManager",
".",
"SETTINGS",
"[",
"cm",
".",
"PROMPT_TO_SAVE",
"]",
"=",... | Called by the parent settings dialog when the user clicks on the Save button.
Stores the current settings in the ConfigManager. | [
"Called",
"by",
"the",
"parent",
"settings",
"dialog",
"when",
"the",
"user",
"clicks",
"on",
"the",
"Save",
"button",
".",
"Stores",
"the",
"current",
"settings",
"in",
"the",
"ConfigManager",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/settings/general.py#L59-L70 |
239,590 | autokey/autokey | lib/autokey/qtui/settings/general.py | GeneralSettings._settings_str | def _settings_str(self):
"""Returns a human readable settings representation for logging purposes."""
settings = "Automatically save changes: {}, " \
"Show tray icon: {}, " \
"Allow keyboard navigation: {}, " \
"Sort by usage count: {}, " \
"Enable undo using backspace: {}, " \
"Tray icon theme: {}".format(
self.autosave_checkbox.isChecked(),
self.show_tray_checkbox.isChecked(),
self.allow_kb_nav_checkbox.isChecked(),
self.sort_by_usage_checkbox.isChecked(),
self.enable_undo_checkbox.isChecked(),
self.system_tray_icon_theme_combobox.currentData(Qt.UserRole)
)
return settings | python | def _settings_str(self):
settings = "Automatically save changes: {}, " \
"Show tray icon: {}, " \
"Allow keyboard navigation: {}, " \
"Sort by usage count: {}, " \
"Enable undo using backspace: {}, " \
"Tray icon theme: {}".format(
self.autosave_checkbox.isChecked(),
self.show_tray_checkbox.isChecked(),
self.allow_kb_nav_checkbox.isChecked(),
self.sort_by_usage_checkbox.isChecked(),
self.enable_undo_checkbox.isChecked(),
self.system_tray_icon_theme_combobox.currentData(Qt.UserRole)
)
return settings | [
"def",
"_settings_str",
"(",
"self",
")",
":",
"settings",
"=",
"\"Automatically save changes: {}, \"",
"\"Show tray icon: {}, \"",
"\"Allow keyboard navigation: {}, \"",
"\"Sort by usage count: {}, \"",
"\"Enable undo using backspace: {}, \"",
"\"Tray icon theme: {}\"",
".",
"format",... | Returns a human readable settings representation for logging purposes. | [
"Returns",
"a",
"human",
"readable",
"settings",
"representation",
"for",
"logging",
"purposes",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/settings/general.py#L72-L87 |
239,591 | autokey/autokey | lib/autokey/model.py | AbstractAbbreviation._should_trigger_abbreviation | def _should_trigger_abbreviation(self, buffer):
"""
Checks whether, based on the settings for the abbreviation and the given input,
the abbreviation should trigger.
@param buffer Input buffer to be checked (as string)
"""
return any(self.__checkInput(buffer, abbr) for abbr in self.abbreviations) | python | def _should_trigger_abbreviation(self, buffer):
return any(self.__checkInput(buffer, abbr) for abbr in self.abbreviations) | [
"def",
"_should_trigger_abbreviation",
"(",
"self",
",",
"buffer",
")",
":",
"return",
"any",
"(",
"self",
".",
"__checkInput",
"(",
"buffer",
",",
"abbr",
")",
"for",
"abbr",
"in",
"self",
".",
"abbreviations",
")"
] | Checks whether, based on the settings for the abbreviation and the given input,
the abbreviation should trigger.
@param buffer Input buffer to be checked (as string) | [
"Checks",
"whether",
"based",
"on",
"the",
"settings",
"for",
"the",
"abbreviation",
"and",
"the",
"given",
"input",
"the",
"abbreviation",
"should",
"trigger",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L175-L182 |
239,592 | autokey/autokey | lib/autokey/model.py | AbstractWindowFilter.get_filter_regex | def get_filter_regex(self):
"""
Used by the GUI to obtain human-readable version of the filter
"""
if self.windowInfoRegex is not None:
if self.isRecursive:
return self.windowInfoRegex.pattern
else:
return self.windowInfoRegex.pattern
elif self.parent is not None:
return self.parent.get_child_filter()
else:
return "" | python | def get_filter_regex(self):
if self.windowInfoRegex is not None:
if self.isRecursive:
return self.windowInfoRegex.pattern
else:
return self.windowInfoRegex.pattern
elif self.parent is not None:
return self.parent.get_child_filter()
else:
return "" | [
"def",
"get_filter_regex",
"(",
"self",
")",
":",
"if",
"self",
".",
"windowInfoRegex",
"is",
"not",
"None",
":",
"if",
"self",
".",
"isRecursive",
":",
"return",
"self",
".",
"windowInfoRegex",
".",
"pattern",
"else",
":",
"return",
"self",
".",
"windowIn... | Used by the GUI to obtain human-readable version of the filter | [
"Used",
"by",
"the",
"GUI",
"to",
"obtain",
"human",
"-",
"readable",
"version",
"of",
"the",
"filter"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L313-L325 |
239,593 | autokey/autokey | lib/autokey/model.py | Folder.add_item | def add_item(self, item):
"""
Add a new script or phrase to the folder.
"""
item.parent = self
#self.phrases[phrase.description] = phrase
self.items.append(item) | python | def add_item(self, item):
item.parent = self
#self.phrases[phrase.description] = phrase
self.items.append(item) | [
"def",
"add_item",
"(",
"self",
",",
"item",
")",
":",
"item",
".",
"parent",
"=",
"self",
"#self.phrases[phrase.description] = phrase",
"self",
".",
"items",
".",
"append",
"(",
"item",
")"
] | Add a new script or phrase to the folder. | [
"Add",
"a",
"new",
"script",
"or",
"phrase",
"to",
"the",
"folder",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L546-L552 |
239,594 | autokey/autokey | lib/autokey/model.py | Folder.get_backspace_count | def get_backspace_count(self, buffer):
"""
Given the input buffer, calculate how many backspaces are needed to erase the text
that triggered this folder.
"""
if TriggerMode.ABBREVIATION in self.modes and self.backspace:
if self._should_trigger_abbreviation(buffer):
abbr = self._get_trigger_abbreviation(buffer)
stringBefore, typedAbbr, stringAfter = self._partition_input(buffer, abbr)
return len(abbr) + len(stringAfter)
if self.parent is not None:
return self.parent.get_backspace_count(buffer)
return 0 | python | def get_backspace_count(self, buffer):
if TriggerMode.ABBREVIATION in self.modes and self.backspace:
if self._should_trigger_abbreviation(buffer):
abbr = self._get_trigger_abbreviation(buffer)
stringBefore, typedAbbr, stringAfter = self._partition_input(buffer, abbr)
return len(abbr) + len(stringAfter)
if self.parent is not None:
return self.parent.get_backspace_count(buffer)
return 0 | [
"def",
"get_backspace_count",
"(",
"self",
",",
"buffer",
")",
":",
"if",
"TriggerMode",
".",
"ABBREVIATION",
"in",
"self",
".",
"modes",
"and",
"self",
".",
"backspace",
":",
"if",
"self",
".",
"_should_trigger_abbreviation",
"(",
"buffer",
")",
":",
"abbr"... | Given the input buffer, calculate how many backspaces are needed to erase the text
that triggered this folder. | [
"Given",
"the",
"input",
"buffer",
"calculate",
"how",
"many",
"backspaces",
"are",
"needed",
"to",
"erase",
"the",
"text",
"that",
"triggered",
"this",
"folder",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L572-L586 |
239,595 | autokey/autokey | lib/autokey/model.py | Phrase.calculate_input | def calculate_input(self, buffer):
"""
Calculate how many keystrokes were used in triggering this phrase.
"""
# TODO: This function is unused?
if TriggerMode.ABBREVIATION in self.modes:
if self._should_trigger_abbreviation(buffer):
if self.immediate:
return len(self._get_trigger_abbreviation(buffer))
else:
return len(self._get_trigger_abbreviation(buffer)) + 1
# TODO - re-enable me if restoring predictive functionality
#if TriggerMode.PREDICTIVE in self.modes:
# if self._should_trigger_predictive(buffer):
# return ConfigManager.SETTINGS[PREDICTIVE_LENGTH]
if TriggerMode.HOTKEY in self.modes:
if buffer == '':
return len(self.modifiers) + 1
return self.parent.calculate_input(buffer) | python | def calculate_input(self, buffer):
# TODO: This function is unused?
if TriggerMode.ABBREVIATION in self.modes:
if self._should_trigger_abbreviation(buffer):
if self.immediate:
return len(self._get_trigger_abbreviation(buffer))
else:
return len(self._get_trigger_abbreviation(buffer)) + 1
# TODO - re-enable me if restoring predictive functionality
#if TriggerMode.PREDICTIVE in self.modes:
# if self._should_trigger_predictive(buffer):
# return ConfigManager.SETTINGS[PREDICTIVE_LENGTH]
if TriggerMode.HOTKEY in self.modes:
if buffer == '':
return len(self.modifiers) + 1
return self.parent.calculate_input(buffer) | [
"def",
"calculate_input",
"(",
"self",
",",
"buffer",
")",
":",
"# TODO: This function is unused?",
"if",
"TriggerMode",
".",
"ABBREVIATION",
"in",
"self",
".",
"modes",
":",
"if",
"self",
".",
"_should_trigger_abbreviation",
"(",
"buffer",
")",
":",
"if",
"self... | Calculate how many keystrokes were used in triggering this phrase. | [
"Calculate",
"how",
"many",
"keystrokes",
"were",
"used",
"in",
"triggering",
"this",
"phrase",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L797-L818 |
239,596 | autokey/autokey | lib/autokey/model.py | Script._persist_metadata | def _persist_metadata(self):
"""
Write all script meta-data, including the persistent script Store.
The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other
non-serializable objects, both as keys or values.
Try to serialize the data, and if it fails, fall back to checking the store and removing all non-serializable
data.
"""
serializable_data = self.get_serializable()
try:
self._try_persist_metadata(serializable_data)
except TypeError:
# The user added non-serializable data to the store, so skip all non-serializable keys or values.
cleaned_data = Script._remove_non_serializable_store_entries(serializable_data["store"])
self._try_persist_metadata(cleaned_data) | python | def _persist_metadata(self):
serializable_data = self.get_serializable()
try:
self._try_persist_metadata(serializable_data)
except TypeError:
# The user added non-serializable data to the store, so skip all non-serializable keys or values.
cleaned_data = Script._remove_non_serializable_store_entries(serializable_data["store"])
self._try_persist_metadata(cleaned_data) | [
"def",
"_persist_metadata",
"(",
"self",
")",
":",
"serializable_data",
"=",
"self",
".",
"get_serializable",
"(",
")",
"try",
":",
"self",
".",
"_try_persist_metadata",
"(",
"serializable_data",
")",
"except",
"TypeError",
":",
"# The user added non-serializable data... | Write all script meta-data, including the persistent script Store.
The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other
non-serializable objects, both as keys or values.
Try to serialize the data, and if it fails, fall back to checking the store and removing all non-serializable
data. | [
"Write",
"all",
"script",
"meta",
"-",
"data",
"including",
"the",
"persistent",
"script",
"Store",
".",
"The",
"Store",
"instance",
"might",
"contain",
"arbitrary",
"user",
"data",
"like",
"function",
"objects",
"OpenCL",
"contexts",
"or",
"whatever",
"other",
... | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L949-L963 |
239,597 | autokey/autokey | lib/autokey/model.py | Script._remove_non_serializable_store_entries | def _remove_non_serializable_store_entries(store: Store) -> dict:
"""
Copy all serializable data into a new dict, and skip the rest.
This makes sure to keep the items during runtime, even if the user edits and saves the script.
"""
cleaned_store_data = {}
for key, value in store.items():
if Script._is_serializable(key) and Script._is_serializable(value):
cleaned_store_data[key] = value
else:
_logger.info("Skip non-serializable item in the local script store. Key: '{}', Value: '{}'. "
"This item cannot be saved and therefore will be lost when autokey quits.".format(
key, value
))
return cleaned_store_data | python | def _remove_non_serializable_store_entries(store: Store) -> dict:
cleaned_store_data = {}
for key, value in store.items():
if Script._is_serializable(key) and Script._is_serializable(value):
cleaned_store_data[key] = value
else:
_logger.info("Skip non-serializable item in the local script store. Key: '{}', Value: '{}'. "
"This item cannot be saved and therefore will be lost when autokey quits.".format(
key, value
))
return cleaned_store_data | [
"def",
"_remove_non_serializable_store_entries",
"(",
"store",
":",
"Store",
")",
"->",
"dict",
":",
"cleaned_store_data",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"store",
".",
"items",
"(",
")",
":",
"if",
"Script",
".",
"_is_serializable",
"(",
... | Copy all serializable data into a new dict, and skip the rest.
This makes sure to keep the items during runtime, even if the user edits and saves the script. | [
"Copy",
"all",
"serializable",
"data",
"into",
"a",
"new",
"dict",
"and",
"skip",
"the",
"rest",
".",
"This",
"makes",
"sure",
"to",
"keep",
"the",
"items",
"during",
"runtime",
"even",
"if",
"the",
"user",
"edits",
"and",
"saves",
"the",
"script",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/model.py#L970-L984 |
239,598 | autokey/autokey | lib/autokey/qtapp.py | Application._configure_root_logger | def _configure_root_logger(self):
"""Initialise logging system"""
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
if self.args.verbose:
handler = logging.StreamHandler(sys.stdout)
else:
handler = logging.handlers.RotatingFileHandler(
common.LOG_FILE,
maxBytes=common.MAX_LOG_SIZE,
backupCount=common.MAX_LOG_COUNT
)
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter(common.LOG_FORMAT))
root_logger.addHandler(handler) | python | def _configure_root_logger(self):
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
if self.args.verbose:
handler = logging.StreamHandler(sys.stdout)
else:
handler = logging.handlers.RotatingFileHandler(
common.LOG_FILE,
maxBytes=common.MAX_LOG_SIZE,
backupCount=common.MAX_LOG_COUNT
)
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter(common.LOG_FORMAT))
root_logger.addHandler(handler) | [
"def",
"_configure_root_logger",
"(",
"self",
")",
":",
"root_logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"root_logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"if",
"self",
".",
"args",
".",
"verbose",
":",
"handler",
"=",
"logging",... | Initialise logging system | [
"Initialise",
"logging",
"system"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtapp.py#L165-L179 |
239,599 | autokey/autokey | lib/autokey/qtapp.py | Application._create_storage_directories | def _create_storage_directories():
"""Create various storage directories, if those do not exist."""
# Create configuration directory
if not os.path.exists(common.CONFIG_DIR):
os.makedirs(common.CONFIG_DIR)
# Create data directory (for log file)
if not os.path.exists(common.DATA_DIR):
os.makedirs(common.DATA_DIR)
# Create run directory (for lock file)
if not os.path.exists(common.RUN_DIR):
os.makedirs(common.RUN_DIR) | python | def _create_storage_directories():
# Create configuration directory
if not os.path.exists(common.CONFIG_DIR):
os.makedirs(common.CONFIG_DIR)
# Create data directory (for log file)
if not os.path.exists(common.DATA_DIR):
os.makedirs(common.DATA_DIR)
# Create run directory (for lock file)
if not os.path.exists(common.RUN_DIR):
os.makedirs(common.RUN_DIR) | [
"def",
"_create_storage_directories",
"(",
")",
":",
"# Create configuration directory",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"common",
".",
"CONFIG_DIR",
")",
":",
"os",
".",
"makedirs",
"(",
"common",
".",
"CONFIG_DIR",
")",
"# Create data direc... | Create various storage directories, if those do not exist. | [
"Create",
"various",
"storage",
"directories",
"if",
"those",
"do",
"not",
"exist",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtapp.py#L182-L192 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.