CSIT-1504: Soak tests - box plots
[csit.git] / resources / tools / presentation / utils.py
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:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
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.
13
14 """General purpose utilities.
15 """
16
17 import multiprocessing
18 import subprocess
19 import numpy as np
20 import logging
21 import csv
22 import prettytable
23
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
29
30 from errors import PresentationError
31 from jumpavg.BitCountingClassifier import BitCountingClassifier
32
33
34 def mean(items):
35     """Calculate mean value from the items.
36
37     :param items: Mean value is calculated from these items.
38     :type items: list
39     :returns: MEan value.
40     :rtype: float
41     """
42
43     return float(sum(items)) / len(items)
44
45
46 def stdev(items):
47     """Calculate stdev from the items.
48
49     :param items: Stdev is calculated from these items.
50     :type items: list
51     :returns: Stdev.
52     :rtype: float
53     """
54     return Series.std(Series(items))
55
56
57 def relative_change(nr1, nr2):
58     """Compute relative change of two values.
59
60     :param nr1: The first number.
61     :param nr2: The second number.
62     :type nr1: float
63     :type nr2: float
64     :returns: Relative change of nr1.
65     :rtype: float
66     """
67
68     return float(((nr2 - nr1) / nr1) * 100)
69
70
71 def get_files(path, extension=None, full_path=True):
72     """Generates the list of files to process.
73
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.
78     :type path: str
79     :type extension: str
80     :type full_path: bool
81     :returns: List of files to process.
82     :rtype: list
83     """
84
85     file_list = list()
86     for root, _, files in walk(path):
87         for filename in files:
88             if extension:
89                 if filename.endswith(extension):
90                     if full_path:
91                         file_list.append(join(root, filename))
92                     else:
93                         file_list.append(filename)
94             else:
95                 file_list.append(join(root, filename))
96
97     return file_list
98
99
100 def get_rst_title_char(level):
101     """Return character used for the given title level in rst files.
102
103     :param level: Level of the title.
104     :type: int
105     :returns: Character used for the given title level in rst files.
106     :rtype: str
107     """
108     chars = ('=', '-', '`', "'", '.', '~', '*', '+', '^')
109     if level < len(chars):
110         return chars[level]
111     else:
112         return chars[-1]
113
114
115 def execute_command(cmd):
116     """Execute the command in a subprocess and log the stdout and stderr.
117
118     :param cmd: Command to execute.
119     :type cmd: str
120     :returns: Return code of the executed command, stdout and stderr.
121     :rtype: tuple(int, str, str)
122     """
123
124     env = environ.copy()
125     proc = subprocess.Popen(
126         [cmd],
127         stdout=subprocess.PIPE,
128         stderr=subprocess.PIPE,
129         shell=True,
130         env=env)
131
132     stdout, stderr = proc.communicate()
133
134     if stdout:
135         logging.info(stdout)
136     if stderr:
137         logging.info(stderr)
138
139     if proc.returncode != 0:
140         logging.error("    Command execution failed.")
141     return proc.returncode, stdout, stderr
142
143
144 def get_last_successful_build_number(jenkins_url, job_name):
145     """Get the number of the last successful build of the given job.
146
147     :param jenkins_url: Jenkins URL.
148     :param job_name: Job name.
149     :type jenkins_url: str
150     :type job_name: str
151     :returns: The build number as a string.
152     :rtype: str
153     """
154
155     url = "{}/{}/lastSuccessfulBuild/buildNumber".format(jenkins_url, job_name)
156     cmd = "wget -qO- {url}".format(url=url)
157
158     return execute_command(cmd)
159
160
161 def get_last_completed_build_number(jenkins_url, job_name):
162     """Get the number of the last completed build of the given job.
163
164     :param jenkins_url: Jenkins URL.
165     :param job_name: Job name.
166     :type jenkins_url: str
167     :type job_name: str
168     :returns: The build number as a string.
169     :rtype: str
170     """
171
172     url = "{}/{}/lastCompletedBuild/buildNumber".format(jenkins_url, job_name)
173     cmd = "wget -qO- {url}".format(url=url)
174
175     return execute_command(cmd)
176
177
178 def get_build_timestamp(jenkins_url, job_name, build_nr):
179     """Get the timestamp of the build of the given job.
180
181     :param jenkins_url: Jenkins URL.
182     :param job_name: Job name.
183     :param build_nr: Build number.
184     :type jenkins_url: str
185     :type job_name: str
186     :type build_nr: int
187     :returns: The timestamp.
188     :rtype: datetime.datetime
189     """
190
191     url = "{jenkins_url}/{job_name}/{build_nr}".format(jenkins_url=jenkins_url,
192                                                        job_name=job_name,
193                                                        build_nr=build_nr)
194     cmd = "wget -qO- {url}".format(url=url)
195
196     timestamp = execute_command(cmd)
197
198     return datetime.fromtimestamp(timestamp/1000)
199
200
201 def archive_input_data(spec):
202     """Archive the report.
203
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.
207     """
208
209     logging.info("    Archiving the input data files ...")
210
211     extension = spec.input["file-format"]
212     data_files = get_files(spec.environment["paths"]["DIR[WORKING,DATA]"],
213                            extension=extension)
214     dst = spec.environment["paths"]["DIR[STATIC,ARCH]"]
215     logging.info("      Destination: {0}".format(dst))
216
217     try:
218         if not isdir(dst):
219             makedirs(dst)
220
221         for data_file in data_files:
222             logging.info("      Moving the file: {0} ...".format(data_file))
223             move(data_file, dst)
224
225     except (Error, OSError) as err:
226         raise PresentationError("Not possible to archive the input data.",
227                                 str(err))
228
229     logging.info("    Done.")
230
231
232 def classify_anomalies(data):
233     """Process the data and return anomalies and trending values.
234
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.
238
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
243     """
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.
251     classification = []
252     avgs = []
253     active_group = None
254     values_left = 0
255     avg = 0.0
256     for _, sample in data.iteritems():
257         if np.isnan(sample.avg):
258             classification.append("outlier")
259             avgs.append(sample.avg)
260             continue
261         if values_left < 1 or active_group is None:
262             values_left = 0
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)
268             avgs.append(avg)
269             values_left -= 1
270             continue
271         classification.append("normal")
272         avgs.append(avg)
273         values_left -= 1
274     return classification, avgs
275
276
277 def convert_csv_to_pretty_txt(csv_file, txt_file):
278     """Convert the given csv table to pretty text table.
279
280     :param csv_file: The path to the input csv file.
281     :param txt_file: The path to the output pretty text file.
282     :type csv_file: str
283     :type txt_file: str
284     """
285
286     txt_table = None
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)
292             else:
293                 txt_table.add_row(row)
294         txt_table.align["Test case"] = "l"
295     if txt_table:
296         with open(txt_file, "w") as txt_file:
297             txt_file.write(str(txt_table))
298
299
300 class Worker(multiprocessing.Process):
301     """Worker class used to process tasks in separate parallel processes.
302     """
303
304     def __init__(self, work_queue, data_queue, func):
305         """Initialization.
306
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
315         """
316         super(Worker, self).__init__()
317         self._work_queue = work_queue
318         self._data_queue = data_queue
319         self._func = func
320
321     def run(self):
322         """Method representing the process's activity.
323         """
324
325         while True:
326             try:
327                 self.process(self._work_queue.get())
328             finally:
329                 self._work_queue.task_done()
330
331     def process(self, item_to_process):
332         """Method executed by the runner.
333
334         :param item_to_process: Data to be processed by the function.
335         :type item_to_process: tuple
336         """
337         self._func(self.pid, self._data_queue, *item_to_process)