2 # Copyright (C) 2019 - Jonathan Rajotte <jonathan.rajotte-julien@efficios.com>
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 from statistics
import mean
23 from operator
import add
25 import matplotlib
.pyplot
as plt
26 from matplotlib
.backends
.backend_pdf
import PdfPages
27 from matplotlib
.ticker
import PercentFormatter
33 from minio
import Minio
34 from minio
.error
import NoSuchKey
35 from minio
.error
import ResponseError
38 BENCHMARK_TYPES
= ["dummy", "text"]
39 DEFAULT_BUCKET
= "lava"
42 def graph_get_color(branch
):
44 Get the color matching the branch.
46 color
= {"stable-1.5": "red", "stable-2.0": "green", "master": "blue"}
50 def graph_get_title(branch
, benchmark_type
):
52 Get title for graph based on benchmark type.
54 string
= {"dummy": "Dummy output", "text": "Text output"}
55 return "{} - {}".format(branch
, string
[benchmark_type
])
60 Return minio client configured.
63 "obj.internal.efficios.com", access_key
="jenkins", secret_key
="echo123456"
67 def get_file(client
, prefix
, file_name
, workdir_name
):
69 Return the path of the downloaded file.
72 destination
= os
.path
.join(workdir_name
, file_name
)
73 object_name
= "{}/{}".format(prefix
, file_name
)
75 client
.fget_object(DEFAULT_BUCKET
, object_name
, destination
)
82 def delete_file(client
, prefix
, file_name
):
84 Delete the file on remote.
86 object_name
= "{}/{}".format(prefix
, file_name
)
88 client
.remove_object(DEFAULT_BUCKET
, object_name
)
89 except ResponseError
as err
:
95 def get_git_log(bt_version
, cutoff
, repo_path
):
97 Return an ordered (older to newer) list of commits for the bt_version and
98 cutoff. WARNING: This changes the git repo HEAD.
100 repo
= git
.Repo(repo_path
)
103 "{}..origin/{}".format(cutoff
, bt_version
), "--pretty=format:%H", "--reverse"
107 def parse_result(result_path
):
109 Parse the result file. Return a dataset of User time + System time.
111 with
open(result_path
) as result
:
112 parsed_result
= json
.load(result
)
116 parsed_result
["User time (seconds)"],
117 parsed_result
["System time (seconds)"],
122 def get_benchmark_results(client
, commit
, workdir
):
124 Fetch the benchmark result from a certain commit across all benchmark type.
127 benchmark_valid
= True
128 for b_type
in BENCHMARK_TYPES
:
129 prefix
= "/results/benchmarks/babeltrace/{}/".format(b_type
)
130 result_file
= get_file(client
, prefix
, commit
, workdir
)
133 Benchmark is either corrupted or not complete.
135 return None, benchmark_valid
136 results
[b_type
] = parse_result(result_file
)
137 if all(i
== 0.0 for i
in results
[b_type
]):
138 benchmark_valid
= False
139 print("Invalid benchmark for {}/{}/{}".format(prefix
, b_type
, commit
))
140 # The dataset is valid return immediately.
141 return results
, benchmark_valid
144 def plot_raw_value(branch
, benchmark_type
, x_data
, y_data
, labels
, latest_values
):
146 Plot the graph using the raw value.
152 for pos
in range(len(x_data
)):
154 valid_points
, outliers
= sanitize_dataset(y_data
[pos
])
155 for y
in valid_points
:
156 point_x_data
.append(x
)
157 point_y_data
.append(y
)
159 outlier_x_data
.append(x
)
160 outlier_y_data
.append(y
)
163 point_x_data
, point_y_data
, "o", label
=branch
, color
=graph_get_color(branch
)
165 plt
.plot(outlier_x_data
, outlier_y_data
, "+", label
="outlier", color
="black")
169 ymin
= 0.8 * min([item
for sublist
in y_data
for item
in sublist
])
170 ymax
= 1.2 * max([item
for sublist
in y_data
for item
in sublist
])
171 # Put latest of other branches for reference as horizontal line.
172 for l_branch
, l_result
in latest_values
.items():
173 if not l_result
or l_branch
== branch
:
177 label
="Latest {}".format(l_branch
),
178 color
=graph_get_color(l_branch
),
181 ymax
= 1.2 * l_result
183 plt
.ylim(ymin
=0, ymax
=ymax
)
184 plt
.xticks(x_data
, labels
, rotation
=90, family
="monospace")
185 plt
.title(graph_get_title(branch
, benchmark_type
), fontweight
="bold")
186 plt
.ylabel("User + system time (s)")
187 plt
.xlabel("Latest commits")
190 # Put tick on the right side
191 ax
.tick_params(labeltop
=False, labelright
=True)
196 def plot_delta_between_point(branch
, benchmark_type
, x_data
, y_data
, labels
, latest_values
):
198 Plot the graph of delta between each sequential commit.
202 # Transform y_data to a list of for which the reference is the first
205 for pos
, y
in enumerate(y_data
):
207 local_y_data
.append(0.0)
209 local_y_data
.append(y
- y_data
[pos
- 1])
211 plt
.plot(x_data
, local_y_data
, "o", label
=branch
, color
=graph_get_color(branch
))
213 # Get max absolute value to align the y axis with zero in the middle.
215 local_abs_max
= abs(max(local_y_data
, key
=abs)) * 1.3
217 plt
.ylim(ymin
=local_abs_max
* -1, ymax
=local_abs_max
)
220 plt
.xticks(x_data
, labels
, rotation
=90, family
="monospace")
221 plt
.title(graph_get_title(branch
, benchmark_type
) + " Delta to previous commit", fontweight
="bold")
222 plt
.ylabel("Seconds")
223 plt
.xlabel("Latest commits")
226 # Put tick on the right side
227 ax
.tick_params(labeltop
=False, labelright
=True)
232 def plot_ratio(branch
, benchmark_type
, x_data
, y_data
, labels
, latest_values
):
234 Plot the graph using a ratio using first point as reference (0%).
240 reference
= y_data
[0]
242 # Transform y_data to a list of ratio for which the reference is the first
244 local_y_data
= list(map(lambda y
: ((y
/ reference
) - 1.0) * 100, y_data
))
246 plt
.plot(x_data
, local_y_data
, "o", label
=branch
, color
=graph_get_color(branch
))
248 # Put latest of other branches for reference as horizontal line.
249 for l_branch
, l_result
in latest_values
.items():
250 if not l_result
or l_branch
== branch
:
252 ratio_l_result
= ((l_result
/ reference
) - 1.0) * 100.0
254 "branch {} branch {} value {} l_result {} reference {}".format(
255 branch
, l_branch
, ratio_l_result
, l_result
, reference
260 label
="Latest {}".format(l_branch
),
261 color
=graph_get_color(l_branch
),
264 # Draw the reference line.
265 plt
.axhline(y
=0, label
="Reference (leftmost point)", linestyle
="-", color
="Black")
267 # Get max absolute value to align the y axis with zero in the middle.
269 local_abs_max
= abs(max(local_y_data
, key
=abs)) * 1.3
271 y_abs_max
= local_abs_max
273 plt
.ylim(ymin
=y_abs_max
* -1, ymax
=y_abs_max
)
276 percent_formatter
= PercentFormatter()
277 ax
.yaxis
.set_major_formatter(percent_formatter
)
278 ax
.yaxis
.set_minor_formatter(percent_formatter
)
279 plt
.xticks(x_data
, labels
, rotation
=90, family
="monospace")
280 plt
.title(graph_get_title(branch
, benchmark_type
), fontweight
="bold")
282 plt
.xlabel("Latest commits")
285 # Put tick on the right side
286 ax
.tick_params(labeltop
=False, labelright
=True)
291 def generate_graph(branches
, report_name
, git_path
):
294 pdf_pages
= PdfPages(report_name
)
296 client
= get_client()
297 branch_results
= dict()
299 # Fetch the results for each branch.
300 for branch
, cutoff
in branches
.items():
301 commits
= get_git_log(branch
, cutoff
, git_path
)
303 with tempfile
.TemporaryDirectory() as workdir
:
304 for commit
in commits
:
305 b_results
, valid
= get_benchmark_results(client
, commit
, workdir
)
306 if not b_results
or not valid
:
308 results
.append((commit
, b_results
))
309 branch_results
[branch
] = results
311 for b_type
in BENCHMARK_TYPES
:
315 # Find the maximum size for a series inside our series dataset.
316 # This is used later to compute the size of the actual plot (pdf).
317 # While there gather the comparison value used to draw comparison line
319 for branch
, results
in branch_results
.items():
320 max_len
= max([max_len
, len(results
)])
322 latest_values
[branch
] = mean(
323 sanitize_dataset(results
[-1][1][b_type
])[0]
326 latest_values
[branch
] = None
328 for branch
, results
in branch_results
.items():
329 # Create a figure instance
330 if max_len
and max_len
> 10:
331 width
= 0.16 * max_len
335 x_data
= list(range(len(results
)))
336 y_data
= [c
[1][b_type
] for c
in results
]
337 labels
= [c
[0][:8] for c
in results
]
339 fig
= plt
.figure(figsize
=(width
, 8.27), dpi
=100)
340 plot_raw_value(branch
, b_type
, x_data
, y_data
, labels
, latest_values
)
341 pdf_pages
.savefig(fig
)
343 # Use the mean of each sanitize dataset here, we do not care for
344 # variance for ratio. At least not yet.
345 y_data
= [mean(sanitize_dataset(c
[1][b_type
])[0]) for c
in results
]
346 fig
= plt
.figure(figsize
=(width
, 8.27), dpi
=100)
347 plot_ratio(branch
, b_type
, x_data
, y_data
, labels
, latest_values
)
348 pdf_pages
.savefig(fig
)
350 fig
= plt
.figure(figsize
=(width
, 8.27), dpi
=100)
351 plot_delta_between_point(branch
, b_type
, x_data
, y_data
, labels
, latest_values
)
352 pdf_pages
.savefig(fig
)
357 def launch_jobs(branches
, git_path
, wait_for_completion
, debug
, force
):
359 Lauch jobs for all missing results.
361 client
= get_client()
362 for branch
, cutoff
in branches
.items():
363 commits
= get_git_log(branch
, cutoff
, git_path
)
365 with tempfile
.TemporaryDirectory() as workdir
:
366 for commit
in commits
:
367 b_results
= get_benchmark_results(client
, commit
, workdir
)[0]
368 if b_results
and not force
:
371 commit
, wait_for_completion
=wait_for_completion
, debug
=debug
377 Parse arguments and execute as needed.
380 "master": "31976fe2d70a8b6b7f8b31b9e0b3bc004d415575",
381 "stable-2.0": "07f585356018b4ddfbd0e09c49a14e38977c6973",
382 "stable-1.5": "49e98b837a5667130e0d1e062a6bd7985c7c4582",
385 parser
= argparse
.ArgumentParser(description
="Babeltrace benchmark utility")
387 "--generate-jobs", action
="store_true", help="Generate and send jobs"
390 "--force-jobs", action
="store_true", help="Force the queueing of jobs to lava"
393 "--do-not-wait-on-completion",
396 help="Wait for the completion of each jobs sent. This is useful"
397 "for the ci. Otherwise we could end up spaming the lava instance.",
402 help="Generate graphs and save them to pdf",
405 "--report-name", default
="report.pdf", help="The name of the pdf report."
408 "--debug", action
="store_true", default
=False, help="Do not send jobs to lava."
411 "--repo-path", help="The location of the git repo to use.", required
=True
414 args
= parser
.parse_args()
416 if not os
.path
.exists(args
.repo_path
):
417 print("Repository location does not exists.")
420 if args
.generate_jobs
:
421 print("Launching jobs for:")
423 for branch
, cutoff
in bt_branches
.items():
424 print("\t Branch {} with cutoff {}".format(branch
, cutoff
))
429 not args
.do_not_wait_on_completion
,
434 if args
.generate_report
:
435 print("Generating pdf report ({}) for:".format(args
.report_name
))
436 for branch
, cutoff
in bt_branches
.items():
437 print("\t Branch {} with cutoff {}".format(branch
, cutoff
))
438 generate_graph(bt_branches
, args
.report_name
, args
.repo_path
)
443 def sanitize_dataset(dataset
):
445 Use IRQ 1.5 [1] to remove outlier from the dataset. This is useful to get a
446 representative mean without outlier in it.
447 [1] https://en.wikipedia.org/wiki/Interquartile_range#Outliers
449 sorted_data
= sorted(dataset
)
450 q1
, q3
= numpy
.percentile(sorted_data
, [25, 75])
452 lower_bound
= q1
- (1.5 * iqr
)
453 upper_bound
= q3
+ (1.5 * iqr
)
457 if lower_bound
<= i
<= upper_bound
:
458 new_dataset
.append(i
)
461 return new_dataset
, outliers
464 if __name__
== "__main__":