1 # Copyright (c) 2022 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 """Prepare data for Plotly Dash applications.
18 import awswrangler as wr
20 from yaml import load, FullLoader, YAMLError
21 from datetime import datetime, timedelta
24 from pandas import DataFrame
25 from awswrangler.exceptions import EmptyDataFrame, NoFilesFound
29 """Gets the data from parquets and stores it for further use by dash
33 def __init__(self, data_spec_file: str, debug: bool=False) -> None:
34 """Initialize the Data object.
36 :param data_spec_file: Path to file specifying the data to be read from
38 :param debug: If True, the debuf information is printed to stdout.
39 :type data_spec_file: str
41 :raises RuntimeError: if it is not possible to open data_spec_file or it
42 is not a valid yaml file.
46 self._data_spec_file = data_spec_file
49 # Specification of data to be read from parquets:
50 self._data_spec = None
52 # Data frame to keep the data:
57 with open(self._data_spec_file, "r") as file_read:
58 self._data_spec = load(file_read, Loader=FullLoader)
59 except IOError as err:
61 f"Not possible to open the file {self._data_spec_file,}\n{err}"
63 except YAMLError as err:
65 f"An error occurred while parsing the specification file "
66 f"{self._data_spec_file,}\n"
74 def _get_columns(self, parquet: str) -> list:
75 """Get the list of columns from the data specification file to be read
78 :param parquet: The parquet's name.
80 :raises RuntimeError: if the parquet is not defined in the data
81 specification file or it does not have any columns specified.
82 :returns: List of columns.
87 return self._data_spec[parquet]["columns"]
88 except KeyError as err:
90 f"The parquet {parquet} is not defined in the specification "
91 f"file {self._data_spec_file} or it does not have any columns "
95 def _get_path(self, parquet: str) -> str:
96 """Get the path from the data specification file to be read from
99 :param parquet: The parquet's name.
101 :raises RuntimeError: if the parquet is not defined in the data
102 specification file or it does not have the path specified.
108 return self._data_spec[parquet]["path"]
109 except KeyError as err:
111 f"The parquet {parquet} is not defined in the specification "
112 f"file {self._data_spec_file} or it does not have the path "
116 def _create_dataframe_from_parquet(self,
117 path, partition_filter=None,
119 validate_schema=False,
120 last_modified_begin=None,
121 last_modified_end=None,
122 days=None) -> DataFrame:
123 """Read parquet stored in S3 compatible storage and returns Pandas
126 :param path: S3 prefix (accepts Unix shell-style wildcards)
127 (e.g. s3://bucket/prefix) or list of S3 objects paths
128 (e.g. [s3://bucket/key0, s3://bucket/key1]).
129 :param partition_filter: Callback Function filters to apply on PARTITION
130 columns (PUSH-DOWN filter). This function MUST receive a single
131 argument (Dict[str, str]) where keys are partitions names and values
132 are partitions values. Partitions values will be always strings
133 extracted from S3. This function MUST return a bool, True to read
134 the partition or False to ignore it. Ignored if dataset=False.
135 :param columns: Names of columns to read from the file(s).
136 :param validate_schema: Check that individual file schemas are all the
137 same / compatible. Schemas within a folder prefix should all be the
138 same. Disable if you have schemas that are different and want to
140 :param last_modified_begin: Filter the s3 files by the Last modified
141 date of the object. The filter is applied only after list all s3
143 :param last_modified_end: Filter the s3 files by the Last modified date
144 of the object. The filter is applied only after list all s3 files.
145 :type path: Union[str, List[str]]
146 :type partition_filter: Callable[[Dict[str, str]], bool], optional
147 :type columns: List[str], optional
148 :type validate_schema: bool, optional
149 :type last_modified_begin: datetime, optional
150 :type last_modified_end: datetime, optional
151 :returns: Pandas DataFrame or None if DataFrame cannot be fetched.
157 last_modified_begin = datetime.now(tz=UTC) - timedelta(days=days)
159 df = wr.s3.read_parquet(
161 path_suffix="parquet",
163 validate_schema=validate_schema,
167 partition_filter=partition_filter,
168 last_modified_begin=last_modified_begin,
169 last_modified_end=last_modified_end
172 df.info(verbose=True, memory_usage='deep')
175 f"Creation of dataframe {path} took: {time() - start}"
178 except NoFilesFound as err:
179 logging.error(f"No parquets found.\n{err}")
180 except EmptyDataFrame as err:
181 logging.error(f"No data.\n{err}")
186 def read_stats(self, days: int=None) -> tuple:
187 """Read statistics from parquet.
190 - Suite Result Analysis (SRA) partition,
191 - NDRPDR trending partition,
192 - MRR trending partition.
194 :param days: Number of days back to the past for which the data will be
197 :returns: tuple of pandas DataFrame-s with data read from specified
199 :rtype: tuple of pandas DataFrame-s
202 l_stats = lambda part: True if part["stats_type"] == "sra" else False
203 l_mrr = lambda part: True if part["test_type"] == "mrr" else False
204 l_ndrpdr = lambda part: True if part["test_type"] == "ndrpdr" else False
207 self._create_dataframe_from_parquet(
208 path=self._get_path("statistics"),
209 partition_filter=l_stats,
210 columns=self._get_columns("statistics"),
213 self._create_dataframe_from_parquet(
214 path=self._get_path("statistics-trending-mrr"),
215 partition_filter=l_mrr,
216 columns=self._get_columns("statistics-trending-mrr"),
219 self._create_dataframe_from_parquet(
220 path=self._get_path("statistics-trending-ndrpdr"),
221 partition_filter=l_ndrpdr,
222 columns=self._get_columns("statistics-trending-ndrpdr"),
227 def read_trending_mrr(self, days: int=None) -> DataFrame:
228 """Read MRR data partition from parquet.
230 :param days: Number of days back to the past for which the data will be
233 :returns: Pandas DataFrame with read data.
237 lambda_f = lambda part: True if part["test_type"] == "mrr" else False
239 return self._create_dataframe_from_parquet(
240 path=self._get_path("trending-mrr"),
241 partition_filter=lambda_f,
242 columns=self._get_columns("trending-mrr"),
246 def read_trending_ndrpdr(self, days: int=None) -> DataFrame:
247 """Read NDRPDR data partition from iterative parquet.
249 :param days: Number of days back to the past for which the data will be
252 :returns: Pandas DataFrame with read data.
256 lambda_f = lambda part: True if part["test_type"] == "ndrpdr" else False
258 return self._create_dataframe_from_parquet(
259 path=self._get_path("trending-ndrpdr"),
260 partition_filter=lambda_f,
261 columns=self._get_columns("trending-ndrpdr"),
265 def read_iterative_mrr(self, release: str) -> DataFrame:
266 """Read MRR data partition from iterative parquet.
268 :param release: The CSIT release from which the data will be read.
270 :returns: Pandas DataFrame with read data.
274 lambda_f = lambda part: True if part["test_type"] == "mrr" else False
276 return self._create_dataframe_from_parquet(
277 path=self._get_path("iterative-mrr").format(release=release),
278 partition_filter=lambda_f,
279 columns=self._get_columns("iterative-mrr")
282 def read_iterative_ndrpdr(self, release: str) -> DataFrame:
283 """Read NDRPDR data partition from parquet.
285 :param release: The CSIT release from which the data will be read.
287 :returns: Pandas DataFrame with read data.
291 lambda_f = lambda part: True if part["test_type"] == "ndrpdr" else False
293 return self._create_dataframe_from_parquet(
294 path=self._get_path("iterative-ndrpdr").format(release=release),
295 partition_filter=lambda_f,
296 columns=self._get_columns("iterative-ndrpdr")