repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
python-diamond/Diamond | src/collectors/processresources/processresources.py | ProcessResourcesCollector.collect | def collect(self):
"""
Collects resources usage of each process defined under the
`process` subsection of the config file
"""
if not psutil:
self.log.error('Unable to import psutil')
self.log.error('No process resource metrics retrieved')
return None
for process in psutil.process_iter():
self.collect_process_info(process)
# publish results
for pg_name, counters in self.processes_info.iteritems():
if counters:
metrics = (
("%s.%s" % (pg_name, key), value)
for key, value in counters.iteritems())
else:
if self.processes[pg_name]['count_workers']:
metrics = (('%s.workers_count' % pg_name, 0), )
else:
metrics = ()
[self.publish(*metric) for metric in metrics]
# reinitialize process info
self.processes_info[pg_name] = {} | python | def collect(self):
"""
Collects resources usage of each process defined under the
`process` subsection of the config file
"""
if not psutil:
self.log.error('Unable to import psutil')
self.log.error('No process resource metrics retrieved')
return None
for process in psutil.process_iter():
self.collect_process_info(process)
# publish results
for pg_name, counters in self.processes_info.iteritems():
if counters:
metrics = (
("%s.%s" % (pg_name, key), value)
for key, value in counters.iteritems())
else:
if self.processes[pg_name]['count_workers']:
metrics = (('%s.workers_count' % pg_name, 0), )
else:
metrics = ()
[self.publish(*metric) for metric in metrics]
# reinitialize process info
self.processes_info[pg_name] = {} | [
"def",
"collect",
"(",
"self",
")",
":",
"if",
"not",
"psutil",
":",
"self",
".",
"log",
".",
"error",
"(",
"'Unable to import psutil'",
")",
"self",
".",
"log",
".",
"error",
"(",
"'No process resource metrics retrieved'",
")",
"return",
"None",
"for",
"pro... | Collects resources usage of each process defined under the
`process` subsection of the config file | [
"Collects",
"resources",
"usage",
"of",
"each",
"process",
"defined",
"under",
"the",
"process",
"subsection",
"of",
"the",
"config",
"file"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/processresources/processresources.py#L187-L214 | train | 217,200 |
python-diamond/Diamond | src/diamond/metric.py | Metric.parse | def parse(cls, string):
"""
Parse a string and create a metric
"""
match = re.match(r'^(?P<name>[A-Za-z0-9\.\-_]+)\s+' +
'(?P<value>[0-9\.]+)\s+' +
'(?P<timestamp>[0-9\.]+)(\n?)$',
string)
try:
groups = match.groupdict()
# TODO: get precision from value string
return Metric(groups['name'],
groups['value'],
float(groups['timestamp']))
except:
raise DiamondException(
"Metric could not be parsed from string: %s." % string) | python | def parse(cls, string):
"""
Parse a string and create a metric
"""
match = re.match(r'^(?P<name>[A-Za-z0-9\.\-_]+)\s+' +
'(?P<value>[0-9\.]+)\s+' +
'(?P<timestamp>[0-9\.]+)(\n?)$',
string)
try:
groups = match.groupdict()
# TODO: get precision from value string
return Metric(groups['name'],
groups['value'],
float(groups['timestamp']))
except:
raise DiamondException(
"Metric could not be parsed from string: %s." % string) | [
"def",
"parse",
"(",
"cls",
",",
"string",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(?P<name>[A-Za-z0-9\\.\\-_]+)\\s+'",
"+",
"'(?P<value>[0-9\\.]+)\\s+'",
"+",
"'(?P<timestamp>[0-9\\.]+)(\\n?)$'",
",",
"string",
")",
"try",
":",
"groups",
"=",
"match"... | Parse a string and create a metric | [
"Parse",
"a",
"string",
"and",
"create",
"a",
"metric"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/metric.py#L100-L116 | train | 217,201 |
python-diamond/Diamond | src/diamond/metric.py | Metric.getPathPrefix | def getPathPrefix(self):
"""
Returns the path prefix path
servers.host.cpu.total.idle
return "servers"
"""
# If we don't have a host name, assume it's just the first part of the
# metric path
if self.host is None:
return self.path.split('.')[0]
offset = self.path.index(self.host) - 1
return self.path[0:offset] | python | def getPathPrefix(self):
"""
Returns the path prefix path
servers.host.cpu.total.idle
return "servers"
"""
# If we don't have a host name, assume it's just the first part of the
# metric path
if self.host is None:
return self.path.split('.')[0]
offset = self.path.index(self.host) - 1
return self.path[0:offset] | [
"def",
"getPathPrefix",
"(",
"self",
")",
":",
"# If we don't have a host name, assume it's just the first part of the",
"# metric path",
"if",
"self",
".",
"host",
"is",
"None",
":",
"return",
"self",
".",
"path",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"... | Returns the path prefix path
servers.host.cpu.total.idle
return "servers" | [
"Returns",
"the",
"path",
"prefix",
"path",
"servers",
".",
"host",
".",
"cpu",
".",
"total",
".",
"idle",
"return",
"servers"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/metric.py#L118-L130 | train | 217,202 |
python-diamond/Diamond | src/diamond/metric.py | Metric.getCollectorPath | def getCollectorPath(self):
"""
Returns collector path
servers.host.cpu.total.idle
return "cpu"
"""
# If we don't have a host name, assume it's just the third part of the
# metric path
if self.host is None:
return self.path.split('.')[2]
offset = self.path.index(self.host)
offset += len(self.host) + 1
endoffset = self.path.index('.', offset)
return self.path[offset:endoffset] | python | def getCollectorPath(self):
"""
Returns collector path
servers.host.cpu.total.idle
return "cpu"
"""
# If we don't have a host name, assume it's just the third part of the
# metric path
if self.host is None:
return self.path.split('.')[2]
offset = self.path.index(self.host)
offset += len(self.host) + 1
endoffset = self.path.index('.', offset)
return self.path[offset:endoffset] | [
"def",
"getCollectorPath",
"(",
"self",
")",
":",
"# If we don't have a host name, assume it's just the third part of the",
"# metric path",
"if",
"self",
".",
"host",
"is",
"None",
":",
"return",
"self",
".",
"path",
".",
"split",
"(",
"'.'",
")",
"[",
"2",
"]",
... | Returns collector path
servers.host.cpu.total.idle
return "cpu" | [
"Returns",
"collector",
"path",
"servers",
".",
"host",
".",
"cpu",
".",
"total",
".",
"idle",
"return",
"cpu"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/metric.py#L132-L146 | train | 217,203 |
python-diamond/Diamond | src/diamond/metric.py | Metric.getMetricPath | def getMetricPath(self):
"""
Returns the metric path after the collector name
servers.host.cpu.total.idle
return "total.idle"
"""
# If we don't have a host name, assume it's just the fourth+ part of the
# metric path
if self.host is None:
path = self.path.split('.')[3:]
return '.'.join(path)
prefix = '.'.join([self.getPathPrefix(), self.host,
self.getCollectorPath()])
offset = len(prefix) + 1
return self.path[offset:] | python | def getMetricPath(self):
"""
Returns the metric path after the collector name
servers.host.cpu.total.idle
return "total.idle"
"""
# If we don't have a host name, assume it's just the fourth+ part of the
# metric path
if self.host is None:
path = self.path.split('.')[3:]
return '.'.join(path)
prefix = '.'.join([self.getPathPrefix(), self.host,
self.getCollectorPath()])
offset = len(prefix) + 1
return self.path[offset:] | [
"def",
"getMetricPath",
"(",
"self",
")",
":",
"# If we don't have a host name, assume it's just the fourth+ part of the",
"# metric path",
"if",
"self",
".",
"host",
"is",
"None",
":",
"path",
"=",
"self",
".",
"path",
".",
"split",
"(",
"'.'",
")",
"[",
"3",
"... | Returns the metric path after the collector name
servers.host.cpu.total.idle
return "total.idle" | [
"Returns",
"the",
"metric",
"path",
"after",
"the",
"collector",
"name",
"servers",
".",
"host",
".",
"cpu",
".",
"total",
".",
"idle",
"return",
"total",
".",
"idle"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/metric.py#L148-L164 | train | 217,204 |
python-diamond/Diamond | src/diamond/handler/Handler.py | Handler._process | def _process(self, metric):
"""
Decorator for processing handlers with a lock, catching exceptions
"""
if not self.enabled:
return
try:
try:
self.lock.acquire()
self.process(metric)
except Exception:
self.log.error(traceback.format_exc())
finally:
if self.lock.locked():
self.lock.release() | python | def _process(self, metric):
"""
Decorator for processing handlers with a lock, catching exceptions
"""
if not self.enabled:
return
try:
try:
self.lock.acquire()
self.process(metric)
except Exception:
self.log.error(traceback.format_exc())
finally:
if self.lock.locked():
self.lock.release() | [
"def",
"_process",
"(",
"self",
",",
"metric",
")",
":",
"if",
"not",
"self",
".",
"enabled",
":",
"return",
"try",
":",
"try",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"self",
".",
"process",
"(",
"metric",
")",
"except",
"Exception",
"... | Decorator for processing handlers with a lock, catching exceptions | [
"Decorator",
"for",
"processing",
"handlers",
"with",
"a",
"lock",
"catching",
"exceptions"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/Handler.py#L65-L79 | train | 217,205 |
python-diamond/Diamond | src/diamond/handler/Handler.py | Handler._flush | def _flush(self):
"""
Decorator for flushing handlers with an lock, catching exceptions
"""
if not self.enabled:
return
try:
try:
self.lock.acquire()
self.flush()
except Exception:
self.log.error(traceback.format_exc())
finally:
if self.lock.locked():
self.lock.release() | python | def _flush(self):
"""
Decorator for flushing handlers with an lock, catching exceptions
"""
if not self.enabled:
return
try:
try:
self.lock.acquire()
self.flush()
except Exception:
self.log.error(traceback.format_exc())
finally:
if self.lock.locked():
self.lock.release() | [
"def",
"_flush",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"enabled",
":",
"return",
"try",
":",
"try",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"self",
".",
"flush",
"(",
")",
"except",
"Exception",
":",
"self",
".",
"log",
"."... | Decorator for flushing handlers with an lock, catching exceptions | [
"Decorator",
"for",
"flushing",
"handlers",
"with",
"an",
"lock",
"catching",
"exceptions"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/Handler.py#L89-L103 | train | 217,206 |
python-diamond/Diamond | src/diamond/handler/Handler.py | Handler._throttle_error | def _throttle_error(self, msg, *args, **kwargs):
"""
Avoids sending errors repeatedly. Waits at least
`self.server_error_interval` seconds before sending the same error
string to the error logging facility. If not enough time has passed,
it calls `log.debug` instead
Receives the same parameters as `Logger.error` an passes them on to the
selected logging function, but ignores all parameters but the main
message string when checking the last emission time.
:returns: the return value of `Logger.debug` or `Logger.error`
"""
now = time.time()
if msg in self._errors:
if ((now - self._errors[msg]) >=
self.server_error_interval):
fn = self.log.error
self._errors[msg] = now
else:
fn = self.log.debug
else:
self._errors[msg] = now
fn = self.log.error
return fn(msg, *args, **kwargs) | python | def _throttle_error(self, msg, *args, **kwargs):
"""
Avoids sending errors repeatedly. Waits at least
`self.server_error_interval` seconds before sending the same error
string to the error logging facility. If not enough time has passed,
it calls `log.debug` instead
Receives the same parameters as `Logger.error` an passes them on to the
selected logging function, but ignores all parameters but the main
message string when checking the last emission time.
:returns: the return value of `Logger.debug` or `Logger.error`
"""
now = time.time()
if msg in self._errors:
if ((now - self._errors[msg]) >=
self.server_error_interval):
fn = self.log.error
self._errors[msg] = now
else:
fn = self.log.debug
else:
self._errors[msg] = now
fn = self.log.error
return fn(msg, *args, **kwargs) | [
"def",
"_throttle_error",
"(",
"self",
",",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"msg",
"in",
"self",
".",
"_errors",
":",
"if",
"(",
"(",
"now",
"-",
"self",
".",
"_errors... | Avoids sending errors repeatedly. Waits at least
`self.server_error_interval` seconds before sending the same error
string to the error logging facility. If not enough time has passed,
it calls `log.debug` instead
Receives the same parameters as `Logger.error` an passes them on to the
selected logging function, but ignores all parameters but the main
message string when checking the last emission time.
:returns: the return value of `Logger.debug` or `Logger.error` | [
"Avoids",
"sending",
"errors",
"repeatedly",
".",
"Waits",
"at",
"least",
"self",
".",
"server_error_interval",
"seconds",
"before",
"sending",
"the",
"same",
"error",
"string",
"to",
"the",
"error",
"logging",
"facility",
".",
"If",
"not",
"enough",
"time",
"... | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/Handler.py#L113-L138 | train | 217,207 |
python-diamond/Diamond | src/diamond/handler/Handler.py | Handler._reset_errors | def _reset_errors(self, msg=None):
"""
Resets the logging throttle cache, so the next error is emitted
regardless of the value in `self.server_error_interval`
:param msg: if present, only this key is reset. Otherwise, the whole
cache is cleaned.
"""
if msg is not None and msg in self._errors:
del self._errors[msg]
else:
self._errors = {} | python | def _reset_errors(self, msg=None):
"""
Resets the logging throttle cache, so the next error is emitted
regardless of the value in `self.server_error_interval`
:param msg: if present, only this key is reset. Otherwise, the whole
cache is cleaned.
"""
if msg is not None and msg in self._errors:
del self._errors[msg]
else:
self._errors = {} | [
"def",
"_reset_errors",
"(",
"self",
",",
"msg",
"=",
"None",
")",
":",
"if",
"msg",
"is",
"not",
"None",
"and",
"msg",
"in",
"self",
".",
"_errors",
":",
"del",
"self",
".",
"_errors",
"[",
"msg",
"]",
"else",
":",
"self",
".",
"_errors",
"=",
"... | Resets the logging throttle cache, so the next error is emitted
regardless of the value in `self.server_error_interval`
:param msg: if present, only this key is reset. Otherwise, the whole
cache is cleaned. | [
"Resets",
"the",
"logging",
"throttle",
"cache",
"so",
"the",
"next",
"error",
"is",
"emitted",
"regardless",
"of",
"the",
"value",
"in",
"self",
".",
"server_error_interval"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/Handler.py#L140-L151 | train | 217,208 |
python-diamond/Diamond | src/diamond/utils/signals.py | signal_to_exception | def signal_to_exception(signum, frame):
"""
Called by the timeout alarm during the collector run time
"""
if signum == signal.SIGALRM:
raise SIGALRMException()
if signum == signal.SIGHUP:
raise SIGHUPException()
if signum == signal.SIGUSR1:
raise SIGUSR1Exception()
if signum == signal.SIGUSR2:
raise SIGUSR2Exception()
raise SignalException(signum) | python | def signal_to_exception(signum, frame):
"""
Called by the timeout alarm during the collector run time
"""
if signum == signal.SIGALRM:
raise SIGALRMException()
if signum == signal.SIGHUP:
raise SIGHUPException()
if signum == signal.SIGUSR1:
raise SIGUSR1Exception()
if signum == signal.SIGUSR2:
raise SIGUSR2Exception()
raise SignalException(signum) | [
"def",
"signal_to_exception",
"(",
"signum",
",",
"frame",
")",
":",
"if",
"signum",
"==",
"signal",
".",
"SIGALRM",
":",
"raise",
"SIGALRMException",
"(",
")",
"if",
"signum",
"==",
"signal",
".",
"SIGHUP",
":",
"raise",
"SIGHUPException",
"(",
")",
"if",... | Called by the timeout alarm during the collector run time | [
"Called",
"by",
"the",
"timeout",
"alarm",
"during",
"the",
"collector",
"run",
"time"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/signals.py#L6-L18 | train | 217,209 |
python-diamond/Diamond | src/collectors/servertechpdu/servertechpdu.py | ServerTechPDUCollector.collect_snmp | def collect_snmp(self, device, host, port, community):
"""
Collect stats from device
"""
# Log
self.log.info("Collecting ServerTech PDU statistics from: %s" % device)
# Set timestamp
timestamp = time.time()
inputFeeds = {}
# Collect PDU input gauge values
for gaugeName, gaugeOid in self.PDU_SYSTEM_GAUGES.items():
systemGauges = self.walk(gaugeOid, host, port, community)
for o, gaugeValue in systemGauges.items():
# Get Metric Name
metricName = gaugeName
# Get Metric Value
metricValue = float(gaugeValue)
# Get Metric Path
metricPath = '.'.join(
['devices', device, 'system', metricName])
# Create Metric
metric = Metric(metricPath, metricValue, timestamp, 2)
# Publish Metric
self.publish_metric(metric)
# Collect PDU input feed names
inputFeedNames = self.walk(
self.PDU_INFEED_NAMES, host, port, community)
for o, inputFeedName in inputFeedNames.items():
# Extract input feed name
inputFeed = ".".join(o.split(".")[-2:])
inputFeeds[inputFeed] = inputFeedName
# Collect PDU input gauge values
for gaugeName, gaugeOid in self.PDU_INFEED_GAUGES.items():
inputFeedGauges = self.walk(gaugeOid, host, port, community)
for o, gaugeValue in inputFeedGauges.items():
# Extract input feed name
inputFeed = ".".join(o.split(".")[-2:])
# Get Metric Name
metricName = '.'.join([re.sub(r'\.|\\', '_',
inputFeeds[inputFeed]),
gaugeName])
# Get Metric Value
if gaugeName == "infeedVolts":
# Note: Voltage is in "tenth volts", so divide by 10
metricValue = float(gaugeValue) / 10.0
elif gaugeName == "infeedAmps":
# Note: Amps is in "hundredth amps", so divide by 100
metricValue = float(gaugeValue) / 100.0
else:
metricValue = float(gaugeValue)
# Get Metric Path
metricPath = '.'.join(['devices', device, 'input', metricName])
# Create Metric
metric = Metric(metricPath, metricValue, timestamp, 2)
# Publish Metric
self.publish_metric(metric) | python | def collect_snmp(self, device, host, port, community):
"""
Collect stats from device
"""
# Log
self.log.info("Collecting ServerTech PDU statistics from: %s" % device)
# Set timestamp
timestamp = time.time()
inputFeeds = {}
# Collect PDU input gauge values
for gaugeName, gaugeOid in self.PDU_SYSTEM_GAUGES.items():
systemGauges = self.walk(gaugeOid, host, port, community)
for o, gaugeValue in systemGauges.items():
# Get Metric Name
metricName = gaugeName
# Get Metric Value
metricValue = float(gaugeValue)
# Get Metric Path
metricPath = '.'.join(
['devices', device, 'system', metricName])
# Create Metric
metric = Metric(metricPath, metricValue, timestamp, 2)
# Publish Metric
self.publish_metric(metric)
# Collect PDU input feed names
inputFeedNames = self.walk(
self.PDU_INFEED_NAMES, host, port, community)
for o, inputFeedName in inputFeedNames.items():
# Extract input feed name
inputFeed = ".".join(o.split(".")[-2:])
inputFeeds[inputFeed] = inputFeedName
# Collect PDU input gauge values
for gaugeName, gaugeOid in self.PDU_INFEED_GAUGES.items():
inputFeedGauges = self.walk(gaugeOid, host, port, community)
for o, gaugeValue in inputFeedGauges.items():
# Extract input feed name
inputFeed = ".".join(o.split(".")[-2:])
# Get Metric Name
metricName = '.'.join([re.sub(r'\.|\\', '_',
inputFeeds[inputFeed]),
gaugeName])
# Get Metric Value
if gaugeName == "infeedVolts":
# Note: Voltage is in "tenth volts", so divide by 10
metricValue = float(gaugeValue) / 10.0
elif gaugeName == "infeedAmps":
# Note: Amps is in "hundredth amps", so divide by 100
metricValue = float(gaugeValue) / 100.0
else:
metricValue = float(gaugeValue)
# Get Metric Path
metricPath = '.'.join(['devices', device, 'input', metricName])
# Create Metric
metric = Metric(metricPath, metricValue, timestamp, 2)
# Publish Metric
self.publish_metric(metric) | [
"def",
"collect_snmp",
"(",
"self",
",",
"device",
",",
"host",
",",
"port",
",",
"community",
")",
":",
"# Log",
"self",
".",
"log",
".",
"info",
"(",
"\"Collecting ServerTech PDU statistics from: %s\"",
"%",
"device",
")",
"# Set timestamp",
"timestamp",
"=",
... | Collect stats from device | [
"Collect",
"stats",
"from",
"device"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/servertechpdu/servertechpdu.py#L66-L129 | train | 217,210 |
python-diamond/Diamond | src/collectors/users/users.py | UsersCollector.get_default_config_help | def get_default_config_help(self):
"""
Returns the default collector help text
"""
config_help = super(UsersCollector, self).get_default_config_help()
config_help.update({
})
return config_help | python | def get_default_config_help(self):
"""
Returns the default collector help text
"""
config_help = super(UsersCollector, self).get_default_config_help()
config_help.update({
})
return config_help | [
"def",
"get_default_config_help",
"(",
"self",
")",
":",
"config_help",
"=",
"super",
"(",
"UsersCollector",
",",
"self",
")",
".",
"get_default_config_help",
"(",
")",
"config_help",
".",
"update",
"(",
"{",
"}",
")",
"return",
"config_help"
] | Returns the default collector help text | [
"Returns",
"the",
"default",
"collector",
"help",
"text"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/users/users.py#L29-L36 | train | 217,211 |
python-diamond/Diamond | src/diamond/handler/stats_d.py | StatsdHandler._send | def _send(self):
"""
Send data to statsd. Fire and forget. Cross fingers and it'll arrive.
"""
if not statsd:
return
for metric in self.metrics:
# Split the path into a prefix and a name
# to work with the statsd module's view of the world.
# It will get re-joined by the python-statsd module.
#
# For the statsd module, you specify prefix in the constructor
# so we just use the full metric path.
(prefix, name) = metric.path.rsplit(".", 1)
logging.debug("Sending %s %s|g", name, metric.value)
if metric.metric_type == 'GAUGE':
if hasattr(statsd, 'StatsClient'):
self.connection.gauge(metric.path, metric.value)
else:
statsd.Gauge(prefix, self.connection).send(
name, metric.value)
else:
# To send a counter, we need to just send the delta
# but without any time delta changes
value = metric.raw_value
if metric.path in self.old_values:
value = value - self.old_values[metric.path]
self.old_values[metric.path] = metric.raw_value
if hasattr(statsd, 'StatsClient'):
self.connection.incr(metric.path, value)
else:
statsd.Counter(prefix, self.connection).increment(
name, value)
if hasattr(statsd, 'StatsClient'):
self.connection.send()
self.metrics = [] | python | def _send(self):
"""
Send data to statsd. Fire and forget. Cross fingers and it'll arrive.
"""
if not statsd:
return
for metric in self.metrics:
# Split the path into a prefix and a name
# to work with the statsd module's view of the world.
# It will get re-joined by the python-statsd module.
#
# For the statsd module, you specify prefix in the constructor
# so we just use the full metric path.
(prefix, name) = metric.path.rsplit(".", 1)
logging.debug("Sending %s %s|g", name, metric.value)
if metric.metric_type == 'GAUGE':
if hasattr(statsd, 'StatsClient'):
self.connection.gauge(metric.path, metric.value)
else:
statsd.Gauge(prefix, self.connection).send(
name, metric.value)
else:
# To send a counter, we need to just send the delta
# but without any time delta changes
value = metric.raw_value
if metric.path in self.old_values:
value = value - self.old_values[metric.path]
self.old_values[metric.path] = metric.raw_value
if hasattr(statsd, 'StatsClient'):
self.connection.incr(metric.path, value)
else:
statsd.Counter(prefix, self.connection).increment(
name, value)
if hasattr(statsd, 'StatsClient'):
self.connection.send()
self.metrics = [] | [
"def",
"_send",
"(",
"self",
")",
":",
"if",
"not",
"statsd",
":",
"return",
"for",
"metric",
"in",
"self",
".",
"metrics",
":",
"# Split the path into a prefix and a name",
"# to work with the statsd module's view of the world.",
"# It will get re-joined by the python-statsd... | Send data to statsd. Fire and forget. Cross fingers and it'll arrive. | [
"Send",
"data",
"to",
"statsd",
".",
"Fire",
"and",
"forget",
".",
"Cross",
"fingers",
"and",
"it",
"ll",
"arrive",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/stats_d.py#L106-L145 | train | 217,212 |
python-diamond/Diamond | src/diamond/handler/stats_d.py | StatsdHandler._connect | def _connect(self):
"""
Connect to the statsd server
"""
if not statsd:
return
if hasattr(statsd, 'StatsClient'):
self.connection = statsd.StatsClient(
host=self.host,
port=self.port
).pipeline()
else:
# Create socket
self.connection = statsd.Connection(
host=self.host,
port=self.port,
sample_rate=1.0
) | python | def _connect(self):
"""
Connect to the statsd server
"""
if not statsd:
return
if hasattr(statsd, 'StatsClient'):
self.connection = statsd.StatsClient(
host=self.host,
port=self.port
).pipeline()
else:
# Create socket
self.connection = statsd.Connection(
host=self.host,
port=self.port,
sample_rate=1.0
) | [
"def",
"_connect",
"(",
"self",
")",
":",
"if",
"not",
"statsd",
":",
"return",
"if",
"hasattr",
"(",
"statsd",
",",
"'StatsClient'",
")",
":",
"self",
".",
"connection",
"=",
"statsd",
".",
"StatsClient",
"(",
"host",
"=",
"self",
".",
"host",
",",
... | Connect to the statsd server | [
"Connect",
"to",
"the",
"statsd",
"server"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/stats_d.py#L151-L169 | train | 217,213 |
python-diamond/Diamond | src/diamond/handler/signalfx.py | SignalfxHandler._match_metric | def _match_metric(self, metric):
"""
matches the metric path, if the metrics are empty, it shorts to True
"""
if len(self._compiled_filters) == 0:
return True
for (collector, filter_regex) in self._compiled_filters:
if collector != metric.getCollectorPath():
continue
if filter_regex.match(metric.getMetricPath()):
return True
return False | python | def _match_metric(self, metric):
"""
matches the metric path, if the metrics are empty, it shorts to True
"""
if len(self._compiled_filters) == 0:
return True
for (collector, filter_regex) in self._compiled_filters:
if collector != metric.getCollectorPath():
continue
if filter_regex.match(metric.getMetricPath()):
return True
return False | [
"def",
"_match_metric",
"(",
"self",
",",
"metric",
")",
":",
"if",
"len",
"(",
"self",
".",
"_compiled_filters",
")",
"==",
"0",
":",
"return",
"True",
"for",
"(",
"collector",
",",
"filter_regex",
")",
"in",
"self",
".",
"_compiled_filters",
":",
"if",... | matches the metric path, if the metrics are empty, it shorts to True | [
"matches",
"the",
"metric",
"path",
"if",
"the",
"metrics",
"are",
"empty",
"it",
"shorts",
"to",
"True"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/signalfx.py#L55-L66 | train | 217,214 |
python-diamond/Diamond | src/diamond/handler/signalfx.py | SignalfxHandler.process | def process(self, metric):
"""
Queue a metric. Flushing queue if batch size reached
"""
if self._match_metric(metric):
self.metrics.append(metric)
if self.should_flush():
self._send() | python | def process(self, metric):
"""
Queue a metric. Flushing queue if batch size reached
"""
if self._match_metric(metric):
self.metrics.append(metric)
if self.should_flush():
self._send() | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"if",
"self",
".",
"_match_metric",
"(",
"metric",
")",
":",
"self",
".",
"metrics",
".",
"append",
"(",
"metric",
")",
"if",
"self",
".",
"should_flush",
"(",
")",
":",
"self",
".",
"_send",
... | Queue a metric. Flushing queue if batch size reached | [
"Queue",
"a",
"metric",
".",
"Flushing",
"queue",
"if",
"batch",
"size",
"reached"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/signalfx.py#L103-L110 | train | 217,215 |
python-diamond/Diamond | src/diamond/handler/signalfx.py | SignalfxHandler.into_signalfx_point | def into_signalfx_point(self, metric):
"""
Convert diamond metric into something signalfx can understand
"""
dims = {
"collector": metric.getCollectorPath(),
"prefix": metric.getPathPrefix(),
}
if metric.host is not None and metric.host != "":
dims["host"] = metric.host
return {
"metric": metric.getMetricPath(),
"value": metric.value,
"dimensions": dims,
# We expect ms timestamps
"timestamp": metric.timestamp * 1000,
} | python | def into_signalfx_point(self, metric):
"""
Convert diamond metric into something signalfx can understand
"""
dims = {
"collector": metric.getCollectorPath(),
"prefix": metric.getPathPrefix(),
}
if metric.host is not None and metric.host != "":
dims["host"] = metric.host
return {
"metric": metric.getMetricPath(),
"value": metric.value,
"dimensions": dims,
# We expect ms timestamps
"timestamp": metric.timestamp * 1000,
} | [
"def",
"into_signalfx_point",
"(",
"self",
",",
"metric",
")",
":",
"dims",
"=",
"{",
"\"collector\"",
":",
"metric",
".",
"getCollectorPath",
"(",
")",
",",
"\"prefix\"",
":",
"metric",
".",
"getPathPrefix",
"(",
")",
",",
"}",
"if",
"metric",
".",
"hos... | Convert diamond metric into something signalfx can understand | [
"Convert",
"diamond",
"metric",
"into",
"something",
"signalfx",
"can",
"understand"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/signalfx.py#L116-L133 | train | 217,216 |
python-diamond/Diamond | src/diamond/gmetric.py | gmetric_write | def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP):
"""
Arguments are in all upper-case to match XML
"""
packer = Packer()
HOSTNAME = "test"
SPOOF = 0
# Meta data about a metric
packer.pack_int(128)
packer.pack_string(HOSTNAME)
packer.pack_string(NAME)
packer.pack_int(SPOOF)
packer.pack_string(TYPE)
packer.pack_string(NAME)
packer.pack_string(UNITS)
packer.pack_int(slope_str2int[SLOPE]) # map slope string to int
packer.pack_uint(int(TMAX))
packer.pack_uint(int(DMAX))
# Magic number. Indicates number of entries to follow. Put in 1 for GROUP
if GROUP == "":
packer.pack_int(0)
else:
packer.pack_int(1)
packer.pack_string("GROUP")
packer.pack_string(GROUP)
# Actual data sent in a separate packet
data = Packer()
data.pack_int(128 + 5)
data.pack_string(HOSTNAME)
data.pack_string(NAME)
data.pack_int(SPOOF)
data.pack_string("%s")
data.pack_string(str(VAL))
return packer.get_buffer(), data.get_buffer() | python | def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP):
"""
Arguments are in all upper-case to match XML
"""
packer = Packer()
HOSTNAME = "test"
SPOOF = 0
# Meta data about a metric
packer.pack_int(128)
packer.pack_string(HOSTNAME)
packer.pack_string(NAME)
packer.pack_int(SPOOF)
packer.pack_string(TYPE)
packer.pack_string(NAME)
packer.pack_string(UNITS)
packer.pack_int(slope_str2int[SLOPE]) # map slope string to int
packer.pack_uint(int(TMAX))
packer.pack_uint(int(DMAX))
# Magic number. Indicates number of entries to follow. Put in 1 for GROUP
if GROUP == "":
packer.pack_int(0)
else:
packer.pack_int(1)
packer.pack_string("GROUP")
packer.pack_string(GROUP)
# Actual data sent in a separate packet
data = Packer()
data.pack_int(128 + 5)
data.pack_string(HOSTNAME)
data.pack_string(NAME)
data.pack_int(SPOOF)
data.pack_string("%s")
data.pack_string(str(VAL))
return packer.get_buffer(), data.get_buffer() | [
"def",
"gmetric_write",
"(",
"NAME",
",",
"VAL",
",",
"TYPE",
",",
"UNITS",
",",
"SLOPE",
",",
"TMAX",
",",
"DMAX",
",",
"GROUP",
")",
":",
"packer",
"=",
"Packer",
"(",
")",
"HOSTNAME",
"=",
"\"test\"",
"SPOOF",
"=",
"0",
"# Meta data about a metric",
... | Arguments are in all upper-case to match XML | [
"Arguments",
"are",
"in",
"all",
"upper",
"-",
"case",
"to",
"match",
"XML"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/gmetric.py#L103-L138 | train | 217,217 |
python-diamond/Diamond | src/collectors/disktemp/disktemp.py | DiskTemperatureCollector.collect | def collect(self):
"""
Collect and publish disk temperatures
"""
instances = {}
# Support disks such as /dev/(sd.*)
for device in os.listdir('/dev/'):
instances.update(self.match_device(device, '/dev/'))
# Support disk by id such as /dev/disk/by-id/wwn-(.*)
for device_id in os.listdir('/dev/disk/by-id/'):
instances.update(self.match_device(device, '/dev/disk/by-id/'))
metrics = {}
for device, p in instances.items():
output = p.communicate()[0].strip()
try:
metrics[device + ".Temperature"] = float(output)
except:
self.log.warn('Disk temperature retrieval failed on ' + device)
for metric in metrics.keys():
self.publish(metric, metrics[metric]) | python | def collect(self):
"""
Collect and publish disk temperatures
"""
instances = {}
# Support disks such as /dev/(sd.*)
for device in os.listdir('/dev/'):
instances.update(self.match_device(device, '/dev/'))
# Support disk by id such as /dev/disk/by-id/wwn-(.*)
for device_id in os.listdir('/dev/disk/by-id/'):
instances.update(self.match_device(device, '/dev/disk/by-id/'))
metrics = {}
for device, p in instances.items():
output = p.communicate()[0].strip()
try:
metrics[device + ".Temperature"] = float(output)
except:
self.log.warn('Disk temperature retrieval failed on ' + device)
for metric in metrics.keys():
self.publish(metric, metrics[metric]) | [
"def",
"collect",
"(",
"self",
")",
":",
"instances",
"=",
"{",
"}",
"# Support disks such as /dev/(sd.*)",
"for",
"device",
"in",
"os",
".",
"listdir",
"(",
"'/dev/'",
")",
":",
"instances",
".",
"update",
"(",
"self",
".",
"match_device",
"(",
"device",
... | Collect and publish disk temperatures | [
"Collect",
"and",
"publish",
"disk",
"temperatures"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/disktemp/disktemp.py#L76-L100 | train | 217,218 |
python-diamond/Diamond | src/collectors/elasticsearch/elasticsearch.py | ElasticSearchCollector._get | def _get(self, scheme, host, port, path, assert_key=None):
"""
Execute a ES API call. Convert response into JSON and
optionally assert its structure.
"""
url = '%s://%s:%i/%s' % (scheme, host, port, path)
try:
request = urllib2.Request(url)
if self.config['user'] and self.config['password']:
base64string = base64.standard_b64encode(
'%s:%s' % (self.config['user'], self.config['password']))
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)
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 elasticsearch as a" +
" json object")
return False
if assert_key and assert_key not in doc:
self.log.error("Bad response from elasticsearch, expected key "
"'%s' was missing for %s" % (assert_key, url))
return False
return doc | python | def _get(self, scheme, host, port, path, assert_key=None):
"""
Execute a ES API call. Convert response into JSON and
optionally assert its structure.
"""
url = '%s://%s:%i/%s' % (scheme, host, port, path)
try:
request = urllib2.Request(url)
if self.config['user'] and self.config['password']:
base64string = base64.standard_b64encode(
'%s:%s' % (self.config['user'], self.config['password']))
request.add_header("Authorization", "Basic %s" % base64string)
response = urllib2.urlopen(request)
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 elasticsearch as a" +
" json object")
return False
if assert_key and assert_key not in doc:
self.log.error("Bad response from elasticsearch, expected key "
"'%s' was missing for %s" % (assert_key, url))
return False
return doc | [
"def",
"_get",
"(",
"self",
",",
"scheme",
",",
"host",
",",
"port",
",",
"path",
",",
"assert_key",
"=",
"None",
")",
":",
"url",
"=",
"'%s://%s:%i/%s'",
"%",
"(",
"scheme",
",",
"host",
",",
"port",
",",
"path",
")",
"try",
":",
"request",
"=",
... | Execute a ES API call. Convert response into JSON and
optionally assert its structure. | [
"Execute",
"a",
"ES",
"API",
"call",
".",
"Convert",
"response",
"into",
"JSON",
"and",
"optionally",
"assert",
"its",
"structure",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/elasticsearch/elasticsearch.py#L107-L135 | train | 217,219 |
python-diamond/Diamond | src/collectors/elasticsearch/elasticsearch.py | ElasticSearchCollector._set_or_sum_metric | def _set_or_sum_metric(self, metrics, metric_path, value):
"""If we already have a datapoint for this metric, lets add
the value. This is used when the logstash mode is enabled."""
if metric_path in metrics:
metrics[metric_path] += value
else:
metrics[metric_path] = value | python | def _set_or_sum_metric(self, metrics, metric_path, value):
"""If we already have a datapoint for this metric, lets add
the value. This is used when the logstash mode is enabled."""
if metric_path in metrics:
metrics[metric_path] += value
else:
metrics[metric_path] = value | [
"def",
"_set_or_sum_metric",
"(",
"self",
",",
"metrics",
",",
"metric_path",
",",
"value",
")",
":",
"if",
"metric_path",
"in",
"metrics",
":",
"metrics",
"[",
"metric_path",
"]",
"+=",
"value",
"else",
":",
"metrics",
"[",
"metric_path",
"]",
"=",
"value... | If we already have a datapoint for this metric, lets add
the value. This is used when the logstash mode is enabled. | [
"If",
"we",
"already",
"have",
"a",
"datapoint",
"for",
"this",
"metric",
"lets",
"add",
"the",
"value",
".",
"This",
"is",
"used",
"when",
"the",
"logstash",
"mode",
"is",
"enabled",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/elasticsearch/elasticsearch.py#L183-L189 | train | 217,220 |
python-diamond/Diamond | src/collectors/redisstat/redisstat.py | RedisCollector._client | def _client(self, host, port, unix_socket, auth):
"""Return a redis client for the configuration.
:param str host: redis host
:param int port: redis port
:rtype: redis.Redis
"""
db = int(self.config['db'])
timeout = int(self.config['timeout'])
try:
cli = redis.Redis(host=host, port=port,
db=db, socket_timeout=timeout, password=auth,
unix_socket_path=unix_socket)
cli.ping()
return cli
except Exception as ex:
self.log.error("RedisCollector: failed to connect to %s:%i. %s.",
unix_socket or host, port, ex) | python | def _client(self, host, port, unix_socket, auth):
"""Return a redis client for the configuration.
:param str host: redis host
:param int port: redis port
:rtype: redis.Redis
"""
db = int(self.config['db'])
timeout = int(self.config['timeout'])
try:
cli = redis.Redis(host=host, port=port,
db=db, socket_timeout=timeout, password=auth,
unix_socket_path=unix_socket)
cli.ping()
return cli
except Exception as ex:
self.log.error("RedisCollector: failed to connect to %s:%i. %s.",
unix_socket or host, port, ex) | [
"def",
"_client",
"(",
"self",
",",
"host",
",",
"port",
",",
"unix_socket",
",",
"auth",
")",
":",
"db",
"=",
"int",
"(",
"self",
".",
"config",
"[",
"'db'",
"]",
")",
"timeout",
"=",
"int",
"(",
"self",
".",
"config",
"[",
"'timeout'",
"]",
")"... | Return a redis client for the configuration.
:param str host: redis host
:param int port: redis port
:rtype: redis.Redis | [
"Return",
"a",
"redis",
"client",
"for",
"the",
"configuration",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L209-L227 | train | 217,221 |
python-diamond/Diamond | src/collectors/redisstat/redisstat.py | RedisCollector._precision | def _precision(self, value):
"""Return the precision of the number
:param str value: The value to find the precision of
:rtype: int
"""
value = str(value)
decimal = value.rfind('.')
if decimal == -1:
return 0
return len(value) - decimal - 1 | python | def _precision(self, value):
"""Return the precision of the number
:param str value: The value to find the precision of
:rtype: int
"""
value = str(value)
decimal = value.rfind('.')
if decimal == -1:
return 0
return len(value) - decimal - 1 | [
"def",
"_precision",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"decimal",
"=",
"value",
".",
"rfind",
"(",
"'.'",
")",
"if",
"decimal",
"==",
"-",
"1",
":",
"return",
"0",
"return",
"len",
"(",
"value",
")",
"-"... | Return the precision of the number
:param str value: The value to find the precision of
:rtype: int | [
"Return",
"the",
"precision",
"of",
"the",
"number"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L229-L240 | train | 217,222 |
python-diamond/Diamond | src/collectors/redisstat/redisstat.py | RedisCollector._get_info | def _get_info(self, host, port, unix_socket, auth):
"""Return info dict from specified Redis instance
:param str host: redis host
:param int port: redis port
:rtype: dict
"""
client = self._client(host, port, unix_socket, auth)
if client is None:
return None
info = client.info()
del client
return info | python | def _get_info(self, host, port, unix_socket, auth):
"""Return info dict from specified Redis instance
:param str host: redis host
:param int port: redis port
:rtype: dict
"""
client = self._client(host, port, unix_socket, auth)
if client is None:
return None
info = client.info()
del client
return info | [
"def",
"_get_info",
"(",
"self",
",",
"host",
",",
"port",
",",
"unix_socket",
",",
"auth",
")",
":",
"client",
"=",
"self",
".",
"_client",
"(",
"host",
",",
"port",
",",
"unix_socket",
",",
"auth",
")",
"if",
"client",
"is",
"None",
":",
"return",
... | Return info dict from specified Redis instance
:param str host: redis host
:param int port: redis port
:rtype: dict | [
"Return",
"info",
"dict",
"from",
"specified",
"Redis",
"instance"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L252-L267 | train | 217,223 |
python-diamond/Diamond | src/collectors/redisstat/redisstat.py | RedisCollector._get_config | def _get_config(self, host, port, unix_socket, auth, config_key):
"""Return config string from specified Redis instance and config key
:param str host: redis host
:param int port: redis port
:param str host: redis config_key
:rtype: str
"""
client = self._client(host, port, unix_socket, auth)
if client is None:
return None
config_value = client.config_get(config_key)
del client
return config_value | python | def _get_config(self, host, port, unix_socket, auth, config_key):
"""Return config string from specified Redis instance and config key
:param str host: redis host
:param int port: redis port
:param str host: redis config_key
:rtype: str
"""
client = self._client(host, port, unix_socket, auth)
if client is None:
return None
config_value = client.config_get(config_key)
del client
return config_value | [
"def",
"_get_config",
"(",
"self",
",",
"host",
",",
"port",
",",
"unix_socket",
",",
"auth",
",",
"config_key",
")",
":",
"client",
"=",
"self",
".",
"_client",
"(",
"host",
",",
"port",
",",
"unix_socket",
",",
"auth",
")",
"if",
"client",
"is",
"N... | Return config string from specified Redis instance and config key
:param str host: redis host
:param int port: redis port
:param str host: redis config_key
:rtype: str | [
"Return",
"config",
"string",
"from",
"specified",
"Redis",
"instance",
"and",
"config",
"key"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L269-L285 | train | 217,224 |
python-diamond/Diamond | src/collectors/redisstat/redisstat.py | RedisCollector.collect_instance | def collect_instance(self, nick, host, port, unix_socket, auth):
"""Collect metrics from a single Redis instance
:param str nick: nickname of redis instance
:param str host: redis host
:param int port: redis port
:param str unix_socket: unix socket, if applicable
:param str auth: authentication password
"""
# Connect to redis and get the info
info = self._get_info(host, port, unix_socket, auth)
if info is None:
return
# The structure should include the port for multiple instances per
# server
data = dict()
# Role needs to be handled outside the the _KEYS dict
# since the value is a string, not a int / float
# Also, master_sync_in_progress is only available if the
# redis instance is a slave, so default it here so that
# the metric is cleared if the instance flips from slave
# to master
if 'role' in info:
if info['role'] == "master":
data['replication.master'] = 1
data['replication.master_sync_in_progress'] = 0
else:
data['replication.master'] = 0
# Connect to redis and get the maxmemory config value
# Then calculate the % maxmemory of memory used
maxmemory_config = self._get_config(host, port, unix_socket, auth,
'maxmemory')
if maxmemory_config and 'maxmemory' in maxmemory_config.keys():
maxmemory = float(maxmemory_config['maxmemory'])
# Only report % used if maxmemory is a non zero value
if maxmemory == 0:
maxmemory_percent = 0.0
else:
maxmemory_percent = info['used_memory'] / maxmemory * 100
maxmemory_percent = round(maxmemory_percent, 2)
data['memory.used_percent'] = float("%.2f" % maxmemory_percent)
# Iterate over the top level keys
for key in self._KEYS:
if self._KEYS[key] in info:
data[key] = info[self._KEYS[key]]
# Iterate over renamed keys for 2.6 support
for key in self._RENAMED_KEYS:
if self._RENAMED_KEYS[key] in info:
data[key] = info[self._RENAMED_KEYS[key]]
# Look for databaase speific stats
for dbnum in range(0, int(self.config.get('databases',
self._DATABASE_COUNT))):
db = 'db%i' % dbnum
if db in info:
for key in info[db]:
data['%s.%s' % (db, key)] = info[db][key]
# Time since last save
for key in ['last_save_time', 'rdb_last_save_time']:
if key in info:
data['last_save.time_since'] = int(time.time()) - info[key]
# Publish the data to graphite
for key in data:
self.publish(self._publish_key(nick, key),
data[key],
precision=self._precision(data[key]),
metric_type='GAUGE') | python | def collect_instance(self, nick, host, port, unix_socket, auth):
"""Collect metrics from a single Redis instance
:param str nick: nickname of redis instance
:param str host: redis host
:param int port: redis port
:param str unix_socket: unix socket, if applicable
:param str auth: authentication password
"""
# Connect to redis and get the info
info = self._get_info(host, port, unix_socket, auth)
if info is None:
return
# The structure should include the port for multiple instances per
# server
data = dict()
# Role needs to be handled outside the the _KEYS dict
# since the value is a string, not a int / float
# Also, master_sync_in_progress is only available if the
# redis instance is a slave, so default it here so that
# the metric is cleared if the instance flips from slave
# to master
if 'role' in info:
if info['role'] == "master":
data['replication.master'] = 1
data['replication.master_sync_in_progress'] = 0
else:
data['replication.master'] = 0
# Connect to redis and get the maxmemory config value
# Then calculate the % maxmemory of memory used
maxmemory_config = self._get_config(host, port, unix_socket, auth,
'maxmemory')
if maxmemory_config and 'maxmemory' in maxmemory_config.keys():
maxmemory = float(maxmemory_config['maxmemory'])
# Only report % used if maxmemory is a non zero value
if maxmemory == 0:
maxmemory_percent = 0.0
else:
maxmemory_percent = info['used_memory'] / maxmemory * 100
maxmemory_percent = round(maxmemory_percent, 2)
data['memory.used_percent'] = float("%.2f" % maxmemory_percent)
# Iterate over the top level keys
for key in self._KEYS:
if self._KEYS[key] in info:
data[key] = info[self._KEYS[key]]
# Iterate over renamed keys for 2.6 support
for key in self._RENAMED_KEYS:
if self._RENAMED_KEYS[key] in info:
data[key] = info[self._RENAMED_KEYS[key]]
# Look for databaase speific stats
for dbnum in range(0, int(self.config.get('databases',
self._DATABASE_COUNT))):
db = 'db%i' % dbnum
if db in info:
for key in info[db]:
data['%s.%s' % (db, key)] = info[db][key]
# Time since last save
for key in ['last_save_time', 'rdb_last_save_time']:
if key in info:
data['last_save.time_since'] = int(time.time()) - info[key]
# Publish the data to graphite
for key in data:
self.publish(self._publish_key(nick, key),
data[key],
precision=self._precision(data[key]),
metric_type='GAUGE') | [
"def",
"collect_instance",
"(",
"self",
",",
"nick",
",",
"host",
",",
"port",
",",
"unix_socket",
",",
"auth",
")",
":",
"# Connect to redis and get the info",
"info",
"=",
"self",
".",
"_get_info",
"(",
"host",
",",
"port",
",",
"unix_socket",
",",
"auth",... | Collect metrics from a single Redis instance
:param str nick: nickname of redis instance
:param str host: redis host
:param int port: redis port
:param str unix_socket: unix socket, if applicable
:param str auth: authentication password | [
"Collect",
"metrics",
"from",
"a",
"single",
"Redis",
"instance"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L287-L363 | train | 217,225 |
python-diamond/Diamond | src/collectors/redisstat/redisstat.py | RedisCollector.collect | def collect(self):
"""Collect the stats from the redis instance and publish them.
"""
if redis is None:
self.log.error('Unable to import module redis')
return {}
for nick in self.instances.keys():
(host, port, unix_socket, auth) = self.instances[nick]
self.collect_instance(nick, host, int(port), unix_socket, auth) | python | def collect(self):
"""Collect the stats from the redis instance and publish them.
"""
if redis is None:
self.log.error('Unable to import module redis')
return {}
for nick in self.instances.keys():
(host, port, unix_socket, auth) = self.instances[nick]
self.collect_instance(nick, host, int(port), unix_socket, auth) | [
"def",
"collect",
"(",
"self",
")",
":",
"if",
"redis",
"is",
"None",
":",
"self",
".",
"log",
".",
"error",
"(",
"'Unable to import module redis'",
")",
"return",
"{",
"}",
"for",
"nick",
"in",
"self",
".",
"instances",
".",
"keys",
"(",
")",
":",
"... | Collect the stats from the redis instance and publish them. | [
"Collect",
"the",
"stats",
"from",
"the",
"redis",
"instance",
"and",
"publish",
"them",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L365-L375 | train | 217,226 |
python-diamond/Diamond | src/collectors/xfs/xfs.py | XFSCollector.get_default_config | def get_default_config(self):
"""
Returns the xfs collector settings
"""
config = super(XFSCollector, self).get_default_config()
config.update({
'path': 'xfs'
})
return config | python | def get_default_config(self):
"""
Returns the xfs collector settings
"""
config = super(XFSCollector, self).get_default_config()
config.update({
'path': 'xfs'
})
return config | [
"def",
"get_default_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"XFSCollector",
",",
"self",
")",
".",
"get_default_config",
"(",
")",
"config",
".",
"update",
"(",
"{",
"'path'",
":",
"'xfs'",
"}",
")",
"return",
"config"
] | Returns the xfs collector settings | [
"Returns",
"the",
"xfs",
"collector",
"settings"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/xfs/xfs.py#L25-L33 | train | 217,227 |
python-diamond/Diamond | src/diamond/handler/cloudwatch.py | cloudwatchHandler._bind | def _bind(self):
"""
Create CloudWatch Connection
"""
self.log.debug(
"CloudWatch: Attempting to connect to CloudWatch at Region: %s",
self.region)
try:
self.connection = boto.ec2.cloudwatch.connect_to_region(
self.region)
self.log.debug(
"CloudWatch: Succesfully Connected to CloudWatch at Region: %s",
self.region)
except boto.exception.EC2ResponseError:
self.log.error('CloudWatch: CloudWatch Exception Handler: ') | python | def _bind(self):
"""
Create CloudWatch Connection
"""
self.log.debug(
"CloudWatch: Attempting to connect to CloudWatch at Region: %s",
self.region)
try:
self.connection = boto.ec2.cloudwatch.connect_to_region(
self.region)
self.log.debug(
"CloudWatch: Succesfully Connected to CloudWatch at Region: %s",
self.region)
except boto.exception.EC2ResponseError:
self.log.error('CloudWatch: CloudWatch Exception Handler: ') | [
"def",
"_bind",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"CloudWatch: Attempting to connect to CloudWatch at Region: %s\"",
",",
"self",
".",
"region",
")",
"try",
":",
"self",
".",
"connection",
"=",
"boto",
".",
"ec2",
".",
"cloudwatch... | Create CloudWatch Connection | [
"Create",
"CloudWatch",
"Connection"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/cloudwatch.py#L163-L178 | train | 217,228 |
python-diamond/Diamond | src/diamond/handler/cloudwatch.py | cloudwatchHandler.process | def process(self, metric):
"""
Process a metric and send it to CloudWatch
"""
if not boto:
return
collector = str(metric.getCollectorPath())
metricname = str(metric.getMetricPath())
# Send the data as ......
for rule in self.rules:
self.log.debug(
"Comparing Collector: [%s] with (%s) "
"and Metric: [%s] with (%s)",
str(rule['collector']),
collector,
str(rule['metric']),
metricname
)
if ((str(rule['collector']) == collector and
str(rule['metric']) == metricname)):
if rule['collect_by_instance'] and self.instance_id:
self.send_metrics_to_cloudwatch(
rule,
metric,
{'InstanceId': self.instance_id})
if rule['collect_without_dimension']:
self.send_metrics_to_cloudwatch(
rule,
metric,
{}) | python | def process(self, metric):
"""
Process a metric and send it to CloudWatch
"""
if not boto:
return
collector = str(metric.getCollectorPath())
metricname = str(metric.getMetricPath())
# Send the data as ......
for rule in self.rules:
self.log.debug(
"Comparing Collector: [%s] with (%s) "
"and Metric: [%s] with (%s)",
str(rule['collector']),
collector,
str(rule['metric']),
metricname
)
if ((str(rule['collector']) == collector and
str(rule['metric']) == metricname)):
if rule['collect_by_instance'] and self.instance_id:
self.send_metrics_to_cloudwatch(
rule,
metric,
{'InstanceId': self.instance_id})
if rule['collect_without_dimension']:
self.send_metrics_to_cloudwatch(
rule,
metric,
{}) | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"if",
"not",
"boto",
":",
"return",
"collector",
"=",
"str",
"(",
"metric",
".",
"getCollectorPath",
"(",
")",
")",
"metricname",
"=",
"str",
"(",
"metric",
".",
"getMetricPath",
"(",
")",
")",
... | Process a metric and send it to CloudWatch | [
"Process",
"a",
"metric",
"and",
"send",
"it",
"to",
"CloudWatch"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/cloudwatch.py#L189-L224 | train | 217,229 |
python-diamond/Diamond | src/diamond/handler/cloudwatch.py | cloudwatchHandler.send_metrics_to_cloudwatch | def send_metrics_to_cloudwatch(self, rule, metric, dimensions):
"""
Send metrics to CloudWatch for the given dimensions
"""
timestamp = datetime.datetime.utcfromtimestamp(metric.timestamp)
self.log.debug(
"CloudWatch: Attempting to publish metric: %s to %s "
"with value (%s) for dimensions %s @%s",
rule['name'],
rule['namespace'],
str(metric.value),
str(dimensions),
str(metric.timestamp)
)
try:
self.connection.put_metric_data(
str(rule['namespace']),
str(rule['name']),
str(metric.value),
timestamp, str(rule['unit']),
dimensions)
self.log.debug(
"CloudWatch: Successfully published metric: %s to"
" %s with value (%s) for dimensions %s",
rule['name'],
rule['namespace'],
str(metric.value),
str(dimensions))
except AttributeError as e:
self.log.error(
"CloudWatch: Failed publishing - %s ", str(e))
except Exception as e: # Rough connection re-try logic.
self.log.error(
"CloudWatch: Failed publishing - %s\n%s ",
str(e),
str(sys.exc_info()[0]))
self._bind() | python | def send_metrics_to_cloudwatch(self, rule, metric, dimensions):
"""
Send metrics to CloudWatch for the given dimensions
"""
timestamp = datetime.datetime.utcfromtimestamp(metric.timestamp)
self.log.debug(
"CloudWatch: Attempting to publish metric: %s to %s "
"with value (%s) for dimensions %s @%s",
rule['name'],
rule['namespace'],
str(metric.value),
str(dimensions),
str(metric.timestamp)
)
try:
self.connection.put_metric_data(
str(rule['namespace']),
str(rule['name']),
str(metric.value),
timestamp, str(rule['unit']),
dimensions)
self.log.debug(
"CloudWatch: Successfully published metric: %s to"
" %s with value (%s) for dimensions %s",
rule['name'],
rule['namespace'],
str(metric.value),
str(dimensions))
except AttributeError as e:
self.log.error(
"CloudWatch: Failed publishing - %s ", str(e))
except Exception as e: # Rough connection re-try logic.
self.log.error(
"CloudWatch: Failed publishing - %s\n%s ",
str(e),
str(sys.exc_info()[0]))
self._bind() | [
"def",
"send_metrics_to_cloudwatch",
"(",
"self",
",",
"rule",
",",
"metric",
",",
"dimensions",
")",
":",
"timestamp",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"metric",
".",
"timestamp",
")",
"self",
".",
"log",
".",
"debug",
"(",
... | Send metrics to CloudWatch for the given dimensions | [
"Send",
"metrics",
"to",
"CloudWatch",
"for",
"the",
"given",
"dimensions"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/cloudwatch.py#L226-L265 | train | 217,230 |
python-diamond/Diamond | src/collectors/mongodb/mongodb.py | MongoDBCollector._publish_replset | def _publish_replset(self, data, base_prefix):
""" Given a response to replSetGetStatus, publishes all numeric values
of the instance, aggregate stats of healthy nodes vs total nodes,
and the observed statuses of all nodes in the replica set.
"""
prefix = base_prefix + ['replset']
self._publish_dict_with_prefix(data, prefix)
total_nodes = len(data['members'])
healthy_nodes = reduce(lambda value, node: value + node['health'],
data['members'], 0)
self._publish_dict_with_prefix({
'healthy_nodes': healthy_nodes,
'total_nodes': total_nodes
}, prefix)
for node in data['members']:
replset_node_name = node[self.config['replset_node_name']]
node_name = str(replset_node_name.split('.')[0])
self._publish_dict_with_prefix(node, prefix + ['node', node_name]) | python | def _publish_replset(self, data, base_prefix):
""" Given a response to replSetGetStatus, publishes all numeric values
of the instance, aggregate stats of healthy nodes vs total nodes,
and the observed statuses of all nodes in the replica set.
"""
prefix = base_prefix + ['replset']
self._publish_dict_with_prefix(data, prefix)
total_nodes = len(data['members'])
healthy_nodes = reduce(lambda value, node: value + node['health'],
data['members'], 0)
self._publish_dict_with_prefix({
'healthy_nodes': healthy_nodes,
'total_nodes': total_nodes
}, prefix)
for node in data['members']:
replset_node_name = node[self.config['replset_node_name']]
node_name = str(replset_node_name.split('.')[0])
self._publish_dict_with_prefix(node, prefix + ['node', node_name]) | [
"def",
"_publish_replset",
"(",
"self",
",",
"data",
",",
"base_prefix",
")",
":",
"prefix",
"=",
"base_prefix",
"+",
"[",
"'replset'",
"]",
"self",
".",
"_publish_dict_with_prefix",
"(",
"data",
",",
"prefix",
")",
"total_nodes",
"=",
"len",
"(",
"data",
... | Given a response to replSetGetStatus, publishes all numeric values
of the instance, aggregate stats of healthy nodes vs total nodes,
and the observed statuses of all nodes in the replica set. | [
"Given",
"a",
"response",
"to",
"replSetGetStatus",
"publishes",
"all",
"numeric",
"values",
"of",
"the",
"instance",
"aggregate",
"stats",
"of",
"healthy",
"nodes",
"vs",
"total",
"nodes",
"and",
"the",
"observed",
"statuses",
"of",
"all",
"nodes",
"in",
"the... | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mongodb/mongodb.py#L230-L248 | train | 217,231 |
python-diamond/Diamond | src/diamond/handler/influxdbHandler.py | InfluxdbHandler._send | def _send(self):
"""
Send data to Influxdb. Data that can not be sent will be kept in queued.
"""
# Check to see if we have a valid socket. If not, try to connect.
try:
if self.influx is None:
self.log.debug("InfluxdbHandler: Socket is not connected. "
"Reconnecting.")
self._connect()
if self.influx is None:
self.log.debug("InfluxdbHandler: Reconnect failed.")
else:
# build metrics data
metrics = []
for path in self.batch:
metrics.append({
"points": self.batch[path],
"name": path,
"columns": ["time", "value"]})
# Send data to influxdb
self.log.debug("InfluxdbHandler: writing %d series of data",
len(metrics))
self.influx.write_points(metrics,
time_precision=self.time_precision)
# empty batch buffer
self.batch = {}
self.batch_count = 0
self.time_multiplier = 1
except Exception:
self._close()
if self.time_multiplier < 5:
self.time_multiplier += 1
self._throttle_error(
"InfluxdbHandler: Error sending metrics, waiting for %ds.",
2**self.time_multiplier)
raise | python | def _send(self):
"""
Send data to Influxdb. Data that can not be sent will be kept in queued.
"""
# Check to see if we have a valid socket. If not, try to connect.
try:
if self.influx is None:
self.log.debug("InfluxdbHandler: Socket is not connected. "
"Reconnecting.")
self._connect()
if self.influx is None:
self.log.debug("InfluxdbHandler: Reconnect failed.")
else:
# build metrics data
metrics = []
for path in self.batch:
metrics.append({
"points": self.batch[path],
"name": path,
"columns": ["time", "value"]})
# Send data to influxdb
self.log.debug("InfluxdbHandler: writing %d series of data",
len(metrics))
self.influx.write_points(metrics,
time_precision=self.time_precision)
# empty batch buffer
self.batch = {}
self.batch_count = 0
self.time_multiplier = 1
except Exception:
self._close()
if self.time_multiplier < 5:
self.time_multiplier += 1
self._throttle_error(
"InfluxdbHandler: Error sending metrics, waiting for %ds.",
2**self.time_multiplier)
raise | [
"def",
"_send",
"(",
"self",
")",
":",
"# Check to see if we have a valid socket. If not, try to connect.",
"try",
":",
"if",
"self",
".",
"influx",
"is",
"None",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"InfluxdbHandler: Socket is not connected. \"",
"\"Reconnecti... | Send data to Influxdb. Data that can not be sent will be kept in queued. | [
"Send",
"data",
"to",
"Influxdb",
".",
"Data",
"that",
"can",
"not",
"be",
"sent",
"will",
"be",
"kept",
"in",
"queued",
"."
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/influxdbHandler.py#L156-L194 | train | 217,232 |
python-diamond/Diamond | src/diamond/handler/influxdbHandler.py | InfluxdbHandler._connect | def _connect(self):
"""
Connect to the influxdb server
"""
try:
# Open Connection
self.influx = InfluxDBClient(self.hostname, self.port,
self.username, self.password,
self.database, self.ssl)
# Log
self.log.debug("InfluxdbHandler: Established connection to "
"%s:%d/%s.",
self.hostname, self.port, self.database)
except Exception as ex:
# Log Error
self._throttle_error("InfluxdbHandler: Failed to connect to "
"%s:%d/%s. %s",
self.hostname, self.port, self.database, ex)
# Close Socket
self._close()
return | python | def _connect(self):
"""
Connect to the influxdb server
"""
try:
# Open Connection
self.influx = InfluxDBClient(self.hostname, self.port,
self.username, self.password,
self.database, self.ssl)
# Log
self.log.debug("InfluxdbHandler: Established connection to "
"%s:%d/%s.",
self.hostname, self.port, self.database)
except Exception as ex:
# Log Error
self._throttle_error("InfluxdbHandler: Failed to connect to "
"%s:%d/%s. %s",
self.hostname, self.port, self.database, ex)
# Close Socket
self._close()
return | [
"def",
"_connect",
"(",
"self",
")",
":",
"try",
":",
"# Open Connection",
"self",
".",
"influx",
"=",
"InfluxDBClient",
"(",
"self",
".",
"hostname",
",",
"self",
".",
"port",
",",
"self",
".",
"username",
",",
"self",
".",
"password",
",",
"self",
".... | Connect to the influxdb server | [
"Connect",
"to",
"the",
"influxdb",
"server"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/influxdbHandler.py#L196-L217 | train | 217,233 |
python-diamond/Diamond | src/diamond/handler/rabbitmq_pubsub.py | rmqHandler.get_config | def get_config(self):
""" Get and set config options from config file """
if 'rmq_port' in self.config:
self.rmq_port = int(self.config['rmq_port'])
if 'rmq_user' in self.config:
self.rmq_user = self.config['rmq_user']
if 'rmq_password' in self.config:
self.rmq_password = self.config['rmq_password']
if 'rmq_vhost' in self.config:
self.rmq_vhost = self.config['rmq_vhost']
if 'rmq_exchange_type' in self.config:
self.rmq_exchange_type = self.config['rmq_exchange_type']
if 'rmq_durable' in self.config:
self.rmq_durable = bool(self.config['rmq_durable'])
if 'rmq_heartbeat_interval' in self.config:
self.rmq_heartbeat_interval = int(
self.config['rmq_heartbeat_interval']) | python | def get_config(self):
""" Get and set config options from config file """
if 'rmq_port' in self.config:
self.rmq_port = int(self.config['rmq_port'])
if 'rmq_user' in self.config:
self.rmq_user = self.config['rmq_user']
if 'rmq_password' in self.config:
self.rmq_password = self.config['rmq_password']
if 'rmq_vhost' in self.config:
self.rmq_vhost = self.config['rmq_vhost']
if 'rmq_exchange_type' in self.config:
self.rmq_exchange_type = self.config['rmq_exchange_type']
if 'rmq_durable' in self.config:
self.rmq_durable = bool(self.config['rmq_durable'])
if 'rmq_heartbeat_interval' in self.config:
self.rmq_heartbeat_interval = int(
self.config['rmq_heartbeat_interval']) | [
"def",
"get_config",
"(",
"self",
")",
":",
"if",
"'rmq_port'",
"in",
"self",
".",
"config",
":",
"self",
".",
"rmq_port",
"=",
"int",
"(",
"self",
".",
"config",
"[",
"'rmq_port'",
"]",
")",
"if",
"'rmq_user'",
"in",
"self",
".",
"config",
":",
"sel... | Get and set config options from config file | [
"Get",
"and",
"set",
"config",
"options",
"from",
"config",
"file"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_pubsub.py#L63-L85 | train | 217,234 |
python-diamond/Diamond | src/diamond/handler/rabbitmq_pubsub.py | rmqHandler._unbind | def _unbind(self, rmq_server=None):
""" Close AMQP connection and unset channel """
try:
self.connections[rmq_server].close()
except AttributeError:
pass
self.connections[rmq_server] = None
self.channels[rmq_server] = None | python | def _unbind(self, rmq_server=None):
""" Close AMQP connection and unset channel """
try:
self.connections[rmq_server].close()
except AttributeError:
pass
self.connections[rmq_server] = None
self.channels[rmq_server] = None | [
"def",
"_unbind",
"(",
"self",
",",
"rmq_server",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"connections",
"[",
"rmq_server",
"]",
".",
"close",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"connections",
"[",
"rmq_server",
"]",
... | Close AMQP connection and unset channel | [
"Close",
"AMQP",
"connection",
"and",
"unset",
"channel"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_pubsub.py#L172-L180 | train | 217,235 |
python-diamond/Diamond | src/diamond/handler/rabbitmq_pubsub.py | rmqHandler.process | def process(self, metric):
"""
Process a metric and send it to RMQ pub socket
"""
for rmq_server in self.connections.keys():
try:
if ((self.connections[rmq_server] is None or
self.connections[rmq_server].is_open is False)):
self._bind(rmq_server)
channel = self.channels[rmq_server]
channel.basic_publish(exchange=self.rmq_exchange,
routing_key='', body="%s" % metric)
except Exception as exception:
self.log.error(
"Failed publishing to %s, attempting reconnect",
rmq_server)
self.log.debug("Caught exception: %s", exception)
self._unbind(rmq_server)
self._bind(rmq_server) | python | def process(self, metric):
"""
Process a metric and send it to RMQ pub socket
"""
for rmq_server in self.connections.keys():
try:
if ((self.connections[rmq_server] is None or
self.connections[rmq_server].is_open is False)):
self._bind(rmq_server)
channel = self.channels[rmq_server]
channel.basic_publish(exchange=self.rmq_exchange,
routing_key='', body="%s" % metric)
except Exception as exception:
self.log.error(
"Failed publishing to %s, attempting reconnect",
rmq_server)
self.log.debug("Caught exception: %s", exception)
self._unbind(rmq_server)
self._bind(rmq_server) | [
"def",
"process",
"(",
"self",
",",
"metric",
")",
":",
"for",
"rmq_server",
"in",
"self",
".",
"connections",
".",
"keys",
"(",
")",
":",
"try",
":",
"if",
"(",
"(",
"self",
".",
"connections",
"[",
"rmq_server",
"]",
"is",
"None",
"or",
"self",
"... | Process a metric and send it to RMQ pub socket | [
"Process",
"a",
"metric",
"and",
"send",
"it",
"to",
"RMQ",
"pub",
"socket"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_pubsub.py#L190-L209 | train | 217,236 |
python-diamond/Diamond | src/collectors/netstat/netstat.py | NetstatCollector._load | def _load():
""" Read the table of tcp connections & remove header """
with open(NetstatCollector.PROC_TCP, 'r') as f:
content = f.readlines()
content.pop(0)
return content | python | def _load():
""" Read the table of tcp connections & remove header """
with open(NetstatCollector.PROC_TCP, 'r') as f:
content = f.readlines()
content.pop(0)
return content | [
"def",
"_load",
"(",
")",
":",
"with",
"open",
"(",
"NetstatCollector",
".",
"PROC_TCP",
",",
"'r'",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"readlines",
"(",
")",
"content",
".",
"pop",
"(",
"0",
")",
"return",
"content"
] | Read the table of tcp connections & remove header | [
"Read",
"the",
"table",
"of",
"tcp",
"connections",
"&",
"remove",
"header"
] | 0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47 | https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netstat/netstat.py#L62-L67 | train | 217,237 |
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):
"""
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 | [
"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 | train | 217,238 |
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):
"""
Returns default settings for collector.
"""
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 | train | 217,239 |
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):
"""
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") | [
"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 | train | 217,240 |
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):
"""
Read contents of given file.
"""
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 | train | 217,241 |
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):
"""
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(), ['*']) | [
"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 | train | 217,242 |
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):
"""
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() | [
"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 | train | 217,243 |
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):
"""
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) | [
"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 | train | 217,244 |
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):
"""
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]) | [
"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 | train | 217,245 |
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):
"""
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 | [
"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 | train | 217,246 |
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):
"""
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 | [
"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 | train | 217,247 |
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):
"""
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 | [
"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 | train | 217,248 |
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):
"""
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() | [
"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 | train | 217,249 |
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):
"""
Send data to Librato.
"""
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 | train | 217,250 |
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):
"""
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]) | [
"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 | train | 217,251 |
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):
"""
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 | [
"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 | train | 217,252 |
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):
""" 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 | [
"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 | train | 217,253 |
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):
""" 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 | [
"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 | train | 217,254 |
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):
""" 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 | [
"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 | train | 217,255 |
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):
""" 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 | [
"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 | train | 217,256 |
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):
""" 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) | [
"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 | train | 217,257 |
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):
""" 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 | [
"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 | train | 217,258 |
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):
""" 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 | [
"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 | train | 217,259 |
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):
"""
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 | [
"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 | train | 217,260 |
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):
""" Trim left-right given string """
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 | train | 217,261 |
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):
"""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 {} | [
"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 | train | 217,262 |
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):
"""
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) | [
"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 | train | 217,263 |
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):
"""
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 | [
"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 | train | 217,264 |
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):
"""
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) | [
"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 | train | 217,265 |
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):
"""
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 | [
"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 | train | 217,266 |
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):
"""Remove non-alphanumerical characters from metric word.
And trim excessive underscores.
"""
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 | train | 217,267 |
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):
"""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] | [
"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 | train | 217,268 |
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):
"""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 | [
"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 | train | 217,269 |
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):
"""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) | [
"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 | train | 217,270 |
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):
"""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) | [
"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 | train | 217,271 |
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):
"""
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 | [
"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 | train | 217,272 |
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):
"""
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 | [
"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 | train | 217,273 |
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):
"""
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() | [
"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 | train | 217,274 |
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):
"""
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 | [
"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 | train | 217,275 |
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):
"""
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 | [
"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 | train | 217,276 |
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):
"""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) | [
"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 | train | 217,277 |
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):
"""
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) | [
"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 | train | 217,278 |
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 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() | [
"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 | train | 217,279 |
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):
"""
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:] | [
"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 | train | 217,280 |
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):
"""
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 | [
"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 | train | 217,281 |
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):
"""
Process a metric by doing nothing
"""
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 | train | 217,282 |
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):
"""
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() | [
"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 | train | 217,283 |
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):
"""
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']) | [
"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 | train | 217,284 |
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):
"""
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]) | [
"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 | train | 217,285 |
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):
"""
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) | [
"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 | train | 217,286 |
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):
"""
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 | [
"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 | train | 217,287 |
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):
"""
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() | [
"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 | train | 217,288 |
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):
"""
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 | [
"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 | train | 217,289 |
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):
"""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 | [
"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 | train | 217,290 |
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_):
"""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 | [
"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 | train | 217,291 |
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):
"""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() | [
"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 | train | 217,292 |
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):
""" 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) | [
"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 | train | 217,293 |
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):
""" 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 | [
"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 | train | 217,294 |
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):
"""return more complete message"""
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 | train | 217,295 |
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):
"""
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 | [
"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 | train | 217,296 |
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):
"""
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 | [
"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 | train | 217,297 |
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):
"""
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)) | [
"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 | train | 217,298 |
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):
"""
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) | [
"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 | train | 217,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.