INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return random sentences. | def sentences(quantity=2, as_list=False):
"""Return random sentences."""
result = [sntc.strip() for sntc in
random.sample(get_dictionary('lorem_ipsum'), quantity)]
if as_list:
return result
else:
return ' '.join(result) |
Return a random paragraph. | def paragraph(separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3):
"""Return a random paragraph."""
return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start,
wrap_end=wrap_end, html=html,
sentences_quantity=sen... |
Return random paragraphs. | def paragraphs(quantity=2, separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3, as_list=False):
"""Return random paragraphs."""
if html:
wrap_start = '<p>'
wrap_end = '</p>'
separator = '\n\n'
result = []
try:
for _ in xrange(0, ... |
Return a lowercased string with non alphabetic chars removed. | def _to_lower_alpha_only(s):
"""Return a lowercased string with non alphabetic chars removed.
White spaces are not to be removed."""
s = re.sub(r'\n', ' ', s.lower())
return re.sub(r'[^a-z\s]', '', s) |
Return random characters. | def characters(quantity=10):
"""Return random characters."""
line = map(_to_lower_alpha_only,
''.join(random.sample(get_dictionary('lorem_ipsum'), quantity)))
return ''.join(line)[:quantity] |
An aggregator for all above defined public methods. | def text(what="sentence", *args, **kwargs):
"""An aggregator for all above defined public methods."""
if what == "character":
return character(*args, **kwargs)
elif what == "characters":
return characters(*args, **kwargs)
elif what == "word":
return word(*args, **kwargs)
eli... |
Return a random user name. | def user_name(with_num=False):
"""Return a random user name.
Basically it's lowercased result of
:py:func:`~forgery_py.forgery.name.first_name()` with a number appended
if `with_num`.
"""
result = first_name()
if with_num:
result += str(random.randint(63, 94))
return result.low... |
Return a random domain name. | def domain_name():
"""Return a random domain name.
Lowercased result of :py:func:`~forgery_py.forgery.name.company_name()`
plus :py:func:`~top_level_domain()`.
"""
result = random.choice(get_dictionary('company_names')).strip()
result += '.' + top_level_domain()
return result.lower() |
Return random e - mail address in a hopefully imaginary domain. | def email_address(user=None):
"""Return random e-mail address in a hopefully imaginary domain.
If `user` is ``None`` :py:func:`~user_name()` will be used. Otherwise it
will be lowercased and will have spaces replaced with ``_``.
Domain name is created using :py:func:`~domain_name()`.
"""
if no... |
Return a random bank account number. | def account_number():
"""Return a random bank account number."""
account = [random.randint(1, 9) for _ in range(20)]
return "".join(map(str, account)) |
Return a random bank identification number. | def bik():
"""Return a random bank identification number."""
return '04' + \
''.join([str(random.randint(1, 9)) for _ in range(5)]) + \
str(random.randint(0, 49) + 50) |
Return a random taxation ID number for a company. | def legal_inn():
"""Return a random taxation ID number for a company."""
mask = [2, 4, 10, 3, 5, 9, 4, 6, 8]
inn = [random.randint(1, 9) for _ in range(10)]
weighted = [v * mask[i] for i, v in enumerate(inn[:-1])]
inn[9] = sum(weighted) % 11 % 10
return "".join(map(str, inn)) |
Return a random government registration ID for a company. | def legal_ogrn():
"""Return a random government registration ID for a company."""
ogrn = "".join(map(str, [random.randint(1, 9) for _ in range(12)]))
ogrn += str((int(ogrn) % 11 % 10))
return ogrn |
Return a random taxation ID number for a natural person. | def person_inn():
"""Return a random taxation ID number for a natural person."""
mask11 = [7, 2, 4, 10, 3, 5, 9, 4, 6, 8]
mask12 = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8]
inn = [random.randint(1, 9) for _ in range(12)]
# get the 11th digit of the INN
weighted11 = [v * mask11[i] for i, v in enumerate... |
Return SHA1 hexdigest of a password ( optionally salted with a string ). | def encrypt(password='password', salt=None):
"""
Return SHA1 hexdigest of a password (optionally salted with a string).
"""
if not salt:
salt = str(datetime.utcnow())
try:
# available for python 2.7.8 and python 3.4+
dk = hashlib.pbkdf2_hmac('sha1', password.encode(), sal... |
Return a random string for use as a password. | def password(at_least=6, at_most=12, lowercase=True,
uppercase=True, digits=True, spaces=False, punctuation=False):
"""Return a random string for use as a password."""
return text(at_least=at_least, at_most=at_most, lowercase=lowercase,
uppercase=uppercase, digits=digits, spaces=spa... |
Write your forwards methods here. | def forwards(self, orm):
"Write your forwards methods here."
# Note: Don't use "from appname.models import ModelName".
# Use orm.ModelName to refer to models in this application,
# and orm['appname.ModelName'] for models in other applications.
print("Updating: JednostkaAdministr... |
Write your forwards methods here. | def forwards(self, orm):
"Write your forwards methods here."
# Note: Don't use "from appname.models import ModelName".
# Use orm.ModelName to refer to models in this application,
# and orm['appname.ModelName'] for models in other applications.
LEN_TYPE = {
7: 'GMI',
... |
Converts an identifier from one case type to another. An identifier is an ASCII string consisting of letters digits and underscores not starting with a digit. The supported case types are camelCase PascalCase snake_case and CONSTANT_CASE identified as camel pascal snake and constant. The input identifier is given as a ... | def case(*, to, **kwargs):
"""Converts an identifier from one case type to another.
An identifier is an ASCII string consisting of letters, digits and underscores, not starting with a digit.
The supported case types are camelCase, PascalCase, snake_case, and CONSTANT_CASE,
identified as camel, pascal, s... |
Using a schema deserialize a stream of consecutive Avro values. | def read_stream(schema, stream, *, buffer_size=io.DEFAULT_BUFFER_SIZE):
"""Using a schema, deserialize a stream of consecutive Avro values.
:param str schema: json string representing the Avro schema
:param file-like stream: a buffered stream of binary input
:param int buffer_size: size of bytes to rea... |
Parse the user defined metric class information: param config_obj: ConfigParser object: param metric_classes: list of metric classes to be updated: return: | def parse_user_defined_metric_classes(config_obj, metric_classes):
"""
Parse the user defined metric class information
:param config_obj: ConfigParser object
:param metric_classes: list of metric classes to be updated
:return:
"""
user_defined_metric_list = config_obj.get('GLOBAL', 'user_defined_metrics')... |
Check if a given string is in the correct URL format or not | def is_valid_url(url):
"""
Check if a given string is in the correct URL format or not
:param str url:
:return: True or False
"""
regex = re.compile(r'^(?:http|ftp)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localho... |
Download a file pointed to by url to a temp file on local disk | def download_file(url):
"""
Download a file pointed to by url to a temp file on local disk
:param str url:
:return: local_file
"""
try:
(local_file, headers) = urllib.urlretrieve(url)
except:
sys.exit("ERROR: Problem downloading config file. Please check the URL (" + url + "). Exiting...")
retu... |
check the validity of metric_name in config ; the metric_name will be used for creation of sub - dir so only contains: alphabet digits. - and _: param str metric_name: metric_name: return: True if valid | def is_valid_metric_name(metric_name):
"""
check the validity of metric_name in config; the metric_name will be used for creation of sub-dir, so only contains: alphabet, digits , '.', '-' and '_'
:param str metric_name: metric_name
:return: True if valid
"""
reg = re.compile('^[a-zA-Z0-9\.\-\_]+$')
if reg... |
This method finds the time range which covers all the Run_Steps | def get_run_time_period(run_steps):
"""
This method finds the time range which covers all the Run_Steps
:param run_steps: list of Run_Step objects
:return: tuple of start and end timestamps
"""
init_ts_start = get_standardized_timestamp('now', None)
ts_start = init_ts_start
ts_end = '0'
for run_step ... |
Extract rule strings from a section: param config_obj: ConfigParser object: param section: Section name: return: the rule strings | def get_rule_strings(config_obj, section):
"""
Extract rule strings from a section
:param config_obj: ConfigParser object
:param section: Section name
:return: the rule strings
"""
rule_strings = {}
kwargs = dict(config_obj.items(section))
for key in kwargs.keys():
if key.endswith('.sla'):
r... |
Helper function to parse diff config file which contains SLA rules for diff comparisons | def extract_diff_sla_from_config_file(obj, options_file):
"""
Helper function to parse diff config file, which contains SLA rules for diff comparisons
"""
rule_strings = {}
config_obj = ConfigParser.ConfigParser()
config_obj.optionxform = str
config_obj.read(options_file)
for section in config_obj.secti... |
Parse basic options from metric sections of the config: param config_obj: ConfigParser object: param section: Section name: return: all the parsed options | def parse_basic_metric_options(config_obj, section):
"""
Parse basic options from metric sections of the config
:param config_obj: ConfigParser object
:param section: Section name
:return: all the parsed options
"""
infile = {}
aggr_hosts = None
aggr_metrics = None
ts_start = None
ts_end = None
... |
Parse a metric section and create a Metric object: param config_obj: ConfigParser object: param section: Section name: param metric_classes: List of valid metric types: param metrics: List of all regular metric objects ( used by aggregate metric ): param aggregate_metric_classes: List of all valid aggregate metric type... | def parse_metric_section(config_obj, section, metric_classes, metrics, aggregate_metric_classes, outdir_default, resource_path):
"""
Parse a metric section and create a Metric object
:param config_obj: ConfigParser object
:param section: Section name
:param metric_classes: List of valid metric types
:param ... |
Parse GLOBAL section in the config to return global settings: param config_obj: ConfigParser object: param section: Section name: return: ts_start and ts_end time | def parse_global_section(config_obj, section):
"""
Parse GLOBAL section in the config to return global settings
:param config_obj: ConfigParser object
:param section: Section name
:return: ts_start and ts_end time
"""
ts_start = None
ts_end = None
if config_obj.has_option(section, 'ts_start'):
ts_... |
Parse a RUN - STEP section in the config to return a Run_Step object: param config_obj: ConfigParser objection: param section: Section name: return: an initialized Run_Step object | def parse_run_step_section(config_obj, section):
"""
Parse a RUN-STEP section in the config to return a Run_Step object
:param config_obj: ConfigParser objection
:param section: Section name
:return: an initialized Run_Step object
"""
kill_after_seconds = None
try:
run_cmd = config_obj.get(section, ... |
Parse the GRAPH section of the config to extract useful values: param config_obj: ConfigParser object: param section: Section name: param outdir_default: Default output directory passed in args: param indir_default: Default input directory passed in args: return: List of options extracted from the GRAPH section | def parse_graph_section(config_obj, section, outdir_default, indir_default):
"""
Parse the GRAPH section of the config to extract useful values
:param config_obj: ConfigParser object
:param section: Section name
:param outdir_default: Default output directory passed in args
:param indir_default: Default inp... |
parse the [ REPORT ] section of a config file to extract various reporting options to be passed to the Report object: param: config_obj: configparser object for the config file passed in to naarad: param: section: name of the section. REPORT should be passed in here: return: report_kwargs: dictionary of Reporting optio... | def parse_report_section(config_obj, section):
"""
parse the [REPORT] section of a config file to extract various reporting options to be passed to the Report object
:param: config_obj : configparser object for the config file passed in to naarad
:param: section: name of the section. 'REPORT' should be passed i... |
Calculate statistics for given data. | def calculate_stats(data_list, stats_to_calculate=['mean', 'std'], percentiles_to_calculate=[]):
"""
Calculate statistics for given data.
:param list data_list: List of floats
:param list stats_to_calculate: List of strings with statistics to calculate. Supported stats are defined in constant stats_to_numpy_me... |
Check if the specifed file exists and is not empty | def is_valid_file(filename):
"""
Check if the specifed file exists and is not empty
:param filename: full path to the file that needs to be checked
:return: Status, Message
"""
if os.path.exists(filename):
if not os.path.getsize(filename):
logger.warning('%s : file is empty.', filename)
ret... |
Given an input timestamp string determine what format is it likely in. | def detect_timestamp_format(timestamp):
"""
Given an input timestamp string, determine what format is it likely in.
:param string timestamp: the timestamp string for which we need to determine format
:return: best guess timestamp format
"""
time_formats = {
'epoch': re.compile(r'^[0-9]{10}$'),
... |
Given a timestamp string return a time stamp in the epoch ms format. If no date is present in timestamp then today s date will be added as a prefix before conversion to epoch ms | def get_standardized_timestamp(timestamp, ts_format):
"""
Given a timestamp string, return a time stamp in the epoch ms format. If no date is present in
timestamp then today's date will be added as a prefix before conversion to epoch ms
"""
if not timestamp:
return None
if timestamp == 'now':
timest... |
Extract SLAs from a set of rules | def set_sla(obj, metric, sub_metric, rules):
"""
Extract SLAs from a set of rules
"""
if not hasattr(obj, 'sla_map'):
return False
rules_list = rules.split()
for rule in rules_list:
if '<' in rule:
stat, threshold = rule.split('<')
sla = SLA(metric, sub_metric, stat, threshold, 'lt')
... |
Check if all SLAs pass: return: 0 ( if all SLAs pass ) or the number of SLAs failures | def check_slas(metric):
"""
Check if all SLAs pass
:return: 0 (if all SLAs pass) or the number of SLAs failures
"""
if not hasattr(metric, 'sla_map'):
return
for metric_label in metric.sla_map.keys():
for sub_metric in metric.sla_map[metric_label].keys():
for stat_name in metric.sla_map[metric... |
Initialize the naarad logger.: param: logger: logger object to initialize: param: log_file: log file name: param: log_level: log level ( debug info warn error ) | def init_logging(logger, log_file, log_level):
"""
Initialize the naarad logger.
:param: logger: logger object to initialize
:param: log_file: log file name
:param: log_level: log level (debug, info, warn, error)
"""
with open(log_file, 'w'):
pass
numeric_level = getattr(logging, log_level.upper(), ... |
Initialize list of valid arguments accepted by Naarad CLI: return: arg_parser: argeparse. ArgumentParser object initialized with naarad CLI parameters | def get_argument_parser():
"""
Initialize list of valid arguments accepted by Naarad CLI
:return: arg_parser: argeparse.ArgumentParser object initialized with naarad CLI parameters
"""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-c', '--config', help="file with specifications for each me... |
Return a dictionary of variables specified at CLI: param: args: Command Line Arguments namespace | def get_variables(args):
"""
Return a dictionary of variables specified at CLI
:param: args: Command Line Arguments namespace
"""
variables_dict = {}
if args.variables:
for var in args.variables:
words = var.split('=')
variables_dict[words[0]] = words[1]
return variables_dict |
Validate that the necessary argument for normal or diff analysis are specified.: param: args: Command line arguments namespace | def validate_arguments(args):
"""
Validate that the necessary argument for normal or diff analysis are specified.
:param: args: Command line arguments namespace
"""
if args.diff:
if not args.output_dir:
logger.error('No Output location specified')
print_usage()
sys.exit(0)
# elif not (... |
Auto discover metric types from the files that exist in input_directory and return a list of metrics: param: input_directory: The location to scan for log files: param: output_directory: The location for the report | def discover_by_name(input_directory, output_directory):
"""
Auto discover metric types from the files that exist in input_directory and return a list of metrics
:param: input_directory: The location to scan for log files
:param: output_directory: The location for the report
"""
metric_list = []
log_files... |
Initialize appropriate metric based on type of metric.: param: section: config section name or auto discovered metric type: param: infile_list: list of input log files for the metric: param: hostname: hostname associated with the logs origin: param: output_directory: report location: param: resource_path: resource path... | def initialize_metric(section, infile_list, hostname, aggr_metrics, output_directory, resource_path, label, ts_start, ts_end, rule_strings,
important_sub_metrics, anomaly_detection_metrics, other_options):
"""
Initialize appropriate metric based on type of metric.
:param: section: config sec... |
Initialize aggregate metric: param: section: config section name: param: aggr_hosts: list of hostnames to aggregate: param: aggr_metrics: list of metrics to aggregate: param: metrics: list of metric objects associated with the current naarad analysis: param: outdir_default: report location: param: resource_path: resour... | def initialize_aggregate_metric(section, aggr_hosts, aggr_metrics, metrics, outdir_default, resource_path, label, ts_start, ts_end, rule_strings,
important_sub_metrics, anomaly_detection_metrics, other_options):
"""
Initialize aggregate metric
:param: section: config section name
... |
Single metric graphing function | def graph_csv(output_directory, resource_path, csv_file, plot_title, output_filename, y_label=None, precision=None, graph_height="600", graph_width="1500"):
""" Single metric graphing function """
if not os.path.getsize(csv_file):
return False, ""
y_label = y_label or plot_title
div_id = str(random.random()... |
Organize and store the count of data from the log line into the metric store by metric type transaction timestamp | def aggregate_count_over_time(self, metric_store, line_data, transaction_list, aggregate_timestamp):
"""
Organize and store the count of data from the log line into the metric store by metric type, transaction, timestamp
:param dict metric_store: The metric store used to store all the parsed jmeter log dat... |
Organize and store the data from the log line into the metric store by metric type transaction timestamp | def aggregate_values_over_time(self, metric_store, line_data, transaction_list, metric_list, aggregate_timestamp):
"""
Organize and store the data from the log line into the metric store by metric type, transaction, timestamp
:param dict metric_store: The metric store used to store all the parsed jmeter lo... |
Create the time series for the various metrics averaged over the aggregation period being used for plots | def average_values_for_plot(self, metric_store, data, averaging_factor):
"""
Create the time series for the various metrics, averaged over the aggregation period being used for plots
:param dict metric_store: The metric store used to store all the parsed jmeter log data
:param dict data: Dict with all ... |
Calculate key statistics for given data and store in the class variables calculated_stats and calculated_percentiles calculated_stats: mean std median min max calculated_percentiles: range ( 5 101 5 ) 99: param dict metric_store: The metric store used to store all the parsed jmeter log data: return: none | def calculate_key_stats(self, metric_store):
"""
Calculate key statistics for given data and store in the class variables calculated_stats and calculated_percentiles
calculated_stats:
'mean', 'std', 'median', 'min', 'max'
calculated_percentiles:
range(5,101,5), 99
:param dict metric_stor... |
Parse the Jmeter file and calculate key stats | def parse(self):
"""
Parse the Jmeter file and calculate key stats
:return: status of the metric parse
"""
file_status = True
for infile in self.infile_list:
file_status = file_status and naarad.utils.is_valid_file(infile)
if not file_status:
return False
status = self.... |
Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics | def parse_xml_jtl(self, granularity):
"""
Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics
:param string granularity: The time period over which to aggregate and average the raw data. Valid values are 'hour', 'minute' or 'second'
:return: status... |
Take the ( col value ) in values append value into col in self. data [] | def put_values_into_data(self, values):
"""
Take the (col, value) in 'values', append value into 'col' in self.data[]
"""
for col, value in values.items():
if col in self.column_csv_map:
out_csv = self.column_csv_map[col]
else:
out_csv = self.get_csv(col) # column_csv_map[]... |
Process the line starting with top Example log: top - 00: 00: 02 up 32 days 7: 08 19 users load average: 0. 00 0. 00 0. 00 | def process_top_line(self, words):
"""
Process the line starting with "top"
Example log: top - 00:00:02 up 32 days, 7:08, 19 users, load average: 0.00, 0.00, 0.00
"""
self.ts_time = words[2]
self.ts = self.ts_date + ' ' + self.ts_time
self.ts = ts = naarad.utils.get_standardized_timestam... |
Process the line starting with Tasks: Example log: Tasks: 446 total 1 running 442 sleeping 2 stopped 1 zombie | def process_tasks_line(self, words):
"""
Process the line starting with "Tasks:"
Example log: Tasks: 446 total, 1 running, 442 sleeping, 2 stopped, 1 zombie
"""
words = words[1:]
length = len(words) / 2 # The number of pairs
values = {}
for offset in range(length):
k = wor... |
Process the line starting with Cpu ( s ): Example log: Cpu ( s ): 1. 3%us 0. 5%sy 0. 0%ni 98. 2%id 0. 0%wa 0. 0%hi 0. 0%si 0. 0%st | def process_cpu_line(self, words):
"""
Process the line starting with "Cpu(s):"
Example log: Cpu(s): 1.3%us, 0.5%sy, 0.0%ni, 98.2%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
"""
values = {}
for word in words[1:]:
val, key = word.split('%')
values['cpu_' + key.strip(',')] = val
sel... |
Given a size such as 2333M return the converted value in G | def convert_to_G(self, word):
"""
Given a size such as '2333M', return the converted value in G
"""
value = 0.0
if word[-1] == 'G' or word[-1] == 'g':
value = float(word[:-1])
elif word[-1] == 'M' or word[-1] == 'm':
value = float(word[:-1]) / 1000.0
elif word[-1] == 'K' or word[... |
Process the line starting with Swap: Example log: Swap: 63. 998G total 0. 000k used 63. 998G free 11. 324G cached For each value needs to convert to G ( needs to handle cases of K M ) | def process_swap_line(self, words):
"""
Process the line starting with "Swap:"
Example log: Swap: 63.998G total, 0.000k used, 63.998G free, 11.324G cached
For each value, needs to convert to 'G' (needs to handle cases of K, M)
"""
words = words[1:]
length = len(words) / 2 # The num... |
process the individual lines like this: #PID USER PR NI VIRT RES SHR S %CPU %MEM TIME + COMMAND 29303 root 20 0 35300 2580 1664 R 3. 9 0. 0 0: 00. 02 top 11 root RT 0 0 0 0 S 1. 9 0. 0 0: 18. 87 migration/ 2 3702 root 20 0 34884 4192 1692 S 1. 9 0. 0 31: 40. 47 cf - serverd It does not record all processes due to memor... | def process_individual_command(self, words):
"""
process the individual lines like this:
#PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
29303 root 20 0 35300 2580 1664 R 3.9 0.0 0:00.02 top
11 root RT 0 0 0 0 S 1.9 0.0 0:18.87 migration/2
3702... |
Parse the top output file Return status of the metric parse | def parse(self):
"""
Parse the top output file
Return status of the metric parse
The raw log file is like the following:
2014-06-23
top - 00:00:02 up 18 days, 7:08, 19 users, load average: 0.05, 0.03, 0.00
Tasks: 447 total, 1 running, 443 sleeping, 2 stopped, 1 zombie
Cpu(s): 1... |
Base function which takes a single url download it to outdir/ outfile: param str url: a full/ absolute url e. g. http:// www. cnn. com/ log. zip: param str outdir: the absolute local directory. e. g./ home/ user1/ tmp/: param str outfile: ( optional ) filename stored in local directory. If outfile is not given extract ... | def handle_single_url(url, outdir, outfile=None):
"""
Base function which takes a single url, download it to outdir/outfile
:param str url: a full/absolute url, e.g. http://www.cnn.com/log.zip
:param str outdir: the absolute local directory. e.g. /home/user1/tmp/
:param str outfile: (optional) filename stored... |
Read response of specified url into memory and return to caller. No persistence to disk.: return: response content if accessing the URL succeeds False otherwise | def stream_url(url):
"""
Read response of specified url into memory and return to caller. No persistence to disk.
:return: response content if accessing the URL succeeds, False otherwise
"""
try:
response = urllib2.urlopen(url)
response_content = response.read()
return response_content
except (u... |
get a list of urls from a seeding url return a list of urls | def get_urls_from_seed(url):
"""
get a list of urls from a seeding url, return a list of urls
:param str url: a full/absolute url, e.g. http://www.cnn.com/logs/
:return: a list of full/absolute urls.
"""
if not url or type(url) != str or not naarad.utils.is_valid_url(url):
logger.error("get_urls_from_... |
Downloads a http ( s ) url to a local file: param str inputs: the absolute url: param str outdir: Required. the local directory to put the downloadedfiles.: param str outfile:// Optional. If this is given the downloaded url will be renated to outfile ; If this is not given then the local file will be the original one a... | def download_url_single(inputs, outdir, outfile=None):
"""
Downloads a http(s) url to a local file
:param str inputs: the absolute url
:param str outdir: Required. the local directory to put the downloadedfiles.
:param str outfile: // Optional. If this is given, the downloaded url will be renated to outfile;... |
Downloads http ( s ) urls to a local files: param str inputs: Required the seed url: param str outdir: Required. the local directory to put the downloadedfiles.: param str regex: Optional a regex string. If not given then all urls will be valid: return: A list of local full path names ( downloaded from inputs ) | def download_url_regex(inputs, outdir, regex=".*"):
"""
Downloads http(s) urls to a local files
:param str inputs: Required, the seed url
:param str outdir: Required. the local directory to put the downloadedfiles.
:param str regex: Optional, a regex string. If not given, then all urls will be valid
:return... |
Read data from a csv file into a dictionary.: param str csv_name: path to a csv file.: return dict: a dictionary represents the data in file. | def read_csv(csv_name):
"""
Read data from a csv file into a dictionary.
:param str csv_name: path to a csv file.
:return dict: a dictionary represents the data in file.
"""
data = {}
if not isinstance(csv_name, (str, unicode)):
raise exceptions.InvalidDataFormat('luminol.utils: csv_name has to be a s... |
Run the command infer time period to be used in metric analysis phase.: return: None | def run(self):
"""
Run the command, infer time period to be used in metric analysis phase.
:return: None
"""
cmd_args = shlex.split(self.run_cmd)
logger.info('Local command RUN-STEP starting with rank %d', self.run_rank)
logger.info('Running subprocess command with following args: ' + str(cm... |
If run_step needs to be killed this method will be called: return: None | def kill(self):
"""
If run_step needs to be killed, this method will be called
:return: None
"""
try:
logger.info('Trying to terminating run_step...')
self.process.terminate()
time_waited_seconds = 0
while self.process.poll() is None and time_waited_seconds < CONSTANTS.SECOND... |
Copy local js/ css includes from naarad resources to the report/ resources directory: return: None | def copy_local_includes(self):
"""
Copy local js/css includes from naarad resources to the report/resources directory
:return: None
"""
resource_folder = self.get_resources_location()
for stylesheet in self.stylesheet_includes:
if ('http' not in stylesheet) and naarad.utils.is_valid_file(o... |
Create the client charting page for the diff report with time series data from the two diffed reports.: return: generated html to be written to disk | def generate_client_charting_page(self, data_sources):
"""
Create the client charting page for the diff report, with time series data from the two diffed reports.
:return: generated html to be written to disk
"""
if not os.path.exists(self.resource_directory):
os.makedirs(self.resource_directo... |
Generate the summary diff report html from template: return: generated html to be written to disk | def generate_diff_html(self):
"""
Generate the summary diff report html from template
:return: generated html to be written to disk
"""
if not os.path.exists(self.resource_directory):
os.makedirs(self.resource_directory)
self.copy_local_includes()
div_html = ''
for plot_div in sort... |
Determine what summary stats time series and CDF csv exist for the reports that need to be diffed.: return: boolean: return whether the summary stats/ time series/ CDF csv summary was successfully located | def discover(self, metafile):
"""
Determine what summary stats, time series, and CDF csv exist for the reports that need to be diffed.
:return: boolean: return whether the summary stats / time series / CDF csv summary was successfully located
"""
for report in self.reports:
if report.remote_lo... |
Identify what time series exist in both the diffed reports and download them to the diff report resources directory: return: True/ False: return status of whether the download of time series resources succeeded. | def collect_datasources(self):
"""
Identify what time series exist in both the diffed reports and download them to the diff report resources directory
:return: True/False : return status of whether the download of time series resources succeeded.
"""
report_count = 0
if self.status != 'OK':
... |
Generate CDF diff plots of the submetrics | def plot_diff(self, graphing_library='matplotlib'):
"""
Generate CDF diff plots of the submetrics
"""
diff_datasource = sorted(set(self.reports[0].datasource) & set(self.reports[1].datasource))
graphed = False
for submetric in diff_datasource:
baseline_csv = naarad.utils.get_default_csv(se... |
Check whether the SLA has passed or failed | def check_sla(self, sla, diff_metric):
"""
Check whether the SLA has passed or failed
"""
try:
if sla.display is '%':
diff_val = float(diff_metric['percent_diff'])
else:
diff_val = float(diff_metric['absolute_diff'])
except ValueError:
return False
if not (sla.c... |
Generate a diff report from the reports specified.: return: True/ False: return status of whether the diff report generation succeeded. | def generate(self):
"""
Generate a diff report from the reports specified.
:return: True/False : return status of whether the diff report generation succeeded.
"""
if (self.discover(CONSTANTS.STATS_CSV_LIST_FILE) and self.discover(CONSTANTS.PLOTS_CSV_LIST_FILE) and self.discover(CONSTANTS.CDF_PLOTS_... |
Return a timestamp from the raw epoch time based on the granularity preferences passed in. | def get_aggregation_timestamp(self, timestamp, granularity='second'):
"""
Return a timestamp from the raw epoch time based on the granularity preferences passed in.
:param string timestamp: timestamp from the log line
:param string granularity: aggregation granularity used for plots.
:return: strin... |
Organize and store the count of data from the log line into the metric store by columnm group name timestamp | def aggregate_count_over_time(self, metric_store, groupby_name, aggregate_timestamp):
"""
Organize and store the count of data from the log line into the metric store by columnm, group name, timestamp
:param dict metric_store: The metric store used to store all the parsed the log data
:param string gro... |
Organize and store the data from the log line into the metric store by metric type transaction timestamp | def aggregate_values_over_time(self, metric_store, data, groupby_name, column_name, aggregate_timestamp):
"""
Organize and store the data from the log line into the metric store by metric type, transaction, timestamp
:param dict metric_store: The metric store used to store all the parsed log data
:para... |
Create the time series for the various metrics averaged over the aggregation period being used for plots | def average_values_for_plot(self, metric_store, data, averaging_factor):
"""
Create the time series for the various metrics, averaged over the aggregation period being used for plots
:param dict metric_store: The metric store used to store all the parsed log data
:param dict data: Dict with all the met... |
Calculate stats such as percentile and mean | def calc_key_stats(self, metric_store):
"""
Calculate stats such as percentile and mean
:param dict metric_store: The metric store used to store all the parsed log data
:return: None
"""
stats_to_calculate = ['mean', 'std', 'min', 'max'] # TODO: get input from user
percentiles_to_calculate... |
Calculate stats with different function depending on the metric type: Data is recorded in memory for base metric type and use calculate_base_metric_stats () Data is recorded in CSV file for other metric types and use calculate_other_metric_stats () | def calculate_stats(self):
"""
Calculate stats with different function depending on the metric type:
Data is recorded in memory for base metric type, and use calculate_base_metric_stats()
Data is recorded in CSV file for other metric types, and use calculate_other_metric_stats()
"""
metric_type... |
plot timeseries for sub - metrics | def plot_timeseries(self, graphing_library='matplotlib'):
"""
plot timeseries for sub-metrics
"""
if self.groupby:
plot_data = {}
# plot time series data for submetrics
for out_csv in sorted(self.csv_files, reverse=True):
csv_filename = os.path.basename(out_csv)
transac... |
check whether the given sub metric is in important_sub_metrics list | def check_important_sub_metrics(self, sub_metric):
"""
check whether the given sub metric is in important_sub_metrics list
"""
if not self.important_sub_metrics:
return False
if sub_metric in self.important_sub_metrics:
return True
items = sub_metric.split('.')
if items[-1] in se... |
plot CDF for important sub - metrics | def plot_cdf(self, graphing_library='matplotlib'):
"""
plot CDF for important sub-metrics
"""
graphed = False
for percentile_csv in self.percentiles_files:
csv_filename = os.path.basename(percentile_csv)
# The last element is .csv, don't need that in the name of the chart
column = ... |
graph generates two types of graphs time: generate a time - series plot for all submetrics ( the x - axis is a time series ) cdf: generate a CDF plot for important submetrics ( the x - axis shows percentiles ) | def graph(self, graphing_library='matplotlib'):
"""
graph generates two types of graphs
'time': generate a time-series plot for all submetrics (the x-axis is a time series)
'cdf': generate a CDF plot for important submetrics (the x-axis shows percentiles)
"""
logger.info('Using graphing_library ... |
Detect anomalies in the timeseries data for the submetrics specified in the config file. Identified anomalies are stored in self. anomalies as well as written to. anomalies. csv file to be used by the client charting page. Anomaly detection uses the luminol library ( http:// pypi. python. org/ pypi/ luminol ) | def detect_anomaly(self):
"""
Detect anomalies in the timeseries data for the submetrics specified in the config file. Identified anomalies are
stored in self.anomalies as well as written to .anomalies.csv file to be used by the client charting page. Anomaly
detection uses the luminol library (http://py... |
: param fields: a list which contains either 0 1 or 2 values: return: a tuple with default values of ; | def _get_tuple(self, fields):
"""
:param fields: a list which contains either 0,1,or 2 values
:return: a tuple with default values of '';
"""
v1 = ''
v2 = ''
if len(fields) > 0:
v1 = fields[0]
if len(fields) > 1:
v2 = fields[1]
return v1, v2 |
Given user input of interested connections it will extract the info and output a list of tuples. - input can be multiple values separated by space ; - either host or port is optional - it may be just one end - e. g. host1< - > host2 host3< - > host1: port1< - > host2: return: None | def _extract_input_connections(self):
"""
Given user input of interested connections, it will extract the info and output a list of tuples.
- input can be multiple values, separated by space;
- either host or port is optional
- it may be just one end,
- e.g., "host1<->host2 host3<-> host1:port1... |
Given user input of interested processes it will extract the info and output a list of tuples. - input can be multiple values separated by space ; - either pid or process_name is optional - e. g. 10001/ python 10002/ java cpp: return: None | def _extract_input_processes(self):
"""
Given user input of interested processes, it will extract the info and output a list of tuples.
- input can be multiple values, separated by space;
- either pid or process_name is optional
- e.g., "10001/python 10002/java cpp"
:return: None
"""
for... |
Determine whether user - specified ( host port ) matches current ( cur_host cur_port ): param host port: The user input of ( host port ): param cur_host cur_port: The current connection: return: True or Not | def _match_host_port(self, host, port, cur_host, cur_port):
"""
Determine whether user-specified (host,port) matches current (cur_host, cur_port)
:param host,port: The user input of (host,port)
:param cur_host, cur_port: The current connection
:return: True or Not
"""
# if host is '', true; ... |
Determine whether user - specified pid/ processes contain this process: param pid: The user input of pid: param name: The user input of process name: param process: current process info: return: True or Not ; ( if both pid/ process are given then both of them need to match ) | def _match_processes(self, pid, name, cur_process):
"""
Determine whether user-specified "pid/processes" contain this process
:param pid: The user input of pid
:param name: The user input of process name
:param process: current process info
:return: True or Not; (if both pid/process are given, t... |
Check whether the connection is of interest or not: param local_end: Local connection end point e. g. host1: port1: param remote_end: Remote connection end point e. g. host2: port2: param process: Current connection s process info e. g. 1234/ firefox: return: a tuple of ( local_end remote_end True/ False ) ; e. g. ( ho... | def _check_connection(self, local_end, remote_end, process):
"""
Check whether the connection is of interest or not
:param local_end: Local connection end point, e.g., 'host1:port1'
:param remote_end: Remote connection end point, e.g., 'host2:port2'
:param process: Current connection 's process info... |
Append the data point to the dictionary of data: param data: The dictionary containing all data: param col: The sub - metric name e. g. host1_port1. host2_port2. SendQ: param value: integer: param ts: timestamp: return: None | def _add_data_line(self, data, col, value, ts):
"""
Append the data point to the dictionary of "data"
:param data: The dictionary containing all data
:param col: The sub-metric name e.g. 'host1_port1.host2_port2.SendQ'
:param value: integer
:param ts: timestamp
:return: None
"""
if c... |
Parse the netstat output file: return: status of the metric parse | def parse(self):
"""
Parse the netstat output file
:return: status of the metric parse
"""
# sample netstat output: 2014-04-02 15:44:02.86612 tcp 9600 0 host1.localdomain.com.:21567 remote.remotedomain.com:51168 ESTABLISH pid/process
data = {} # stores the data of each sub-metric
f... |
Returns the CSV file related to the given metric. The metric is determined by the cpu and device. The cpu is the CPU as in the interrupts file for example CPU12. The metric is a combination of the CPU and device. The device consists of IRQ # the irq device ASCII name. | def get_csv(self, cpu, device=None):
"""
Returns the CSV file related to the given metric. The metric is determined by the cpu and device.
The cpu is the CPU as in the interrupts file for example CPU12.
The metric is a combination of the CPU and device. The device consists of IRQ #, the irq device ASCII... |
Parses the file and tries to find the header line. The header line has format: | def find_header(self, infile):
"""
Parses the file and tries to find the header line. The header line has format:
2014-10-29 00:28:42.15161 CPU0 CPU1 CPU2 CPU3 ...
So should always have CPU# for each core. This function verifies a good header and
returns the list of CPUs that exist... |
Processes the files for each IRQ and each CPU in terms of the differences. Also produces accumulated interrupt count differences for each set of Ethernet IRQs. Generally Ethernet has 8 TxRx IRQs thus all are combined so that one can see the overall interrupts being generated by the NIC. | def parse(self):
"""
Processes the files for each IRQ and each CPU in terms of the differences.
Also produces accumulated interrupt count differences for each set of Ethernet IRQs.
Generally Ethernet has 8 TxRx IRQs thus all are combined so that one can see the overall interrupts being generated by the ... |
Parse the vmstat file: return: status of the metric parse | def parse(self):
"""
Parse the vmstat file
:return: status of the metric parse
"""
file_status = True
for input_file in self.infile_list:
file_status = file_status and naarad.utils.is_valid_file(input_file)
if not file_status:
return False
status = True
data = {} # s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.