1 # Copyright (c) 2019 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 """General purpose utilities.
22 from os import walk, makedirs, environ
23 from os.path import join, isdir
24 from shutil import move, Error
25 from datetime import datetime
30 from pandas import Series
32 from resources.libraries.python import jumpavg
34 from pal_errors import PresentationError
38 """Calculate mean value from the items.
40 :param items: Mean value is calculated from these items.
46 return float(sum(items)) / len(items)
50 """Calculate stdev from the items.
52 :param items: Stdev is calculated from these items.
57 return Series.std(Series(items))
60 def relative_change(nr1, nr2):
61 """Compute relative change of two values.
63 :param nr1: The first number.
64 :param nr2: The second number.
67 :returns: Relative change of nr1.
71 return float(((nr2 - nr1) / nr1) * 100)
74 def relative_change_stdev(mean1, mean2, std1, std2):
75 """Compute relative standard deviation of change of two values.
77 The "1" values are the base for comparison.
78 Results are returned as percentage (and percentual points for stdev).
79 Linearized theory is used, so results are wrong for relatively large stdev.
81 :param mean1: Mean of the first number.
82 :param mean2: Mean of the second number.
83 :param std1: Standard deviation estimate of the first number.
84 :param std2: Standard deviation estimate of the second number.
89 :returns: Relative change and its stdev.
92 mean1, mean2 = float(mean1), float(mean2)
93 quotient = mean2 / mean1
96 std = quotient * math.sqrt(first * first + second * second)
97 return (quotient - 1) * 100, std * 100
100 def get_files(path, extension=None, full_path=True):
101 """Generates the list of files to process.
103 :param path: Path to files.
104 :param extension: Extension of files to process. If it is the empty string,
105 all files will be processed.
106 :param full_path: If True, the files with full path are generated.
109 :type full_path: bool
110 :returns: List of files to process.
115 for root, _, files in walk(path):
116 for filename in files:
118 if filename.endswith(extension):
120 file_list.append(join(root, filename))
122 file_list.append(filename)
124 file_list.append(join(root, filename))
129 def get_rst_title_char(level):
130 """Return character used for the given title level in rst files.
132 :param level: Level of the title.
134 :returns: Character used for the given title level in rst files.
137 chars = (u'=', u'-', u'`', u"'", u'.', u'~', u'*', u'+', u'^')
138 if level < len(chars):
143 def execute_command(cmd):
144 """Execute the command in a subprocess and log the stdout and stderr.
146 :param cmd: Command to execute.
148 :returns: Return code of the executed command, stdout and stderr.
149 :rtype: tuple(int, str, str)
153 proc = subprocess.Popen(
155 stdout=subprocess.PIPE,
156 stderr=subprocess.PIPE,
160 stdout, stderr = proc.communicate()
163 logging.info(stdout.decode())
165 logging.info(stderr.decode())
167 if proc.returncode != 0:
168 logging.error(u" Command execution failed.")
169 return proc.returncode, stdout.decode(), stderr.decode()
172 def get_last_successful_build_nr(jenkins_url, job_name):
173 """Get the number of the last successful build of the given job.
175 :param jenkins_url: Jenkins URL.
176 :param job_name: Job name.
177 :type jenkins_url: str
179 :returns: The build number as a string.
182 return execute_command(
183 f"wget -qO- {jenkins_url}/{job_name}/lastSuccessfulBuild/buildNumber"
187 def get_last_completed_build_number(jenkins_url, job_name):
188 """Get the number of the last completed build of the given job.
190 :param jenkins_url: Jenkins URL.
191 :param job_name: Job name.
192 :type jenkins_url: str
194 :returns: The build number as a string.
197 return execute_command(
198 f"wget -qO- {jenkins_url}/{job_name}/lastCompletedBuild/buildNumber"
202 def get_build_timestamp(jenkins_url, job_name, build_nr):
203 """Get the timestamp of the build of the given job.
205 :param jenkins_url: Jenkins URL.
206 :param job_name: Job name.
207 :param build_nr: Build number.
208 :type jenkins_url: str
211 :returns: The timestamp.
212 :rtype: datetime.datetime
214 timestamp = execute_command(
215 f"wget -qO- {jenkins_url}/{job_name}/{build_nr}"
217 return datetime.fromtimestamp(timestamp/1000)
220 def archive_input_data(spec):
221 """Archive the report.
223 :param spec: Specification read from the specification file.
224 :type spec: Specification
225 :raises PresentationError: If it is not possible to archive the input data.
228 logging.info(u" Archiving the input data files ...")
230 extension = spec.input[u"arch-file-format"]
232 for ext in extension:
233 data_files.extend(get_files(
234 spec.environment[u"paths"][u"DIR[WORKING,DATA]"], extension=ext))
235 dst = spec.environment[u"paths"][u"DIR[STATIC,ARCH]"]
236 logging.info(f" Destination: {dst}")
242 for data_file in data_files:
243 logging.info(f" Moving the file: {data_file} ...")
246 except (Error, OSError) as err:
247 raise PresentationError(
248 u"Not possible to archive the input data.",
252 logging.info(u" Done.")
255 def classify_anomalies(data):
256 """Process the data and return anomalies and trending values.
258 Gather data into groups with average as trend value.
259 Decorate values within groups to be normal,
260 the first value of changed average as a regression, or a progression.
262 :param data: Full data set with unavailable samples replaced by nan.
263 :type data: OrderedDict
264 :returns: Classification and trend values
265 :rtype: 2-tuple, list of strings and list of floats
267 # Nan means something went wrong.
268 # Use 0.0 to cause that being reported as a severe regression.
269 bare_data = [0.0 if np.isnan(sample) else sample
270 for sample in data.values()]
271 # TODO: Make BitCountingGroupList a subclass of list again?
272 group_list = jumpavg.classify(bare_data).group_list
273 group_list.reverse() # Just to use .pop() for FIFO.
279 for sample in data.values():
281 classification.append(u"outlier")
284 if values_left < 1 or active_group is None:
286 while values_left < 1: # Ignore empty groups (should not happen).
287 active_group = group_list.pop()
288 values_left = len(active_group.run_list)
289 avg = active_group.stats.avg
290 classification.append(active_group.comment)
294 classification.append(u"normal")
297 return classification, avgs
300 def convert_csv_to_pretty_txt(csv_file_name, txt_file_name):
301 """Convert the given csv table to pretty text table.
303 :param csv_file_name: The path to the input csv file.
304 :param txt_file_name: The path to the output pretty text file.
305 :type csv_file_name: str
306 :type txt_file_name: str
310 with open(csv_file_name, u"rt") as csv_file:
311 csv_content = csv.reader(csv_file, delimiter=u',', quotechar=u'"')
312 for row in csv_content:
313 if txt_table is None:
314 txt_table = prettytable.PrettyTable(row)
316 txt_table.add_row(row)
317 txt_table.align[u"Test case"] = u"l"
319 with open(txt_file_name, u"wt") as txt_file:
320 txt_file.write(str(txt_table))