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 from ..utils.url_processing import url_decode
34 from .graphs import graph_statistics, select_data
38 """The layout of the dash app and the callbacks.
44 data_stats: pd.DataFrame,
45 data_trending: pd.DataFrame,
46 html_layout_file: str,
47 graph_layout_file: str,
51 - save the input parameters,
52 - read and pre-process the data,
53 - prepare data for the control panel,
54 - read HTML layout file,
55 - read tooltips from the tooltip file.
57 :param app: Flask application running the dash application.
58 :param data_stats: Pandas dataframe with staistical data.
59 :param data_trending: Pandas dataframe with trending data.
60 :param html_layout_file: Path and name of the file specifying the HTML
61 layout of the dash application.
62 :param graph_layout_file: Path and name of the file with layout of
64 :param tooltip_file: Path and name of the yaml file specifying the
67 :type data_stats: pandas.DataFrame
68 :type data_trending: pandas.DataFrame
69 :type html_layout_file: str
70 :type graph_layout_file: str
71 :type tooltip_file: str
76 self._html_layout_file = html_layout_file
77 self._graph_layout_file = graph_layout_file
78 self._tooltip_file = tooltip_file
80 # Pre-process the data:
81 data_stats = data_stats[~data_stats.job.str.contains("-verify-")]
82 data_stats = data_stats[~data_stats.job.str.contains("-coverage-")]
83 data_stats = data_stats[~data_stats.job.str.contains("-iterative-")]
84 data_stats = data_stats[["job", "build", "start_time", "duration"]]
86 jobs = sorted(list(data_stats["job"].unique()))
95 lst_job = job.split("-")
96 d_job_info["job"].append(job)
97 d_job_info["dut"].append(lst_job[1])
98 d_job_info["ttype"].append(lst_job[3])
99 d_job_info["cadence"].append(lst_job[4])
100 d_job_info["tbed"].append("-".join(lst_job[-2:]))
101 self._job_info = pd.DataFrame.from_dict(d_job_info)
103 self._default = set_job_params(self._job_info, C.STATS_DEFAULT_JOB)
109 "dut_version": list(),
116 df_job = data_trending.loc[(data_trending["job"] == job)]
117 builds = df_job["build"].unique()
119 df_build = df_job.loc[(df_job["build"] == build)]
120 tst_info["job"].append(job)
121 tst_info["build"].append(build)
122 tst_info["dut_type"].append(df_build["dut_type"].iloc[-1])
123 tst_info["dut_version"].append(df_build["dut_version"].iloc[-1])
124 tst_info["hosts"].append(df_build["hosts"].iloc[-1])
126 passed = df_build.value_counts(subset="passed")[True]
130 failed = df_build.value_counts(subset="passed")[False]
131 failed_tests = df_build.loc[(df_build["passed"] == False)]\
132 ["test_id"].to_list()
134 for tst in failed_tests:
135 lst_tst = tst.split(".")
136 suite = lst_tst[-2].replace("2n1l-", "").\
137 replace("1n1l-", "").replace("2n-", "")
138 l_failed.append(f"{suite.split('-')[0]}-{lst_tst[-1]}")
142 tst_info["passed"].append(passed)
143 tst_info["failed"].append(failed)
144 tst_info["lst_failed"].append(sorted(l_failed))
146 self._data = data_stats.merge(pd.DataFrame.from_dict(tst_info))
149 self._html_layout = str()
150 self._graph_layout = None
151 self._tooltips = dict()
154 with open(self._html_layout_file, "r") as file_read:
155 self._html_layout = file_read.read()
156 except IOError as err:
158 f"Not possible to open the file {self._html_layout_file}\n{err}"
162 with open(self._graph_layout_file, "r") as file_read:
163 self._graph_layout = load(file_read, Loader=FullLoader)
164 except IOError as err:
166 f"Not possible to open the file {self._graph_layout_file}\n"
169 except YAMLError as err:
171 f"An error occurred while parsing the specification file "
172 f"{self._graph_layout_file}\n{err}"
176 with open(self._tooltip_file, "r") as file_read:
177 self._tooltips = load(file_read, Loader=FullLoader)
178 except IOError as err:
180 f"Not possible to open the file {self._tooltip_file}\n{err}"
182 except YAMLError as err:
184 f"An error occurred while parsing the specification file "
185 f"{self._tooltip_file}\n{err}"
188 # Control panel partameters and their default values.
190 "ri-ttypes-options": self._default["ttypes"],
191 "ri-cadences-options": self._default["cadences"],
192 "dd-tbeds-options": self._default["tbeds"],
193 "ri-duts-value": self._default["dut"],
194 "ri-ttypes-value": self._default["ttype"],
195 "ri-cadences-value": self._default["cadence"],
196 "dd-tbeds-value": self._default["tbed"],
197 "al-job-children": html.A(
198 self._default["job"],
199 href=f"{C.URL_JENKINS}{self._default['job']}",
205 if self._app is not None and hasattr(self, "callbacks"):
206 self.callbacks(self._app)
209 def html_layout(self) -> dict:
210 return self._html_layout
212 def add_content(self):
213 """Top level method which generated the web page.
216 - Store for user input data,
218 - Main area with control panel and ploting area.
220 If no HTML layout is provided, an error message is displayed instead.
222 :returns: The HTML div with the whole page.
231 dcc.Store(id="control-panel"),
232 dcc.Location(id="url", refresh=False),
236 children=[navbar_trending((False, False, True, False))]
241 id="offcanvas-metadata",
242 title="Detailed Information",
246 dbc.Row(id="row-metadata")
254 self._add_ctrl_col(),
255 self._add_plotting_col()
260 id="offcanvas-documentation",
261 title="Documentation",
264 children=html.Iframe(
265 src=C.URL_DOC_TRENDING,
285 def _add_ctrl_col(self) -> dbc.Col:
286 """Add column with controls. It is placed on the left side.
288 :returns: Column with the control panel.
293 children=self._add_ctrl_panel(),
294 className="sticky-top"
298 def _add_plotting_col(self) -> dbc.Col:
299 """Add column with plots and tables. It is placed on the right side.
301 :returns: Column with tables.
305 id="col-plotting-area",
311 class_name="g-0 p-0",
322 def _add_ctrl_panel(self) -> dbc.Row:
323 """Add control panel.
325 :returns: Control panel.
330 class_name="g-0 p-1",
334 dbc.InputGroupText(show_tooltip(
342 value=self._default["dut"],
343 options=self._default["duts"],
344 class_name="form-control"
352 class_name="g-0 p-1",
356 dbc.InputGroupText(show_tooltip(
364 value=self._default["ttype"],
365 options=self._default["ttypes"],
366 class_name="form-control"
374 class_name="g-0 p-1",
378 dbc.InputGroupText(show_tooltip(
386 value=self._default["cadence"],
387 options=self._default["cadences"],
388 class_name="form-control"
396 class_name="g-0 p-1",
400 dbc.InputGroupText(show_tooltip(
407 placeholder="Select a test bed...",
408 value=self._default["tbed"],
409 options=self._default["tbeds"]
417 class_name="g-0 p-1",
422 children=self._default["job"]
428 def _get_plotting_area(
433 """Generate the plotting area with all its content.
435 :param job: The job which data will be displayed.
436 :param url: URL to be displayed in the modal window.
439 :returns: List of rows with elements to be displayed in the plotting
444 figs = graph_statistics(self._data, job, self._graph_layout)
451 id="row-graph-passed",
452 class_name="g-0 p-1",
461 id="row-graph-duration",
462 class_name="g-0 p-1",
480 "text-transform": "none",
481 "padding": "0rem 1rem"
486 dbc.ModalHeader(dbc.ModalTitle("URL")),
495 id="plot-btn-download",
496 children="Download Data",
500 "text-transform": "none",
501 "padding": "0rem 1rem"
504 dcc.Download(id="download-stats-data")
507 "d-grid gap-0 d-md-flex justify-content-md-end"
514 def callbacks(self, app):
515 """Callbacks for the whole application.
517 :param app: The application.
522 Output("control-panel", "data"), # Store
523 Output("plotting-area", "children"),
524 Output("ri-ttypes", "options"),
525 Output("ri-cadences", "options"),
526 Output("dd-tbeds", "options"),
527 Output("ri-duts", "value"),
528 Output("ri-ttypes", "value"),
529 Output("ri-cadences", "value"),
530 Output("dd-tbeds", "value"),
531 Output("al-job", "children"),
532 State("control-panel", "data"), # Store
533 Input("ri-duts", "value"),
534 Input("ri-ttypes", "value"),
535 Input("ri-cadences", "value"),
536 Input("dd-tbeds", "value"),
539 def _update_ctrl_panel(cp_data: dict, dut: str, ttype: str,
540 cadence: str, tbed: str, href: str) -> tuple:
541 """Update the application when the event is detected.
543 :param cp_data: Current status of the control panel stored in
545 :param dut: Input - DUT name.
546 :param ttype: Input - Test type.
547 :param cadence: Input - The cadence of the job.
548 :param tbed: Input - The test bed.
549 :param href: Input - The URL provided by the browser.
556 :returns: New values for web page elements.
560 ctrl_panel = ControlPanel(self._cp_default, cp_data)
563 parsed_url = url_decode(href)
565 url_params = parsed_url["params"]
569 trigger_id = callback_context.triggered[0]["prop_id"].split(".")[0]
570 if trigger_id == "ri-duts":
571 ttype_opts = generate_options(get_ttypes(self._job_info, dut))
572 ttype_val = ttype_opts[0]["value"]
573 cad_opts = generate_options(get_cadences(
574 self._job_info, dut, ttype_val))
575 cad_val = cad_opts[0]["value"]
576 tbed_opts = generate_options(get_test_beds(
577 self._job_info, dut, ttype_val, cad_val))
578 tbed_val = tbed_opts[0]["value"]
580 "ri-duts-value": dut,
581 "ri-ttypes-options": ttype_opts,
582 "ri-ttypes-value": ttype_val,
583 "ri-cadences-options": cad_opts,
584 "ri-cadences-value": cad_val,
585 "dd-tbeds-options": tbed_opts,
586 "dd-tbeds-value": tbed_val
588 elif trigger_id == "ri-ttypes":
589 cad_opts = generate_options(get_cadences(
590 self._job_info, ctrl_panel.get("ri-duts-value"), ttype))
591 cad_val = cad_opts[0]["value"]
592 tbed_opts = generate_options(get_test_beds(
593 self._job_info, ctrl_panel.get("ri-duts-value"), ttype,
595 tbed_val = tbed_opts[0]["value"]
597 "ri-ttypes-value": ttype,
598 "ri-cadences-options": cad_opts,
599 "ri-cadences-value": cad_val,
600 "dd-tbeds-options": tbed_opts,
601 "dd-tbeds-value": tbed_val
603 elif trigger_id == "ri-cadences":
604 tbed_opts = generate_options(get_test_beds(
605 self._job_info, ctrl_panel.get("ri-duts-value"),
606 ctrl_panel.get("ri-ttypes-value"), cadence))
607 tbed_val = tbed_opts[0]["value"]
609 "ri-cadences-value": cadence,
610 "dd-tbeds-options": tbed_opts,
611 "dd-tbeds-value": tbed_val
613 elif trigger_id == "dd-tbeds":
615 "dd-tbeds-value": tbed
617 elif trigger_id == "url":
619 new_job = url_params.get("job", list())[0]
621 job_params = set_job_params(self._job_info, new_job)
622 ctrl_panel = ControlPanel(
624 "ri-ttypes-options": job_params["ttypes"],
625 "ri-cadences-options": job_params["cadences"],
626 "dd-tbeds-options": job_params["tbeds"],
627 "ri-duts-value": job_params["dut"],
628 "ri-ttypes-value": job_params["ttype"],
629 "ri-cadences-value": job_params["cadence"],
630 "dd-tbeds-value": job_params["tbed"],
631 "al-job-children": html.A(
632 self._default["job"],
635 f"{self._default['job']}"
643 ctrl_panel = ControlPanel(self._cp_default, cp_data)
647 ctrl_panel.get("ri-duts-value"),
648 ctrl_panel.get("ri-ttypes-value"),
649 ctrl_panel.get("ri-cadences-value"),
650 ctrl_panel.get("dd-tbeds-value")
655 "al-job-children": html.A(
657 href=f"{C.URL_JENKINS}{job}",
662 plotting_area = self._get_plotting_area(
664 gen_new_url(parsed_url, {"job": job})
671 ret_val.extend(ctrl_panel.values)
675 Output("plot-mod-url", "is_open"),
676 [Input("plot-btn-url", "n_clicks")],
677 [State("plot-mod-url", "is_open")],
679 def toggle_plot_mod_url(n, is_open):
680 """Toggle the modal window with url.
687 Output("download-stats-data", "data"),
688 State("control-panel", "data"), # Store
689 Input("plot-btn-download", "n_clicks"),
690 prevent_initial_call=True
692 def _download_data(cp_data: dict, n_clicks: int):
695 :param cp_data: Current status of the control panel stored in
697 :param n_clicks: Number of clicks on the button "Download".
700 :returns: dict of data frame content (base64 encoded) and meta data
701 used by the Download component.
707 ctrl_panel = ControlPanel(self._cp_default, cp_data)
711 ctrl_panel.get("ri-duts-value"),
712 ctrl_panel.get("ri-ttypes-value"),
713 ctrl_panel.get("ri-cadences-value"),
714 ctrl_panel.get("dd-tbeds-value")
717 data = select_data(self._data, job)
718 data = data.drop(columns=["job", ])
720 return dcc.send_data_frame(
721 data.T.to_csv, f"{job}-{C.STATS_DOWNLOAD_FILE_NAME}")
724 Output("row-metadata", "children"),
725 Output("offcanvas-metadata", "is_open"),
726 Input("graph-passed", "clickData"),
727 Input("graph-duration", "clickData"),
728 prevent_initial_call=True
730 def _show_metadata_from_graphs(
731 passed_data: dict, duration_data: dict) -> tuple:
732 """Generates the data for the offcanvas displayed when a particular
733 point in a graph is clicked on.
735 :param passed_data: The data from the clicked point in the graph
736 displaying the pass/fail data.
737 :param duration_data: The data from the clicked point in the graph
738 displaying the duration data.
739 :type passed_data: dict
740 :type duration data: dict
741 :returns: The data to be displayed on the offcanvas (job statistics
742 and the list of failed tests) and the information to show the
744 :rtype: tuple(list, bool)
747 if not (passed_data or duration_data):
752 title = "Job Statistics"
753 trigger_id = callback_context.triggered[0]["prop_id"].split(".")[0]
754 if trigger_id == "graph-passed":
755 graph_data = passed_data["points"][0].get("hovertext", "")
756 elif trigger_id == "graph-duration":
757 graph_data = duration_data["points"][0].get("text", "")
759 lst_graph_data = graph_data.split("<br>")
761 # Prepare list of failed tests:
764 for itm in lst_graph_data:
765 if "csit-ref:" in itm:
766 job, build = itm.split(" ")[-1].split("/")
769 fail_tests = self._data.loc[
770 (self._data["job"] == job) &
771 (self._data["build"] == build)
772 ]["lst_failed"].values[0]
778 # Create the content of the offcanvas:
779 list_group_items = list()
780 for itm in lst_graph_data:
781 lst_itm = itm.split(": ")
782 if lst_itm[0] == "csit-ref":
783 list_group_item = dbc.ListGroupItem([
784 dbc.Badge(lst_itm[0]),
787 href=f"{C.URL_JENKINS}{lst_itm[1]}",
792 list_group_item = dbc.ListGroupItem([
793 dbc.Badge(lst_itm[0]),
796 list_group_items.append(list_group_item)
799 class_name="gy-2 p-0",
803 target_id="metadata",
805 style={"display": "inline-block"}
810 dbc.ListGroup(list_group_items, flush=True),
818 if fail_tests is not None:
821 class_name="gy-2 p-0",
824 f"List of Failed Tests ({len(fail_tests)})"
829 children=[dbc.ListGroup(
831 dbc.ListGroupItem(x) \
843 return metadata, open_canvas
846 Output("offcanvas-documentation", "is_open"),
847 Input("btn-documentation", "n_clicks"),
848 State("offcanvas-documentation", "is_open")
850 def toggle_offcanvas_documentation(n_clicks, is_open):