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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
236,200 | python-diamond/Diamond | src/collectors/memory_lxc/memory_lxc.py | MemoryLxcCollector.get_default_config_help | def get_default_config_help(self):
"""
Return help text for collector configuration.
"""
config_help = super(MemoryLxcCollector, self).get_default_config_help()
config_help.update({
"sys_path": "Defaults to '/sys/fs/cgroup/lxc'",
})
return config_help | python | def get_default_config_help(self):
config_help = super(MemoryLxcCollector, self).get_default_config_help()
config_help.update({
"sys_path": "Defaults to '/sys/fs/cgroup/lxc'",
})
return config_help | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config_help",
"=",
"super",
"(",
"MemoryLxcCollector",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config_help",
".",
"update",
"(",
"{",
"\"sys_path\"",
":",
"\"Defaults to '/sys/fs/cgroup/l... | Return help text for collector configuration. | [
"Return",
"help",
"text",
"for",
"collector",
"configuration",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/memory_lxc/memory_lxc.py#L18-L26 |
236,201 | python-diamond/Diamond | src/collectors/memory_lxc/memory_lxc.py | MemoryLxcCollector.get_default_config | def get_default_config(self):
"""
Returns default settings for collector.
"""
config = super(MemoryLxcCollector, self).get_default_config()
config.update({
"path": "lxc",
"sys_path": "/sys/fs/cgroup/lxc",
})
return config | python | def get_default_config(self):
config = super(MemoryLxcCollector, self).get_default_config()
config.update({
"path": "lxc",
"sys_path": "/sys/fs/cgroup/lxc",
})
return config | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"MemoryLxcCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"\"path\"",
":",
"\"lxc\"",
",",
"\"sys_path\"",
":",
"\"/sys/fs/... | Returns default settings for collector. | [
"Returns",
"default",
"settings",
"for",
"collector",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/memory_lxc/memory_lxc.py#L28-L37 |
236,202 | python-diamond/Diamond | src/collectors/memory_lxc/memory_lxc.py | MemoryLxcCollector.collect | def collect(self):
"""
Collect memory stats of LXCs.
"""
lxc_metrics = ["memory.usage_in_bytes", "memory.limit_in_bytes"]
if os.path.isdir(self.config["sys_path"]) is False:
self.log.debug("sys_path '%s' isn't directory.",
self.config["sys_path"])
return {}
collected = {}
for item in os.listdir(self.config["sys_path"]):
fpath = "%s/%s" % (self.config["sys_path"], item)
if os.path.isdir(fpath) is False:
continue
for lxc_metric in lxc_metrics:
filename = "%s/%s" % (fpath, lxc_metric)
metric_name = "%s.%s" % (
item.replace(".", "_"),
lxc_metric.replace("_in_bytes", ""))
self.log.debug("Trying to collect from %s", filename)
collected[metric_name] = self._read_file(filename)
for key in collected.keys():
if collected[key] is None:
continue
for unit in self.config["byte_unit"]:
value = diamond.convertor.binary.convert(
collected[key],
oldUnit="B",
newUnit=unit)
new_key = "%s_in_%ss" % (key, unit)
self.log.debug("Publishing '%s %s'", new_key, value)
self.publish(new_key, value, metric_type="GAUGE") | python | def collect(self):
lxc_metrics = ["memory.usage_in_bytes", "memory.limit_in_bytes"]
if os.path.isdir(self.config["sys_path"]) is False:
self.log.debug("sys_path '%s' isn't directory.",
self.config["sys_path"])
return {}
collected = {}
for item in os.listdir(self.config["sys_path"]):
fpath = "%s/%s" % (self.config["sys_path"], item)
if os.path.isdir(fpath) is False:
continue
for lxc_metric in lxc_metrics:
filename = "%s/%s" % (fpath, lxc_metric)
metric_name = "%s.%s" % (
item.replace(".", "_"),
lxc_metric.replace("_in_bytes", ""))
self.log.debug("Trying to collect from %s", filename)
collected[metric_name] = self._read_file(filename)
for key in collected.keys():
if collected[key] is None:
continue
for unit in self.config["byte_unit"]:
value = diamond.convertor.binary.convert(
collected[key],
oldUnit="B",
newUnit=unit)
new_key = "%s_in_%ss" % (key, unit)
self.log.debug("Publishing '%s %s'", new_key, value)
self.publish(new_key, value, metric_type="GAUGE") | [
"def",
"collect",
"(",
"self",
")",
":",
"lxc_metrics",
"=",
"[",
"\"memory.usage_in_bytes\"",
",",
"\"memory.limit_in_bytes\"",
"]",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"config",
"[",
"\"sys_path\"",
"]",
")",
"is",
"False",
":",
"sel... | Collect memory stats of LXCs. | [
"Collect",
"memory",
"stats",
"of",
"LXCs",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/memory_lxc/memory_lxc.py#L39-L74 |
236,203 | python-diamond/Diamond | src/collectors/memory_lxc/memory_lxc.py | MemoryLxcCollector._read_file | def _read_file(self, filename):
"""
Read contents of given file.
"""
try:
with open(filename, "r") as fhandle:
stats = float(fhandle.readline().rstrip("\n"))
except Exception:
stats = None
return stats | python | def _read_file(self, filename):
try:
with open(filename, "r") as fhandle:
stats = float(fhandle.readline().rstrip("\n"))
except Exception:
stats = None
return stats | [
"def",
"_read_file",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"fhandle",
":",
"stats",
"=",
"float",
"(",
"fhandle",
".",
"readline",
"(",
")",
".",
"rstrip",
"(",
"\"\\n\"",
")",
... | Read contents of given file. | [
"Read",
"contents",
"of",
"given",
"file",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/memory_lxc/memory_lxc.py#L76-L86 |
236,204 | python-diamond/Diamond | src/diamond/util.py | load_modules_from_path | def load_modules_from_path(path):
"""
Import all modules from the given directory
"""
# Check and fix the path
if path[-1:] != '/':
path += '/'
# Get a list of files in the directory, if the directory exists
if not os.path.exists(path):
raise OSError("Directory does not exist: %s" % path)
# Add path to the system path
sys.path.append(path)
# Load all the files in path
for f in os.listdir(path):
# Ignore anything that isn't a .py file
if len(f) > 3 and f[-3:] == '.py':
modname = f[:-3]
# Import the module
__import__(modname, globals(), locals(), ['*']) | python | def load_modules_from_path(path):
# Check and fix the path
if path[-1:] != '/':
path += '/'
# Get a list of files in the directory, if the directory exists
if not os.path.exists(path):
raise OSError("Directory does not exist: %s" % path)
# Add path to the system path
sys.path.append(path)
# Load all the files in path
for f in os.listdir(path):
# Ignore anything that isn't a .py file
if len(f) > 3 and f[-3:] == '.py':
modname = f[:-3]
# Import the module
__import__(modname, globals(), locals(), ['*']) | [
"def",
"load_modules_from_path",
"(",
"path",
")",
":",
"# Check and fix the path",
"if",
"path",
"[",
"-",
"1",
":",
"]",
"!=",
"'/'",
":",
"path",
"+=",
"'/'",
"# Get a list of files in the directory, if the directory exists",
"if",
"not",
"os",
".",
"path",
"."... | Import all modules from the given directory | [
"Import",
"all",
"modules",
"from",
"the",
"given",
"directory"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/util.py#L16-L36 |
236,205 | python-diamond/Diamond | src/diamond/handler/logentries_diamond.py | LogentriesDiamondHandler.process | def process(self, metric):
"""
Process metric by sending it to datadog api
"""
self.queue.append(metric)
if len(self.queue) >= self.queue_size:
logging.debug("Queue is full, sending logs to Logentries")
self._send() | python | def process(self, metric):
self.queue.append(metric)
if len(self.queue) >= self.queue_size:
logging.debug("Queue is full, sending logs to Logentries")
self._send() | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"self",
".",
"queue",
".",
"append",
"(",
"metric",
")",
"if",
"len",
"(",
"self",
".",
"queue",
")",
">=",
"self",
".",
"queue_size",
":",
"logging",
".",
"debug",
"(",
"\"Queue is full, sending ... | Process metric by sending it to datadog api | [
"Process",
"metric",
"by",
"sending",
"it",
"to",
"datadog",
"api"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/logentries_diamond.py#L60-L68 |
236,206 | python-diamond/Diamond | src/diamond/handler/logentries_diamond.py | LogentriesDiamondHandler._send | def _send(self):
"""
Convert message to a json object and send to Lognetries
"""
while len(self.queue) > 0:
metric = self.queue.popleft()
topic, value, timestamp = str(metric).split()
msg = json.dumps({"event": {topic: value}})
req = urllib2.Request("https://js.logentries.com/v1/logs/" +
self.log_token, msg)
try:
urllib2.urlopen(req)
except urllib2.URLError as e:
logging.error("Can't send log message to Logentries %s", e) | python | def _send(self):
while len(self.queue) > 0:
metric = self.queue.popleft()
topic, value, timestamp = str(metric).split()
msg = json.dumps({"event": {topic: value}})
req = urllib2.Request("https://js.logentries.com/v1/logs/" +
self.log_token, msg)
try:
urllib2.urlopen(req)
except urllib2.URLError as e:
logging.error("Can't send log message to Logentries %s", e) | [
"def",
"_send",
"(",
"self",
")",
":",
"while",
"len",
"(",
"self",
".",
"queue",
")",
">",
"0",
":",
"metric",
"=",
"self",
".",
"queue",
".",
"popleft",
"(",
")",
"topic",
",",
"value",
",",
"timestamp",
"=",
"str",
"(",
"metric",
")",
".",
"... | Convert message to a json object and send to Lognetries | [
"Convert",
"message",
"to",
"a",
"json",
"object",
"and",
"send",
"to",
"Lognetries"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/logentries_diamond.py#L70-L83 |
236,207 | python-diamond/Diamond | src/collectors/smart/smart.py | SmartCollector.collect | def collect(self):
"""
Collect and publish S.M.A.R.T. attributes
"""
devices = re.compile(self.config['devices'])
for device in os.listdir('/dev'):
if devices.match(device):
command = [self.config['bin'], "-A", os.path.join('/dev',
device)]
if str_to_bool(self.config['use_sudo']):
command.insert(0, self.config['sudo_cmd'])
attributes = subprocess.Popen(
command,
stdout=subprocess.PIPE
).communicate()[0].strip().splitlines()
metrics = {}
start_line = self.find_attr_start_line(attributes)
for attr in attributes[start_line:]:
attribute = attr.split()
if attribute[1] != "Unknown_Attribute":
metric = "%s.%s" % (device, attribute[1])
else:
metric = "%s.%s" % (device, attribute[0])
# 234 Thermal_Throttle (...) 0/0
if '/' in attribute[9]:
expanded = attribute[9].split('/')
for i, subattribute in enumerate(expanded):
submetric = '%s_%d' % (metric, i)
if submetric not in metrics:
metrics[submetric] = subattribute
elif metrics[submetric] == 0 and subattribute > 0:
metrics[submetric] = subattribute
else:
# New metric? Store it
if metric not in metrics:
metrics[metric] = attribute[9]
# Duplicate metric? Only store if it has a larger value
# This happens semi-often with the Temperature_Celsius
# attribute You will have a PASS/FAIL after the real
# temp, so only overwrite if The earlier one was a
# PASS/FAIL (0/1)
elif metrics[metric] == 0 and attribute[9] > 0:
metrics[metric] = attribute[9]
else:
continue
for metric in metrics.keys():
self.publish(metric, metrics[metric]) | python | def collect(self):
devices = re.compile(self.config['devices'])
for device in os.listdir('/dev'):
if devices.match(device):
command = [self.config['bin'], "-A", os.path.join('/dev',
device)]
if str_to_bool(self.config['use_sudo']):
command.insert(0, self.config['sudo_cmd'])
attributes = subprocess.Popen(
command,
stdout=subprocess.PIPE
).communicate()[0].strip().splitlines()
metrics = {}
start_line = self.find_attr_start_line(attributes)
for attr in attributes[start_line:]:
attribute = attr.split()
if attribute[1] != "Unknown_Attribute":
metric = "%s.%s" % (device, attribute[1])
else:
metric = "%s.%s" % (device, attribute[0])
# 234 Thermal_Throttle (...) 0/0
if '/' in attribute[9]:
expanded = attribute[9].split('/')
for i, subattribute in enumerate(expanded):
submetric = '%s_%d' % (metric, i)
if submetric not in metrics:
metrics[submetric] = subattribute
elif metrics[submetric] == 0 and subattribute > 0:
metrics[submetric] = subattribute
else:
# New metric? Store it
if metric not in metrics:
metrics[metric] = attribute[9]
# Duplicate metric? Only store if it has a larger value
# This happens semi-often with the Temperature_Celsius
# attribute You will have a PASS/FAIL after the real
# temp, so only overwrite if The earlier one was a
# PASS/FAIL (0/1)
elif metrics[metric] == 0 and attribute[9] > 0:
metrics[metric] = attribute[9]
else:
continue
for metric in metrics.keys():
self.publish(metric, metrics[metric]) | [
"def",
"collect",
"(",
"self",
")",
":",
"devices",
"=",
"re",
".",
"compile",
"(",
"self",
".",
"config",
"[",
"'devices'",
"]",
")",
"for",
"device",
"in",
"os",
".",
"listdir",
"(",
"'/dev'",
")",
":",
"if",
"devices",
".",
"match",
"(",
"device... | Collect and publish S.M.A.R.T. attributes | [
"Collect",
"and",
"publish",
"S",
".",
"M",
".",
"A",
".",
"R",
".",
"T",
".",
"attributes"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/smart/smart.py#L45-L99 |
236,208 | python-diamond/Diamond | src/collectors/smart/smart.py | SmartCollector.find_attr_start_line | def find_attr_start_line(self, lines, min_line=4, max_line=9):
"""
Return line number of the first real attribute and value.
The first line is 0. If the 'ATTRIBUTE_NAME' header is not
found, return the index after max_line.
"""
for idx, line in enumerate(lines[min_line:max_line]):
col = line.split()
if len(col) > 1 and col[1] == 'ATTRIBUTE_NAME':
return idx + min_line + 1
self.log.warn('ATTRIBUTE_NAME not found in second column of'
' smartctl output between lines %d and %d.'
% (min_line, max_line))
return max_line + 1 | python | def find_attr_start_line(self, lines, min_line=4, max_line=9):
for idx, line in enumerate(lines[min_line:max_line]):
col = line.split()
if len(col) > 1 and col[1] == 'ATTRIBUTE_NAME':
return idx + min_line + 1
self.log.warn('ATTRIBUTE_NAME not found in second column of'
' smartctl output between lines %d and %d.'
% (min_line, max_line))
return max_line + 1 | [
"def",
"find_attr_start_line",
"(",
"self",
",",
"lines",
",",
"min_line",
"=",
"4",
",",
"max_line",
"=",
"9",
")",
":",
"for",
"idx",
",",
"line",
"in",
"enumerate",
"(",
"lines",
"[",
"min_line",
":",
"max_line",
"]",
")",
":",
"col",
"=",
"line",... | Return line number of the first real attribute and value.
The first line is 0. If the 'ATTRIBUTE_NAME' header is not
found, return the index after max_line. | [
"Return",
"line",
"number",
"of",
"the",
"first",
"real",
"attribute",
"and",
"value",
".",
"The",
"first",
"line",
"is",
"0",
".",
"If",
"the",
"ATTRIBUTE_NAME",
"header",
"is",
"not",
"found",
"return",
"the",
"index",
"after",
"max_line",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/smart/smart.py#L101-L116 |
236,209 | python-diamond/Diamond | src/collectors/diskspace/diskspace.py | DiskSpaceCollector.get_disk_labels | def get_disk_labels(self):
"""
Creates a mapping of device nodes to filesystem labels
"""
path = '/dev/disk/by-label/'
labels = {}
if not os.path.isdir(path):
return labels
for label in os.listdir(path):
label = label.replace('\\x2f', '/')
device = os.path.realpath(path + '/' + label)
labels[device] = label
return labels | python | def get_disk_labels(self):
path = '/dev/disk/by-label/'
labels = {}
if not os.path.isdir(path):
return labels
for label in os.listdir(path):
label = label.replace('\\x2f', '/')
device = os.path.realpath(path + '/' + label)
labels[device] = label
return labels | [
"def",
"get_disk_labels",
"(",
"self",
")",
":",
"path",
"=",
"'/dev/disk/by-label/'",
"labels",
"=",
"{",
"}",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"labels",
"for",
"label",
"in",
"os",
".",
"listdir",
"(",
... | Creates a mapping of device nodes to filesystem labels | [
"Creates",
"a",
"mapping",
"of",
"device",
"nodes",
"to",
"filesystem",
"labels"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/diskspace/diskspace.py#L96-L110 |
236,210 | python-diamond/Diamond | src/collectors/diskspace/diskspace.py | DiskSpaceCollector.get_file_systems | def get_file_systems(self):
"""
Creates a map of mounted filesystems on the machine.
iostat(1): Each sector has size of 512 bytes.
Returns:
st_dev -> FileSystem(device, mount_point)
"""
result = {}
if os.access('/proc/mounts', os.R_OK):
file = open('/proc/mounts')
for line in file:
try:
mount = line.split()
device = mount[0]
mount_point = mount[1]
fs_type = mount[2]
except (IndexError, ValueError):
continue
# Skip the filesystem if it is not in the list of valid
# filesystems
if fs_type not in self.filesystems:
self.log.debug("Ignoring %s since it is of type %s " +
" which is not in the list of filesystems.",
mount_point, fs_type)
continue
# Process the filters
if self.exclude_reg.search(mount_point):
self.log.debug("Ignoring %s since it is in the " +
"exclude_filter list.", mount_point)
continue
if ((('/' in device or device == 'tmpfs') and
mount_point.startswith('/'))):
try:
stat = os.stat(mount_point)
except OSError:
self.log.debug("Path %s is not mounted - skipping.",
mount_point)
continue
if stat.st_dev in result:
continue
result[stat.st_dev] = {
'device': os.path.realpath(device),
'mount_point': mount_point,
'fs_type': fs_type
}
file.close()
else:
if not psutil:
self.log.error('Unable to import psutil')
return None
partitions = psutil.disk_partitions(False)
for partition in partitions:
result[len(result)] = {
'device': os.path.realpath(partition.device),
'mount_point': partition.mountpoint,
'fs_type': partition.fstype
}
pass
return result | python | def get_file_systems(self):
result = {}
if os.access('/proc/mounts', os.R_OK):
file = open('/proc/mounts')
for line in file:
try:
mount = line.split()
device = mount[0]
mount_point = mount[1]
fs_type = mount[2]
except (IndexError, ValueError):
continue
# Skip the filesystem if it is not in the list of valid
# filesystems
if fs_type not in self.filesystems:
self.log.debug("Ignoring %s since it is of type %s " +
" which is not in the list of filesystems.",
mount_point, fs_type)
continue
# Process the filters
if self.exclude_reg.search(mount_point):
self.log.debug("Ignoring %s since it is in the " +
"exclude_filter list.", mount_point)
continue
if ((('/' in device or device == 'tmpfs') and
mount_point.startswith('/'))):
try:
stat = os.stat(mount_point)
except OSError:
self.log.debug("Path %s is not mounted - skipping.",
mount_point)
continue
if stat.st_dev in result:
continue
result[stat.st_dev] = {
'device': os.path.realpath(device),
'mount_point': mount_point,
'fs_type': fs_type
}
file.close()
else:
if not psutil:
self.log.error('Unable to import psutil')
return None
partitions = psutil.disk_partitions(False)
for partition in partitions:
result[len(result)] = {
'device': os.path.realpath(partition.device),
'mount_point': partition.mountpoint,
'fs_type': partition.fstype
}
pass
return result | [
"def",
"get_file_systems",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"if",
"os",
".",
"access",
"(",
"'/proc/mounts'",
",",
"os",
".",
"R_OK",
")",
":",
"file",
"=",
"open",
"(",
"'/proc/mounts'",
")",
"for",
"line",
"in",
"file",
":",
"try",
... | Creates a map of mounted filesystems on the machine.
iostat(1): Each sector has size of 512 bytes.
Returns:
st_dev -> FileSystem(device, mount_point) | [
"Creates",
"a",
"map",
"of",
"mounted",
"filesystems",
"on",
"the",
"machine",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/diskspace/diskspace.py#L112-L181 |
236,211 | python-diamond/Diamond | src/diamond/handler/libratohandler.py | LibratoHandler.process | def process(self, metric):
"""
Process a metric by sending it to Librato
"""
path = metric.getCollectorPath()
path += '.'
path += metric.getMetricPath()
if self.config['apply_metric_prefix']:
path = metric.getPathPrefix() + '.' + path
if self.include_reg.match(path):
if metric.metric_type == 'GAUGE':
m_type = 'gauge'
else:
m_type = 'counter'
self.queue.add(path, # name
float(metric.value), # value
type=m_type,
source=metric.host,
measure_time=metric.timestamp)
self.current_n_measurements += 1
else:
self.log.debug("LibratoHandler: Skip %s, no include_filters match",
path)
if (self.current_n_measurements >= self.queue_max_size or
time.time() >= self.queue_max_timestamp):
self.log.debug("LibratoHandler: Sending batch size: %d",
self.current_n_measurements)
self._send() | python | def process(self, metric):
path = metric.getCollectorPath()
path += '.'
path += metric.getMetricPath()
if self.config['apply_metric_prefix']:
path = metric.getPathPrefix() + '.' + path
if self.include_reg.match(path):
if metric.metric_type == 'GAUGE':
m_type = 'gauge'
else:
m_type = 'counter'
self.queue.add(path, # name
float(metric.value), # value
type=m_type,
source=metric.host,
measure_time=metric.timestamp)
self.current_n_measurements += 1
else:
self.log.debug("LibratoHandler: Skip %s, no include_filters match",
path)
if (self.current_n_measurements >= self.queue_max_size or
time.time() >= self.queue_max_timestamp):
self.log.debug("LibratoHandler: Sending batch size: %d",
self.current_n_measurements)
self._send() | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"path",
"=",
"metric",
".",
"getCollectorPath",
"(",
")",
"path",
"+=",
"'.'",
"path",
"+=",
"metric",
".",
"getMetricPath",
"(",
")",
"if",
"self",
".",
"config",
"[",
"'apply_metric_prefix'",
"]",... | Process a metric by sending it to Librato | [
"Process",
"a",
"metric",
"by",
"sending",
"it",
"to",
"Librato"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/libratohandler.py#L98-L127 |
236,212 | python-diamond/Diamond | src/diamond/handler/libratohandler.py | LibratoHandler._send | def _send(self):
"""
Send data to Librato.
"""
self.queue.submit()
self.queue_max_timestamp = int(time.time() + self.queue_max_interval)
self.current_n_measurements = 0 | python | def _send(self):
self.queue.submit()
self.queue_max_timestamp = int(time.time() + self.queue_max_interval)
self.current_n_measurements = 0 | [
"def",
"_send",
"(",
"self",
")",
":",
"self",
".",
"queue",
".",
"submit",
"(",
")",
"self",
".",
"queue_max_timestamp",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
"+",
"self",
".",
"queue_max_interval",
")",
"self",
".",
"current_n_measurements",
... | Send data to Librato. | [
"Send",
"data",
"to",
"Librato",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/libratohandler.py#L133-L139 |
236,213 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector.collect | def collect(self):
"""
Collect and publish metrics
"""
stats = self.parse_stats_file(self.config["status_path"])
if len(stats) == 0:
return {}
elif "info" not in stats.keys():
return {}
elif "programstatus" not in stats.keys():
return {}
metrics = self.get_icinga_stats(stats["programstatus"])
if "hoststatus" in stats.keys():
metrics = dict(
metrics.items() + self.get_host_stats(
stats["hoststatus"]).items())
if "servicestatus" in stats.keys():
metrics = dict(
metrics.items() + self.get_svc_stats(
stats["servicestatus"]).items())
for metric in metrics.keys():
self.log.debug("Publishing '%s %s'.", metric, metrics[metric])
self.publish(metric, metrics[metric]) | python | def collect(self):
stats = self.parse_stats_file(self.config["status_path"])
if len(stats) == 0:
return {}
elif "info" not in stats.keys():
return {}
elif "programstatus" not in stats.keys():
return {}
metrics = self.get_icinga_stats(stats["programstatus"])
if "hoststatus" in stats.keys():
metrics = dict(
metrics.items() + self.get_host_stats(
stats["hoststatus"]).items())
if "servicestatus" in stats.keys():
metrics = dict(
metrics.items() + self.get_svc_stats(
stats["servicestatus"]).items())
for metric in metrics.keys():
self.log.debug("Publishing '%s %s'.", metric, metrics[metric])
self.publish(metric, metrics[metric]) | [
"def",
"collect",
"(",
"self",
")",
":",
"stats",
"=",
"self",
".",
"parse_stats_file",
"(",
"self",
".",
"config",
"[",
"\"status_path\"",
"]",
")",
"if",
"len",
"(",
"stats",
")",
"==",
"0",
":",
"return",
"{",
"}",
"elif",
"\"info\"",
"not",
"in",... | Collect and publish metrics | [
"Collect",
"and",
"publish",
"metrics"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L19-L44 |
236,214 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector.get_default_config | def get_default_config(self):
"""
Returns default settings for collector
"""
config = super(IcingaStatsCollector, self).get_default_config()
config.update({
"path": "icinga_stats",
"status_path": "/var/lib/icinga/status.dat",
})
return config | python | def get_default_config(self):
config = super(IcingaStatsCollector, self).get_default_config()
config.update({
"path": "icinga_stats",
"status_path": "/var/lib/icinga/status.dat",
})
return config | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"IcingaStatsCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"\"path\"",
":",
"\"icinga_stats\"",
",",
"\"status_path\"",
":",... | Returns default settings for collector | [
"Returns",
"default",
"settings",
"for",
"collector"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L57-L66 |
236,215 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector.get_icinga_stats | def get_icinga_stats(self, app_stats):
""" Extract metrics from 'programstatus' """
stats = {}
stats = dict(stats.items() + self._get_active_stats(app_stats).items())
stats = dict(stats.items() + self._get_cached_stats(app_stats).items())
stats = dict(
stats.items() + self._get_command_execution(app_stats).items())
stats = dict(
stats.items() + self._get_externalcmd_stats(app_stats).items())
stats["uptime"] = self._get_uptime(app_stats)
return stats | python | def get_icinga_stats(self, app_stats):
stats = {}
stats = dict(stats.items() + self._get_active_stats(app_stats).items())
stats = dict(stats.items() + self._get_cached_stats(app_stats).items())
stats = dict(
stats.items() + self._get_command_execution(app_stats).items())
stats = dict(
stats.items() + self._get_externalcmd_stats(app_stats).items())
stats["uptime"] = self._get_uptime(app_stats)
return stats | [
"def",
"get_icinga_stats",
"(",
"self",
",",
"app_stats",
")",
":",
"stats",
"=",
"{",
"}",
"stats",
"=",
"dict",
"(",
"stats",
".",
"items",
"(",
")",
"+",
"self",
".",
"_get_active_stats",
"(",
"app_stats",
")",
".",
"items",
"(",
")",
")",
"stats"... | Extract metrics from 'programstatus' | [
"Extract",
"metrics",
"from",
"programstatus"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L68-L78 |
236,216 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector.parse_stats_file | def parse_stats_file(self, file_name):
""" Read and parse given file_name, return config as a dictionary """
stats = {}
try:
with open(file_name, "r") as fhandle:
fbuffer = []
save_buffer = False
for line in fhandle:
line = line.rstrip("\n")
line = self._trim(line)
if line == "" or line.startswith("#"):
continue
elif line.endswith("{"):
save_buffer = True
fbuffer.append(line)
continue
elif line.endswith("}"):
tmp_dict = self._parse_config_buffer(fbuffer)
fbuffer = None
fbuffer = list()
if len(tmp_dict) < 1:
continue
if tmp_dict["_type"] == "info":
stats["info"] = tmp_dict
elif tmp_dict["_type"] == "programstatus":
stats["programstatus"] = tmp_dict
else:
entity_type = tmp_dict["_type"]
if entity_type not in stats.keys():
stats[entity_type] = []
stats[entity_type].append(tmp_dict)
continue
elif save_buffer is True:
fbuffer.append(line)
except Exception as exception:
self.log.info("Caught exception: %s", exception)
return stats | python | def parse_stats_file(self, file_name):
stats = {}
try:
with open(file_name, "r") as fhandle:
fbuffer = []
save_buffer = False
for line in fhandle:
line = line.rstrip("\n")
line = self._trim(line)
if line == "" or line.startswith("#"):
continue
elif line.endswith("{"):
save_buffer = True
fbuffer.append(line)
continue
elif line.endswith("}"):
tmp_dict = self._parse_config_buffer(fbuffer)
fbuffer = None
fbuffer = list()
if len(tmp_dict) < 1:
continue
if tmp_dict["_type"] == "info":
stats["info"] = tmp_dict
elif tmp_dict["_type"] == "programstatus":
stats["programstatus"] = tmp_dict
else:
entity_type = tmp_dict["_type"]
if entity_type not in stats.keys():
stats[entity_type] = []
stats[entity_type].append(tmp_dict)
continue
elif save_buffer is True:
fbuffer.append(line)
except Exception as exception:
self.log.info("Caught exception: %s", exception)
return stats | [
"def",
"parse_stats_file",
"(",
"self",
",",
"file_name",
")",
":",
"stats",
"=",
"{",
"}",
"try",
":",
"with",
"open",
"(",
"file_name",
",",
"\"r\"",
")",
"as",
"fhandle",
":",
"fbuffer",
"=",
"[",
"]",
"save_buffer",
"=",
"False",
"for",
"line",
"... | Read and parse given file_name, return config as a dictionary | [
"Read",
"and",
"parse",
"given",
"file_name",
"return",
"config",
"as",
"a",
"dictionary"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L80-L121 |
236,217 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector.get_host_stats | def get_host_stats(self, hosts):
""" Get statistics for Hosts, resp. Host entities """
stats = {
"hosts.total": 0,
"hosts.ok": 0,
"hosts.down": 0,
"hosts.unreachable": 0,
"hosts.flapping": 0,
"hosts.in_downtime": 0,
"hosts.checked": 0,
"hosts.scheduled": 0,
"hosts.active_checks": 0,
"hosts.passive_checks": 0,
}
for host in list(hosts):
if type(host) is not dict:
continue
sane = self._sanitize_entity(host)
stats["hosts.total"] += 1
stats["hosts.flapping"] += self._trans_binary(sane["flapping"])
stats[
"hosts.in_downtime"] += self._trans_dtime(sane["in_downtime"])
stats["hosts.checked"] += self._trans_binary(sane["checked"])
stats["hosts.scheduled"] += self._trans_binary(sane["scheduled"])
stats["hosts.active_checks"] += sane["active_checks"]
stats["hosts.passive_checks"] += sane["passive_checks"]
state_key = self._trans_host_state(sane["state"])
stats["hosts.%s" % (state_key)] += 1
return stats | python | def get_host_stats(self, hosts):
stats = {
"hosts.total": 0,
"hosts.ok": 0,
"hosts.down": 0,
"hosts.unreachable": 0,
"hosts.flapping": 0,
"hosts.in_downtime": 0,
"hosts.checked": 0,
"hosts.scheduled": 0,
"hosts.active_checks": 0,
"hosts.passive_checks": 0,
}
for host in list(hosts):
if type(host) is not dict:
continue
sane = self._sanitize_entity(host)
stats["hosts.total"] += 1
stats["hosts.flapping"] += self._trans_binary(sane["flapping"])
stats[
"hosts.in_downtime"] += self._trans_dtime(sane["in_downtime"])
stats["hosts.checked"] += self._trans_binary(sane["checked"])
stats["hosts.scheduled"] += self._trans_binary(sane["scheduled"])
stats["hosts.active_checks"] += sane["active_checks"]
stats["hosts.passive_checks"] += sane["passive_checks"]
state_key = self._trans_host_state(sane["state"])
stats["hosts.%s" % (state_key)] += 1
return stats | [
"def",
"get_host_stats",
"(",
"self",
",",
"hosts",
")",
":",
"stats",
"=",
"{",
"\"hosts.total\"",
":",
"0",
",",
"\"hosts.ok\"",
":",
"0",
",",
"\"hosts.down\"",
":",
"0",
",",
"\"hosts.unreachable\"",
":",
"0",
",",
"\"hosts.flapping\"",
":",
"0",
",",
... | Get statistics for Hosts, resp. Host entities | [
"Get",
"statistics",
"for",
"Hosts",
"resp",
".",
"Host",
"entities"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L123-L153 |
236,218 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector.get_svc_stats | def get_svc_stats(self, svcs):
""" Get statistics for Services, resp. Service entities """
stats = {
"services.total": 0,
"services.ok": 0,
"services.warning": 0,
"services.critical": 0,
"services.unknown": 0,
"services.flapping": 0,
"services.in_downtime": 0,
"services.checked": 0,
"services.scheduled": 0,
"services.active_checks": 0,
"services.passive_checks": 0,
}
for svc in svcs:
if type(svc) is not dict:
continue
sane = self._sanitize_entity(svc)
stats["services.total"] += 1
stats["services.flapping"] += self._trans_binary(sane["flapping"])
stats["services.in_downtime"] += self._trans_dtime(
sane["in_downtime"])
stats["services.checked"] += self._trans_binary(sane["checked"])
stats[
"services.scheduled"] += self._trans_binary(sane["scheduled"])
stats["services.active_checks"] += sane["active_checks"]
stats["services.passive_checks"] += sane["passive_checks"]
state_key = self._trans_svc_state(sane["state"])
stats["services.%s" % (state_key)] += 1
return stats | python | def get_svc_stats(self, svcs):
stats = {
"services.total": 0,
"services.ok": 0,
"services.warning": 0,
"services.critical": 0,
"services.unknown": 0,
"services.flapping": 0,
"services.in_downtime": 0,
"services.checked": 0,
"services.scheduled": 0,
"services.active_checks": 0,
"services.passive_checks": 0,
}
for svc in svcs:
if type(svc) is not dict:
continue
sane = self._sanitize_entity(svc)
stats["services.total"] += 1
stats["services.flapping"] += self._trans_binary(sane["flapping"])
stats["services.in_downtime"] += self._trans_dtime(
sane["in_downtime"])
stats["services.checked"] += self._trans_binary(sane["checked"])
stats[
"services.scheduled"] += self._trans_binary(sane["scheduled"])
stats["services.active_checks"] += sane["active_checks"]
stats["services.passive_checks"] += sane["passive_checks"]
state_key = self._trans_svc_state(sane["state"])
stats["services.%s" % (state_key)] += 1
return stats | [
"def",
"get_svc_stats",
"(",
"self",
",",
"svcs",
")",
":",
"stats",
"=",
"{",
"\"services.total\"",
":",
"0",
",",
"\"services.ok\"",
":",
"0",
",",
"\"services.warning\"",
":",
"0",
",",
"\"services.critical\"",
":",
"0",
",",
"\"services.unknown\"",
":",
... | Get statistics for Services, resp. Service entities | [
"Get",
"statistics",
"for",
"Services",
"resp",
".",
"Service",
"entities"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L155-L187 |
236,219 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector._convert_tripplet | def _convert_tripplet(self, tripplet):
""" Turn '10,178,528' into tuple of integers """
splitted = tripplet.split(",")
if len(splitted) != 3:
self.log.debug("Got %i chunks, expected 3.", len(splitted))
return (0, 0, 0)
try:
x01 = int(splitted[0])
x05 = int(splitted[1])
x15 = int(splitted[2])
except Exception as exception:
self.log.warning("Caught exception: %s", exception)
x01 = 0
x05 = 0
x15 = 0
return (x01, x05, x15) | python | def _convert_tripplet(self, tripplet):
splitted = tripplet.split(",")
if len(splitted) != 3:
self.log.debug("Got %i chunks, expected 3.", len(splitted))
return (0, 0, 0)
try:
x01 = int(splitted[0])
x05 = int(splitted[1])
x15 = int(splitted[2])
except Exception as exception:
self.log.warning("Caught exception: %s", exception)
x01 = 0
x05 = 0
x15 = 0
return (x01, x05, x15) | [
"def",
"_convert_tripplet",
"(",
"self",
",",
"tripplet",
")",
":",
"splitted",
"=",
"tripplet",
".",
"split",
"(",
"\",\"",
")",
"if",
"len",
"(",
"splitted",
")",
"!=",
"3",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Got %i chunks, expected 3.\"",
... | Turn '10,178,528' into tuple of integers | [
"Turn",
"10",
"178",
"528",
"into",
"tuple",
"of",
"integers"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L189-L206 |
236,220 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector._get_uptime | def _get_uptime(self, app_stats):
""" Return Icinga's uptime """
if "program_start" not in app_stats.keys():
return 0
if not app_stats["program_start"].isdigit():
return 0
uptime = int(time.time()) - int(app_stats["program_start"])
if uptime < 0:
return 0
return uptime | python | def _get_uptime(self, app_stats):
if "program_start" not in app_stats.keys():
return 0
if not app_stats["program_start"].isdigit():
return 0
uptime = int(time.time()) - int(app_stats["program_start"])
if uptime < 0:
return 0
return uptime | [
"def",
"_get_uptime",
"(",
"self",
",",
"app_stats",
")",
":",
"if",
"\"program_start\"",
"not",
"in",
"app_stats",
".",
"keys",
"(",
")",
":",
"return",
"0",
"if",
"not",
"app_stats",
"[",
"\"program_start\"",
"]",
".",
"isdigit",
"(",
")",
":",
"return... | Return Icinga's uptime | [
"Return",
"Icinga",
"s",
"uptime"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L323-L335 |
236,221 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector._parse_config_buffer | def _parse_config_buffer(self, fbuffer):
""" Parse buffered chunk of config into dict """
if len(fbuffer) < 1 or not fbuffer[0].endswith("{"):
# Invalid input
return {}
entity = {}
entity_type = fbuffer.pop(0)
entity_type = entity_type.rstrip("{")
entity["_type"] = self._trim(entity_type)
for chunk in fbuffer:
splitted = chunk.split("=")
if len(splitted) < 2:
# If there is no '=', then it's an invalid line
continue
key = self._trim(splitted[0])
value = self._trim("=".join(splitted[1:]))
entity[key] = value
return entity | python | def _parse_config_buffer(self, fbuffer):
if len(fbuffer) < 1 or not fbuffer[0].endswith("{"):
# Invalid input
return {}
entity = {}
entity_type = fbuffer.pop(0)
entity_type = entity_type.rstrip("{")
entity["_type"] = self._trim(entity_type)
for chunk in fbuffer:
splitted = chunk.split("=")
if len(splitted) < 2:
# If there is no '=', then it's an invalid line
continue
key = self._trim(splitted[0])
value = self._trim("=".join(splitted[1:]))
entity[key] = value
return entity | [
"def",
"_parse_config_buffer",
"(",
"self",
",",
"fbuffer",
")",
":",
"if",
"len",
"(",
"fbuffer",
")",
"<",
"1",
"or",
"not",
"fbuffer",
"[",
"0",
"]",
".",
"endswith",
"(",
"\"{\"",
")",
":",
"# Invalid input",
"return",
"{",
"}",
"entity",
"=",
"{... | Parse buffered chunk of config into dict | [
"Parse",
"buffered",
"chunk",
"of",
"config",
"into",
"dict"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L337-L357 |
236,222 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector._sanitize_entity | def _sanitize_entity(self, entity):
"""
Make given entity 'sane' for further use.
"""
aliases = {
"current_state": "state",
"is_flapping": "flapping",
"scheduled_downtime_depth": "in_downtime",
"has_been_checked": "checked",
"should_be_scheduled": "scheduled",
"active_checks_enabled": "active_checks",
"passive_checks_enabled": "passive_checks",
}
sane = {}
for akey in aliases.keys():
sane[aliases[akey]] = None
aliases_keys = aliases.keys()
for key in entity.keys():
if key not in aliases_keys:
continue
alias = aliases[key]
try:
sane[alias] = int(entity[key])
except Exception:
sane[alias] = None
if sane["active_checks"] not in [0, 1]:
sane["active_checks"] = 0
elif sane["active_checks"] == 1:
sane["passive_checks"] = 0
if sane["passive_checks"] not in [0, 1]:
sane["passive_checks"] = 0
return sane | python | def _sanitize_entity(self, entity):
aliases = {
"current_state": "state",
"is_flapping": "flapping",
"scheduled_downtime_depth": "in_downtime",
"has_been_checked": "checked",
"should_be_scheduled": "scheduled",
"active_checks_enabled": "active_checks",
"passive_checks_enabled": "passive_checks",
}
sane = {}
for akey in aliases.keys():
sane[aliases[akey]] = None
aliases_keys = aliases.keys()
for key in entity.keys():
if key not in aliases_keys:
continue
alias = aliases[key]
try:
sane[alias] = int(entity[key])
except Exception:
sane[alias] = None
if sane["active_checks"] not in [0, 1]:
sane["active_checks"] = 0
elif sane["active_checks"] == 1:
sane["passive_checks"] = 0
if sane["passive_checks"] not in [0, 1]:
sane["passive_checks"] = 0
return sane | [
"def",
"_sanitize_entity",
"(",
"self",
",",
"entity",
")",
":",
"aliases",
"=",
"{",
"\"current_state\"",
":",
"\"state\"",
",",
"\"is_flapping\"",
":",
"\"flapping\"",
",",
"\"scheduled_downtime_depth\"",
":",
"\"in_downtime\"",
",",
"\"has_been_checked\"",
":",
"... | Make given entity 'sane' for further use. | [
"Make",
"given",
"entity",
"sane",
"for",
"further",
"use",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L359-L395 |
236,223 | python-diamond/Diamond | src/collectors/icinga_stats/icinga_stats.py | IcingaStatsCollector._trim | def _trim(self, somestr):
""" Trim left-right given string """
tmp = RE_LSPACES.sub("", somestr)
tmp = RE_TSPACES.sub("", tmp)
return str(tmp) | python | def _trim(self, somestr):
tmp = RE_LSPACES.sub("", somestr)
tmp = RE_TSPACES.sub("", tmp)
return str(tmp) | [
"def",
"_trim",
"(",
"self",
",",
"somestr",
")",
":",
"tmp",
"=",
"RE_LSPACES",
".",
"sub",
"(",
"\"\"",
",",
"somestr",
")",
"tmp",
"=",
"RE_TSPACES",
".",
"sub",
"(",
"\"\"",
",",
"tmp",
")",
"return",
"str",
"(",
"tmp",
")"
] | Trim left-right given string | [
"Trim",
"left",
"-",
"right",
"given",
"string"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/icinga_stats/icinga_stats.py#L441-L445 |
236,224 | python-diamond/Diamond | src/collectors/jolokia/jolokia.py | JolokiaCollector._list_request | def _list_request(self):
"""Returns a dictionary with JMX domain names as keys"""
try:
# https://jolokia.org/reference/html/protocol.html
#
# A maxDepth of 1 restricts the return value to a map with the JMX
# domains as keys. The values of the maps don't have any meaning
# and are dummy values.
#
# maxCollectionSize=0 means "unlimited". This works around an issue
# prior to Jolokia 1.3 where results were truncated at 1000
#
url = "http://%s:%s/%s%s?maxDepth=1&maxCollectionSize=0" % (
self.config['host'],
self.config['port'],
self.jolokia_path,
self.LIST_URL)
# need some time to process the downloaded metrics, so that's why
# timeout is lower than the interval.
timeout = max(2, float(self.config['interval']) * 2 / 3)
with closing(urllib2.urlopen(self._create_request(url),
timeout=timeout)) as response:
return self._read_json(response)
except (urllib2.HTTPError, ValueError) as e:
self.log.error('Unable to read JSON response: %s', str(e))
return {} | python | def _list_request(self):
try:
# https://jolokia.org/reference/html/protocol.html
#
# A maxDepth of 1 restricts the return value to a map with the JMX
# domains as keys. The values of the maps don't have any meaning
# and are dummy values.
#
# maxCollectionSize=0 means "unlimited". This works around an issue
# prior to Jolokia 1.3 where results were truncated at 1000
#
url = "http://%s:%s/%s%s?maxDepth=1&maxCollectionSize=0" % (
self.config['host'],
self.config['port'],
self.jolokia_path,
self.LIST_URL)
# need some time to process the downloaded metrics, so that's why
# timeout is lower than the interval.
timeout = max(2, float(self.config['interval']) * 2 / 3)
with closing(urllib2.urlopen(self._create_request(url),
timeout=timeout)) as response:
return self._read_json(response)
except (urllib2.HTTPError, ValueError) as e:
self.log.error('Unable to read JSON response: %s', str(e))
return {} | [
"def",
"_list_request",
"(",
"self",
")",
":",
"try",
":",
"# https://jolokia.org/reference/html/protocol.html",
"#",
"# A maxDepth of 1 restricts the return value to a map with the JMX",
"# domains as keys. The values of the maps don't have any meaning",
"# and are dummy values.",
"#",
... | Returns a dictionary with JMX domain names as keys | [
"Returns",
"a",
"dictionary",
"with",
"JMX",
"domain",
"names",
"as",
"keys"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jolokia/jolokia.py#L213-L238 |
236,225 | python-diamond/Diamond | src/collectors/cephstats/cephstats.py | CephStatsCollector._get_stats | def _get_stats(self):
"""
Get ceph stats
"""
try:
output = subprocess.check_output(['ceph', '-s'])
except subprocess.CalledProcessError as err:
self.log.info(
'Could not get stats: %s' % err)
self.log.exception('Could not get stats')
return {}
return process_ceph_status(output) | python | def _get_stats(self):
try:
output = subprocess.check_output(['ceph', '-s'])
except subprocess.CalledProcessError as err:
self.log.info(
'Could not get stats: %s' % err)
self.log.exception('Could not get stats')
return {}
return process_ceph_status(output) | [
"def",
"_get_stats",
"(",
"self",
")",
":",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ceph'",
",",
"'-s'",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"err",
":",
"self",
".",
"log",
".",
"info",
"... | Get ceph stats | [
"Get",
"ceph",
"stats"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/cephstats/cephstats.py#L65-L76 |
236,226 | python-diamond/Diamond | src/collectors/filestat/filestat.py | FilestatCollector.process_lsof | def process_lsof(self, users, types):
"""
Get the list of users and file types to collect for and collect the
data from lsof
"""
d = {}
for u in users:
d[u] = {}
tmp = os.popen("lsof -wbu %s | awk '{ print $5 }'" % (
u)).read().split()
for t in types:
d[u][t] = tmp.count(t)
return d | python | def process_lsof(self, users, types):
d = {}
for u in users:
d[u] = {}
tmp = os.popen("lsof -wbu %s | awk '{ print $5 }'" % (
u)).read().split()
for t in types:
d[u][t] = tmp.count(t)
return d | [
"def",
"process_lsof",
"(",
"self",
",",
"users",
",",
"types",
")",
":",
"d",
"=",
"{",
"}",
"for",
"u",
"in",
"users",
":",
"d",
"[",
"u",
"]",
"=",
"{",
"}",
"tmp",
"=",
"os",
".",
"popen",
"(",
"\"lsof -wbu %s | awk '{ print $5 }'\"",
"%",
"(",... | Get the list of users and file types to collect for and collect the
data from lsof | [
"Get",
"the",
"list",
"of",
"users",
"and",
"file",
"types",
"to",
"collect",
"for",
"and",
"collect",
"the",
"data",
"from",
"lsof"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/filestat/filestat.py#L231-L243 |
236,227 | python-diamond/Diamond | src/collectors/nfacct/nfacct.py | NetfilterAccountingCollector.collect | def collect(self):
"""
Collect and publish netfilter counters
"""
cmd = [self.config['bin'], "list"]
if str_to_bool(self.config['reset']):
cmd.append("reset")
if str_to_bool(self.config['use_sudo']):
cmd.insert(0, self.config['sudo_cmd'])
# We avoid use of the XML format to mtaintain compatbility with older
# versions of nfacct and also to avoid the bug where pkts and bytes were
# flipped
# Each line is of the format:
# { pkts = 00000000000001121700, bytes = 00000000000587037355 } = ipv4;
matcher = re.compile("{ pkts = (.*), bytes = (.*) } = (.*);")
lines = Popen(cmd, stdout=PIPE).communicate()[0].strip().splitlines()
for line in lines:
matches = re.match(matcher, line)
if matches:
num_packets = int(matches.group(1))
num_bytes = int(matches.group(2))
name = matches.group(3)
self.publish(name + ".pkts", num_packets)
self.publish(name + ".bytes", num_bytes) | python | def collect(self):
cmd = [self.config['bin'], "list"]
if str_to_bool(self.config['reset']):
cmd.append("reset")
if str_to_bool(self.config['use_sudo']):
cmd.insert(0, self.config['sudo_cmd'])
# We avoid use of the XML format to mtaintain compatbility with older
# versions of nfacct and also to avoid the bug where pkts and bytes were
# flipped
# Each line is of the format:
# { pkts = 00000000000001121700, bytes = 00000000000587037355 } = ipv4;
matcher = re.compile("{ pkts = (.*), bytes = (.*) } = (.*);")
lines = Popen(cmd, stdout=PIPE).communicate()[0].strip().splitlines()
for line in lines:
matches = re.match(matcher, line)
if matches:
num_packets = int(matches.group(1))
num_bytes = int(matches.group(2))
name = matches.group(3)
self.publish(name + ".pkts", num_packets)
self.publish(name + ".bytes", num_bytes) | [
"def",
"collect",
"(",
"self",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"config",
"[",
"'bin'",
"]",
",",
"\"list\"",
"]",
"if",
"str_to_bool",
"(",
"self",
".",
"config",
"[",
"'reset'",
"]",
")",
":",
"cmd",
".",
"append",
"(",
"\"reset\"",
")",
... | Collect and publish netfilter counters | [
"Collect",
"and",
"publish",
"netfilter",
"counters"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nfacct/nfacct.py#L47-L75 |
236,228 | python-diamond/Diamond | src/collectors/openvpn/openvpn.py | OpenVPNCollector.parse_url | def parse_url(self, uri):
"""
Convert urlparse from a python 2.4 layout to a python 2.7 layout
"""
parsed = urlparse.urlparse(uri)
if 'scheme' not in parsed:
class Object(object):
pass
newparsed = Object()
newparsed.scheme = parsed[0]
newparsed.netloc = parsed[1]
newparsed.path = parsed[2]
newparsed.params = parsed[3]
newparsed.query = parsed[4]
newparsed.fragment = parsed[5]
newparsed.username = ''
newparsed.password = ''
newparsed.hostname = ''
newparsed.port = ''
parsed = newparsed
return parsed | python | def parse_url(self, uri):
parsed = urlparse.urlparse(uri)
if 'scheme' not in parsed:
class Object(object):
pass
newparsed = Object()
newparsed.scheme = parsed[0]
newparsed.netloc = parsed[1]
newparsed.path = parsed[2]
newparsed.params = parsed[3]
newparsed.query = parsed[4]
newparsed.fragment = parsed[5]
newparsed.username = ''
newparsed.password = ''
newparsed.hostname = ''
newparsed.port = ''
parsed = newparsed
return parsed | [
"def",
"parse_url",
"(",
"self",
",",
"uri",
")",
":",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"uri",
")",
"if",
"'scheme'",
"not",
"in",
"parsed",
":",
"class",
"Object",
"(",
"object",
")",
":",
"pass",
"newparsed",
"=",
"Object",
"(",
")"... | Convert urlparse from a python 2.4 layout to a python 2.7 layout | [
"Convert",
"urlparse",
"from",
"a",
"python",
"2",
".",
"4",
"layout",
"to",
"a",
"python",
"2",
".",
"7",
"layout"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/openvpn/openvpn.py#L66-L86 |
236,229 | python-diamond/Diamond | src/collectors/jcollectd/jcollectd.py | sanitize_word | def sanitize_word(s):
"""Remove non-alphanumerical characters from metric word.
And trim excessive underscores.
"""
s = re.sub('[^\w-]+', '_', s)
s = re.sub('__+', '_', s)
return s.strip('_') | python | def sanitize_word(s):
s = re.sub('[^\w-]+', '_', s)
s = re.sub('__+', '_', s)
return s.strip('_') | [
"def",
"sanitize_word",
"(",
"s",
")",
":",
"s",
"=",
"re",
".",
"sub",
"(",
"'[^\\w-]+'",
",",
"'_'",
",",
"s",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"'__+'",
",",
"'_'",
",",
"s",
")",
"return",
"s",
".",
"strip",
"(",
"'_'",
")"
] | Remove non-alphanumerical characters from metric word.
And trim excessive underscores. | [
"Remove",
"non",
"-",
"alphanumerical",
"characters",
"from",
"metric",
"word",
".",
"And",
"trim",
"excessive",
"underscores",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/jcollectd.py#L197-L203 |
236,230 | python-diamond/Diamond | src/collectors/mesos/mesos.py | MesosCollector._add_cpu_usage | def _add_cpu_usage(self, cur_read):
"""Compute cpu usage based on cpu time spent compared to elapsed time
"""
for executor_id, cur_data in cur_read.items():
if executor_id in self.executors_prev_read:
prev_data = self.executors_prev_read[executor_id]
prev_stats = prev_data['statistics']
cur_stats = cur_data['statistics']
# from sum of current cpus time subtract previous sum
cpus_time_diff_s = cur_stats['cpus_user_time_secs']
cpus_time_diff_s += cur_stats['cpus_system_time_secs']
cpus_time_diff_s -= prev_stats['cpus_user_time_secs']
cpus_time_diff_s -= prev_stats['cpus_system_time_secs']
ts_diff = cur_stats['timestamp'] - prev_stats['timestamp']
if ts_diff != 0:
cur_stats['cpus_utilisation'] = cpus_time_diff_s / ts_diff
self.executors_prev_read[executor_id] = cur_read[executor_id] | python | def _add_cpu_usage(self, cur_read):
for executor_id, cur_data in cur_read.items():
if executor_id in self.executors_prev_read:
prev_data = self.executors_prev_read[executor_id]
prev_stats = prev_data['statistics']
cur_stats = cur_data['statistics']
# from sum of current cpus time subtract previous sum
cpus_time_diff_s = cur_stats['cpus_user_time_secs']
cpus_time_diff_s += cur_stats['cpus_system_time_secs']
cpus_time_diff_s -= prev_stats['cpus_user_time_secs']
cpus_time_diff_s -= prev_stats['cpus_system_time_secs']
ts_diff = cur_stats['timestamp'] - prev_stats['timestamp']
if ts_diff != 0:
cur_stats['cpus_utilisation'] = cpus_time_diff_s / ts_diff
self.executors_prev_read[executor_id] = cur_read[executor_id] | [
"def",
"_add_cpu_usage",
"(",
"self",
",",
"cur_read",
")",
":",
"for",
"executor_id",
",",
"cur_data",
"in",
"cur_read",
".",
"items",
"(",
")",
":",
"if",
"executor_id",
"in",
"self",
".",
"executors_prev_read",
":",
"prev_data",
"=",
"self",
".",
"execu... | Compute cpu usage based on cpu time spent compared to elapsed time | [
"Compute",
"cpu",
"usage",
"based",
"on",
"cpu",
"time",
"spent",
"compared",
"to",
"elapsed",
"time"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mesos/mesos.py#L101-L119 |
236,231 | python-diamond/Diamond | src/collectors/mesos/mesos.py | MesosCollector._add_cpu_percent | def _add_cpu_percent(self, cur_read):
"""Compute cpu percent basing on the provided utilisation
"""
for executor_id, cur_data in cur_read.items():
stats = cur_data['statistics']
cpus_limit = stats.get('cpus_limit')
cpus_utilisation = stats.get('cpus_utilisation')
if cpus_utilisation and cpus_limit != 0:
stats['cpus_percent'] = cpus_utilisation / cpus_limit | python | def _add_cpu_percent(self, cur_read):
for executor_id, cur_data in cur_read.items():
stats = cur_data['statistics']
cpus_limit = stats.get('cpus_limit')
cpus_utilisation = stats.get('cpus_utilisation')
if cpus_utilisation and cpus_limit != 0:
stats['cpus_percent'] = cpus_utilisation / cpus_limit | [
"def",
"_add_cpu_percent",
"(",
"self",
",",
"cur_read",
")",
":",
"for",
"executor_id",
",",
"cur_data",
"in",
"cur_read",
".",
"items",
"(",
")",
":",
"stats",
"=",
"cur_data",
"[",
"'statistics'",
"]",
"cpus_limit",
"=",
"stats",
".",
"get",
"(",
"'cp... | Compute cpu percent basing on the provided utilisation | [
"Compute",
"cpu",
"percent",
"basing",
"on",
"the",
"provided",
"utilisation"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mesos/mesos.py#L121-L129 |
236,232 | python-diamond/Diamond | src/collectors/mesos/mesos.py | MesosCollector._add_mem_percent | def _add_mem_percent(self, cur_read):
"""Compute memory percent utilisation based on the
mem_rss_bytes and mem_limit_bytes
"""
for executor_id, cur_data in cur_read.items():
stats = cur_data['statistics']
mem_rss_bytes = stats.get('mem_rss_bytes')
mem_limit_bytes = stats.get('mem_limit_bytes')
if mem_rss_bytes and mem_limit_bytes != 0:
stats['mem_percent'] = mem_rss_bytes / float(mem_limit_bytes) | python | def _add_mem_percent(self, cur_read):
for executor_id, cur_data in cur_read.items():
stats = cur_data['statistics']
mem_rss_bytes = stats.get('mem_rss_bytes')
mem_limit_bytes = stats.get('mem_limit_bytes')
if mem_rss_bytes and mem_limit_bytes != 0:
stats['mem_percent'] = mem_rss_bytes / float(mem_limit_bytes) | [
"def",
"_add_mem_percent",
"(",
"self",
",",
"cur_read",
")",
":",
"for",
"executor_id",
",",
"cur_data",
"in",
"cur_read",
".",
"items",
"(",
")",
":",
"stats",
"=",
"cur_data",
"[",
"'statistics'",
"]",
"mem_rss_bytes",
"=",
"stats",
".",
"get",
"(",
"... | Compute memory percent utilisation based on the
mem_rss_bytes and mem_limit_bytes | [
"Compute",
"memory",
"percent",
"utilisation",
"based",
"on",
"the",
"mem_rss_bytes",
"and",
"mem_limit_bytes"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mesos/mesos.py#L131-L140 |
236,233 | python-diamond/Diamond | src/collectors/mesos/mesos.py | MesosCollector._group_and_publish_tasks_statistics | def _group_and_publish_tasks_statistics(self, result):
"""This function group statistics of same tasks by adding them.
It also add 'instances_count' statistic to get information about
how many instances is running on the server
Args:
result: result of mesos query. List of dictionaries with
'executor_id', 'framework_id' as a strings and 'statistics'
as dictionary of labeled numbers
"""
for i in result:
executor_id = i['executor_id']
i['executor_id'] = executor_id[:executor_id.rfind('.')]
i['statistics']['instances_count'] = 1
r = {}
for i in result:
executor_id = i['executor_id']
r[executor_id] = r.get(executor_id, {})
r[executor_id]['framework_id'] = i['framework_id']
r[executor_id]['statistics'] = r[executor_id].get('statistics', {})
r[executor_id]['statistics'] = self._sum_statistics(
i['statistics'], r[executor_id]['statistics'])
self._add_cpu_usage(r)
self._add_cpu_percent(r)
self._add_mem_percent(r)
self._publish(r) | python | def _group_and_publish_tasks_statistics(self, result):
for i in result:
executor_id = i['executor_id']
i['executor_id'] = executor_id[:executor_id.rfind('.')]
i['statistics']['instances_count'] = 1
r = {}
for i in result:
executor_id = i['executor_id']
r[executor_id] = r.get(executor_id, {})
r[executor_id]['framework_id'] = i['framework_id']
r[executor_id]['statistics'] = r[executor_id].get('statistics', {})
r[executor_id]['statistics'] = self._sum_statistics(
i['statistics'], r[executor_id]['statistics'])
self._add_cpu_usage(r)
self._add_cpu_percent(r)
self._add_mem_percent(r)
self._publish(r) | [
"def",
"_group_and_publish_tasks_statistics",
"(",
"self",
",",
"result",
")",
":",
"for",
"i",
"in",
"result",
":",
"executor_id",
"=",
"i",
"[",
"'executor_id'",
"]",
"i",
"[",
"'executor_id'",
"]",
"=",
"executor_id",
"[",
":",
"executor_id",
".",
"rfind"... | This function group statistics of same tasks by adding them.
It also add 'instances_count' statistic to get information about
how many instances is running on the server
Args:
result: result of mesos query. List of dictionaries with
'executor_id', 'framework_id' as a strings and 'statistics'
as dictionary of labeled numbers | [
"This",
"function",
"group",
"statistics",
"of",
"same",
"tasks",
"by",
"adding",
"them",
".",
"It",
"also",
"add",
"instances_count",
"statistic",
"to",
"get",
"information",
"about",
"how",
"many",
"instances",
"is",
"running",
"on",
"the",
"server"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mesos/mesos.py#L142-L169 |
236,234 | python-diamond/Diamond | src/collectors/mesos/mesos.py | MesosCollector._get | def _get(self, path):
"""
Execute a Mesos API call.
"""
url = self._get_url(path)
try:
response = urllib2.urlopen(url)
except Exception as err:
self.log.error("%s: %s", url, err)
return False
try:
doc = json.load(response)
except (TypeError, ValueError):
self.log.error("Unable to parse response from Mesos as a"
" json object")
return False
return doc | python | def _get(self, path):
url = self._get_url(path)
try:
response = urllib2.urlopen(url)
except Exception as err:
self.log.error("%s: %s", url, err)
return False
try:
doc = json.load(response)
except (TypeError, ValueError):
self.log.error("Unable to parse response from Mesos as a"
" json object")
return False
return doc | [
"def",
"_get",
"(",
"self",
",",
"path",
")",
":",
"url",
"=",
"self",
".",
"_get_url",
"(",
"path",
")",
"try",
":",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"except",
"Exception",
"as",
"err",
":",
"self",
".",
"log",
".",
"... | Execute a Mesos API call. | [
"Execute",
"a",
"Mesos",
"API",
"call",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mesos/mesos.py#L194-L212 |
236,235 | python-diamond/Diamond | src/collectors/postgres/postgres.py | PostgresqlCollector.get_default_config_help | def get_default_config_help(self):
"""
Return help text for collector
"""
config_help = super(PostgresqlCollector,
self).get_default_config_help()
config_help.update({
'host': 'Hostname',
'dbname': 'DB to connect to in order to get list of DBs in PgSQL',
'user': 'Username',
'password': 'Password',
'port': 'Port number',
'password_provider': "Whether to auth with supplied password or"
" .pgpass file <password|pgpass>",
'sslmode': 'Whether to use SSL - <disable|allow|require|...>',
'underscore': 'Convert _ to .',
'extended': 'Enable collection of extended database stats.',
'metrics': 'List of enabled metrics to collect',
'pg_version': "The version of postgres that you'll be monitoring"
" eg. in format 9.2",
'has_admin': 'Admin privileges are required to execute some'
' queries.',
})
return config_help | python | def get_default_config_help(self):
config_help = super(PostgresqlCollector,
self).get_default_config_help()
config_help.update({
'host': 'Hostname',
'dbname': 'DB to connect to in order to get list of DBs in PgSQL',
'user': 'Username',
'password': 'Password',
'port': 'Port number',
'password_provider': "Whether to auth with supplied password or"
" .pgpass file <password|pgpass>",
'sslmode': 'Whether to use SSL - <disable|allow|require|...>',
'underscore': 'Convert _ to .',
'extended': 'Enable collection of extended database stats.',
'metrics': 'List of enabled metrics to collect',
'pg_version': "The version of postgres that you'll be monitoring"
" eg. in format 9.2",
'has_admin': 'Admin privileges are required to execute some'
' queries.',
})
return config_help | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config_help",
"=",
"super",
"(",
"PostgresqlCollector",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config_help",
".",
"update",
"(",
"{",
"'host'",
":",
"'Hostname'",
",",
"'dbname'",
... | Return help text for collector | [
"Return",
"help",
"text",
"for",
"collector"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/postgres/postgres.py#L27-L50 |
236,236 | python-diamond/Diamond | src/collectors/postgres/postgres.py | PostgresqlCollector.collect | def collect(self):
"""
Do pre-flight checks, get list of db names, collect metrics, publish
"""
if psycopg2 is None:
self.log.error('Unable to import module psycopg2')
return {}
# Get list of databases
dbs = self._get_db_names()
if len(dbs) == 0:
self.log.error("I have 0 databases!")
return {}
if self.config['metrics']:
metrics = self.config['metrics']
elif str_to_bool(self.config['extended']):
metrics = registry['extended']
if str_to_bool(self.config['has_admin']) \
and 'WalSegmentStats' not in metrics:
metrics.append('WalSegmentStats')
else:
metrics = registry['basic']
# Iterate every QueryStats class
for metric_name in set(metrics):
if metric_name not in metrics_registry:
self.log.error(
'metric_name %s not found in metric registry' % metric_name)
continue
for dbase in dbs:
conn = self._connect(database=dbase)
try:
klass = metrics_registry[metric_name]
stat = klass(dbase, conn,
underscore=self.config['underscore'])
stat.fetch(self.config['pg_version'])
for metric, value in stat:
if value is not None:
self.publish(metric, value)
# Setting multi_db to True will run this query on all known
# databases. This is bad for queries that hit views like
# pg_database, which are shared across databases.
#
# If multi_db is False, bail early after the first query
# iteration. Otherwise, continue to remaining databases.
if stat.multi_db is False:
break
finally:
conn.close() | python | def collect(self):
if psycopg2 is None:
self.log.error('Unable to import module psycopg2')
return {}
# Get list of databases
dbs = self._get_db_names()
if len(dbs) == 0:
self.log.error("I have 0 databases!")
return {}
if self.config['metrics']:
metrics = self.config['metrics']
elif str_to_bool(self.config['extended']):
metrics = registry['extended']
if str_to_bool(self.config['has_admin']) \
and 'WalSegmentStats' not in metrics:
metrics.append('WalSegmentStats')
else:
metrics = registry['basic']
# Iterate every QueryStats class
for metric_name in set(metrics):
if metric_name not in metrics_registry:
self.log.error(
'metric_name %s not found in metric registry' % metric_name)
continue
for dbase in dbs:
conn = self._connect(database=dbase)
try:
klass = metrics_registry[metric_name]
stat = klass(dbase, conn,
underscore=self.config['underscore'])
stat.fetch(self.config['pg_version'])
for metric, value in stat:
if value is not None:
self.publish(metric, value)
# Setting multi_db to True will run this query on all known
# databases. This is bad for queries that hit views like
# pg_database, which are shared across databases.
#
# If multi_db is False, bail early after the first query
# iteration. Otherwise, continue to remaining databases.
if stat.multi_db is False:
break
finally:
conn.close() | [
"def",
"collect",
"(",
"self",
")",
":",
"if",
"psycopg2",
"is",
"None",
":",
"self",
".",
"log",
".",
"error",
"(",
"'Unable to import module psycopg2'",
")",
"return",
"{",
"}",
"# Get list of databases",
"dbs",
"=",
"self",
".",
"_get_db_names",
"(",
")",... | Do pre-flight checks, get list of db names, collect metrics, publish | [
"Do",
"pre",
"-",
"flight",
"checks",
"get",
"list",
"of",
"db",
"names",
"collect",
"metrics",
"publish"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/postgres/postgres.py#L74-L126 |
236,237 | python-diamond/Diamond | src/collectors/postgres/postgres.py | PostgresqlCollector._get_db_names | def _get_db_names(self):
"""
Try to get a list of db names
"""
query = """
SELECT datname FROM pg_database
WHERE datallowconn AND NOT datistemplate
AND NOT datname='postgres' AND NOT datname='rdsadmin' ORDER BY 1
"""
conn = self._connect(self.config['dbname'])
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(query)
datnames = [d['datname'] for d in cursor.fetchall()]
conn.close()
# Exclude `postgres` database list, unless it is the
# only database available (required for querying pg_stat_database)
if not datnames:
datnames = ['postgres']
return datnames | python | def _get_db_names(self):
query = """
SELECT datname FROM pg_database
WHERE datallowconn AND NOT datistemplate
AND NOT datname='postgres' AND NOT datname='rdsadmin' ORDER BY 1
"""
conn = self._connect(self.config['dbname'])
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cursor.execute(query)
datnames = [d['datname'] for d in cursor.fetchall()]
conn.close()
# Exclude `postgres` database list, unless it is the
# only database available (required for querying pg_stat_database)
if not datnames:
datnames = ['postgres']
return datnames | [
"def",
"_get_db_names",
"(",
"self",
")",
":",
"query",
"=",
"\"\"\"\n SELECT datname FROM pg_database\n WHERE datallowconn AND NOT datistemplate\n AND NOT datname='postgres' AND NOT datname='rdsadmin' ORDER BY 1\n \"\"\"",
"conn",
"=",
"self",
".",
... | Try to get a list of db names | [
"Try",
"to",
"get",
"a",
"list",
"of",
"db",
"names"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/postgres/postgres.py#L128-L148 |
236,238 | python-diamond/Diamond | src/collectors/postgres/postgres.py | PostgresqlCollector._connect | def _connect(self, database=None):
"""
Connect to given database
"""
conn_args = {
'host': self.config['host'],
'user': self.config['user'],
'password': self.config['password'],
'port': self.config['port'],
'sslmode': self.config['sslmode'],
}
if database:
conn_args['database'] = database
else:
conn_args['database'] = 'postgres'
# libpq will use ~/.pgpass only if no password supplied
if self.config['password_provider'] == 'pgpass':
del conn_args['password']
try:
conn = psycopg2.connect(**conn_args)
except Exception as e:
self.log.error(e)
raise e
# Avoid using transactions, set isolation level to autocommit
conn.set_isolation_level(0)
return conn | python | def _connect(self, database=None):
conn_args = {
'host': self.config['host'],
'user': self.config['user'],
'password': self.config['password'],
'port': self.config['port'],
'sslmode': self.config['sslmode'],
}
if database:
conn_args['database'] = database
else:
conn_args['database'] = 'postgres'
# libpq will use ~/.pgpass only if no password supplied
if self.config['password_provider'] == 'pgpass':
del conn_args['password']
try:
conn = psycopg2.connect(**conn_args)
except Exception as e:
self.log.error(e)
raise e
# Avoid using transactions, set isolation level to autocommit
conn.set_isolation_level(0)
return conn | [
"def",
"_connect",
"(",
"self",
",",
"database",
"=",
"None",
")",
":",
"conn_args",
"=",
"{",
"'host'",
":",
"self",
".",
"config",
"[",
"'host'",
"]",
",",
"'user'",
":",
"self",
".",
"config",
"[",
"'user'",
"]",
",",
"'password'",
":",
"self",
... | Connect to given database | [
"Connect",
"to",
"given",
"database"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/postgres/postgres.py#L150-L179 |
236,239 | python-diamond/Diamond | src/collectors/iodrivesnmp/iodrivesnmp.py | IODriveSNMPCollector.get_string_index_oid | def get_string_index_oid(self, s):
"""Turns a string into an oid format is length of name followed by
name chars in ascii"""
return (len(self.get_bytes(s)), ) + self.get_bytes(s) | python | def get_string_index_oid(self, s):
return (len(self.get_bytes(s)), ) + self.get_bytes(s) | [
"def",
"get_string_index_oid",
"(",
"self",
",",
"s",
")",
":",
"return",
"(",
"len",
"(",
"self",
".",
"get_bytes",
"(",
"s",
")",
")",
",",
")",
"+",
"self",
".",
"get_bytes",
"(",
"s",
")"
] | Turns a string into an oid format is length of name followed by
name chars in ascii | [
"Turns",
"a",
"string",
"into",
"an",
"oid",
"format",
"is",
"length",
"of",
"name",
"followed",
"by",
"name",
"chars",
"in",
"ascii"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/iodrivesnmp/iodrivesnmp.py#L89-L92 |
236,240 | python-diamond/Diamond | src/collectors/iodrivesnmp/iodrivesnmp.py | IODriveSNMPCollector.collect_snmp | def collect_snmp(self, device, host, port, community):
"""
Collect Fusion IO Drive SNMP stats from device
host and device are from the conf file. In the future device should be
changed to be what IODRive device it being checked.
i.e. fioa, fiob.
"""
# Set timestamp
timestamp = time.time()
for k, v in self.IODRIVE_STATS.items():
# Get Metric Name and Value
metricName = '.'.join([k])
metricValue = int(self.get(v, host, port, community)[v])
# Get Metric Path
metricPath = '.'.join(['servers', host, device, metricName])
# Create Metric
metric = Metric(metricPath, metricValue, timestamp, 0)
# Publish Metric
self.publish_metric(metric)
for k, v in self.IODRIVE_BYTE_STATS.items():
# Get Metric Name and Value
metricName = '.'.join([k])
metricValue = int(self.get(v, host, port, community)[v])
# Get Metric Path
metricPath = '.'.join(['servers', host, device, metricName])
# Create Metric
metric = Metric(metricPath, metricValue, timestamp, 0)
# Publish Metric
self.publish_metric(metric) | python | def collect_snmp(self, device, host, port, community):
# Set timestamp
timestamp = time.time()
for k, v in self.IODRIVE_STATS.items():
# Get Metric Name and Value
metricName = '.'.join([k])
metricValue = int(self.get(v, host, port, community)[v])
# Get Metric Path
metricPath = '.'.join(['servers', host, device, metricName])
# Create Metric
metric = Metric(metricPath, metricValue, timestamp, 0)
# Publish Metric
self.publish_metric(metric)
for k, v in self.IODRIVE_BYTE_STATS.items():
# Get Metric Name and Value
metricName = '.'.join([k])
metricValue = int(self.get(v, host, port, community)[v])
# Get Metric Path
metricPath = '.'.join(['servers', host, device, metricName])
# Create Metric
metric = Metric(metricPath, metricValue, timestamp, 0)
# Publish Metric
self.publish_metric(metric) | [
"def",
"collect_snmp",
"(",
"self",
",",
"device",
",",
"host",
",",
"port",
",",
"community",
")",
":",
"# Set timestamp",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"IODRIVE_STATS",
".",
"items",
"(",
... | Collect Fusion IO Drive SNMP stats from device
host and device are from the conf file. In the future device should be
changed to be what IODRive device it being checked.
i.e. fioa, fiob. | [
"Collect",
"Fusion",
"IO",
"Drive",
"SNMP",
"stats",
"from",
"device",
"host",
"and",
"device",
"are",
"from",
"the",
"conf",
"file",
".",
"In",
"the",
"future",
"device",
"should",
"be",
"changed",
"to",
"be",
"what",
"IODRive",
"device",
"it",
"being",
... | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/iodrivesnmp/iodrivesnmp.py#L98-L135 |
236,241 | python-diamond/Diamond | src/diamond/handler/graphite.py | GraphiteHandler._send_data | def _send_data(self, data):
"""
Try to send all data in buffer.
"""
try:
self.socket.sendall(data)
self._reset_errors()
except:
self._close()
self._throttle_error("GraphiteHandler: Socket error, "
"trying reconnect.")
self._connect()
try:
self.socket.sendall(data)
except:
return
self._reset_errors() | python | def _send_data(self, data):
try:
self.socket.sendall(data)
self._reset_errors()
except:
self._close()
self._throttle_error("GraphiteHandler: Socket error, "
"trying reconnect.")
self._connect()
try:
self.socket.sendall(data)
except:
return
self._reset_errors() | [
"def",
"_send_data",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"self",
".",
"socket",
".",
"sendall",
"(",
"data",
")",
"self",
".",
"_reset_errors",
"(",
")",
"except",
":",
"self",
".",
"_close",
"(",
")",
"self",
".",
"_throttle_error",
"(",... | Try to send all data in buffer. | [
"Try",
"to",
"send",
"all",
"data",
"in",
"buffer",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/graphite.py#L126-L142 |
236,242 | python-diamond/Diamond | src/diamond/handler/graphite.py | GraphiteHandler._send | def _send(self):
"""
Send data to graphite. Data that can not be sent will be queued.
"""
# Check to see if we have a valid socket. If not, try to connect.
try:
try:
if self.socket is None:
self.log.debug("GraphiteHandler: Socket is not connected. "
"Reconnecting.")
self._connect()
if self.socket is None:
self.log.debug("GraphiteHandler: Reconnect failed.")
else:
# Send data to socket
self._send_data(''.join(self.metrics))
self.metrics = []
if self._time_to_reconnect():
self._close()
except Exception:
self._close()
self._throttle_error("GraphiteHandler: Error sending metrics.")
raise
finally:
if len(self.metrics) >= (
self.batch_size * self.max_backlog_multiplier):
trim_offset = (self.batch_size *
self.trim_backlog_multiplier * -1)
self.log.warn('GraphiteHandler: Trimming backlog. Removing' +
' oldest %d and keeping newest %d metrics',
len(self.metrics) - abs(trim_offset),
abs(trim_offset))
self.metrics = self.metrics[trim_offset:] | python | def _send(self):
# Check to see if we have a valid socket. If not, try to connect.
try:
try:
if self.socket is None:
self.log.debug("GraphiteHandler: Socket is not connected. "
"Reconnecting.")
self._connect()
if self.socket is None:
self.log.debug("GraphiteHandler: Reconnect failed.")
else:
# Send data to socket
self._send_data(''.join(self.metrics))
self.metrics = []
if self._time_to_reconnect():
self._close()
except Exception:
self._close()
self._throttle_error("GraphiteHandler: Error sending metrics.")
raise
finally:
if len(self.metrics) >= (
self.batch_size * self.max_backlog_multiplier):
trim_offset = (self.batch_size *
self.trim_backlog_multiplier * -1)
self.log.warn('GraphiteHandler: Trimming backlog. Removing' +
' oldest %d and keeping newest %d metrics',
len(self.metrics) - abs(trim_offset),
abs(trim_offset))
self.metrics = self.metrics[trim_offset:] | [
"def",
"_send",
"(",
"self",
")",
":",
"# Check to see if we have a valid socket. If not, try to connect.",
"try",
":",
"try",
":",
"if",
"self",
".",
"socket",
"is",
"None",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"GraphiteHandler: Socket is not connected. \"",... | Send data to graphite. Data that can not be sent will be queued. | [
"Send",
"data",
"to",
"graphite",
".",
"Data",
"that",
"can",
"not",
"be",
"sent",
"will",
"be",
"queued",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/graphite.py#L151-L183 |
236,243 | python-diamond/Diamond | src/diamond/handler/graphite.py | GraphiteHandler._connect | def _connect(self):
"""
Connect to the graphite server
"""
if (self.proto == 'udp'):
stream = socket.SOCK_DGRAM
else:
stream = socket.SOCK_STREAM
if (self.proto[-1] == '4'):
family = socket.AF_INET
connection_struct = (self.host, self.port)
elif (self.proto[-1] == '6'):
family = socket.AF_INET6
connection_struct = (self.host, self.port,
self.flow_info, self.scope_id)
else:
connection_struct = (self.host, self.port)
try:
addrinfo = socket.getaddrinfo(self.host, self.port, 0, stream)
except socket.gaierror as ex:
self.log.error("GraphiteHandler: Error looking up graphite host"
" '%s' - %s",
self.host, ex)
return
if (len(addrinfo) > 0):
family = addrinfo[0][0]
if (family == socket.AF_INET6):
connection_struct = (self.host, self.port,
self.flow_info, self.scope_id)
else:
family = socket.AF_INET
# Create socket
self.socket = socket.socket(family, stream)
if self.socket is None:
# Log Error
self.log.error("GraphiteHandler: Unable to create socket.")
# Close Socket
self._close()
return
# Enable keepalives?
if self.proto != 'udp' and self.keepalive:
self.log.error("GraphiteHandler: Setting socket keepalives...")
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
self.keepaliveinterval)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL,
self.keepaliveinterval)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)
# Set socket timeout
self.socket.settimeout(self.timeout)
# Connect to graphite server
try:
self.socket.connect(connection_struct)
# Log
self.log.debug("GraphiteHandler: Established connection to "
"graphite server %s:%d.",
self.host, self.port)
self.last_connect_timestamp = time.time()
except Exception as ex:
# Log Error
self._throttle_error("GraphiteHandler: Failed to connect to "
"%s:%i. %s.", self.host, self.port, ex)
# Close Socket
self._close()
return | python | def _connect(self):
if (self.proto == 'udp'):
stream = socket.SOCK_DGRAM
else:
stream = socket.SOCK_STREAM
if (self.proto[-1] == '4'):
family = socket.AF_INET
connection_struct = (self.host, self.port)
elif (self.proto[-1] == '6'):
family = socket.AF_INET6
connection_struct = (self.host, self.port,
self.flow_info, self.scope_id)
else:
connection_struct = (self.host, self.port)
try:
addrinfo = socket.getaddrinfo(self.host, self.port, 0, stream)
except socket.gaierror as ex:
self.log.error("GraphiteHandler: Error looking up graphite host"
" '%s' - %s",
self.host, ex)
return
if (len(addrinfo) > 0):
family = addrinfo[0][0]
if (family == socket.AF_INET6):
connection_struct = (self.host, self.port,
self.flow_info, self.scope_id)
else:
family = socket.AF_INET
# Create socket
self.socket = socket.socket(family, stream)
if self.socket is None:
# Log Error
self.log.error("GraphiteHandler: Unable to create socket.")
# Close Socket
self._close()
return
# Enable keepalives?
if self.proto != 'udp' and self.keepalive:
self.log.error("GraphiteHandler: Setting socket keepalives...")
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE,
self.keepaliveinterval)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL,
self.keepaliveinterval)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 3)
# Set socket timeout
self.socket.settimeout(self.timeout)
# Connect to graphite server
try:
self.socket.connect(connection_struct)
# Log
self.log.debug("GraphiteHandler: Established connection to "
"graphite server %s:%d.",
self.host, self.port)
self.last_connect_timestamp = time.time()
except Exception as ex:
# Log Error
self._throttle_error("GraphiteHandler: Failed to connect to "
"%s:%i. %s.", self.host, self.port, ex)
# Close Socket
self._close()
return | [
"def",
"_connect",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"proto",
"==",
"'udp'",
")",
":",
"stream",
"=",
"socket",
".",
"SOCK_DGRAM",
"else",
":",
"stream",
"=",
"socket",
".",
"SOCK_STREAM",
"if",
"(",
"self",
".",
"proto",
"[",
"-",
"1"... | Connect to the graphite server | [
"Connect",
"to",
"the",
"graphite",
"server"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/graphite.py#L185-L251 |
236,244 | python-diamond/Diamond | src/diamond/handler/null.py | NullHandler.process | def process(self, metric):
"""
Process a metric by doing nothing
"""
self.log.debug("Metric: %s", str(metric).rstrip().replace(' ', '\t')) | python | def process(self, metric):
self.log.debug("Metric: %s", str(metric).rstrip().replace(' ', '\t')) | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Metric: %s\"",
",",
"str",
"(",
"metric",
")",
".",
"rstrip",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'\\t'",
")",
")"
] | Process a metric by doing nothing | [
"Process",
"a",
"metric",
"by",
"doing",
"nothing"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/null.py#L15-L19 |
236,245 | python-diamond/Diamond | src/diamond/collector.py | Collector.load_config | def load_config(self, configfile=None, override_config=None):
"""
Process a configfile, or reload if previously given one.
"""
self.config = configobj.ConfigObj()
# Load in the collector's defaults
if self.get_default_config() is not None:
self.config.merge(self.get_default_config())
if configfile is not None:
self.configfile = os.path.abspath(configfile)
if self.configfile is not None:
config = load_config(self.configfile)
if 'collectors' in config:
if 'default' in config['collectors']:
self.config.merge(config['collectors']['default'])
if self.name in config['collectors']:
self.config.merge(config['collectors'][self.name])
if override_config is not None:
if 'collectors' in override_config:
if 'default' in override_config['collectors']:
self.config.merge(override_config['collectors']['default'])
if self.name in override_config['collectors']:
self.config.merge(override_config['collectors'][self.name])
self.process_config() | python | def load_config(self, configfile=None, override_config=None):
self.config = configobj.ConfigObj()
# Load in the collector's defaults
if self.get_default_config() is not None:
self.config.merge(self.get_default_config())
if configfile is not None:
self.configfile = os.path.abspath(configfile)
if self.configfile is not None:
config = load_config(self.configfile)
if 'collectors' in config:
if 'default' in config['collectors']:
self.config.merge(config['collectors']['default'])
if self.name in config['collectors']:
self.config.merge(config['collectors'][self.name])
if override_config is not None:
if 'collectors' in override_config:
if 'default' in override_config['collectors']:
self.config.merge(override_config['collectors']['default'])
if self.name in override_config['collectors']:
self.config.merge(override_config['collectors'][self.name])
self.process_config() | [
"def",
"load_config",
"(",
"self",
",",
"configfile",
"=",
"None",
",",
"override_config",
"=",
"None",
")",
":",
"self",
".",
"config",
"=",
"configobj",
".",
"ConfigObj",
"(",
")",
"# Load in the collector's defaults",
"if",
"self",
".",
"get_default_config",
... | Process a configfile, or reload if previously given one. | [
"Process",
"a",
"configfile",
"or",
"reload",
"if",
"previously",
"given",
"one",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/collector.py#L181-L212 |
236,246 | python-diamond/Diamond | src/diamond/collector.py | Collector.process_config | def process_config(self):
"""
Intended to put any code that should be run after any config reload
event
"""
if 'byte_unit' in self.config:
if isinstance(self.config['byte_unit'], basestring):
self.config['byte_unit'] = self.config['byte_unit'].split()
if 'enabled' in self.config:
self.config['enabled'] = str_to_bool(self.config['enabled'])
if 'measure_collector_time' in self.config:
self.config['measure_collector_time'] = str_to_bool(
self.config['measure_collector_time'])
# Raise an error if both whitelist and blacklist are specified
if ((self.config.get('metrics_whitelist', None) and
self.config.get('metrics_blacklist', None))):
raise DiamondException(
'Both metrics_whitelist and metrics_blacklist specified ' +
'in file %s' % self.configfile)
if self.config.get('metrics_whitelist', None):
self.config['metrics_whitelist'] = re.compile(
self.config['metrics_whitelist'])
elif self.config.get('metrics_blacklist', None):
self.config['metrics_blacklist'] = re.compile(
self.config['metrics_blacklist']) | python | def process_config(self):
if 'byte_unit' in self.config:
if isinstance(self.config['byte_unit'], basestring):
self.config['byte_unit'] = self.config['byte_unit'].split()
if 'enabled' in self.config:
self.config['enabled'] = str_to_bool(self.config['enabled'])
if 'measure_collector_time' in self.config:
self.config['measure_collector_time'] = str_to_bool(
self.config['measure_collector_time'])
# Raise an error if both whitelist and blacklist are specified
if ((self.config.get('metrics_whitelist', None) and
self.config.get('metrics_blacklist', None))):
raise DiamondException(
'Both metrics_whitelist and metrics_blacklist specified ' +
'in file %s' % self.configfile)
if self.config.get('metrics_whitelist', None):
self.config['metrics_whitelist'] = re.compile(
self.config['metrics_whitelist'])
elif self.config.get('metrics_blacklist', None):
self.config['metrics_blacklist'] = re.compile(
self.config['metrics_blacklist']) | [
"def",
"process_config",
"(",
"self",
")",
":",
"if",
"'byte_unit'",
"in",
"self",
".",
"config",
":",
"if",
"isinstance",
"(",
"self",
".",
"config",
"[",
"'byte_unit'",
"]",
",",
"basestring",
")",
":",
"self",
".",
"config",
"[",
"'byte_unit'",
"]",
... | Intended to put any code that should be run after any config reload
event | [
"Intended",
"to",
"put",
"any",
"code",
"that",
"should",
"be",
"run",
"after",
"any",
"config",
"reload",
"event"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/collector.py#L214-L242 |
236,247 | python-diamond/Diamond | src/diamond/collector.py | Collector.get_metric_path | def get_metric_path(self, name, instance=None):
"""
Get metric path.
Instance indicates that this is a metric for a
virtual machine and should have a different
root prefix.
"""
if 'path' in self.config:
path = self.config['path']
else:
path = self.__class__.__name__
if instance is not None:
if 'instance_prefix' in self.config:
prefix = self.config['instance_prefix']
else:
prefix = 'instances'
if path == '.':
return '.'.join([prefix, instance, name])
else:
return '.'.join([prefix, instance, path, name])
if 'path_prefix' in self.config:
prefix = self.config['path_prefix']
else:
prefix = 'systems'
if 'path_suffix' in self.config:
suffix = self.config['path_suffix']
else:
suffix = None
hostname = get_hostname(self.config)
if hostname is not None:
if prefix:
prefix = ".".join((prefix, hostname))
else:
prefix = hostname
# if there is a suffix, add after the hostname
if suffix:
prefix = '.'.join((prefix, suffix))
is_path_invalid = path == '.' or not path
if is_path_invalid and prefix:
return '.'.join([prefix, name])
elif prefix:
return '.'.join([prefix, path, name])
elif is_path_invalid:
return name
else:
return '.'.join([path, name]) | python | def get_metric_path(self, name, instance=None):
if 'path' in self.config:
path = self.config['path']
else:
path = self.__class__.__name__
if instance is not None:
if 'instance_prefix' in self.config:
prefix = self.config['instance_prefix']
else:
prefix = 'instances'
if path == '.':
return '.'.join([prefix, instance, name])
else:
return '.'.join([prefix, instance, path, name])
if 'path_prefix' in self.config:
prefix = self.config['path_prefix']
else:
prefix = 'systems'
if 'path_suffix' in self.config:
suffix = self.config['path_suffix']
else:
suffix = None
hostname = get_hostname(self.config)
if hostname is not None:
if prefix:
prefix = ".".join((prefix, hostname))
else:
prefix = hostname
# if there is a suffix, add after the hostname
if suffix:
prefix = '.'.join((prefix, suffix))
is_path_invalid = path == '.' or not path
if is_path_invalid and prefix:
return '.'.join([prefix, name])
elif prefix:
return '.'.join([prefix, path, name])
elif is_path_invalid:
return name
else:
return '.'.join([path, name]) | [
"def",
"get_metric_path",
"(",
"self",
",",
"name",
",",
"instance",
"=",
"None",
")",
":",
"if",
"'path'",
"in",
"self",
".",
"config",
":",
"path",
"=",
"self",
".",
"config",
"[",
"'path'",
"]",
"else",
":",
"path",
"=",
"self",
".",
"__class__",
... | Get metric path.
Instance indicates that this is a metric for a
virtual machine and should have a different
root prefix. | [
"Get",
"metric",
"path",
".",
"Instance",
"indicates",
"that",
"this",
"is",
"a",
"metric",
"for",
"a",
"virtual",
"machine",
"and",
"should",
"have",
"a",
"different",
"root",
"prefix",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/collector.py#L310-L362 |
236,248 | python-diamond/Diamond | src/diamond/collector.py | Collector.publish | def publish(self, name, value, raw_value=None, precision=0,
metric_type='GAUGE', instance=None):
"""
Publish a metric with the given name
"""
# Check whitelist/blacklist
if self.config['metrics_whitelist']:
if not self.config['metrics_whitelist'].match(name):
return
elif self.config['metrics_blacklist']:
if self.config['metrics_blacklist'].match(name):
return
# Get metric Path
path = self.get_metric_path(name, instance=instance)
# Get metric TTL
ttl = float(self.config['interval']) * float(
self.config['ttl_multiplier'])
# Create Metric
try:
metric = Metric(path, value, raw_value=raw_value, timestamp=None,
precision=precision, host=self.get_hostname(),
metric_type=metric_type, ttl=ttl)
except DiamondException:
self.log.error(('Error when creating new Metric: path=%r, '
'value=%r'), path, value)
raise
# Publish Metric
self.publish_metric(metric) | python | def publish(self, name, value, raw_value=None, precision=0,
metric_type='GAUGE', instance=None):
# Check whitelist/blacklist
if self.config['metrics_whitelist']:
if not self.config['metrics_whitelist'].match(name):
return
elif self.config['metrics_blacklist']:
if self.config['metrics_blacklist'].match(name):
return
# Get metric Path
path = self.get_metric_path(name, instance=instance)
# Get metric TTL
ttl = float(self.config['interval']) * float(
self.config['ttl_multiplier'])
# Create Metric
try:
metric = Metric(path, value, raw_value=raw_value, timestamp=None,
precision=precision, host=self.get_hostname(),
metric_type=metric_type, ttl=ttl)
except DiamondException:
self.log.error(('Error when creating new Metric: path=%r, '
'value=%r'), path, value)
raise
# Publish Metric
self.publish_metric(metric) | [
"def",
"publish",
"(",
"self",
",",
"name",
",",
"value",
",",
"raw_value",
"=",
"None",
",",
"precision",
"=",
"0",
",",
"metric_type",
"=",
"'GAUGE'",
",",
"instance",
"=",
"None",
")",
":",
"# Check whitelist/blacklist",
"if",
"self",
".",
"config",
"... | Publish a metric with the given name | [
"Publish",
"a",
"metric",
"with",
"the",
"given",
"name"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/collector.py#L373-L404 |
236,249 | python-diamond/Diamond | src/diamond/collector.py | Collector.derivative | def derivative(self, name, new, max_value=0,
time_delta=True, interval=None,
allow_negative=False, instance=None):
"""
Calculate the derivative of the metric.
"""
# Format Metric Path
path = self.get_metric_path(name, instance=instance)
if path in self.last_values:
old = self.last_values[path]
# Check for rollover
if new < old:
old = old - max_value
# Get Change in X (value)
derivative_x = new - old
# If we pass in a interval, use it rather then the configured one
if interval is None:
interval = float(self.config['interval'])
# Get Change in Y (time)
if time_delta:
derivative_y = interval
else:
derivative_y = 1
result = float(derivative_x) / float(derivative_y)
if result < 0 and not allow_negative:
result = 0
else:
result = 0
# Store Old Value
self.last_values[path] = new
# Return result
return result | python | def derivative(self, name, new, max_value=0,
time_delta=True, interval=None,
allow_negative=False, instance=None):
# Format Metric Path
path = self.get_metric_path(name, instance=instance)
if path in self.last_values:
old = self.last_values[path]
# Check for rollover
if new < old:
old = old - max_value
# Get Change in X (value)
derivative_x = new - old
# If we pass in a interval, use it rather then the configured one
if interval is None:
interval = float(self.config['interval'])
# Get Change in Y (time)
if time_delta:
derivative_y = interval
else:
derivative_y = 1
result = float(derivative_x) / float(derivative_y)
if result < 0 and not allow_negative:
result = 0
else:
result = 0
# Store Old Value
self.last_values[path] = new
# Return result
return result | [
"def",
"derivative",
"(",
"self",
",",
"name",
",",
"new",
",",
"max_value",
"=",
"0",
",",
"time_delta",
"=",
"True",
",",
"interval",
"=",
"None",
",",
"allow_negative",
"=",
"False",
",",
"instance",
"=",
"None",
")",
":",
"# Format Metric Path",
"pat... | Calculate the derivative of the metric. | [
"Calculate",
"the",
"derivative",
"of",
"the",
"metric",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/collector.py#L430-L467 |
236,250 | python-diamond/Diamond | src/diamond/collector.py | Collector._run | def _run(self):
"""
Run the collector unless it's already running
"""
try:
start_time = time.time()
# Collect Data
self.collect()
end_time = time.time()
collector_time = int((end_time - start_time) * 1000)
self.log.debug('Collection took %s ms', collector_time)
if 'measure_collector_time' in self.config:
if self.config['measure_collector_time']:
metric_name = 'collector_time_ms'
metric_value = collector_time
self.publish(metric_name, metric_value)
finally:
# After collector run, invoke a flush
# method on each handler.
for handler in self.handlers:
handler._flush() | python | def _run(self):
try:
start_time = time.time()
# Collect Data
self.collect()
end_time = time.time()
collector_time = int((end_time - start_time) * 1000)
self.log.debug('Collection took %s ms', collector_time)
if 'measure_collector_time' in self.config:
if self.config['measure_collector_time']:
metric_name = 'collector_time_ms'
metric_value = collector_time
self.publish(metric_name, metric_value)
finally:
# After collector run, invoke a flush
# method on each handler.
for handler in self.handlers:
handler._flush() | [
"def",
"_run",
"(",
"self",
")",
":",
"try",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"# Collect Data",
"self",
".",
"collect",
"(",
")",
"end_time",
"=",
"time",
".",
"time",
"(",
")",
"collector_time",
"=",
"int",
"(",
"(",
"end_time"... | Run the collector unless it's already running | [
"Run",
"the",
"collector",
"unless",
"it",
"s",
"already",
"running"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/collector.py#L469-L493 |
236,251 | python-diamond/Diamond | src/diamond/collector.py | Collector.find_binary | def find_binary(self, binary):
"""
Scan and return the first path to a binary that we can find
"""
if os.path.exists(binary):
return binary
# Extract out the filename if we were given a full path
binary_name = os.path.basename(binary)
# Gather $PATH
search_paths = os.environ['PATH'].split(':')
# Extra paths to scan...
default_paths = [
'/usr/bin',
'/bin'
'/usr/local/bin',
'/usr/sbin',
'/sbin'
'/usr/local/sbin',
]
for path in default_paths:
if path not in search_paths:
search_paths.append(path)
for path in search_paths:
if os.path.isdir(path):
filename = os.path.join(path, binary_name)
if os.path.exists(filename):
return filename
return binary | python | def find_binary(self, binary):
if os.path.exists(binary):
return binary
# Extract out the filename if we were given a full path
binary_name = os.path.basename(binary)
# Gather $PATH
search_paths = os.environ['PATH'].split(':')
# Extra paths to scan...
default_paths = [
'/usr/bin',
'/bin'
'/usr/local/bin',
'/usr/sbin',
'/sbin'
'/usr/local/sbin',
]
for path in default_paths:
if path not in search_paths:
search_paths.append(path)
for path in search_paths:
if os.path.isdir(path):
filename = os.path.join(path, binary_name)
if os.path.exists(filename):
return filename
return binary | [
"def",
"find_binary",
"(",
"self",
",",
"binary",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"binary",
")",
":",
"return",
"binary",
"# Extract out the filename if we were given a full path",
"binary_name",
"=",
"os",
".",
"path",
".",
"basename",
... | Scan and return the first path to a binary that we can find | [
"Scan",
"and",
"return",
"the",
"first",
"path",
"to",
"a",
"binary",
"that",
"we",
"can",
"find"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/collector.py#L495-L528 |
236,252 | python-diamond/Diamond | src/collectors/memcached_slab/memcached_slab.py | parse_slab_stats | def parse_slab_stats(slab_stats):
"""Convert output from memcached's `stats slabs` into a Python dict.
Newlines are returned by memcached along with carriage returns
(i.e. '\r\n').
>>> parse_slab_stats(
"STAT 1:chunk_size 96\r\nSTAT 1:chunks_per_page 10922\r\nSTAT "
"active_slabs 1\r\nSTAT total_malloced 1048512\r\nEND\r\n")
{
'slabs': {
1: {
'chunk_size': 96,
'chunks_per_page': 10922,
# ...
},
},
'active_slabs': 1,
'total_malloced': 1048512,
}
"""
stats_dict = {'slabs': defaultdict(lambda: {})}
for line in slab_stats.splitlines():
if line == 'END':
break
# e.g.: "STAT 1:chunks_per_page 10922"
cmd, key, value = line.split(' ')
if cmd != 'STAT':
continue
# e.g.: "STAT active_slabs 1"
if ":" not in key:
stats_dict[key] = int(value)
continue
slab, key = key.split(':')
stats_dict['slabs'][int(slab)][key] = int(value)
return stats_dict | python | def parse_slab_stats(slab_stats):
stats_dict = {'slabs': defaultdict(lambda: {})}
for line in slab_stats.splitlines():
if line == 'END':
break
# e.g.: "STAT 1:chunks_per_page 10922"
cmd, key, value = line.split(' ')
if cmd != 'STAT':
continue
# e.g.: "STAT active_slabs 1"
if ":" not in key:
stats_dict[key] = int(value)
continue
slab, key = key.split(':')
stats_dict['slabs'][int(slab)][key] = int(value)
return stats_dict | [
"def",
"parse_slab_stats",
"(",
"slab_stats",
")",
":",
"stats_dict",
"=",
"{",
"'slabs'",
":",
"defaultdict",
"(",
"lambda",
":",
"{",
"}",
")",
"}",
"for",
"line",
"in",
"slab_stats",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
"==",
"'END'",
":"... | Convert output from memcached's `stats slabs` into a Python dict.
Newlines are returned by memcached along with carriage returns
(i.e. '\r\n').
>>> parse_slab_stats(
"STAT 1:chunk_size 96\r\nSTAT 1:chunks_per_page 10922\r\nSTAT "
"active_slabs 1\r\nSTAT total_malloced 1048512\r\nEND\r\n")
{
'slabs': {
1: {
'chunk_size': 96,
'chunks_per_page': 10922,
# ...
},
},
'active_slabs': 1,
'total_malloced': 1048512,
} | [
"Convert",
"output",
"from",
"memcached",
"s",
"stats",
"slabs",
"into",
"a",
"Python",
"dict",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/memcached_slab/memcached_slab.py#L19-L56 |
236,253 | python-diamond/Diamond | src/collectors/memcached_slab/memcached_slab.py | dict_to_paths | def dict_to_paths(dict_):
"""Convert a dict to metric paths.
>>> dict_to_paths({'foo': {'bar': 1}, 'baz': 2})
{
'foo.bar': 1,
'baz': 2,
}
"""
metrics = {}
for k, v in dict_.iteritems():
if isinstance(v, dict):
submetrics = dict_to_paths(v)
for subk, subv in submetrics.iteritems():
metrics['.'.join([str(k), str(subk)])] = subv
else:
metrics[k] = v
return metrics | python | def dict_to_paths(dict_):
metrics = {}
for k, v in dict_.iteritems():
if isinstance(v, dict):
submetrics = dict_to_paths(v)
for subk, subv in submetrics.iteritems():
metrics['.'.join([str(k), str(subk)])] = subv
else:
metrics[k] = v
return metrics | [
"def",
"dict_to_paths",
"(",
"dict_",
")",
":",
"metrics",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"dict_",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"submetrics",
"=",
"dict_to_paths",
"(",
"v",
")",
... | Convert a dict to metric paths.
>>> dict_to_paths({'foo': {'bar': 1}, 'baz': 2})
{
'foo.bar': 1,
'baz': 2,
} | [
"Convert",
"a",
"dict",
"to",
"metric",
"paths",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/memcached_slab/memcached_slab.py#L59-L76 |
236,254 | python-diamond/Diamond | src/collectors/memcached_slab/memcached_slab.py | MemcachedSlabCollector.get_slab_stats | def get_slab_stats(self):
"""Retrieve slab stats from memcached."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
s.send("stats slabs\n")
try:
data = ""
while True:
data += s.recv(4096)
if data.endswith('END\r\n'):
break
return data
finally:
s.close() | python | def get_slab_stats(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
s.send("stats slabs\n")
try:
data = ""
while True:
data += s.recv(4096)
if data.endswith('END\r\n'):
break
return data
finally:
s.close() | [
"def",
"get_slab_stats",
"(",
"self",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"s",
".",
"connect",
"(",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
")",
"s",
... | Retrieve slab stats from memcached. | [
"Retrieve",
"slab",
"stats",
"from",
"memcached",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/memcached_slab/memcached_slab.py#L99-L112 |
236,255 | python-diamond/Diamond | src/collectors/netapp/netapp_inode.py | netapp_inodeCol.push | def push(self, metric_name=None, metric_value=None, volume=None):
""" Ship that shit off to graphite broski
"""
graphite_path = self.path_prefix
graphite_path += '.' + self.device + '.' + 'volume'
graphite_path += '.' + volume + '.' + metric_name
metric = Metric(graphite_path, metric_value, precision=4,
host=self.device)
self.publish_metric(metric) | python | def push(self, metric_name=None, metric_value=None, volume=None):
graphite_path = self.path_prefix
graphite_path += '.' + self.device + '.' + 'volume'
graphite_path += '.' + volume + '.' + metric_name
metric = Metric(graphite_path, metric_value, precision=4,
host=self.device)
self.publish_metric(metric) | [
"def",
"push",
"(",
"self",
",",
"metric_name",
"=",
"None",
",",
"metric_value",
"=",
"None",
",",
"volume",
"=",
"None",
")",
":",
"graphite_path",
"=",
"self",
".",
"path_prefix",
"graphite_path",
"+=",
"'.'",
"+",
"self",
".",
"device",
"+",
"'.'",
... | Ship that shit off to graphite broski | [
"Ship",
"that",
"shit",
"off",
"to",
"graphite",
"broski"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netapp_inode.py#L61-L72 |
236,256 | python-diamond/Diamond | src/collectors/netapp/netapp_inode.py | netapp_inodeCol.get_netapp_data | def get_netapp_data(self):
""" Retrieve netapp volume information
returns ElementTree of netapp volume information
"""
netapp_data = self.server.invoke('volume-list-info')
if netapp_data.results_status() == 'failed':
self.log.error(
'While using netapp API failed to retrieve '
'volume-list-info for netapp filer %s' % self.device)
return
netapp_xml = ET.fromstring(netapp_data.sprintf()).find('volumes')
return netapp_xml | python | def get_netapp_data(self):
netapp_data = self.server.invoke('volume-list-info')
if netapp_data.results_status() == 'failed':
self.log.error(
'While using netapp API failed to retrieve '
'volume-list-info for netapp filer %s' % self.device)
return
netapp_xml = ET.fromstring(netapp_data.sprintf()).find('volumes')
return netapp_xml | [
"def",
"get_netapp_data",
"(",
"self",
")",
":",
"netapp_data",
"=",
"self",
".",
"server",
".",
"invoke",
"(",
"'volume-list-info'",
")",
"if",
"netapp_data",
".",
"results_status",
"(",
")",
"==",
"'failed'",
":",
"self",
".",
"log",
".",
"error",
"(",
... | Retrieve netapp volume information
returns ElementTree of netapp volume information | [
"Retrieve",
"netapp",
"volume",
"information"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netapp_inode.py#L74-L91 |
236,257 | python-diamond/Diamond | src/diamond/handler/sentry.py | BaseResult.verbose_message | def verbose_message(self):
"""return more complete message"""
if self.threshold is None:
return 'No threshold'
return '%.1f is %s than %.1f' % (self.value,
self.adjective,
self.threshold) | python | def verbose_message(self):
if self.threshold is None:
return 'No threshold'
return '%.1f is %s than %.1f' % (self.value,
self.adjective,
self.threshold) | [
"def",
"verbose_message",
"(",
"self",
")",
":",
"if",
"self",
".",
"threshold",
"is",
"None",
":",
"return",
"'No threshold'",
"return",
"'%.1f is %s than %.1f'",
"%",
"(",
"self",
".",
"value",
",",
"self",
".",
"adjective",
",",
"self",
".",
"threshold",
... | return more complete message | [
"return",
"more",
"complete",
"message"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/sentry.py#L77-L83 |
236,258 | python-diamond/Diamond | src/diamond/handler/sentry.py | Rule.process | def process(self, metric, handler):
"""
process a single diamond metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@type handler: diamond.handler.sentry.SentryHandler
@param handler: configured Sentry graphite handler
@rtype None
"""
match = self.regexp.match(metric.path)
if match:
minimum = Minimum(metric.value, self.min)
maximum = Maximum(metric.value, self.max)
if minimum.is_error or maximum.is_error:
self.counter_errors += 1
message = "%s Warning on %s: %.1f" % (self.name,
handler.hostname,
metric.value)
culprit = "%s %s" % (handler.hostname, match.group('path'))
handler.raven_logger.error(message, extra={
'culprit': culprit,
'data': {
'metric prefix': match.group('prefix'),
'metric path': match.group('path'),
'minimum check': minimum.verbose_message,
'maximum check': maximum.verbose_message,
'metric original path': metric.path,
'metric value': metric.value,
'metric precision': metric.precision,
'metric timestamp': metric.timestamp,
'minimum threshold': self.min,
'maximum threshold': self.max,
'path regular expression': self.regexp.pattern,
'total errors': self.counter_errors,
'total pass': self.counter_pass,
'hostname': handler.hostname
}
}
)
else:
self.counter_pass += 1 | python | def process(self, metric, handler):
match = self.regexp.match(metric.path)
if match:
minimum = Minimum(metric.value, self.min)
maximum = Maximum(metric.value, self.max)
if minimum.is_error or maximum.is_error:
self.counter_errors += 1
message = "%s Warning on %s: %.1f" % (self.name,
handler.hostname,
metric.value)
culprit = "%s %s" % (handler.hostname, match.group('path'))
handler.raven_logger.error(message, extra={
'culprit': culprit,
'data': {
'metric prefix': match.group('prefix'),
'metric path': match.group('path'),
'minimum check': minimum.verbose_message,
'maximum check': maximum.verbose_message,
'metric original path': metric.path,
'metric value': metric.value,
'metric precision': metric.precision,
'metric timestamp': metric.timestamp,
'minimum threshold': self.min,
'maximum threshold': self.max,
'path regular expression': self.regexp.pattern,
'total errors': self.counter_errors,
'total pass': self.counter_pass,
'hostname': handler.hostname
}
}
)
else:
self.counter_pass += 1 | [
"def",
"process",
"(",
"self",
",",
"metric",
",",
"handler",
")",
":",
"match",
"=",
"self",
".",
"regexp",
".",
"match",
"(",
"metric",
".",
"path",
")",
"if",
"match",
":",
"minimum",
"=",
"Minimum",
"(",
"metric",
".",
"value",
",",
"self",
"."... | process a single diamond metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@type handler: diamond.handler.sentry.SentryHandler
@param handler: configured Sentry graphite handler
@rtype None | [
"process",
"a",
"single",
"diamond",
"metric"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/sentry.py#L179-L220 |
236,259 | python-diamond/Diamond | src/diamond/handler/sentry.py | SentryHandler.compile_rules | def compile_rules(self):
"""
Compile alert rules
@rtype list of Rules
"""
output = []
# validate configuration, skip invalid section
for key_name, section in self.config.items():
rule = self.compile_section(section)
if rule is not None:
output.append(rule)
return output | python | def compile_rules(self):
output = []
# validate configuration, skip invalid section
for key_name, section in self.config.items():
rule = self.compile_section(section)
if rule is not None:
output.append(rule)
return output | [
"def",
"compile_rules",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"# validate configuration, skip invalid section",
"for",
"key_name",
",",
"section",
"in",
"self",
".",
"config",
".",
"items",
"(",
")",
":",
"rule",
"=",
"self",
".",
"compile_section",
... | Compile alert rules
@rtype list of Rules | [
"Compile",
"alert",
"rules"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/sentry.py#L277-L288 |
236,260 | python-diamond/Diamond | src/diamond/handler/sentry.py | SentryHandler.compile_section | def compile_section(self, section):
"""
Validate if a section is a valid rule
@type section: configobj.Section
@param section: section to validate
@rtype Rule or None
@return None if invalid
"""
if section.__class__ != Section:
# not a section, just skip
return
# name and path are mandatory
keys = section.keys()
for key in ('name', 'path'):
if key not in keys:
self.log.warning("section %s miss key '%s' ignore", key,
section.name)
return
# just warn if invalid key in section
for key in keys:
if key not in self.VALID_RULES_KEYS:
self.log.warning("invalid key %s in section %s",
key, section.name)
# need at least a min or a max
if 'min' not in keys and 'max' not in keys:
self.log.warning("either 'min' or 'max' is defined in %s",
section.name)
return
# add rule to the list
kwargs = {
'name': section['name'],
'path': section['path']
}
for argument in ('min', 'max'):
try:
kwargs[argument] = section[argument]
except KeyError:
pass
# init rule
try:
return Rule(**kwargs)
except InvalidRule as err:
self.log.error(str(err)) | python | def compile_section(self, section):
if section.__class__ != Section:
# not a section, just skip
return
# name and path are mandatory
keys = section.keys()
for key in ('name', 'path'):
if key not in keys:
self.log.warning("section %s miss key '%s' ignore", key,
section.name)
return
# just warn if invalid key in section
for key in keys:
if key not in self.VALID_RULES_KEYS:
self.log.warning("invalid key %s in section %s",
key, section.name)
# need at least a min or a max
if 'min' not in keys and 'max' not in keys:
self.log.warning("either 'min' or 'max' is defined in %s",
section.name)
return
# add rule to the list
kwargs = {
'name': section['name'],
'path': section['path']
}
for argument in ('min', 'max'):
try:
kwargs[argument] = section[argument]
except KeyError:
pass
# init rule
try:
return Rule(**kwargs)
except InvalidRule as err:
self.log.error(str(err)) | [
"def",
"compile_section",
"(",
"self",
",",
"section",
")",
":",
"if",
"section",
".",
"__class__",
"!=",
"Section",
":",
"# not a section, just skip",
"return",
"# name and path are mandatory",
"keys",
"=",
"section",
".",
"keys",
"(",
")",
"for",
"key",
"in",
... | Validate if a section is a valid rule
@type section: configobj.Section
@param section: section to validate
@rtype Rule or None
@return None if invalid | [
"Validate",
"if",
"a",
"section",
"is",
"a",
"valid",
"rule"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/sentry.py#L290-L337 |
236,261 | python-diamond/Diamond | src/diamond/handler/sentry.py | SentryHandler.configure_sentry_errors | def configure_sentry_errors(self):
"""
Configure sentry.errors to use the same loggers as the root handler
@rtype: None
"""
sentry_errors_logger = logging.getLogger('sentry.errors')
root_logger = logging.getLogger()
for handler in root_logger.handlers:
sentry_errors_logger.addHandler(handler) | python | def configure_sentry_errors(self):
sentry_errors_logger = logging.getLogger('sentry.errors')
root_logger = logging.getLogger()
for handler in root_logger.handlers:
sentry_errors_logger.addHandler(handler) | [
"def",
"configure_sentry_errors",
"(",
"self",
")",
":",
"sentry_errors_logger",
"=",
"logging",
".",
"getLogger",
"(",
"'sentry.errors'",
")",
"root_logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"for",
"handler",
"in",
"root_logger",
".",
"handlers",
":"... | Configure sentry.errors to use the same loggers as the root handler
@rtype: None | [
"Configure",
"sentry",
".",
"errors",
"to",
"use",
"the",
"same",
"loggers",
"as",
"the",
"root",
"handler"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/sentry.py#L339-L347 |
236,262 | python-diamond/Diamond | src/diamond/handler/sentry.py | SentryHandler.process | def process(self, metric):
"""
process a single metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@rtype None
"""
for rule in self.rules:
rule.process(metric, self) | python | def process(self, metric):
for rule in self.rules:
rule.process(metric, self) | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"for",
"rule",
"in",
"self",
".",
"rules",
":",
"rule",
".",
"process",
"(",
"metric",
",",
"self",
")"
] | process a single metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@rtype None | [
"process",
"a",
"single",
"metric"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/sentry.py#L349-L357 |
236,263 | python-diamond/Diamond | src/collectors/network/network.py | NetworkCollector.collect | def collect(self):
"""
Collect network interface stats.
"""
# Initialize results
results = {}
if os.access(self.PROC, os.R_OK):
# Open File
file = open(self.PROC)
# Build Regular Expression
greed = ''
if str_to_bool(self.config['greedy']):
greed = '\S*'
exp = (('^(?:\s*)((?:%s)%s):(?:\s*)' +
'(?P<rx_bytes>\d+)(?:\s*)' +
'(?P<rx_packets>\w+)(?:\s*)' +
'(?P<rx_errors>\d+)(?:\s*)' +
'(?P<rx_drop>\d+)(?:\s*)' +
'(?P<rx_fifo>\d+)(?:\s*)' +
'(?P<rx_frame>\d+)(?:\s*)' +
'(?P<rx_compressed>\d+)(?:\s*)' +
'(?P<rx_multicast>\d+)(?:\s*)' +
'(?P<tx_bytes>\d+)(?:\s*)' +
'(?P<tx_packets>\w+)(?:\s*)' +
'(?P<tx_errors>\d+)(?:\s*)' +
'(?P<tx_drop>\d+)(?:\s*)' +
'(?P<tx_fifo>\d+)(?:\s*)' +
'(?P<tx_colls>\d+)(?:\s*)' +
'(?P<tx_carrier>\d+)(?:\s*)' +
'(?P<tx_compressed>\d+)(?:.*)$') %
(('|'.join(self.config['interfaces'])), greed))
reg = re.compile(exp)
# Match Interfaces
for line in file:
match = reg.match(line)
if match:
device = match.group(1)
results[device] = match.groupdict()
# Close File
file.close()
else:
if not psutil:
self.log.error('Unable to import psutil')
self.log.error('No network metrics retrieved')
return None
network_stats = psutil.network_io_counters(True)
for device in network_stats.keys():
network_stat = network_stats[device]
results[device] = {}
results[device]['rx_bytes'] = network_stat.bytes_recv
results[device]['tx_bytes'] = network_stat.bytes_sent
results[device]['rx_packets'] = network_stat.packets_recv
results[device]['tx_packets'] = network_stat.packets_sent
for device in results:
stats = results[device]
for s, v in stats.items():
# Get Metric Name
metric_name = '.'.join([device, s])
# Get Metric Value
metric_value = self.derivative(metric_name,
long(v),
diamond.collector.MAX_COUNTER)
# Convert rx_bytes and tx_bytes
if s == 'rx_bytes' or s == 'tx_bytes':
convertor = diamond.convertor.binary(value=metric_value,
unit='byte')
for u in self.config['byte_unit']:
# Public Converted Metric
self.publish(metric_name.replace('bytes', u),
convertor.get(unit=u), 2)
else:
# Publish Metric Derivative
self.publish(metric_name, metric_value)
return None | python | def collect(self):
# Initialize results
results = {}
if os.access(self.PROC, os.R_OK):
# Open File
file = open(self.PROC)
# Build Regular Expression
greed = ''
if str_to_bool(self.config['greedy']):
greed = '\S*'
exp = (('^(?:\s*)((?:%s)%s):(?:\s*)' +
'(?P<rx_bytes>\d+)(?:\s*)' +
'(?P<rx_packets>\w+)(?:\s*)' +
'(?P<rx_errors>\d+)(?:\s*)' +
'(?P<rx_drop>\d+)(?:\s*)' +
'(?P<rx_fifo>\d+)(?:\s*)' +
'(?P<rx_frame>\d+)(?:\s*)' +
'(?P<rx_compressed>\d+)(?:\s*)' +
'(?P<rx_multicast>\d+)(?:\s*)' +
'(?P<tx_bytes>\d+)(?:\s*)' +
'(?P<tx_packets>\w+)(?:\s*)' +
'(?P<tx_errors>\d+)(?:\s*)' +
'(?P<tx_drop>\d+)(?:\s*)' +
'(?P<tx_fifo>\d+)(?:\s*)' +
'(?P<tx_colls>\d+)(?:\s*)' +
'(?P<tx_carrier>\d+)(?:\s*)' +
'(?P<tx_compressed>\d+)(?:.*)$') %
(('|'.join(self.config['interfaces'])), greed))
reg = re.compile(exp)
# Match Interfaces
for line in file:
match = reg.match(line)
if match:
device = match.group(1)
results[device] = match.groupdict()
# Close File
file.close()
else:
if not psutil:
self.log.error('Unable to import psutil')
self.log.error('No network metrics retrieved')
return None
network_stats = psutil.network_io_counters(True)
for device in network_stats.keys():
network_stat = network_stats[device]
results[device] = {}
results[device]['rx_bytes'] = network_stat.bytes_recv
results[device]['tx_bytes'] = network_stat.bytes_sent
results[device]['rx_packets'] = network_stat.packets_recv
results[device]['tx_packets'] = network_stat.packets_sent
for device in results:
stats = results[device]
for s, v in stats.items():
# Get Metric Name
metric_name = '.'.join([device, s])
# Get Metric Value
metric_value = self.derivative(metric_name,
long(v),
diamond.collector.MAX_COUNTER)
# Convert rx_bytes and tx_bytes
if s == 'rx_bytes' or s == 'tx_bytes':
convertor = diamond.convertor.binary(value=metric_value,
unit='byte')
for u in self.config['byte_unit']:
# Public Converted Metric
self.publish(metric_name.replace('bytes', u),
convertor.get(unit=u), 2)
else:
# Publish Metric Derivative
self.publish(metric_name, metric_value)
return None | [
"def",
"collect",
"(",
"self",
")",
":",
"# Initialize results",
"results",
"=",
"{",
"}",
"if",
"os",
".",
"access",
"(",
"self",
".",
"PROC",
",",
"os",
".",
"R_OK",
")",
":",
"# Open File",
"file",
"=",
"open",
"(",
"self",
".",
"PROC",
")",
"# ... | Collect network interface stats. | [
"Collect",
"network",
"interface",
"stats",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/network/network.py#L51-L133 |
236,264 | python-diamond/Diamond | src/collectors/conntrack/conntrack.py | ConnTrackCollector.get_default_config_help | def get_default_config_help(self):
"""
Return help text for collector configuration
"""
config_help = super(ConnTrackCollector, self).get_default_config_help()
config_help.update({
"dir": "Directories with files of interest, comma seperated",
"files": "List of files to collect statistics from",
})
return config_help | python | def get_default_config_help(self):
config_help = super(ConnTrackCollector, self).get_default_config_help()
config_help.update({
"dir": "Directories with files of interest, comma seperated",
"files": "List of files to collect statistics from",
})
return config_help | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config_help",
"=",
"super",
"(",
"ConnTrackCollector",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config_help",
".",
"update",
"(",
"{",
"\"dir\"",
":",
"\"Directories with files of interest... | Return help text for collector configuration | [
"Return",
"help",
"text",
"for",
"collector",
"configuration"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/conntrack/conntrack.py#L22-L31 |
236,265 | python-diamond/Diamond | src/collectors/netapp/netapp.py | NetAppCollector._replace_and_publish | def _replace_and_publish(self, path, prettyname, value, device):
"""
Inputs a complete path for a metric and a value.
Replace the metric name and publish.
"""
if value is None:
return
newpath = path
# Change metric name before publish if needed.
newpath = ".".join([".".join(path.split(".")[:-1]), prettyname])
metric = Metric(newpath, value, precision=4, host=device)
self.publish_metric(metric) | python | def _replace_and_publish(self, path, prettyname, value, device):
if value is None:
return
newpath = path
# Change metric name before publish if needed.
newpath = ".".join([".".join(path.split(".")[:-1]), prettyname])
metric = Metric(newpath, value, precision=4, host=device)
self.publish_metric(metric) | [
"def",
"_replace_and_publish",
"(",
"self",
",",
"path",
",",
"prettyname",
",",
"value",
",",
"device",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"newpath",
"=",
"path",
"# Change metric name before publish if needed.",
"newpath",
"=",
"\".\"",
".",... | Inputs a complete path for a metric and a value.
Replace the metric name and publish. | [
"Inputs",
"a",
"complete",
"path",
"for",
"a",
"metric",
"and",
"a",
"value",
".",
"Replace",
"the",
"metric",
"name",
"and",
"publish",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netapp.py#L204-L215 |
236,266 | python-diamond/Diamond | src/collectors/netapp/netapp.py | NetAppCollector._gen_delta_depend | def _gen_delta_depend(self, path, derivative, multiplier, prettyname,
device):
"""
For some metrics we need to divide the delta for one metric
with the delta of another.
Publishes a metric if the convertion goes well.
"""
primary_delta = derivative[path]
shortpath = ".".join(path.split(".")[:-1])
basename = path.split(".")[-1]
secondary_delta = None
if basename in self.DIVIDERS.keys():
mateKey = ".".join([shortpath, self.DIVIDERS[basename]])
else:
return
if mateKey in derivative.keys():
secondary_delta = derivative[mateKey]
else:
return
# If we find a corresponding secondary_delta, publish a metric
if primary_delta > 0 and secondary_delta > 0:
value = (float(primary_delta) / secondary_delta) * multiplier
self._replace_and_publish(path, prettyname, value, device) | python | def _gen_delta_depend(self, path, derivative, multiplier, prettyname,
device):
primary_delta = derivative[path]
shortpath = ".".join(path.split(".")[:-1])
basename = path.split(".")[-1]
secondary_delta = None
if basename in self.DIVIDERS.keys():
mateKey = ".".join([shortpath, self.DIVIDERS[basename]])
else:
return
if mateKey in derivative.keys():
secondary_delta = derivative[mateKey]
else:
return
# If we find a corresponding secondary_delta, publish a metric
if primary_delta > 0 and secondary_delta > 0:
value = (float(primary_delta) / secondary_delta) * multiplier
self._replace_and_publish(path, prettyname, value, device) | [
"def",
"_gen_delta_depend",
"(",
"self",
",",
"path",
",",
"derivative",
",",
"multiplier",
",",
"prettyname",
",",
"device",
")",
":",
"primary_delta",
"=",
"derivative",
"[",
"path",
"]",
"shortpath",
"=",
"\".\"",
".",
"join",
"(",
"path",
".",
"split",... | For some metrics we need to divide the delta for one metric
with the delta of another.
Publishes a metric if the convertion goes well. | [
"For",
"some",
"metrics",
"we",
"need",
"to",
"divide",
"the",
"delta",
"for",
"one",
"metric",
"with",
"the",
"delta",
"of",
"another",
".",
"Publishes",
"a",
"metric",
"if",
"the",
"convertion",
"goes",
"well",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netapp.py#L217-L240 |
236,267 | python-diamond/Diamond | src/collectors/netapp/netapp.py | NetAppCollector._gen_delta_per_sec | def _gen_delta_per_sec(self, path, value_delta, time_delta, multiplier,
prettyname, device):
"""
Calulates the difference between to point, and scales is to per second.
"""
if time_delta < 0:
return
value = (value_delta / time_delta) * multiplier
# Only publish if there is any data.
# This helps keep unused metrics out of Graphite
if value > 0.0:
self._replace_and_publish(path, prettyname, value, device) | python | def _gen_delta_per_sec(self, path, value_delta, time_delta, multiplier,
prettyname, device):
if time_delta < 0:
return
value = (value_delta / time_delta) * multiplier
# Only publish if there is any data.
# This helps keep unused metrics out of Graphite
if value > 0.0:
self._replace_and_publish(path, prettyname, value, device) | [
"def",
"_gen_delta_per_sec",
"(",
"self",
",",
"path",
",",
"value_delta",
",",
"time_delta",
",",
"multiplier",
",",
"prettyname",
",",
"device",
")",
":",
"if",
"time_delta",
"<",
"0",
":",
"return",
"value",
"=",
"(",
"value_delta",
"/",
"time_delta",
"... | Calulates the difference between to point, and scales is to per second. | [
"Calulates",
"the",
"difference",
"between",
"to",
"point",
"and",
"scales",
"is",
"to",
"per",
"second",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netapp.py#L242-L253 |
236,268 | python-diamond/Diamond | src/diamond/handler/datadog.py | DatadogHandler._send | def _send(self):
"""
Take metrics from queue and send it to Datadog API
"""
while len(self.queue) > 0:
metric = self.queue.popleft()
path = '%s.%s.%s' % (
metric.getPathPrefix(),
metric.getCollectorPath(),
metric.getMetricPath()
)
topic, value, timestamp = str(metric).split()
logging.debug(
"Sending.. topic[%s], value[%s], timestamp[%s]",
path,
value,
timestamp
)
self.api.metric(path, (timestamp, value), host=metric.host) | python | def _send(self):
while len(self.queue) > 0:
metric = self.queue.popleft()
path = '%s.%s.%s' % (
metric.getPathPrefix(),
metric.getCollectorPath(),
metric.getMetricPath()
)
topic, value, timestamp = str(metric).split()
logging.debug(
"Sending.. topic[%s], value[%s], timestamp[%s]",
path,
value,
timestamp
)
self.api.metric(path, (timestamp, value), host=metric.host) | [
"def",
"_send",
"(",
"self",
")",
":",
"while",
"len",
"(",
"self",
".",
"queue",
")",
">",
"0",
":",
"metric",
"=",
"self",
".",
"queue",
".",
"popleft",
"(",
")",
"path",
"=",
"'%s.%s.%s'",
"%",
"(",
"metric",
".",
"getPathPrefix",
"(",
")",
",... | Take metrics from queue and send it to Datadog API | [
"Take",
"metrics",
"from",
"queue",
"and",
"send",
"it",
"to",
"Datadog",
"API"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/datadog.py#L84-L106 |
236,269 | python-diamond/Diamond | setup.py | get_version | def get_version():
"""
Read the version.txt file to get the new version string
Generate it if version.txt is not available. Generation
is required for pip installs
"""
try:
f = open('version.txt')
except IOError:
os.system("./version.sh > version.txt")
f = open('version.txt')
version = ''.join(f.readlines()).rstrip()
f.close()
return version | python | def get_version():
try:
f = open('version.txt')
except IOError:
os.system("./version.sh > version.txt")
f = open('version.txt')
version = ''.join(f.readlines()).rstrip()
f.close()
return version | [
"def",
"get_version",
"(",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"'version.txt'",
")",
"except",
"IOError",
":",
"os",
".",
"system",
"(",
"\"./version.sh > version.txt\"",
")",
"f",
"=",
"open",
"(",
"'version.txt'",
")",
"version",
"=",
"''",
".... | Read the version.txt file to get the new version string
Generate it if version.txt is not available. Generation
is required for pip installs | [
"Read",
"the",
"version",
".",
"txt",
"file",
"to",
"get",
"the",
"new",
"version",
"string",
"Generate",
"it",
"if",
"version",
".",
"txt",
"is",
"not",
"available",
".",
"Generation",
"is",
"required",
"for",
"pip",
"installs"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/setup.py#L98-L111 |
236,270 | python-diamond/Diamond | setup.py | pkgPath | def pkgPath(root, path, rpath="/"):
"""
Package up a path recursively
"""
global data_files
if not os.path.exists(path):
return
files = []
for spath in os.listdir(path):
# Ignore test directories
if spath == 'test':
continue
subpath = os.path.join(path, spath)
spath = os.path.join(rpath, spath)
if os.path.isfile(subpath):
files.append(subpath)
if os.path.isdir(subpath):
pkgPath(root, subpath, spath)
data_files.append((root + rpath, files)) | python | def pkgPath(root, path, rpath="/"):
global data_files
if not os.path.exists(path):
return
files = []
for spath in os.listdir(path):
# Ignore test directories
if spath == 'test':
continue
subpath = os.path.join(path, spath)
spath = os.path.join(rpath, spath)
if os.path.isfile(subpath):
files.append(subpath)
if os.path.isdir(subpath):
pkgPath(root, subpath, spath)
data_files.append((root + rpath, files)) | [
"def",
"pkgPath",
"(",
"root",
",",
"path",
",",
"rpath",
"=",
"\"/\"",
")",
":",
"global",
"data_files",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"files",
"=",
"[",
"]",
"for",
"spath",
"in",
"os",
".",
"li... | Package up a path recursively | [
"Package",
"up",
"a",
"path",
"recursively"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/setup.py#L114-L132 |
236,271 | python-diamond/Diamond | src/diamond/handler/statsite.py | StatsiteHandler._send | def _send(self, data):
"""
Send data to statsite. Data that can not be sent will be queued.
"""
retry = self.RETRY
# Attempt to send any data in the queue
while retry > 0:
# Check socket
if not self.socket:
# Log Error
self.log.error("StatsiteHandler: Socket unavailable.")
# Attempt to restablish connection
self._connect()
# Decrement retry
retry -= 1
# Try again
continue
try:
# Send data to socket
data = data.split()
data = data[0] + ":" + data[1] + "|kv\n"
self.socket.sendall(data)
# Done
break
except socket.error as e:
# Log Error
self.log.error("StatsiteHandler: Failed sending data. %s.", e)
# Attempt to restablish connection
self._close()
# Decrement retry
retry -= 1
# try again
continue | python | def _send(self, data):
retry = self.RETRY
# Attempt to send any data in the queue
while retry > 0:
# Check socket
if not self.socket:
# Log Error
self.log.error("StatsiteHandler: Socket unavailable.")
# Attempt to restablish connection
self._connect()
# Decrement retry
retry -= 1
# Try again
continue
try:
# Send data to socket
data = data.split()
data = data[0] + ":" + data[1] + "|kv\n"
self.socket.sendall(data)
# Done
break
except socket.error as e:
# Log Error
self.log.error("StatsiteHandler: Failed sending data. %s.", e)
# Attempt to restablish connection
self._close()
# Decrement retry
retry -= 1
# try again
continue | [
"def",
"_send",
"(",
"self",
",",
"data",
")",
":",
"retry",
"=",
"self",
".",
"RETRY",
"# Attempt to send any data in the queue",
"while",
"retry",
">",
"0",
":",
"# Check socket",
"if",
"not",
"self",
".",
"socket",
":",
"# Log Error",
"self",
".",
"log",
... | Send data to statsite. Data that can not be sent will be queued. | [
"Send",
"data",
"to",
"statsite",
".",
"Data",
"that",
"can",
"not",
"be",
"sent",
"will",
"be",
"queued",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/statsite.py#L127-L159 |
236,272 | python-diamond/Diamond | src/diamond/handler/statsite.py | StatsiteHandler._connect | def _connect(self):
"""
Connect to the statsite server
"""
# Create socket
if self.udpport > 0:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.port = self.udpport
elif self.tcpport > 0:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = self.tcpport
if socket is None:
# Log Error
self.log.error("StatsiteHandler: Unable to create socket.")
# Close Socket
self._close()
return
# Set socket timeout
self.socket.settimeout(self.timeout)
# Connect to statsite server
try:
self.socket.connect((self.host, self.port))
# Log
self.log.debug("Established connection to statsite server %s:%d",
self.host, self.port)
except Exception as ex:
# Log Error
self.log.error("StatsiteHandler: Failed to connect to %s:%i. %s",
self.host, self.port, ex)
# Close Socket
self._close()
return | python | def _connect(self):
# Create socket
if self.udpport > 0:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.port = self.udpport
elif self.tcpport > 0:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = self.tcpport
if socket is None:
# Log Error
self.log.error("StatsiteHandler: Unable to create socket.")
# Close Socket
self._close()
return
# Set socket timeout
self.socket.settimeout(self.timeout)
# Connect to statsite server
try:
self.socket.connect((self.host, self.port))
# Log
self.log.debug("Established connection to statsite server %s:%d",
self.host, self.port)
except Exception as ex:
# Log Error
self.log.error("StatsiteHandler: Failed to connect to %s:%i. %s",
self.host, self.port, ex)
# Close Socket
self._close()
return | [
"def",
"_connect",
"(",
"self",
")",
":",
"# Create socket",
"if",
"self",
".",
"udpport",
">",
"0",
":",
"self",
".",
"socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"self",
".",
"port",
... | Connect to the statsite server | [
"Connect",
"to",
"the",
"statsite",
"server"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/statsite.py#L161-L192 |
236,273 | python-diamond/Diamond | src/diamond/utils/classes.py | load_include_path | def load_include_path(paths):
"""
Scan for and add paths to the include path
"""
for path in paths:
# Verify the path is valid
if not os.path.isdir(path):
continue
# Add path to the system path, to avoid name clashes
# with mysql-connector for example ...
if path not in sys.path:
sys.path.insert(1, path)
# Load all the files in path
for f in os.listdir(path):
# Are we a directory? If so process down the tree
fpath = os.path.join(path, f)
if os.path.isdir(fpath):
load_include_path([fpath]) | python | def load_include_path(paths):
for path in paths:
# Verify the path is valid
if not os.path.isdir(path):
continue
# Add path to the system path, to avoid name clashes
# with mysql-connector for example ...
if path not in sys.path:
sys.path.insert(1, path)
# Load all the files in path
for f in os.listdir(path):
# Are we a directory? If so process down the tree
fpath = os.path.join(path, f)
if os.path.isdir(fpath):
load_include_path([fpath]) | [
"def",
"load_include_path",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"# Verify the path is valid",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"continue",
"# Add path to the system path, to avoid name clashes",
"# with mysq... | Scan for and add paths to the include path | [
"Scan",
"for",
"and",
"add",
"paths",
"to",
"the",
"include",
"path"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L19-L36 |
236,274 | python-diamond/Diamond | src/diamond/utils/classes.py | load_dynamic_class | def load_dynamic_class(fqn, subclass):
"""
Dynamically load fqn class and verify it's a subclass of subclass
"""
if not isinstance(fqn, basestring):
return fqn
cls = load_class_from_name(fqn)
if cls == subclass or not issubclass(cls, subclass):
raise TypeError("%s is not a valid %s" % (fqn, subclass.__name__))
return cls | python | def load_dynamic_class(fqn, subclass):
if not isinstance(fqn, basestring):
return fqn
cls = load_class_from_name(fqn)
if cls == subclass or not issubclass(cls, subclass):
raise TypeError("%s is not a valid %s" % (fqn, subclass.__name__))
return cls | [
"def",
"load_dynamic_class",
"(",
"fqn",
",",
"subclass",
")",
":",
"if",
"not",
"isinstance",
"(",
"fqn",
",",
"basestring",
")",
":",
"return",
"fqn",
"cls",
"=",
"load_class_from_name",
"(",
"fqn",
")",
"if",
"cls",
"==",
"subclass",
"or",
"not",
"iss... | Dynamically load fqn class and verify it's a subclass of subclass | [
"Dynamically",
"load",
"fqn",
"class",
"and",
"verify",
"it",
"s",
"a",
"subclass",
"of",
"subclass"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L39-L51 |
236,275 | python-diamond/Diamond | src/diamond/utils/classes.py | load_collectors_from_paths | def load_collectors_from_paths(paths):
"""
Scan for collectors to load from path
"""
# Initialize return value
collectors = {}
if paths is None:
return
if isinstance(paths, basestring):
paths = paths.split(',')
paths = map(str.strip, paths)
load_include_path(paths)
for path in paths:
# Get a list of files in the directory, if the directory exists
if not os.path.exists(path):
raise OSError("Directory does not exist: %s" % path)
if path.endswith('tests') or path.endswith('fixtures'):
return collectors
# Load all the files in path
for f in os.listdir(path):
# Are we a directory? If so process down the tree
fpath = os.path.join(path, f)
if os.path.isdir(fpath):
subcollectors = load_collectors_from_paths([fpath])
for key in subcollectors:
collectors[key] = subcollectors[key]
# Ignore anything that isn't a .py file
elif (os.path.isfile(fpath) and
len(f) > 3 and
f[-3:] == '.py' and
f[0:4] != 'test' and
f[0] != '.'):
modname = f[:-3]
fp, pathname, description = imp.find_module(modname, [path])
try:
# Import the module
mod = imp.load_module(modname, fp, pathname, description)
except (KeyboardInterrupt, SystemExit) as err:
logger.error(
"System or keyboard interrupt "
"while loading module %s"
% modname)
if isinstance(err, SystemExit):
sys.exit(err.code)
raise KeyboardInterrupt
except Exception:
# Log error
logger.error("Failed to import module: %s. %s",
modname,
traceback.format_exc())
else:
for name, cls in get_collectors_from_module(mod):
collectors[name] = cls
finally:
if fp:
fp.close()
# Return Collector classes
return collectors | python | def load_collectors_from_paths(paths):
# Initialize return value
collectors = {}
if paths is None:
return
if isinstance(paths, basestring):
paths = paths.split(',')
paths = map(str.strip, paths)
load_include_path(paths)
for path in paths:
# Get a list of files in the directory, if the directory exists
if not os.path.exists(path):
raise OSError("Directory does not exist: %s" % path)
if path.endswith('tests') or path.endswith('fixtures'):
return collectors
# Load all the files in path
for f in os.listdir(path):
# Are we a directory? If so process down the tree
fpath = os.path.join(path, f)
if os.path.isdir(fpath):
subcollectors = load_collectors_from_paths([fpath])
for key in subcollectors:
collectors[key] = subcollectors[key]
# Ignore anything that isn't a .py file
elif (os.path.isfile(fpath) and
len(f) > 3 and
f[-3:] == '.py' and
f[0:4] != 'test' and
f[0] != '.'):
modname = f[:-3]
fp, pathname, description = imp.find_module(modname, [path])
try:
# Import the module
mod = imp.load_module(modname, fp, pathname, description)
except (KeyboardInterrupt, SystemExit) as err:
logger.error(
"System or keyboard interrupt "
"while loading module %s"
% modname)
if isinstance(err, SystemExit):
sys.exit(err.code)
raise KeyboardInterrupt
except Exception:
# Log error
logger.error("Failed to import module: %s. %s",
modname,
traceback.format_exc())
else:
for name, cls in get_collectors_from_module(mod):
collectors[name] = cls
finally:
if fp:
fp.close()
# Return Collector classes
return collectors | [
"def",
"load_collectors_from_paths",
"(",
"paths",
")",
":",
"# Initialize return value",
"collectors",
"=",
"{",
"}",
"if",
"paths",
"is",
"None",
":",
"return",
"if",
"isinstance",
"(",
"paths",
",",
"basestring",
")",
":",
"paths",
"=",
"paths",
".",
"spl... | Scan for collectors to load from path | [
"Scan",
"for",
"collectors",
"to",
"load",
"from",
"path"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L112-L181 |
236,276 | python-diamond/Diamond | src/diamond/utils/classes.py | load_collectors_from_entry_point | def load_collectors_from_entry_point(path):
"""
Load collectors that were installed into an entry_point.
"""
collectors = {}
for ep in pkg_resources.iter_entry_points(path):
try:
mod = ep.load()
except Exception:
logger.error('Failed to import entry_point: %s. %s',
ep.name,
traceback.format_exc())
else:
collectors.update(get_collectors_from_module(mod))
return collectors | python | def load_collectors_from_entry_point(path):
collectors = {}
for ep in pkg_resources.iter_entry_points(path):
try:
mod = ep.load()
except Exception:
logger.error('Failed to import entry_point: %s. %s',
ep.name,
traceback.format_exc())
else:
collectors.update(get_collectors_from_module(mod))
return collectors | [
"def",
"load_collectors_from_entry_point",
"(",
"path",
")",
":",
"collectors",
"=",
"{",
"}",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"path",
")",
":",
"try",
":",
"mod",
"=",
"ep",
".",
"load",
"(",
")",
"except",
"Exception",
... | Load collectors that were installed into an entry_point. | [
"Load",
"collectors",
"that",
"were",
"installed",
"into",
"an",
"entry_point",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L184-L198 |
236,277 | python-diamond/Diamond | src/diamond/utils/classes.py | get_collectors_from_module | def get_collectors_from_module(mod):
"""
Locate all of the collector classes within a given module
"""
for attrname in dir(mod):
attr = getattr(mod, attrname)
# Only attempt to load classes that are infact classes
# are Collectors but are not the base Collector class
if ((inspect.isclass(attr) and
issubclass(attr, Collector) and
attr != Collector)):
if attrname.startswith('parent_'):
continue
# Get class name
fqcn = '.'.join([mod.__name__, attrname])
try:
# Load Collector class
cls = load_dynamic_class(fqcn, Collector)
# Add Collector class
yield cls.__name__, cls
except Exception:
# Log error
logger.error(
"Failed to load Collector: %s. %s",
fqcn, traceback.format_exc())
continue | python | def get_collectors_from_module(mod):
for attrname in dir(mod):
attr = getattr(mod, attrname)
# Only attempt to load classes that are infact classes
# are Collectors but are not the base Collector class
if ((inspect.isclass(attr) and
issubclass(attr, Collector) and
attr != Collector)):
if attrname.startswith('parent_'):
continue
# Get class name
fqcn = '.'.join([mod.__name__, attrname])
try:
# Load Collector class
cls = load_dynamic_class(fqcn, Collector)
# Add Collector class
yield cls.__name__, cls
except Exception:
# Log error
logger.error(
"Failed to load Collector: %s. %s",
fqcn, traceback.format_exc())
continue | [
"def",
"get_collectors_from_module",
"(",
"mod",
")",
":",
"for",
"attrname",
"in",
"dir",
"(",
"mod",
")",
":",
"attr",
"=",
"getattr",
"(",
"mod",
",",
"attrname",
")",
"# Only attempt to load classes that are infact classes",
"# are Collectors but are not the base Co... | Locate all of the collector classes within a given module | [
"Locate",
"all",
"of",
"the",
"collector",
"classes",
"within",
"a",
"given",
"module"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/classes.py#L201-L226 |
236,278 | python-diamond/Diamond | src/diamond/handler/mysql.py | MySQLHandler._send | def _send(self, data):
"""
Insert the data
"""
data = data.strip().split(' ')
try:
cursor = self.conn.cursor()
cursor.execute("INSERT INTO %s (%s, %s, %s) VALUES(%%s, %%s, %%s)"
% (self.table, self.col_metric,
self.col_time, self.col_value),
(data[0], data[2], data[1]))
cursor.close()
self.conn.commit()
except BaseException as e:
# Log Error
self.log.error("MySQLHandler: Failed sending data. %s.", e)
# Attempt to restablish connection
self._connect() | python | def _send(self, data):
data = data.strip().split(' ')
try:
cursor = self.conn.cursor()
cursor.execute("INSERT INTO %s (%s, %s, %s) VALUES(%%s, %%s, %%s)"
% (self.table, self.col_metric,
self.col_time, self.col_value),
(data[0], data[2], data[1]))
cursor.close()
self.conn.commit()
except BaseException as e:
# Log Error
self.log.error("MySQLHandler: Failed sending data. %s.", e)
# Attempt to restablish connection
self._connect() | [
"def",
"_send",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
".",
"strip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"try",
":",
"cursor",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"INSERT INTO... | Insert the data | [
"Insert",
"the",
"data"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/mysql.py#L73-L90 |
236,279 | python-diamond/Diamond | src/diamond/handler/mysql.py | MySQLHandler._connect | def _connect(self):
"""
Connect to the MySQL server
"""
self._close()
self.conn = MySQLdb.Connect(host=self.hostname,
port=self.port,
user=self.username,
passwd=self.password,
db=self.database) | python | def _connect(self):
self._close()
self.conn = MySQLdb.Connect(host=self.hostname,
port=self.port,
user=self.username,
passwd=self.password,
db=self.database) | [
"def",
"_connect",
"(",
"self",
")",
":",
"self",
".",
"_close",
"(",
")",
"self",
".",
"conn",
"=",
"MySQLdb",
".",
"Connect",
"(",
"host",
"=",
"self",
".",
"hostname",
",",
"port",
"=",
"self",
".",
"port",
",",
"user",
"=",
"self",
".",
"user... | Connect to the MySQL server | [
"Connect",
"to",
"the",
"MySQL",
"server"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/mysql.py#L92-L101 |
236,280 | python-diamond/Diamond | src/collectors/nvidia_gpu/nvidia_gpu.py | NvidiaGPUCollector.collect | def collect(self):
"""
Collector GPU stats
"""
stats_config = self.config['stats']
if USE_PYTHON_BINDING:
collect_metrics = self.collect_via_pynvml
else:
collect_metrics = self.collect_via_nvidia_smi
collect_metrics(stats_config) | python | def collect(self):
stats_config = self.config['stats']
if USE_PYTHON_BINDING:
collect_metrics = self.collect_via_pynvml
else:
collect_metrics = self.collect_via_nvidia_smi
collect_metrics(stats_config) | [
"def",
"collect",
"(",
"self",
")",
":",
"stats_config",
"=",
"self",
".",
"config",
"[",
"'stats'",
"]",
"if",
"USE_PYTHON_BINDING",
":",
"collect_metrics",
"=",
"self",
".",
"collect_via_pynvml",
"else",
":",
"collect_metrics",
"=",
"self",
".",
"collect_via... | Collector GPU stats | [
"Collector",
"GPU",
"stats"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nvidia_gpu/nvidia_gpu.py#L119-L129 |
236,281 | python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | decode_network_values | def decode_network_values(ptype, plen, buf):
"""Decodes a list of DS values in collectd network format
"""
nvalues = short.unpack_from(buf, header.size)[0]
off = header.size + short.size + nvalues
valskip = double.size
# Check whether our expected packet size is the reported one
assert ((valskip + 1) * nvalues + short.size + header.size) == plen
assert double.size == number.size
result = []
for dstype in [ord(x) for x in buf[header.size + short.size:off]]:
if dstype == DS_TYPE_COUNTER:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_GAUGE:
result.append((dstype, double.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_DERIVE:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_ABSOLUTE:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
else:
raise ValueError("DS type %i unsupported" % dstype)
return result | python | def decode_network_values(ptype, plen, buf):
nvalues = short.unpack_from(buf, header.size)[0]
off = header.size + short.size + nvalues
valskip = double.size
# Check whether our expected packet size is the reported one
assert ((valskip + 1) * nvalues + short.size + header.size) == plen
assert double.size == number.size
result = []
for dstype in [ord(x) for x in buf[header.size + short.size:off]]:
if dstype == DS_TYPE_COUNTER:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_GAUGE:
result.append((dstype, double.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_DERIVE:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
elif dstype == DS_TYPE_ABSOLUTE:
result.append((dstype, number.unpack_from(buf, off)[0]))
off += valskip
else:
raise ValueError("DS type %i unsupported" % dstype)
return result | [
"def",
"decode_network_values",
"(",
"ptype",
",",
"plen",
",",
"buf",
")",
":",
"nvalues",
"=",
"short",
".",
"unpack_from",
"(",
"buf",
",",
"header",
".",
"size",
")",
"[",
"0",
"]",
"off",
"=",
"header",
".",
"size",
"+",
"short",
".",
"size",
... | Decodes a list of DS values in collectd network format | [
"Decodes",
"a",
"list",
"of",
"DS",
"values",
"in",
"collectd",
"network",
"format"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L83-L111 |
236,282 | python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | decode_network_packet | def decode_network_packet(buf):
"""Decodes a network packet in collectd format.
"""
off = 0
blen = len(buf)
while off < blen:
ptype, plen = header.unpack_from(buf, off)
if plen > blen - off:
raise ValueError("Packet longer than amount of data in buffer")
if ptype not in _decoders:
raise ValueError("Message type %i not recognized" % ptype)
yield ptype, _decoders[ptype](ptype, plen, buf[off:])
off += plen | python | def decode_network_packet(buf):
off = 0
blen = len(buf)
while off < blen:
ptype, plen = header.unpack_from(buf, off)
if plen > blen - off:
raise ValueError("Packet longer than amount of data in buffer")
if ptype not in _decoders:
raise ValueError("Message type %i not recognized" % ptype)
yield ptype, _decoders[ptype](ptype, plen, buf[off:])
off += plen | [
"def",
"decode_network_packet",
"(",
"buf",
")",
":",
"off",
"=",
"0",
"blen",
"=",
"len",
"(",
"buf",
")",
"while",
"off",
"<",
"blen",
":",
"ptype",
",",
"plen",
"=",
"header",
".",
"unpack_from",
"(",
"buf",
",",
"off",
")",
"if",
"plen",
">",
... | Decodes a network packet in collectd format. | [
"Decodes",
"a",
"network",
"packet",
"in",
"collectd",
"format",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L143-L159 |
236,283 | python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | Reader.receive | def receive(self, poll_interval):
"""Receives a single raw collect network packet.
"""
readable, writeable, errored = select.select(self._readlist, [], [],
poll_interval)
for s in readable:
data, addr = s.recvfrom(self.BUFFER_SIZE)
if data:
return data
return None | python | def receive(self, poll_interval):
readable, writeable, errored = select.select(self._readlist, [], [],
poll_interval)
for s in readable:
data, addr = s.recvfrom(self.BUFFER_SIZE)
if data:
return data
return None | [
"def",
"receive",
"(",
"self",
",",
"poll_interval",
")",
":",
"readable",
",",
"writeable",
",",
"errored",
"=",
"select",
".",
"select",
"(",
"self",
".",
"_readlist",
",",
"[",
"]",
",",
"[",
"]",
",",
"poll_interval",
")",
"for",
"s",
"in",
"read... | Receives a single raw collect network packet. | [
"Receives",
"a",
"single",
"raw",
"collect",
"network",
"packet",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L341-L351 |
236,284 | python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | Reader.decode | def decode(self, poll_interval, buf=None):
"""Decodes a given buffer or the next received packet.
"""
if buf is None:
buf = self.receive(poll_interval)
if buf is None:
return None
return decode_network_packet(buf) | python | def decode(self, poll_interval, buf=None):
if buf is None:
buf = self.receive(poll_interval)
if buf is None:
return None
return decode_network_packet(buf) | [
"def",
"decode",
"(",
"self",
",",
"poll_interval",
",",
"buf",
"=",
"None",
")",
":",
"if",
"buf",
"is",
"None",
":",
"buf",
"=",
"self",
".",
"receive",
"(",
"poll_interval",
")",
"if",
"buf",
"is",
"None",
":",
"return",
"None",
"return",
"decode_... | Decodes a given buffer or the next received packet. | [
"Decodes",
"a",
"given",
"buffer",
"or",
"the",
"next",
"received",
"packet",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L353-L360 |
236,285 | python-diamond/Diamond | src/collectors/jcollectd/collectd_network.py | Reader.interpret | def interpret(self, iterable=None, poll_interval=0.2):
"""Interprets a sequence
"""
if iterable is None:
iterable = self.decode(poll_interval)
if iterable is None:
return None
if isinstance(iterable, basestring):
iterable = self.decode(poll_interval, iterable)
return interpret_opcodes(iterable) | python | def interpret(self, iterable=None, poll_interval=0.2):
if iterable is None:
iterable = self.decode(poll_interval)
if iterable is None:
return None
if isinstance(iterable, basestring):
iterable = self.decode(poll_interval, iterable)
return interpret_opcodes(iterable) | [
"def",
"interpret",
"(",
"self",
",",
"iterable",
"=",
"None",
",",
"poll_interval",
"=",
"0.2",
")",
":",
"if",
"iterable",
"is",
"None",
":",
"iterable",
"=",
"self",
".",
"decode",
"(",
"poll_interval",
")",
"if",
"iterable",
"is",
"None",
":",
"ret... | Interprets a sequence | [
"Interprets",
"a",
"sequence"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/jcollectd/collectd_network.py#L362-L373 |
236,286 | ncclient/ncclient | ncclient/manager.py | make_device_handler | def make_device_handler(device_params):
"""
Create a device handler object that provides device specific parameters and
functions, which are called in various places throughout our code.
If no device_params are defined or the "name" in the parameter dict is not
known then a default handler will be returned.
"""
if device_params is None:
device_params = {}
handler = device_params.get('handler', None)
if handler:
return handler(device_params)
device_name = device_params.get("name", "default")
# Attempt to import device handler class. All device handlers are
# in a module called "ncclient.devices.<devicename>" and in a class named
# "<devicename>DeviceHandler", with the first letter capitalized.
class_name = "%sDeviceHandler" % device_name.capitalize()
devices_module_name = "ncclient.devices.%s" % device_name
dev_module_obj = __import__(devices_module_name)
handler_module_obj = getattr(getattr(dev_module_obj, "devices"), device_name)
class_obj = getattr(handler_module_obj, class_name)
handler_obj = class_obj(device_params)
return handler_obj | python | def make_device_handler(device_params):
if device_params is None:
device_params = {}
handler = device_params.get('handler', None)
if handler:
return handler(device_params)
device_name = device_params.get("name", "default")
# Attempt to import device handler class. All device handlers are
# in a module called "ncclient.devices.<devicename>" and in a class named
# "<devicename>DeviceHandler", with the first letter capitalized.
class_name = "%sDeviceHandler" % device_name.capitalize()
devices_module_name = "ncclient.devices.%s" % device_name
dev_module_obj = __import__(devices_module_name)
handler_module_obj = getattr(getattr(dev_module_obj, "devices"), device_name)
class_obj = getattr(handler_module_obj, class_name)
handler_obj = class_obj(device_params)
return handler_obj | [
"def",
"make_device_handler",
"(",
"device_params",
")",
":",
"if",
"device_params",
"is",
"None",
":",
"device_params",
"=",
"{",
"}",
"handler",
"=",
"device_params",
".",
"get",
"(",
"'handler'",
",",
"None",
")",
"if",
"handler",
":",
"return",
"handler"... | Create a device handler object that provides device specific parameters and
functions, which are called in various places throughout our code.
If no device_params are defined or the "name" in the parameter dict is not
known then a default handler will be returned. | [
"Create",
"a",
"device",
"handler",
"object",
"that",
"provides",
"device",
"specific",
"parameters",
"and",
"functions",
"which",
"are",
"called",
"in",
"various",
"places",
"throughout",
"our",
"code",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/manager.py#L63-L89 |
236,287 | ncclient/ncclient | ncclient/manager.py | Manager.take_notification | def take_notification(self, block=True, timeout=None):
"""Attempt to retrieve one notification from the queue of received
notifications.
If block is True, the call will wait until a notification is
received.
If timeout is a number greater than 0, the call will wait that
many seconds to receive a notification before timing out.
If there is no notification available when block is False or
when the timeout has elapse, None will be returned.
Otherwise a :class:`~ncclient.operations.notify.Notification`
object will be returned.
"""
return self._session.take_notification(block, timeout) | python | def take_notification(self, block=True, timeout=None):
return self._session.take_notification(block, timeout) | [
"def",
"take_notification",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_session",
".",
"take_notification",
"(",
"block",
",",
"timeout",
")"
] | Attempt to retrieve one notification from the queue of received
notifications.
If block is True, the call will wait until a notification is
received.
If timeout is a number greater than 0, the call will wait that
many seconds to receive a notification before timing out.
If there is no notification available when block is False or
when the timeout has elapse, None will be returned.
Otherwise a :class:`~ncclient.operations.notify.Notification`
object will be returned. | [
"Attempt",
"to",
"retrieve",
"one",
"notification",
"from",
"the",
"queue",
"of",
"received",
"notifications",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/manager.py#L258-L274 |
236,288 | ncclient/ncclient | ncclient/operations/third_party/hpcomware/rpc.py | DisplayCommand.request | def request(self, cmds):
"""
Single Execution element is permitted.
cmds can be a list or single command
"""
if isinstance(cmds, list):
cmd = '\n'.join(cmds)
elif isinstance(cmds, str) or isinstance(cmds, unicode):
cmd = cmds
node = etree.Element(qualify('CLI', BASE_NS_1_0))
etree.SubElement(node, qualify('Execution',
BASE_NS_1_0)).text = cmd
return self._request(node) | python | def request(self, cmds):
if isinstance(cmds, list):
cmd = '\n'.join(cmds)
elif isinstance(cmds, str) or isinstance(cmds, unicode):
cmd = cmds
node = etree.Element(qualify('CLI', BASE_NS_1_0))
etree.SubElement(node, qualify('Execution',
BASE_NS_1_0)).text = cmd
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"cmds",
")",
":",
"if",
"isinstance",
"(",
"cmds",
",",
"list",
")",
":",
"cmd",
"=",
"'\\n'",
".",
"join",
"(",
"cmds",
")",
"elif",
"isinstance",
"(",
"cmds",
",",
"str",
")",
"or",
"isinstance",
"(",
"cmds",
... | Single Execution element is permitted.
cmds can be a list or single command | [
"Single",
"Execution",
"element",
"is",
"permitted",
".",
"cmds",
"can",
"be",
"a",
"list",
"or",
"single",
"command"
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/third_party/hpcomware/rpc.py#L7-L22 |
236,289 | ncclient/ncclient | ncclient/xml_.py | validated_element | def validated_element(x, tags=None, attrs=None):
"""Checks if the root element of an XML document or Element meets the supplied criteria.
*tags* if specified is either a single allowable tag name or sequence of allowable alternatives
*attrs* if specified is a sequence of required attributes, each of which may be a sequence of several allowable alternatives
Raises :exc:`XMLError` if the requirements are not met.
"""
ele = to_ele(x)
if tags:
if isinstance(tags, (str, bytes)):
tags = [tags]
if ele.tag not in tags:
raise XMLError("Element [%s] does not meet requirement" % ele.tag)
if attrs:
for req in attrs:
if isinstance(req, (str, bytes)): req = [req]
for alt in req:
if alt in ele.attrib:
break
else:
raise XMLError("Element [%s] does not have required attributes" % ele.tag)
return ele | python | def validated_element(x, tags=None, attrs=None):
ele = to_ele(x)
if tags:
if isinstance(tags, (str, bytes)):
tags = [tags]
if ele.tag not in tags:
raise XMLError("Element [%s] does not meet requirement" % ele.tag)
if attrs:
for req in attrs:
if isinstance(req, (str, bytes)): req = [req]
for alt in req:
if alt in ele.attrib:
break
else:
raise XMLError("Element [%s] does not have required attributes" % ele.tag)
return ele | [
"def",
"validated_element",
"(",
"x",
",",
"tags",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"ele",
"=",
"to_ele",
"(",
"x",
")",
"if",
"tags",
":",
"if",
"isinstance",
"(",
"tags",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"tags",
... | Checks if the root element of an XML document or Element meets the supplied criteria.
*tags* if specified is either a single allowable tag name or sequence of allowable alternatives
*attrs* if specified is a sequence of required attributes, each of which may be a sequence of several allowable alternatives
Raises :exc:`XMLError` if the requirements are not met. | [
"Checks",
"if",
"the",
"root",
"element",
"of",
"an",
"XML",
"document",
"or",
"Element",
"meets",
"the",
"supplied",
"criteria",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/xml_.py#L125-L148 |
236,290 | ncclient/ncclient | ncclient/xml_.py | NCElement.tostring | def tostring(self):
"""return a pretty-printed string output for rpc reply"""
parser = etree.XMLParser(remove_blank_text=True)
outputtree = etree.XML(etree.tostring(self.__doc), parser)
return etree.tostring(outputtree, pretty_print=True) | python | def tostring(self):
parser = etree.XMLParser(remove_blank_text=True)
outputtree = etree.XML(etree.tostring(self.__doc), parser)
return etree.tostring(outputtree, pretty_print=True) | [
"def",
"tostring",
"(",
"self",
")",
":",
"parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"outputtree",
"=",
"etree",
".",
"XML",
"(",
"etree",
".",
"tostring",
"(",
"self",
".",
"__doc",
")",
",",
"parser",
")",
... | return a pretty-printed string output for rpc reply | [
"return",
"a",
"pretty",
"-",
"printed",
"string",
"output",
"for",
"rpc",
"reply"
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/xml_.py#L192-L196 |
236,291 | ncclient/ncclient | ncclient/xml_.py | NCElement.remove_namespaces | def remove_namespaces(self, rpc_reply):
"""remove xmlns attributes from rpc reply"""
self.__xslt=self.__transform_reply
self.__parser = etree.XMLParser(remove_blank_text=True)
self.__xslt_doc = etree.parse(io.BytesIO(self.__xslt), self.__parser)
self.__transform = etree.XSLT(self.__xslt_doc)
self.__root = etree.fromstring(str(self.__transform(etree.parse(StringIO(str(rpc_reply))))))
return self.__root | python | def remove_namespaces(self, rpc_reply):
self.__xslt=self.__transform_reply
self.__parser = etree.XMLParser(remove_blank_text=True)
self.__xslt_doc = etree.parse(io.BytesIO(self.__xslt), self.__parser)
self.__transform = etree.XSLT(self.__xslt_doc)
self.__root = etree.fromstring(str(self.__transform(etree.parse(StringIO(str(rpc_reply))))))
return self.__root | [
"def",
"remove_namespaces",
"(",
"self",
",",
"rpc_reply",
")",
":",
"self",
".",
"__xslt",
"=",
"self",
".",
"__transform_reply",
"self",
".",
"__parser",
"=",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"self",
".",
"__xslt_doc",... | remove xmlns attributes from rpc reply | [
"remove",
"xmlns",
"attributes",
"from",
"rpc",
"reply"
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/xml_.py#L203-L210 |
236,292 | ncclient/ncclient | ncclient/operations/retrieve.py | GetSchema.request | def request(self, identifier, version=None, format=None):
"""Retrieve a named schema, with optional revision and type.
*identifier* name of the schema to be retrieved
*version* version of schema to get
*format* format of the schema to be retrieved, yang is the default
:seealso: :ref:`filter_params`"""
node = etree.Element(qualify("get-schema",NETCONF_MONITORING_NS))
if identifier is not None:
elem = etree.Element(qualify("identifier",NETCONF_MONITORING_NS))
elem.text = identifier
node.append(elem)
if version is not None:
elem = etree.Element(qualify("version",NETCONF_MONITORING_NS))
elem.text = version
node.append(elem)
if format is not None:
elem = etree.Element(qualify("format",NETCONF_MONITORING_NS))
elem.text = format
node.append(elem)
return self._request(node) | python | def request(self, identifier, version=None, format=None):
node = etree.Element(qualify("get-schema",NETCONF_MONITORING_NS))
if identifier is not None:
elem = etree.Element(qualify("identifier",NETCONF_MONITORING_NS))
elem.text = identifier
node.append(elem)
if version is not None:
elem = etree.Element(qualify("version",NETCONF_MONITORING_NS))
elem.text = version
node.append(elem)
if format is not None:
elem = etree.Element(qualify("format",NETCONF_MONITORING_NS))
elem.text = format
node.append(elem)
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"identifier",
",",
"version",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"node",
"=",
"etree",
".",
"Element",
"(",
"qualify",
"(",
"\"get-schema\"",
",",
"NETCONF_MONITORING_NS",
")",
")",
"if",
"identifier",
... | Retrieve a named schema, with optional revision and type.
*identifier* name of the schema to be retrieved
*version* version of schema to get
*format* format of the schema to be retrieved, yang is the default
:seealso: :ref:`filter_params` | [
"Retrieve",
"a",
"named",
"schema",
"with",
"optional",
"revision",
"and",
"type",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/retrieve.py#L175-L198 |
236,293 | ncclient/ncclient | ncclient/devices/default.py | DefaultDeviceHandler.is_rpc_error_exempt | def is_rpc_error_exempt(self, error_text):
"""
Check whether an RPC error message is excempt, thus NOT causing an exception.
On some devices the RPC operations may indicate an error response, even though
the operation actually succeeded. This may be in cases where a warning would be
more appropriate. In that case, the client may be better advised to simply
ignore that error and not raise an exception.
Note that there is also the "raise_mode", set on session and manager, which
controls the exception-raising behaviour in case of returned errors. This error
filter here is independent of that: No matter what the raise_mode says, if the
error message matches one of the exempt errors returned here, an exception
will not be raised.
The exempt error messages are defined in the _EXEMPT_ERRORS field of the device
handler object and can be overwritten by child classes. Wild cards are
possible: Start and/or end with a '*' to indicate that the text can appear at
the start, the end or the middle of the error message to still match. All
comparisons are case insensitive.
Return True/False depending on found match.
"""
if error_text is not None:
error_text = error_text.lower().strip()
else:
error_text = 'no error given'
# Compare the error text against all the exempt errors.
for ex in self._exempt_errors_exact_match:
if error_text == ex:
return True
for ex in self._exempt_errors_startwith_wildcard_match:
if error_text.endswith(ex):
return True
for ex in self._exempt_errors_endwith_wildcard_match:
if error_text.startswith(ex):
return True
for ex in self._exempt_errors_full_wildcard_match:
if ex in error_text:
return True
return False | python | def is_rpc_error_exempt(self, error_text):
if error_text is not None:
error_text = error_text.lower().strip()
else:
error_text = 'no error given'
# Compare the error text against all the exempt errors.
for ex in self._exempt_errors_exact_match:
if error_text == ex:
return True
for ex in self._exempt_errors_startwith_wildcard_match:
if error_text.endswith(ex):
return True
for ex in self._exempt_errors_endwith_wildcard_match:
if error_text.startswith(ex):
return True
for ex in self._exempt_errors_full_wildcard_match:
if ex in error_text:
return True
return False | [
"def",
"is_rpc_error_exempt",
"(",
"self",
",",
"error_text",
")",
":",
"if",
"error_text",
"is",
"not",
"None",
":",
"error_text",
"=",
"error_text",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"else",
":",
"error_text",
"=",
"'no error given'",
"# Co... | Check whether an RPC error message is excempt, thus NOT causing an exception.
On some devices the RPC operations may indicate an error response, even though
the operation actually succeeded. This may be in cases where a warning would be
more appropriate. In that case, the client may be better advised to simply
ignore that error and not raise an exception.
Note that there is also the "raise_mode", set on session and manager, which
controls the exception-raising behaviour in case of returned errors. This error
filter here is independent of that: No matter what the raise_mode says, if the
error message matches one of the exempt errors returned here, an exception
will not be raised.
The exempt error messages are defined in the _EXEMPT_ERRORS field of the device
handler object and can be overwritten by child classes. Wild cards are
possible: Start and/or end with a '*' to indicate that the text can appear at
the start, the end or the middle of the error message to still match. All
comparisons are case insensitive.
Return True/False depending on found match. | [
"Check",
"whether",
"an",
"RPC",
"error",
"message",
"is",
"excempt",
"thus",
"NOT",
"causing",
"an",
"exception",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/devices/default.py#L146-L192 |
236,294 | ncclient/ncclient | ncclient/devices/nexus.py | NexusDeviceHandler.get_ssh_subsystem_names | def get_ssh_subsystem_names(self):
"""
Return a list of possible SSH subsystem names.
Different NXOS versions use different SSH subsystem names for netconf.
Therefore, we return a list so that several can be tried, if necessary.
The Nexus device handler also accepts
"""
preferred_ssh_subsystem = self.device_params.get("ssh_subsystem_name")
name_list = [ "netconf", "xmlagent" ]
if preferred_ssh_subsystem:
return [ preferred_ssh_subsystem ] + \
[ n for n in name_list if n != preferred_ssh_subsystem ]
else:
return name_list | python | def get_ssh_subsystem_names(self):
preferred_ssh_subsystem = self.device_params.get("ssh_subsystem_name")
name_list = [ "netconf", "xmlagent" ]
if preferred_ssh_subsystem:
return [ preferred_ssh_subsystem ] + \
[ n for n in name_list if n != preferred_ssh_subsystem ]
else:
return name_list | [
"def",
"get_ssh_subsystem_names",
"(",
"self",
")",
":",
"preferred_ssh_subsystem",
"=",
"self",
".",
"device_params",
".",
"get",
"(",
"\"ssh_subsystem_name\"",
")",
"name_list",
"=",
"[",
"\"netconf\"",
",",
"\"xmlagent\"",
"]",
"if",
"preferred_ssh_subsystem",
":... | Return a list of possible SSH subsystem names.
Different NXOS versions use different SSH subsystem names for netconf.
Therefore, we return a list so that several can be tried, if necessary.
The Nexus device handler also accepts | [
"Return",
"a",
"list",
"of",
"possible",
"SSH",
"subsystem",
"names",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/devices/nexus.py#L79-L95 |
236,295 | ncclient/ncclient | ncclient/transport/session.py | Session.add_listener | def add_listener(self, listener):
"""Register a listener that will be notified of incoming messages and
errors.
:type listener: :class:`SessionListener`
"""
self.logger.debug('installing listener %r', listener)
if not isinstance(listener, SessionListener):
raise SessionError("Listener must be a SessionListener type")
with self._lock:
self._listeners.add(listener) | python | def add_listener(self, listener):
self.logger.debug('installing listener %r', listener)
if not isinstance(listener, SessionListener):
raise SessionError("Listener must be a SessionListener type")
with self._lock:
self._listeners.add(listener) | [
"def",
"add_listener",
"(",
"self",
",",
"listener",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'installing listener %r'",
",",
"listener",
")",
"if",
"not",
"isinstance",
"(",
"listener",
",",
"SessionListener",
")",
":",
"raise",
"SessionError",
... | Register a listener that will be notified of incoming messages and
errors.
:type listener: :class:`SessionListener` | [
"Register",
"a",
"listener",
"that",
"will",
"be",
"notified",
"of",
"incoming",
"messages",
"and",
"errors",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/transport/session.py#L125-L135 |
236,296 | ncclient/ncclient | ncclient/transport/session.py | Session.remove_listener | def remove_listener(self, listener):
"""Unregister some listener; ignore if the listener was never
registered.
:type listener: :class:`SessionListener`
"""
self.logger.debug('discarding listener %r', listener)
with self._lock:
self._listeners.discard(listener) | python | def remove_listener(self, listener):
self.logger.debug('discarding listener %r', listener)
with self._lock:
self._listeners.discard(listener) | [
"def",
"remove_listener",
"(",
"self",
",",
"listener",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'discarding listener %r'",
",",
"listener",
")",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_listeners",
".",
"discard",
"(",
"listener",
")"... | Unregister some listener; ignore if the listener was never
registered.
:type listener: :class:`SessionListener` | [
"Unregister",
"some",
"listener",
";",
"ignore",
"if",
"the",
"listener",
"was",
"never",
"registered",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/transport/session.py#L137-L145 |
236,297 | ncclient/ncclient | ncclient/transport/session.py | Session.get_listener_instance | def get_listener_instance(self, cls):
"""If a listener of the specified type is registered, returns the
instance.
:type cls: :class:`SessionListener`
"""
with self._lock:
for listener in self._listeners:
if isinstance(listener, cls):
return listener | python | def get_listener_instance(self, cls):
with self._lock:
for listener in self._listeners:
if isinstance(listener, cls):
return listener | [
"def",
"get_listener_instance",
"(",
"self",
",",
"cls",
")",
":",
"with",
"self",
".",
"_lock",
":",
"for",
"listener",
"in",
"self",
".",
"_listeners",
":",
"if",
"isinstance",
"(",
"listener",
",",
"cls",
")",
":",
"return",
"listener"
] | If a listener of the specified type is registered, returns the
instance.
:type cls: :class:`SessionListener` | [
"If",
"a",
"listener",
"of",
"the",
"specified",
"type",
"is",
"registered",
"returns",
"the",
"instance",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/transport/session.py#L147-L156 |
236,298 | ncclient/ncclient | ncclient/operations/subscribe.py | CreateSubscription.request | def request(self, filter=None, stream_name=None, start_time=None, stop_time=None):
"""Creates a subscription for notifications from the server.
*filter* specifies the subset of notifications to receive (by
default all notificaitons are received)
:seealso: :ref:`filter_params`
*stream_name* specifies the notification stream name. The
default is None meaning all streams.
*start_time* triggers the notification replay feature to
replay notifications from the given time. The default is None,
meaning that this is not a replay subscription. The format is
an RFC 3339/ISO 8601 date and time.
*stop_time* indicates the end of the notifications of
interest. This parameter must be used with *start_time*. The
default is None, meaning that (if *start_time* is present) the
notifications will continue until the subscription is
terminated. The format is an RFC 3339/ISO 8601 date and time.
"""
node = new_ele_ns("create-subscription", NETCONF_NOTIFICATION_NS)
if filter is not None:
node.append(util.build_filter(filter))
if stream_name is not None:
sub_ele(node, "stream").text = stream_name
if start_time is not None:
sub_ele(node, "startTime").text = start_time
if stop_time is not None:
if start_time is None:
raise ValueError("You must provide start_time if you provide stop_time")
sub_ele(node, "stopTime").text = stop_time
return self._request(node) | python | def request(self, filter=None, stream_name=None, start_time=None, stop_time=None):
node = new_ele_ns("create-subscription", NETCONF_NOTIFICATION_NS)
if filter is not None:
node.append(util.build_filter(filter))
if stream_name is not None:
sub_ele(node, "stream").text = stream_name
if start_time is not None:
sub_ele(node, "startTime").text = start_time
if stop_time is not None:
if start_time is None:
raise ValueError("You must provide start_time if you provide stop_time")
sub_ele(node, "stopTime").text = stop_time
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"stream_name",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"stop_time",
"=",
"None",
")",
":",
"node",
"=",
"new_ele_ns",
"(",
"\"create-subscription\"",
",",
"NETCONF_NOTIFICATION_NS",
")... | Creates a subscription for notifications from the server.
*filter* specifies the subset of notifications to receive (by
default all notificaitons are received)
:seealso: :ref:`filter_params`
*stream_name* specifies the notification stream name. The
default is None meaning all streams.
*start_time* triggers the notification replay feature to
replay notifications from the given time. The default is None,
meaning that this is not a replay subscription. The format is
an RFC 3339/ISO 8601 date and time.
*stop_time* indicates the end of the notifications of
interest. This parameter must be used with *start_time*. The
default is None, meaning that (if *start_time* is present) the
notifications will continue until the subscription is
terminated. The format is an RFC 3339/ISO 8601 date and time. | [
"Creates",
"a",
"subscription",
"for",
"notifications",
"from",
"the",
"server",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/subscribe.py#L27-L64 |
236,299 | ncclient/ncclient | ncclient/operations/edit.py | DeleteConfig.request | def request(self, target):
"""Delete a configuration datastore.
*target* specifies the name or URL of configuration datastore to delete
:seealso: :ref:`srctarget_params`"""
node = new_ele("delete-config")
node.append(util.datastore_or_url("target", target, self._assert))
return self._request(node) | python | def request(self, target):
node = new_ele("delete-config")
node.append(util.datastore_or_url("target", target, self._assert))
return self._request(node) | [
"def",
"request",
"(",
"self",
",",
"target",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"delete-config\"",
")",
"node",
".",
"append",
"(",
"util",
".",
"datastore_or_url",
"(",
"\"target\"",
",",
"target",
",",
"self",
".",
"_assert",
")",
")",
"return",... | Delete a configuration datastore.
*target* specifies the name or URL of configuration datastore to delete
:seealso: :ref:`srctarget_params` | [
"Delete",
"a",
"configuration",
"datastore",
"."
] | 2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/edit.py#L73-L81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.