1 # Copyright (c) 2023 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
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": self._default["job"]
201 if self._app is not None and hasattr(self, "callbacks"):
202 self.callbacks(self._app)
205 def html_layout(self) -> dict:
206 return self._html_layout
208 def add_content(self):
209 """Top level method which generated the web page.
212 - Store for user input data,
214 - Main area with control panel and ploting area.
216 If no HTML layout is provided, an error message is displayed instead.
218 :returns: The HTML div with the whole page.
227 dcc.Store(id="control-panel"),
228 dcc.Location(id="url", refresh=False),
239 id="offcanvas-metadata",
240 title="Detailed Information",
244 dbc.Row(id="row-metadata")
252 self._add_ctrl_col(),
253 self._add_plotting_col()
271 def _add_navbar(self):
272 """Add nav element with navigation panel. It is placed on the top.
274 :returns: Navigation bar.
275 :rtype: dbc.NavbarSimple
277 return dbc.NavbarSimple(
278 id="navbarsimple-main",
291 brand_external_link=True,
296 def _add_ctrl_col(self) -> dbc.Col:
297 """Add column with controls. It is placed on the left side.
299 :returns: Column with the control panel.
304 children=self._add_ctrl_panel(),
305 className="sticky-top"
309 def _add_plotting_col(self) -> dbc.Col:
310 """Add column with plots and tables. It is placed on the right side.
312 :returns: Column with tables.
316 id="col-plotting-area",
322 class_name="g-0 p-0",
333 def _add_ctrl_panel(self) -> dbc.Row:
334 """Add control panel.
336 :returns: Control panel.
341 class_name="g-0 p-1",
346 children=show_tooltip(
355 value=self._default["dut"],
356 options=self._default["duts"],
357 class_name="form-control"
365 class_name="g-0 p-1",
370 children=show_tooltip(
379 value=self._default["ttype"],
380 options=self._default["ttypes"],
381 class_name="form-control"
389 class_name="g-0 p-1",
394 children=show_tooltip(
403 value=self._default["cadence"],
404 options=self._default["cadences"],
405 class_name="form-control"
413 class_name="g-0 p-1",
418 children=show_tooltip(
426 placeholder="Select a test bed...",
427 value=self._default["tbed"],
428 options=self._default["tbeds"]
436 class_name="g-0 p-1",
441 children=self._default["job"]
447 def _get_plotting_area(
452 """Generate the plotting area with all its content.
454 :param job: The job which data will be displayed.
455 :param url: URL to be displayed in the modal window.
458 :returns: List of rows with elements to be displayed in the plotting
463 figs = graph_statistics(self._data, job, self._graph_layout)
470 id="row-graph-passed",
471 class_name="g-0 p-1",
480 id="row-graph-duration",
481 class_name="g-0 p-1",
499 "text-transform": "none",
500 "padding": "0rem 1rem"
505 dbc.ModalHeader(dbc.ModalTitle("URL")),
514 id="plot-btn-download",
515 children="Download Data",
519 "text-transform": "none",
520 "padding": "0rem 1rem"
523 dcc.Download(id="download-stats-data")
526 "d-grid gap-0 d-md-flex justify-content-md-end"
533 def callbacks(self, app):
534 """Callbacks for the whole application.
536 :param app: The application.
541 Output("control-panel", "data"), # Store
542 Output("plotting-area", "children"),
543 Output("ri-ttypes", "options"),
544 Output("ri-cadences", "options"),
545 Output("dd-tbeds", "options"),
546 Output("ri-duts", "value"),
547 Output("ri-ttypes", "value"),
548 Output("ri-cadences", "value"),
549 Output("dd-tbeds", "value"),
550 Output("al-job", "children"),
551 State("control-panel", "data"), # Store
552 Input("ri-duts", "value"),
553 Input("ri-ttypes", "value"),
554 Input("ri-cadences", "value"),
555 Input("dd-tbeds", "value"),
558 def _update_ctrl_panel(cp_data: dict, dut: str, ttype: str, cadence:str,
559 tbed: str, href: str) -> tuple:
560 """Update the application when the event is detected.
562 :param cp_data: Current status of the control panel stored in
564 :param dut: Input - DUT name.
565 :param ttype: Input - Test type.
566 :param cadence: Input - The cadence of the job.
567 :param tbed: Input - The test bed.
568 :param href: Input - The URL provided by the browser.
575 :returns: New values for web page elements.
579 ctrl_panel = ControlPanel(self._cp_default, cp_data)
582 parsed_url = url_decode(href)
584 url_params = parsed_url["params"]
588 trigger_id = callback_context.triggered[0]["prop_id"].split(".")[0]
589 if trigger_id == "ri-duts":
590 ttype_opts = generate_options(get_ttypes(self._job_info, dut))
591 ttype_val = ttype_opts[0]["value"]
592 cad_opts = generate_options(get_cadences(
593 self._job_info, dut, ttype_val))
594 cad_val = cad_opts[0]["value"]
595 tbed_opts = generate_options(get_test_beds(
596 self._job_info, dut, ttype_val, cad_val))
597 tbed_val = tbed_opts[0]["value"]
599 "ri-duts-value": dut,
600 "ri-ttypes-options": ttype_opts,
601 "ri-ttypes-value": ttype_val,
602 "ri-cadences-options": cad_opts,
603 "ri-cadences-value": cad_val,
604 "dd-tbeds-options": tbed_opts,
605 "dd-tbeds-value": tbed_val
607 elif trigger_id == "ri-ttypes":
608 cad_opts = generate_options(get_cadences(
609 self._job_info, ctrl_panel.get("ri-duts-value"), ttype))
610 cad_val = cad_opts[0]["value"]
611 tbed_opts = generate_options(get_test_beds(
612 self._job_info, ctrl_panel.get("ri-duts-value"), ttype,
614 tbed_val = tbed_opts[0]["value"]
616 "ri-ttypes-value": ttype,
617 "ri-cadences-options": cad_opts,
618 "ri-cadences-value": cad_val,
619 "dd-tbeds-options": tbed_opts,
620 "dd-tbeds-value": tbed_val
622 elif trigger_id == "ri-cadences":
623 tbed_opts = generate_options(get_test_beds(
624 self._job_info, ctrl_panel.get("ri-duts-value"),
625 ctrl_panel.get("ri-ttypes-value"), cadence))
626 tbed_val = tbed_opts[0]["value"]
628 "ri-cadences-value": cadence,
629 "dd-tbeds-options": tbed_opts,
630 "dd-tbeds-value": tbed_val
632 elif trigger_id == "dd-tbeds":
634 "dd-tbeds-value": tbed
636 elif trigger_id == "url":
638 new_job = url_params.get("job", list())[0]
640 job_params = set_job_params(self._job_info, new_job)
641 ctrl_panel = ControlPanel(
643 "ri-ttypes-options": job_params["ttypes"],
644 "ri-cadences-options": job_params["cadences"],
645 "dd-tbeds-options": job_params["tbeds"],
646 "ri-duts-value": job_params["dut"],
647 "ri-ttypes-value": job_params["ttype"],
648 "ri-cadences-value": job_params["cadence"],
649 "dd-tbeds-value": job_params["tbed"],
650 "al-job-children": job_params["job"]
655 ctrl_panel = ControlPanel(self._cp_default, cp_data)
659 ctrl_panel.get("ri-duts-value"),
660 ctrl_panel.get("ri-ttypes-value"),
661 ctrl_panel.get("ri-cadences-value"),
662 ctrl_panel.get("dd-tbeds-value")
665 ctrl_panel.set({"al-job-children": job})
666 plotting_area = self._get_plotting_area(
668 gen_new_url(parsed_url, {"job": job})
675 ret_val.extend(ctrl_panel.values)
679 Output("plot-mod-url", "is_open"),
680 [Input("plot-btn-url", "n_clicks")],
681 [State("plot-mod-url", "is_open")],
683 def toggle_plot_mod_url(n, is_open):
684 """Toggle the modal window with url.
691 Output("download-stats-data", "data"),
692 State("control-panel", "data"), # Store
693 Input("plot-btn-download", "n_clicks"),
694 prevent_initial_call=True
696 def _download_data(cp_data: dict, n_clicks: int):
699 :param cp_data: Current status of the control panel stored in
701 :param n_clicks: Number of clicks on the button "Download".
704 :returns: dict of data frame content (base64 encoded) and meta data
705 used by the Download component.
711 ctrl_panel = ControlPanel(self._cp_default, cp_data)
715 ctrl_panel.get("ri-duts-value"),
716 ctrl_panel.get("ri-ttypes-value"),
717 ctrl_panel.get("ri-cadences-value"),
718 ctrl_panel.get("dd-tbeds-value")
721 data = select_data(self._data, job)
722 data = data.drop(columns=["job", ])
724 return dcc.send_data_frame(
725 data.T.to_csv, f"{job}-{C.STATS_DOWNLOAD_FILE_NAME}")
728 Output("row-metadata", "children"),
729 Output("offcanvas-metadata", "is_open"),
730 Input("graph-passed", "clickData"),
731 Input("graph-duration", "clickData"),
732 prevent_initial_call=True
734 def _show_metadata_from_graphs(
735 passed_data: dict, duration_data: dict) -> tuple:
736 """Generates the data for the offcanvas displayed when a particular
737 point in a graph is clicked on.
739 :param passed_data: The data from the clicked point in the graph
740 displaying the pass/fail data.
741 :param duration_data: The data from the clicked point in the graph
742 displaying the duration data.
743 :type passed_data: dict
744 :type duration data: dict
745 :returns: The data to be displayed on the offcanvas (job statistics
746 and the list of failed tests) and the information to show the
748 :rtype: tuple(list, bool)
751 if not (passed_data or duration_data):
756 title = "Job Statistics"
757 trigger_id = callback_context.triggered[0]["prop_id"].split(".")[0]
758 if trigger_id == "graph-passed":
759 graph_data = passed_data["points"][0].get("hovertext", "")
760 elif trigger_id == "graph-duration":
761 graph_data = duration_data["points"][0].get("text", "")
763 lst_graph_data = graph_data.split("<br>")
765 # Prepare list of failed tests:
768 for itm in lst_graph_data:
769 if "csit-ref:" in itm:
770 job, build = itm.split(" ")[-1].split("/")
773 fail_tests = self._data.loc[
774 (self._data["job"] == job) &
775 (self._data["build"] == build)
776 ]["lst_failed"].values[0]
782 # Create the content of the offcanvas:
785 class_name="gy-2 p-0",
787 dbc.CardHeader(children=[
789 target_id="metadata",
791 style={"display": "inline-block"}
798 children=[dbc.ListGroup(
807 ) for x in lst_graph_data
816 if fail_tests is not None:
819 class_name="gy-2 p-0",
822 f"List of Failed Tests ({len(fail_tests)})"
827 children=[dbc.ListGroup(
829 dbc.ListGroupItem(x) \
841 return metadata, open_canvas