1 # Copyright (c) 2018 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.
17 import multiprocessing
24 from os import walk, makedirs, environ
25 from os.path import join, isdir
26 from shutil import move, Error
27 from datetime import datetime
28 from pandas import Series
30 from errors import PresentationError
31 from jumpavg.BitCountingClassifier import BitCountingClassifier
35 """Calculate mean value from the items.
37 :param items: Mean value is calculated from these items.
43 return float(sum(items)) / len(items)
47 """Calculate stdev from the items.
49 :param items: Stdev is calculated from these items.
54 return Series.std(Series(items))
57 def relative_change(nr1, nr2):
58 """Compute relative change of two values.
60 :param nr1: The first number.
61 :param nr2: The second number.
64 :returns: Relative change of nr1.
68 return float(((nr2 - nr1) / nr1) * 100)
71 def get_files(path, extension=None, full_path=True):
72 """Generates the list of files to process.
74 :param path: Path to files.
75 :param extension: Extension of files to process. If it is the empty string,
76 all files will be processed.
77 :param full_path: If True, the files with full path are generated.
81 :returns: List of files to process.
86 for root, _, files in walk(path):
87 for filename in files:
89 if filename.endswith(extension):
91 file_list.append(join(root, filename))
93 file_list.append(filename)
95 file_list.append(join(root, filename))
100 def get_rst_title_char(level):
101 """Return character used for the given title level in rst files.
103 :param level: Level of the title.
105 :returns: Character used for the given title level in rst files.
108 chars = ('=', '-', '`', "'", '.', '~', '*', '+', '^')
109 if level < len(chars):
115 def execute_command(cmd):
116 """Execute the command in a subprocess and log the stdout and stderr.
118 :param cmd: Command to execute.
120 :returns: Return code of the executed command, stdout and stderr.
121 :rtype: tuple(int, str, str)
125 proc = subprocess.Popen(
127 stdout=subprocess.PIPE,
128 stderr=subprocess.PIPE,
132 stdout, stderr = proc.communicate()
139 if proc.returncode != 0:
140 logging.error(" Command execution failed.")
141 return proc.returncode, stdout, stderr
144 def get_last_successful_build_number(jenkins_url, job_name):
145 """Get the number of the last successful build of the given job.
147 :param jenkins_url: Jenkins URL.
148 :param job_name: Job name.
149 :type jenkins_url: str
151 :returns: The build number as a string.
155 url = "{}/{}/lastSuccessfulBuild/buildNumber".format(jenkins_url, job_name)
156 cmd = "wget -qO- {url}".format(url=url)
158 return execute_command(cmd)
161 def get_last_completed_build_number(jenkins_url, job_name):
162 """Get the number of the last completed build of the given job.
164 :param jenkins_url: Jenkins URL.
165 :param job_name: Job name.
166 :type jenkins_url: str
168 :returns: The build number as a string.
172 url = "{}/{}/lastCompletedBuild/buildNumber".format(jenkins_url, job_name)
173 cmd = "wget -qO- {url}".format(url=url)
175 return execute_command(cmd)
178 def get_build_timestamp(jenkins_url, job_name, build_nr):
179 """Get the timestamp of the build of the given job.
181 :param jenkins_url: Jenkins URL.
182 :param job_name: Job name.
183 :param build_nr: Build number.
184 :type jenkins_url: str
187 :returns: The timestamp.
188 :rtype: datetime.datetime
191 url = "{jenkins_url}/{job_name}/{build_nr}".format(jenkins_url=jenkins_url,
194 cmd = "wget -qO- {url}".format(url=url)
196 timestamp = execute_command(cmd)
198 return datetime.fromtimestamp(timestamp/1000)
201 def archive_input_data(spec):
202 """Archive the report.
204 :param spec: Specification read from the specification file.
205 :type spec: Specification
206 :raises PresentationError: If it is not possible to archive the input data.
209 logging.info(" Archiving the input data files ...")
211 extension = spec.input["file-format"]
212 data_files = get_files(spec.environment["paths"]["DIR[WORKING,DATA]"],
214 dst = spec.environment["paths"]["DIR[STATIC,ARCH]"]
215 logging.info(" Destination: {0}".format(dst))
221 for data_file in data_files:
222 logging.info(" Moving the file: {0} ...".format(data_file))
225 except (Error, OSError) as err:
226 raise PresentationError("Not possible to archive the input data.",
229 logging.info(" Done.")
232 def classify_anomalies(data):
233 """Process the data and return anomalies and trending values.
235 Gather data into groups with average as trend value.
236 Decorate values within groups to be normal,
237 the first value of changed average as a regression, or a progression.
239 :param data: Full data set with unavailable samples replaced by nan.
240 :type data: OrderedDict
241 :returns: Classification and trend values
242 :rtype: 2-tuple, list of strings and list of floats
244 # Nan mean something went wrong.
245 # Use 0.0 to cause that being reported as a severe regression.
246 bare_data = [0.0 if np.isnan(sample.avg) else sample
247 for _, sample in data.iteritems()]
248 # TODO: Put analogous iterator into jumpavg library.
249 groups = BitCountingClassifier().classify(bare_data)
250 groups.reverse() # Just to use .pop() for FIFO.
256 for _, sample in data.iteritems():
257 if np.isnan(sample.avg):
258 classification.append("outlier")
259 avgs.append(sample.avg)
261 if values_left < 1 or active_group is None:
263 while values_left < 1: # Ignore empty groups (should not happen).
264 active_group = groups.pop()
265 values_left = len(active_group.values)
266 avg = active_group.metadata.avg
267 classification.append(active_group.metadata.classification)
271 classification.append("normal")
274 return classification, avgs
277 def convert_csv_to_pretty_txt(csv_file, txt_file):
278 """Convert the given csv table to pretty text table.
280 :param csv_file: The path to the input csv file.
281 :param txt_file: The path to the output pretty text file.
287 with open(csv_file, 'rb') as csv_file:
288 csv_content = csv.reader(csv_file, delimiter=',', quotechar='"')
289 for row in csv_content:
290 if txt_table is None:
291 txt_table = prettytable.PrettyTable(row)
293 txt_table.add_row(row)
294 txt_table.align["Test case"] = "l"
296 with open(txt_file, "w") as txt_file:
297 txt_file.write(str(txt_table))
300 class Worker(multiprocessing.Process):
301 """Worker class used to process tasks in separate parallel processes.
304 def __init__(self, work_queue, data_queue, func):
307 :param work_queue: Queue with items to process.
308 :param data_queue: Shared memory between processes. Queue which keeps
309 the result data. This data is then read by the main process and used
310 in further processing.
311 :param func: Function which is executed by the worker.
312 :type work_queue: multiprocessing.JoinableQueue
313 :type data_queue: multiprocessing.Manager().Queue()
314 :type func: Callable object
316 super(Worker, self).__init__()
317 self._work_queue = work_queue
318 self._data_queue = data_queue
322 """Method representing the process's activity.
327 self.process(self._work_queue.get())
329 self._work_queue.task_done()
331 def process(self, item_to_process):
332 """Method executed by the runner.
334 :param item_to_process: Data to be processed by the function.
335 :type item_to_process: tuple
337 self._func(self.pid, self._data_queue, *item_to_process)