1 # Copyright (c) 2024 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 """Plotly Dash HTML layout override.
19 import dash_bootstrap_components as dbc
21 from flask import Flask
24 from dash import callback_context, no_update
25 from dash import Input, Output, State
26 from dash.exceptions import PreventUpdate
27 from yaml import load, FullLoader, YAMLError
29 from ..utils.constants import Constants as C
30 from ..utils.control_panel import ControlPanel
31 from ..utils.utils import show_tooltip, gen_new_url, get_ttypes, get_cadences, \
32 get_test_beds, get_job, generate_options, set_job_params, navbar_trending, \
33 get_url_job, get_url_logs
34 from ..utils.url_processing import url_decode
35 from .graphs import graph_statistics, select_data
39 """The layout of the dash app and the callbacks.
45 data_stats: pd.DataFrame,
46 data_trending: pd.DataFrame,
47 html_layout_file: str,
48 graph_layout_file: str,
52 - save the input parameters,
53 - read and pre-process the data,
54 - prepare data for the control panel,
55 - read HTML layout file,
56 - read tooltips from the tooltip file.
58 :param app: Flask application running the dash application.
59 :param data_stats: Pandas dataframe with staistical data.
60 :param data_trending: Pandas dataframe with trending data.
61 :param html_layout_file: Path and name of the file specifying the HTML
62 layout of the dash application.
63 :param graph_layout_file: Path and name of the file with layout of
65 :param tooltip_file: Path and name of the yaml file specifying the
68 :type data_stats: pandas.DataFrame
69 :type data_trending: pandas.DataFrame
70 :type html_layout_file: str
71 :type graph_layout_file: str
72 :type tooltip_file: str
77 self._html_layout_file = html_layout_file
78 self._graph_layout_file = graph_layout_file
79 self._tooltip_file = tooltip_file
81 # Pre-process the data:
82 data_stats = data_stats[~data_stats.job.str.contains("-verify-")]
83 data_stats = data_stats[~data_stats.job.str.contains("-coverage-")]
84 data_stats = data_stats[~data_stats.job.str.contains("-iterative-")]
85 data_stats = data_stats[["job", "build", "start_time", "duration"]]
87 jobs = sorted(list(data_stats["job"].unique()))
96 idx = -3 if "-x-" in job else -2
97 lst_job = job.split("-")
98 d_job_info["job"].append(job)
99 d_job_info["dut"].append(lst_job[1])
100 d_job_info["ttype"].append(lst_job[3])
101 d_job_info["cadence"].append(lst_job[4])
102 d_job_info["tbed"].append("-".join(lst_job[idx:]))
103 self._job_info = pd.DataFrame.from_dict(d_job_info)
105 self._default = set_job_params(self._job_info, d_job_info["job"][0])
111 "dut_version": list(),
118 df_job = data_trending.loc[(data_trending["job"] == job)]
119 builds = df_job["build"].unique()
121 df_build = df_job.loc[(df_job["build"] == build)]
122 tst_info["job"].append(job)
123 tst_info["build"].append(build)
124 tst_info["dut_type"].append(df_build["dut_type"].iloc[-1])
125 tst_info["dut_version"].append(df_build["dut_version"].iloc[-1])
126 tst_info["hosts"].append(df_build["hosts"].iloc[-1])
128 passed = df_build.value_counts(subset="passed")[True]
132 failed = df_build.value_counts(subset="passed")[False]
133 failed_tests = df_build.loc[(df_build["passed"] == False)]\
134 ["test_id"].to_list()
136 for tst in failed_tests:
137 lst_tst = tst.split(".")
138 suite = lst_tst[-2].replace("2n1l-", "").\
139 replace("1n1l-", "").replace("2n-", "")
140 l_failed.append(f"{suite.split('-')[0]}-{lst_tst[-1]}")
144 tst_info["passed"].append(passed)
145 tst_info["failed"].append(failed)
146 tst_info["lst_failed"].append(sorted(l_failed))
148 self._data = data_stats.merge(pd.DataFrame.from_dict(tst_info))
151 self._html_layout = str()
152 self._graph_layout = None
153 self._tooltips = dict()
156 with open(self._html_layout_file, "r") as file_read:
157 self._html_layout = file_read.read()
158 except IOError as err:
160 f"Not possible to open the file {self._html_layout_file}\n{err}"
164 with open(self._graph_layout_file, "r") as file_read:
165 self._graph_layout = load(file_read, Loader=FullLoader)
166 except IOError as err:
168 f"Not possible to open the file {self._graph_layout_file}\n"
171 except YAMLError as err:
173 f"An error occurred while parsing the specification file "
174 f"{self._graph_layout_file}\n{err}"
178 with open(self._tooltip_file, "r") as file_read:
179 self._tooltips = load(file_read, Loader=FullLoader)
180 except IOError as err:
182 f"Not possible to open the file {self._tooltip_file}\n{err}"
184 except YAMLError as err:
186 f"An error occurred while parsing the specification file "
187 f"{self._tooltip_file}\n{err}"
190 # Control panel partameters and their default values.
192 "ri-ttypes-options": self._default["ttypes"],
193 "ri-cadences-options": self._default["cadences"],
194 "dd-tbeds-options": self._default["tbeds"],
195 "ri-duts-value": self._default["dut"],
196 "ri-ttypes-value": self._default["ttype"],
197 "ri-cadences-value": self._default["cadence"],
198 "dd-tbeds-value": self._default["tbed"],
199 "al-job-children": html.A(
200 self._default["job"],
201 href=get_url_job(self._default["job"]),
207 if self._app is not None and hasattr(self, "callbacks"):
208 self.callbacks(self._app)
211 def html_layout(self) -> dict:
212 return self._html_layout
214 def add_content(self):
215 """Top level method which generated the web page.
218 - Store for user input data,
220 - Main area with control panel and ploting area.
222 If no HTML layout is provided, an error message is displayed instead.
224 :returns: The HTML div with the whole page.
233 dcc.Store(id="control-panel"),
234 dcc.Location(id="url", refresh=False),
238 children=[navbar_trending((False, False, True, False))]
243 id="offcanvas-metadata",
244 title="Detailed Information",
248 dbc.Row(id="row-metadata")
256 self._add_ctrl_col(),
257 self._add_plotting_col()
262 id="offcanvas-documentation",
263 title="Documentation",
266 children=html.Iframe(
267 src=C.URL_DOC_TRENDING,
287 def _add_ctrl_col(self) -> dbc.Col:
288 """Add column with controls. It is placed on the left side.
290 :returns: Column with the control panel.
295 children=self._add_ctrl_panel(),
296 className="sticky-top"
300 def _add_plotting_col(self) -> dbc.Col:
301 """Add column with plots and tables. It is placed on the right side.
303 :returns: Column with tables.
307 id="col-plotting-area",
313 class_name="g-0 p-0",
324 def _add_ctrl_panel(self) -> dbc.Row:
325 """Add control panel.
327 :returns: Control panel.
332 class_name="g-0 p-1",
336 dbc.InputGroupText(show_tooltip(
344 value=self._default["dut"],
345 options=self._default["duts"],
346 class_name="form-control"
354 class_name="g-0 p-1",
358 dbc.InputGroupText(show_tooltip(
366 value=self._default["ttype"],
367 options=self._default["ttypes"],
368 class_name="form-control"
376 class_name="g-0 p-1",
380 dbc.InputGroupText(show_tooltip(
388 value=self._default["cadence"],
389 options=self._default["cadences"],
390 class_name="form-control"
398 class_name="g-0 p-1",
402 dbc.InputGroupText(show_tooltip(
409 placeholder="Select a test bed...",
410 value=self._default["tbed"],
411 options=self._default["tbeds"]
419 class_name="g-0 p-1",
424 children=self._default["job"]
430 def _get_plotting_area(
435 """Generate the plotting area with all its content.
437 :param job: The job which data will be displayed.
438 :param url: URL to be displayed in the modal window.
441 :returns: List of rows with elements to be displayed in the plotting
446 figs = graph_statistics(self._data, job, self._graph_layout)
453 id="row-graph-passed",
454 class_name="g-0 p-1",
463 id="row-graph-duration",
464 class_name="g-0 p-1",
482 "text-transform": "none",
483 "padding": "0rem 1rem"
488 dbc.ModalHeader(dbc.ModalTitle("URL")),
497 id="plot-btn-download",
498 children="Download Data",
502 "text-transform": "none",
503 "padding": "0rem 1rem"
506 dcc.Download(id="download-stats-data")
509 "d-grid gap-0 d-md-flex justify-content-md-end"
516 def callbacks(self, app):
517 """Callbacks for the whole application.
519 :param app: The application.
524 Output("control-panel", "data"), # Store
525 Output("plotting-area", "children"),
526 Output("ri-ttypes", "options"),
527 Output("ri-cadences", "options"),
528 Output("dd-tbeds", "options"),
529 Output("ri-duts", "value"),
530 Output("ri-ttypes", "value"),
531 Output("ri-cadences", "value"),
532 Output("dd-tbeds", "value"),
533 Output("al-job", "children"),
534 State("control-panel", "data"), # Store
535 Input("ri-duts", "value"),
536 Input("ri-ttypes", "value"),
537 Input("ri-cadences", "value"),
538 Input("dd-tbeds", "value"),
541 def _update_ctrl_panel(cp_data: dict, dut: str, ttype: str,
542 cadence: str, tbed: str, href: str) -> tuple:
543 """Update the application when the event is detected.
545 :param cp_data: Current status of the control panel stored in
547 :param dut: Input - DUT name.
548 :param ttype: Input - Test type.
549 :param cadence: Input - The cadence of the job.
550 :param tbed: Input - The test bed.
551 :param href: Input - The URL provided by the browser.
558 :returns: New values for web page elements.
562 ctrl_panel = ControlPanel(self._cp_default, cp_data)
565 parsed_url = url_decode(href)
567 url_params = parsed_url["params"]
571 trigger_id = callback_context.triggered[0]["prop_id"].split(".")[0]
572 if trigger_id == "ri-duts":
573 ttype_opts = generate_options(get_ttypes(self._job_info, dut))
574 ttype_val = ttype_opts[0]["value"]
575 cad_opts = generate_options(get_cadences(
576 self._job_info, dut, ttype_val))
577 cad_val = cad_opts[0]["value"]
578 tbed_opts = generate_options(get_test_beds(
579 self._job_info, dut, ttype_val, cad_val))
580 tbed_val = tbed_opts[0]["value"]
582 "ri-duts-value": dut,
583 "ri-ttypes-options": ttype_opts,
584 "ri-ttypes-value": ttype_val,
585 "ri-cadences-options": cad_opts,
586 "ri-cadences-value": cad_val,
587 "dd-tbeds-options": tbed_opts,
588 "dd-tbeds-value": tbed_val
590 elif trigger_id == "ri-ttypes":
591 cad_opts = generate_options(get_cadences(
592 self._job_info, ctrl_panel.get("ri-duts-value"), ttype))
593 cad_val = cad_opts[0]["value"]
594 tbed_opts = generate_options(get_test_beds(
595 self._job_info, ctrl_panel.get("ri-duts-value"), ttype,
597 tbed_val = tbed_opts[0]["value"]
599 "ri-ttypes-value": ttype,
600 "ri-cadences-options": cad_opts,
601 "ri-cadences-value": cad_val,
602 "dd-tbeds-options": tbed_opts,
603 "dd-tbeds-value": tbed_val
605 elif trigger_id == "ri-cadences":
606 tbed_opts = generate_options(get_test_beds(
607 self._job_info, ctrl_panel.get("ri-duts-value"),
608 ctrl_panel.get("ri-ttypes-value"), cadence))
609 tbed_val = tbed_opts[0]["value"]
611 "ri-cadences-value": cadence,
612 "dd-tbeds-options": tbed_opts,
613 "dd-tbeds-value": tbed_val
615 elif trigger_id == "dd-tbeds":
617 "dd-tbeds-value": tbed
619 elif trigger_id == "url":
621 new_job = url_params.get("job", list())[0]
623 job_params = set_job_params(self._job_info, new_job)
624 ctrl_panel = ControlPanel(
626 "ri-ttypes-options": job_params["ttypes"],
627 "ri-cadences-options": job_params["cadences"],
628 "dd-tbeds-options": job_params["tbeds"],
629 "ri-duts-value": job_params["dut"],
630 "ri-ttypes-value": job_params["ttype"],
631 "ri-cadences-value": job_params["cadence"],
632 "dd-tbeds-value": job_params["tbed"],
633 "al-job-children": html.A(
634 self._default["job"],
635 href=get_url_job(self._default["job"]),
642 ctrl_panel = ControlPanel(self._cp_default, cp_data)
646 ctrl_panel.get("ri-duts-value"),
647 ctrl_panel.get("ri-ttypes-value"),
648 ctrl_panel.get("ri-cadences-value"),
649 ctrl_panel.get("dd-tbeds-value")
654 "al-job-children": html.A(
656 href=get_url_job(job),
661 plotting_area = self._get_plotting_area(
663 gen_new_url(parsed_url, {"job": job})
670 ret_val.extend(ctrl_panel.values)
674 Output("plot-mod-url", "is_open"),
675 [Input("plot-btn-url", "n_clicks")],
676 [State("plot-mod-url", "is_open")],
678 def toggle_plot_mod_url(n, is_open):
679 """Toggle the modal window with url.
686 Output("download-stats-data", "data"),
687 State("control-panel", "data"), # Store
688 Input("plot-btn-download", "n_clicks"),
689 prevent_initial_call=True
691 def _download_data(cp_data: dict, n_clicks: int):
694 :param cp_data: Current status of the control panel stored in
696 :param n_clicks: Number of clicks on the button "Download".
699 :returns: dict of data frame content (base64 encoded) and meta data
700 used by the Download component.
706 ctrl_panel = ControlPanel(self._cp_default, cp_data)
710 ctrl_panel.get("ri-duts-value"),
711 ctrl_panel.get("ri-ttypes-value"),
712 ctrl_panel.get("ri-cadences-value"),
713 ctrl_panel.get("dd-tbeds-value")
716 data = select_data(self._data, job)
717 data = data.drop(columns=["job", ])
719 return dcc.send_data_frame(
720 data.T.to_csv, f"{job}-{C.STATS_DOWNLOAD_FILE_NAME}")
723 Output("row-metadata", "children"),
724 Output("offcanvas-metadata", "is_open"),
725 Input("graph-passed", "clickData"),
726 Input("graph-duration", "clickData"),
727 prevent_initial_call=True
729 def _show_metadata_from_graphs(
730 passed_data: dict, duration_data: dict) -> tuple:
731 """Generates the data for the offcanvas displayed when a particular
732 point in a graph is clicked on.
734 :param passed_data: The data from the clicked point in the graph
735 displaying the pass/fail data.
736 :param duration_data: The data from the clicked point in the graph
737 displaying the duration data.
738 :type passed_data: dict
739 :type duration data: dict
740 :returns: The data to be displayed on the offcanvas (job statistics
741 and the list of failed tests) and the information to show the
743 :rtype: tuple(list, bool)
746 if not (passed_data or duration_data):
751 title = "Job Statistics"
752 trigger_id = callback_context.triggered[0]["prop_id"].split(".")[0]
753 if trigger_id == "graph-passed":
754 graph_data = passed_data["points"][0].get("hovertext", "")
755 elif trigger_id == "graph-duration":
756 graph_data = duration_data["points"][0].get("text", "")
758 lst_graph_data = graph_data.split("<br>")
760 # Prepare list of failed tests:
763 for itm in lst_graph_data:
764 if "csit-ref:" in itm:
765 job, build = itm.split(" ")[-1].split("/")
768 fail_tests = self._data.loc[
769 (self._data["job"] == job) &
770 (self._data["build"] == build)
771 ]["lst_failed"].values[0]
777 # Create the content of the offcanvas:
778 list_group_items = list()
779 for itm in lst_graph_data:
780 lst_itm = itm.split(": ")
781 if lst_itm[0] == "csit-ref":
782 list_group_item = dbc.ListGroupItem([
783 dbc.Badge(lst_itm[0]),
786 href=get_url_logs(lst_itm[1]),
791 list_group_item = dbc.ListGroupItem([
792 dbc.Badge(lst_itm[0]),
795 list_group_items.append(list_group_item)
798 class_name="gy-2 p-0",
802 target_id="metadata",
804 style={"display": "inline-block"}
809 dbc.ListGroup(list_group_items, flush=True),
817 if fail_tests is not None:
820 class_name="gy-2 p-0",
823 f"List of Failed Tests ({len(fail_tests)})"
828 children=[dbc.ListGroup(
830 dbc.ListGroupItem(x) \
842 return metadata, open_canvas
845 Output("offcanvas-documentation", "is_open"),
846 Input("btn-documentation", "n_clicks"),
847 State("offcanvas-documentation", "is_open")
849 def toggle_offcanvas_documentation(n_clicks, is_open):