text stringlengths 81 112k |
|---|
Initialize filesystem to device mappings.
def _initFilesystemInfo(self):
"""Initialize filesystem to device mappings."""
self._mapFSpathDev = {}
fsinfo = FilesystemInfo()
for fs in fsinfo.getFSlist():
devpath = fsinfo.getFSdev(fs)
dev = self._getUniqueDev(devpath... |
Initialize swap partition to device mappings.
def _initSwapInfo(self):
"""Initialize swap partition to device mappings."""
self._swapList = []
sysinfo = SystemInfo()
for (swap,attrs) in sysinfo.getSwapStats().iteritems():
if attrs['type'] == 'partition':
dev ... |
Parse and initialize block device I/O stats in /proc/diskstats.
def _initDiskStats(self):
"""Parse and initialize block device I/O stats in /proc/diskstats."""
self._diskStats = {}
self._mapMajorMinor2dev = {}
try:
fp = open(diskStatsFile, 'r')
data = fp.read()
... |
Sort block devices into lists depending on device class and
initialize device type map and partition map.
def _initDevClasses(self):
"""Sort block devices into lists depending on device class and
initialize device type map and partition map."""
self._devClassTree = {}
self._pa... |
Returns type of device dev.
@return: Device type as string.
def getDevType(self, dev):
"""Returns type of device dev.
@return: Device type as string.
"""
if self._devClassTree is None:
self._initDevClasses()
return self._mapDevType.... |
Returns list of partitions.
@return: List of (disk,partition) pairs.
def getPartitionList(self):
"""Returns list of partitions.
@return: List of (disk,partition) pairs.
"""
if self._partList is None:
self._partList = []
for (dis... |
Returns I/O stats for block device.
@param dev: Device name
@param devtype: Device type. (Ignored if None.)
@return: Dict of stats.
def getDevStats(self, dev, devtype = None):
"""Returns I/O stats for block device.
@param dev: Device name
... |
Returns I/O stats for swap partition.
@param dev: Device name for swap partition.
@return: Dict of stats.
def getSwapStats(self, dev):
"""Returns I/O stats for swap partition.
@param dev: Device name for swap partition.
@return: Dict of stats.
... |
Returns I/O stats for LV.
@param args: Two calling conventions are implemented:
- Passing two parameters vg and lv.
- Passing only one parameter in 'vg-lv' format.
@return: Dict of stats.
def getLVstats(self, *args):
"""Returns I/O stats ... |
Returns I/O stats for filesystem.
@param fs: Filesystem path.
@return: Dict of stats.
def getFilesystemStats(self, fs):
"""Returns I/O stats for filesystem.
@param fs: Filesystem path.
@return: Dict of stats.
"""
if self._mapFSpathDev i... |
Retrieve values for graphs.
def retrieveVals(self):
"""Retrieve values for graphs."""
ntpinfo = NTPinfo()
stats = ntpinfo.getHostOffset(self._remoteHost)
if stats:
graph_name = 'ntp_host_stratum_%s' % self._remoteHost
if self.hasGraph(graph_name):
... |
Returns Rackspace Cloud Files usage stats for containers.
@param limit: Number of containers to return.
@param marker: Return only results whose name is greater than marker.
@return: Dictionary of container stats indexed by container name.
def getContainerStats(self, limit=None,... |
Decode speech for a file or folder and return results
This function wraps the Google Speech API and ffmpeg to decode speech for
free recall experiments. Note: in order for this to work, you must have a
Google Speech account, a google speech credentials file referenced in your
_bash_profile, and ffmpeg... |
Parse input string and return int, float or str depending on format.
@param val: Input string.
@return: Value of type int, float or str.
def parse_value(val):
"""Parse input string and return int, float or str depending on format.
@param val: Input string.
@return: Value of type int... |
Connect to Squid Proxy Manager interface.
def _connect(self):
"""Connect to Squid Proxy Manager interface."""
if sys.version_info[:2] < (2,6):
self._conn = httplib.HTTPConnection(self._host, self._port)
else:
self._conn = httplib.HTTPConnection(self._host, self._port,
... |
Query Squid Proxy Server Manager Interface for stats.
@param map: Statistics map name.
@return: Dictionary of query results.
def _retrieve(self, map):
"""Query Squid Proxy Server Manager Interface for stats.
@param map: Statistics map name.
@return: Dicti... |
Parse simple stats list of key, value pairs.
@param data: Multiline data with one key-value pair in each line.
@return: Dictionary of stats.
def _parseCounters(self, data):
"""Parse simple stats list of key, value pairs.
@param data: Multiline data with one key-val... |
Parse data and separate sections. Returns dictionary that maps
section name to section data.
@param data: Multiline data.
@return: Dictionary that maps section names to section data.
def _parseSections(self, data):
"""Parse data and separate sections. Returns dictionary th... |
Get manager interface section list from Squid Proxy Server
@return: List of tuples (section, description, type)
def getMenu(self):
"""Get manager interface section list from Squid Proxy Server
@return: List of tuples (section, description, type)
"""
... |
Return dictionary of Traffic Stats for each Wanpipe Interface.
@return: Nested dictionary of statistics for each interface.
def getIfaceStats(self):
"""Return dictionary of Traffic Stats for each Wanpipe Interface.
@return: Nested dictionary of statistics for each interface.
... |
Return RDSI Operational Stats for interface.
@param iface: Interface name. (Ex. w1g1)
@return: Nested dictionary of statistics for interface.
def getPRIstats(self, iface):
"""Return RDSI Operational Stats for interface.
@param iface: Interface name. (Ex. w1g1)
... |
Connect to FreeSWITCH ESL Interface.
def _connect(self):
"""Connect to FreeSWITCH ESL Interface."""
try:
self._eslconn = ESL.ESLconnection(self._eslhost,
str(self._eslport),
self._eslpass)
... |
Execute command and return result body as list of lines.
@param cmd: Command string.
@param args: Comand arguments string.
@return: Result dictionary.
def _execCmd(self, cmd, args):
"""Execute command and return result body as list of lines.
... |
Execute 'show' command and return result dictionary.
@param cmd: Command string.
@return: Result dictionary.
def _execShowCmd(self, showcmd):
"""Execute 'show' command and return result dictionary.
@param cmd: Command string.
@return: Result dic... |
Execute 'show' command and return result dictionary.
@param cmd: Command string.
@return: Result dictionary.
def _execShowCountCmd(self, showcmd):
"""Execute 'show' command and return result dictionary.
@param cmd: Command string.
@return: Resul... |
Retrieve values for graphs.
def retrieveVals(self):
"""Retrieve values for graphs."""
if self.hasGraph('asterisk_calls') or self.hasGraph('asterisk_channels'):
stats = self._ami.getChannelStats(self._chanList)
if self.hasGraph('asterisk_calls') and stats:
self.... |
Retrieve values for graphs.
def retrieveVals(self):
"""Retrieve values for graphs."""
fpminfo = PHPfpmInfo(self._host, self._port, self._user, self._password,
self._monpath, self._ssl)
stats = fpminfo.getStats()
if self.hasGraph('php_fpm_connections') and s... |
Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
... |
Ping Redis Server and return Round-Trip-Time in seconds.
@return: Round-trip-time in seconds as float.
def ping(self):
"""Ping Redis Server and return Round-Trip-Time in seconds.
@return: Round-trip-time in seconds as float.
"""
start = time.time()
... |
Makes multi-indexed dataframe of subject data
Parameters
----------
all_data : list of lists of strings
strings are either all presented or all recalled items, in the order of presentation or recall
*should also work for presented / recalled ints and floats, if desired
Returns
---... |
Creates egg data object from zero-indexed recall matrix
Parameters
----------
recmat : list of lists (subs) of lists (encoding lists) of ints or 2D numpy array
recall matrix representing serial positions of freely recalled words \
e.g. [[[16, 15, 0, 2, 3, None, None...],... |
Fills in default distance metrics for fingerprint analyses
def default_dist_funcs(dist_funcs, feature_example):
"""
Fills in default distance metrics for fingerprint analyses
"""
if dist_funcs is None:
dist_funcs = dict()
for key in feature_example:
if ... |
Takes a list of eggs, stacks them and reindexes the subject number
Parameters
----------
eggs : list of Egg data objects
A list of Eggs that you want to combine
meta : string
Determines how the meta data of each Egg combines. Default is 'concatenate'
'concatenate' concatenates k... |
Takes an egg and returns a subset of the subjects or lists
Parameters
----------
egg : Egg data object
Egg that you want to crack
subjects : list
List of subject idxs
lists : list
List of lists idxs
Returns
----------
new_egg : Egg data object
A sliced... |
Convert a MultiIndex df to list
Parameters
----------
df : pandas.DataFrame
A MultiIndex DataFrame where the first level is subjects and the second
level is lists (e.g. egg.pres)
Returns
----------
lst : a list of lists of lists of values
The input df reformatted as a... |
Fills in missing lists (assumes end lists are missing)
def fill_missing(x):
"""
Fills in missing lists (assumes end lists are missing)
"""
# find subject with max number of lists
maxlen = max([len(xi) for xi in x])
subs = []
for sub in x:
if len(sub)<maxlen:
for i in ... |
Parses an egg and returns fields
def parse_egg(egg):
"""Parses an egg and returns fields"""
pres_list = egg.get_pres_items().values[0]
rec_list = egg.get_rec_items().values[0]
feature_list = egg.get_pres_features().values[0]
dist_funcs = egg.dist_funcs
return pres_list, rec_list, feature_list, ... |
Helper function to merge pres and features to support legacy features argument
def merge_pres_feats(pres, features):
"""
Helper function to merge pres and features to support legacy features argument
"""
sub = []
for psub, fsub in zip(pres, features):
exp = []
for pexp, fexp in zip... |
Function that calculates the Fisher z-transformation
Parameters
----------
r : int or ndarray
Correlation value
Returns
----------
result : int or ndarray
Fishers z transformed correlation value
def r2z(r):
"""
Function that calculates the Fisher z-transformation
... |
Function that calculates the inverse Fisher z-transformation
Parameters
----------
z : int or ndarray
Fishers z transformed correlation value
Returns
----------
result : int or ndarray
Correlation value
def z2r(z):
"""
Function that calculates the inverse Fisher z-tran... |
Shuffle an Egg's recalls
def shuffle_egg(egg):
""" Shuffle an Egg's recalls"""
from .egg import Egg
pres, rec, features, dist_funcs = parse_egg(egg)
if pres.ndim==1:
pres = pres.reshape(1, pres.shape[0])
rec = rec.reshape(1, rec.shape[0])
features = features.reshape(1, features... |
Retrieve values for graphs.
def retrieveVals(self):
"""Retrieve values for graphs."""
for iface in self._ifaceList:
stats = self._ifaceStats.get(iface)
graph_name = 'netiface_traffic_%s' % iface
if self.hasGraph(graph_name):
self.setGraphVal(graph_nam... |
Get NTP Peer Stats for localhost by querying local NTP Server.
@return: Dictionary of NTP stats converted to seconds.
def getPeerStats(self):
"""Get NTP Peer Stats for localhost by querying local NTP Server.
@return: Dictionary of NTP stats converted to seconds.
"""
... |
Get NTP Stats and offset of remote host relative to localhost
by querying NTP Server on remote host.
@param host: Remote Host IP.
@return: Dictionary of NTP stats converted to seconds.
def getHostOffset(self, host):
"""Get NTP Stats and offset of remote host relative to loc... |
Get NTP Stats and offset of multiple remote hosts relative to localhost
by querying NTP Servers on remote hosts.
@param host: List of Remote Host IPs.
@return: Dictionary of NTP stats converted to seconds.
def getHostOffsets(self, hosts):
"""Get NTP Stats and offset of mult... |
Return system uptime in seconds.
@return: Float that represents uptime in seconds.
def getUptime(self):
"""Return system uptime in seconds.
@return: Float that represents uptime in seconds.
"""
try:
fp = open(uptimeFile, 'r')
li... |
Return system Load Average.
@return: List of 1 min, 5 min and 15 min Load Average figures.
def getLoadAvg(self):
"""Return system Load Average.
@return: List of 1 min, 5 min and 15 min Load Average figures.
"""
try:
fp = open(loadavgFile, '... |
Return cpu time utilization in seconds.
@return: Dictionary of stats.
def getCPUuse(self):
"""Return cpu time utilization in seconds.
@return: Dictionary of stats.
"""
hz = os.sysconf('SC_CLK_TCK')
info_dict = {}
try:
fp = o... |
Return stats for running and blocked processes, forks,
context switches and interrupts.
@return: Dictionary of stats.
def getProcessStats(self):
"""Return stats for running and blocked processes, forks,
context switches and interrupts.
@return: Dictionary of ... |
Return stats for memory utilization.
@return: Dictionary of stats.
def getMemoryUse(self):
"""Return stats for memory utilization.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(meminfoFile, 'r')
data = ... |
Return information on swap partition and / or files.
@return: Dictionary of stats.
def getSwapStats(self):
"""Return information on swap partition and / or files.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp ... |
Return stats for Virtual Memory Subsystem.
@return: Dictionary of stats.
def getVMstats(self):
"""Return stats for Virtual Memory Subsystem.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(vmstatFile, 'r')
... |
Connect to Memcached.
def _connect(self):
"""Connect to Memcached."""
if self._socketFile is not None:
if not os.path.exists(self._socketFile):
raise Exception("Socket file (%s) for Memcached Instance not found."
% self._socketFile)
tr... |
Send stat command to Memcached Server and return response lines.
@param cmd: Command string.
@return: Array of strings.
def _sendStatCmd(self, cmd):
"""Send stat command to Memcached Server and return response lines.
@param cmd: Command string.
@return: ... |
Parse stats output from memcached and return dictionary of stats-
@param lines: Array of lines of input text.
@param parse_slabs: Parse slab stats if True.
@return: Stats dictionary.
def _parseStats(self, lines, parse_slabs = False):
"""Parse stats output from ... |
Retrieve values for graphs.
def retrieveVals(self):
"""Retrieve values for graphs."""
if self._stats is None:
serverInfo = MemcachedInfo(self._host, self._port, self._socket_file)
stats = serverInfo.getStats()
else:
stats = self._stats
if stats is No... |
Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
... |
Returns correlation distance between a and b
def correlation(a, b):
"Returns correlation distance between a and b"
if isinstance(a, list):
a = np.array(a)
if isinstance(b, list):
b = np.array(b)
a = a.reshape(1, -1)
b = b.reshape(1, -1)
return cdist(a, b, 'correlation') |
Returns euclidean distance between a and b
def euclidean(a, b):
"Returns euclidean distance between a and b"
return np.linalg.norm(np.subtract(a, b)) |
Execute ps command with positional params args and return result as
list of lines.
@param *args: Positional params for ps command.
@return: List of output lines
def execProcCmd(self, *args):
"""Execute ps command with positional params args and return result as
l... |
Execute ps command with custom output format with columns from
fields and return result as a nested list.
The Standard Format Specifiers from ps man page must be used for the
fields parameter.
@param fields: List of fields included in the output.
... |
Execute ps command with custom output format with columns columns
from fields, select lines using the filters defined by kwargs and return
result as a nested list.
The Standard Format Specifiers from ps man page must be used for the
fields parameter.
@param fi... |
Execute ps command with custom output format with columns format with
columns from fields, and return result as a nested dictionary with
the key PID or SPID.
The Standard Format Specifiers from ps man page must be used for the
fields parameter.
@param fields:... |
Return process counts per status and priority.
@param **kwargs: Keyword variables are used for filtering the results
depending on the values of the columns. Each keyword
must correspond to a field name with an optional
suffix:... |
Retrieve values for graphs.
def retrieveVals(self):
"""Retrieve values for graphs."""
ntpinfo = NTPinfo()
stats = ntpinfo.getPeerStats()
if stats:
if self.hasGraph('ntp_peer_stratum'):
self.setGraphVal('ntp_peer_stratum', 'stratum',
... |
Main Block for Munin Plugins.
@param pluginClass: Child class of MuninPlugin that implements plugin.
@param argv: List of command line arguments to Munin Plugin.
@param env: Dictionary of environment variables passed to Munin Plugin.
@param debug: Print debugging messages if Tr... |
Truncate long graph and field labels.
@param label: Label text.
@param maxlen: Maximum field label length in characters.
No maximum field label length is enforced by default.
@param delim: Delimiter for field labels field labels longer than
... |
Private method for parsing through environment variables.
Parses for environment variables common to all Munin Plugins:
- MUNIN_STATEFILE
- MUNIN_CAP_DIRTY_CONFIG
- nested_graphs
@param env: Dictionary of environment variables.
(O... |
Private method for returning graph object with name graph_name.
@param graph_name: Graph Name
@param fail_noexist: If true throw exception if there is no graph with
name graph_name.
@return: Graph Object or None
def _getGraph(self, graph_name... |
Private method for returning subgraph object with name graph_name
and parent graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@param fail_noexist: If true throw exception if there is no subgraph
... |
Private method for generating Multigraph ID from graph name and
subgraph name.
@param graph_name: Graph Name.
@param subgraph_name: Subgraph Name.
@return: Multigraph ID.
def _getMultigraphID(self, graph_name, subgraph_name=None):
"""Private meth... |
Formats configuration directory from Munin Graph and returns
multi-line value entries for the plugin config cycle.
@param conf_dict: Configuration directory.
@return: Multi-line text.
def _formatConfig(self, conf_dict):
"""Formats configuration directory from Munin G... |
Formats value list from Munin Graph and returns multi-line value
entries for the plugin fetch cycle.
@param val_list: List of name-value pairs.
@return: Multi-line text.
def _formatVals(self, val_list):
"""Formats value list from Munin Graph and returns multi-line valu... |
Return value for environment variable or None.
@param name: Name of environment variable.
@param default: Default value if variable is undefined.
@param conv: Function for converting value to desired type.
@return: Value of environment variable.
def envGet(self, ... |
Parse the plugin environment variables to return list from variable
with name list_<name>. The value of the variable must be a comma
separated list of items.
@param name: Name of list.
(Also determines suffix for environment variable name.)
@par... |
Register filter for including, excluding attributes in graphs through
the use of include_<name> and exclude_<name> environment variables.
The value of the variables must be a comma separated list of items.
@param name: Name of filter.
(Also determines ... |
Check if a specific graph attribute is enabled or disabled through
the use of a filter based on include_<name> and exclude_<name>
environment variables.
@param name: Name of the Filter.
@param attr: Name of the Attribute.
@return: Return True if the attribute is en... |
Check graph flag for enabling / disabling attributes through
the use of <name> environment variable.
@param name: Name of flag.
(Also determines the environment variable name.)
@param default: Boolean (True or False). Default value for flag.
@return: ... |
Utility methos to save plugin state stored in stateObj to persistent
storage to permit access to previous state in subsequent plugin runs.
Any object that can be pickled and unpickled can be used to store the
plugin state.
@param stateObj: Object that stores plugin st... |
Utility method to restore plugin state from persistent storage to
permit access to previous plugin state.
@return: Object that stores plugin state.
def restoreState(self):
"""Utility method to restore plugin state from persistent storage to
permit access to previous plugin st... |
Utility method to associate Graph Object to Plugin.
This utility method is for use in constructor of child classes for
associating a MuninGraph instances to the plugin.
@param graph_name: Graph Name
@param graph: MuninGraph Instance
def appendGraph(self, graph_n... |
Utility method to associate Subgraph Instance to Root Graph Instance.
This utility method is for use in constructor of child classes for
associating a MuninGraph Subgraph instance with a Root Graph instance.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name... |
Utility method to set Value for Field in Graph.
The private method is for use in retrieveVals() method of child classes.
@param graph_name: Graph Name
@param field_name: Field Name.
@param val: Value for field.
def setGraphVal(self, graph_name, field_name, val):... |
Set Value for Field in Subgraph.
The private method is for use in retrieveVals() method of child
classes.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@param field_name: Field Name.
@param val: Value for field.
def setSubgraphV... |
Returns list of names of subgraphs for Root Graph with name parent_name.
@param parent_name: Name of Root Graph.
@return: List of subgraph names.
def getSubgraphList(self, parent_name):
"""Returns list of names of subgraphs for Root Graph with name parent_name.
... |
Return true if graph with name graph_name has field with
name field_name.
@param graph_name: Graph Name
@param field_name: Field Name.
@return: Boolean
def graphHasField(self, graph_name, field_name):
"""Return true if graph with name graph_name has field with
... |
Return true if subgraph with name graph_name with parent graph with
name parent_name has field with name field_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@param field_name: Field Name.
@return: Boolean
def subGraphHasField(se... |
Returns list of names of fields for graph with name graph_name.
@param graph_name: Graph Name
@return: List of field names for graph.
def getGraphFieldList(self, graph_name):
"""Returns list of names of fields for graph with name graph_name.
@param graph_name... |
Returns number of fields for graph with name graph_name.
@param graph_name: Graph Name
@return: Number of fields for graph.
def getGraphFieldCount(self, graph_name):
"""Returns number of fields for graph with name graph_name.
@param graph_name: Graph Name
... |
Returns list of names of fields for subgraph with name graph_name
and parent graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: List of field names for subgraph.
def getSubgraphFieldList(self, parent_name, grap... |
Returns number of fields for subgraph with name graph_name and parent
graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: Number of fields for subgraph.
def getSubgraphFieldCount(self, parent_name, graph_name):... |
Implements Munin Plugin Graph Configuration.
Prints out configuration for graphs.
Use as is. Not required to be overwritten in child classes. The plugin
will work correctly as long as the Munin Graph objects have been
populated.
def config(self):
"""Implements Munin P... |
Implements Munin Plugin Fetch Option.
Prints out measured values.
def fetch(self):
"""Implements Munin Plugin Fetch Option.
Prints out measured values.
"""
self.retrieveVals()
for parent_name in self._graphNames:
graph = self._graphDict[parent_name]
... |
Implements main entry point for plugin execution.
def run(self):
"""Implements main entry point for plugin execution."""
if len(self._argv) > 1 and len(self._argv[1]) > 0:
oper = self._argv[1]
else:
oper = 'fetch'
if oper == 'fetch':
ret = self.fetch(... |
Add field to Munin Graph
@param name: Field Name
@param label: Field Label
@param type: Stat Type:
'COUNTER' / 'ABSOLUTE' / 'DERIVE' / 'GAUGE'
@param draw: Graph Type:
'AREA' / 'LINE{1,2,3}'... |
Returns true if field with field_name exists.
@param name: Field Name
@return: Boolean
def hasField(self, name):
"""Returns true if field with field_name exists.
@param name: Field Name
@return: Boolean
"""
if self._autoFixNames... |
Returns dictionary of config entries for Munin Graph.
@return: Dictionary of config entries.
def getConfig(self):
"""Returns dictionary of config entries for Munin Graph.
@return: Dictionary of config entries.
"""
return {'graph': self._graphAttrDict,... |
Set value for field in graph.
@param name : Graph Name
@param value : Value for field.
def setVal(self, name, val):
"""Set value for field in graph.
@param name : Graph Name
@param value : Value for field.
"""
if self._autoFixNam... |
Returns value list for Munin Graph
@return: List of name-value pairs.
def getVals(self):
"""Returns value list for Munin Graph
@return: List of name-value pairs.
"""
return [(name, self._fieldValDict.get(name))
for name in self._fieldN... |
Query and parse Web Server Status Page.
@param extras: Include extra metrics, which can be computationally more
expensive.
def initStats(self, extras=None):
"""Query and parse Web Server Status Page.
@param extras: Include extra metrics, which can be co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.