2021-12-01 12:46:28 +05:30
|
|
|
# Copyright 2021 Collate
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
2021-08-02 15:08:30 +05:30
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2022-08-02 09:13:46 +02:00
|
|
|
|
2022-10-10 16:23:47 +05:30
|
|
|
"""
|
|
|
|
Helpers module for ingestion related methods
|
|
|
|
"""
|
|
|
|
|
2022-10-26 11:18:08 +02:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2022-06-03 11:43:40 +02:00
|
|
|
import re
|
2021-08-01 14:27:44 -07:00
|
|
|
from datetime import datetime, timedelta
|
2022-10-07 07:02:27 +02:00
|
|
|
from functools import wraps
|
2023-03-28 12:59:45 +02:00
|
|
|
from math import floor, log
|
2022-08-17 14:39:50 +05:30
|
|
|
from time import perf_counter
|
2022-10-26 11:18:08 +02:00
|
|
|
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
|
2022-10-15 14:56:30 +02:00
|
|
|
|
|
|
|
from metadata.generated.schema.entity.data.chart import ChartType
|
2022-07-19 12:58:58 +02:00
|
|
|
from metadata.generated.schema.entity.data.table import Column, Table
|
2022-10-26 11:18:08 +02:00
|
|
|
from metadata.generated.schema.type.tagLabel import TagLabel
|
2022-04-29 06:54:30 +02:00
|
|
|
from metadata.utils.logger import utils_logger
|
2021-08-01 14:27:44 -07:00
|
|
|
|
2022-04-29 06:54:30 +02:00
|
|
|
logger = utils_logger()
|
2022-02-23 00:20:36 +05:30
|
|
|
|
2022-10-31 18:12:26 +05:30
|
|
|
|
|
|
|
class BackupRestoreArgs:
|
|
|
|
def __init__( # pylint: disable=too-many-arguments
|
|
|
|
self,
|
|
|
|
host: str,
|
|
|
|
user: str,
|
|
|
|
password: str,
|
|
|
|
database: str,
|
|
|
|
port: str,
|
|
|
|
options: List[str],
|
|
|
|
arguments: List[str],
|
|
|
|
schema: Optional[str] = None,
|
|
|
|
):
|
|
|
|
self.host = host
|
|
|
|
self.user = user
|
|
|
|
self.password = password
|
|
|
|
self.database = database
|
|
|
|
self.port = port
|
|
|
|
self.options = options
|
|
|
|
self.arguments = arguments
|
|
|
|
self.schema = schema
|
|
|
|
|
|
|
|
|
|
|
|
class DockerActions:
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
start: bool,
|
|
|
|
stop: bool,
|
|
|
|
pause: bool,
|
|
|
|
resume: bool,
|
|
|
|
clean: bool,
|
|
|
|
reset_db: bool,
|
|
|
|
):
|
|
|
|
self.start = start
|
|
|
|
self.stop = stop
|
|
|
|
self.pause = pause
|
|
|
|
self.resume = resume
|
|
|
|
self.clean = clean
|
|
|
|
self.reset_db = reset_db
|
|
|
|
|
|
|
|
|
2022-06-08 14:33:48 +05:30
|
|
|
om_chart_type_dict = {
|
|
|
|
"line": ChartType.Line,
|
|
|
|
"big_number": ChartType.Line,
|
|
|
|
"big_number_total": ChartType.Line,
|
|
|
|
"dual_line": ChartType.Line,
|
|
|
|
"line_multi": ChartType.Line,
|
|
|
|
"table": ChartType.Table,
|
|
|
|
"dist_bar": ChartType.Bar,
|
|
|
|
"bar": ChartType.Bar,
|
|
|
|
"box_plot": ChartType.BoxPlot,
|
|
|
|
"boxplot": ChartType.BoxPlot,
|
|
|
|
"histogram": ChartType.Histogram,
|
|
|
|
"treemap": ChartType.Area,
|
|
|
|
"area": ChartType.Area,
|
|
|
|
"pie": ChartType.Pie,
|
|
|
|
"text": ChartType.Text,
|
|
|
|
"scatter": ChartType.Scatter,
|
|
|
|
}
|
|
|
|
|
2021-08-01 14:27:44 -07:00
|
|
|
|
2022-08-17 14:39:50 +05:30
|
|
|
def calculate_execution_time(func):
|
2022-10-10 16:23:47 +05:30
|
|
|
"""
|
|
|
|
Method to calculate workflow execution time
|
|
|
|
"""
|
|
|
|
|
2022-10-07 07:02:27 +02:00
|
|
|
@wraps(func)
|
2022-08-17 14:39:50 +05:30
|
|
|
def calculate_debug_time(*args, **kwargs):
|
|
|
|
start = perf_counter()
|
|
|
|
func(*args, **kwargs)
|
|
|
|
end = perf_counter()
|
|
|
|
logger.debug(
|
|
|
|
f"{func.__name__} executed in { pretty_print_time_duration(end - start)}"
|
|
|
|
)
|
|
|
|
|
|
|
|
return calculate_debug_time
|
|
|
|
|
|
|
|
|
|
|
|
def calculate_execution_time_generator(func):
|
2022-10-10 16:23:47 +05:30
|
|
|
"""
|
|
|
|
Generator method to calculate workflow execution time
|
|
|
|
"""
|
|
|
|
|
2022-08-17 14:39:50 +05:30
|
|
|
def calculate_debug_time(*args, **kwargs):
|
|
|
|
start = perf_counter()
|
|
|
|
yield from func(*args, **kwargs)
|
|
|
|
end = perf_counter()
|
|
|
|
logger.debug(
|
|
|
|
f"{func.__name__} executed in { pretty_print_time_duration(end - start)}"
|
|
|
|
)
|
|
|
|
|
|
|
|
return calculate_debug_time
|
|
|
|
|
|
|
|
|
2022-10-26 11:18:08 +02:00
|
|
|
def pretty_print_time_duration(duration: Union[int, float]) -> str:
|
2022-10-10 16:23:47 +05:30
|
|
|
"""
|
|
|
|
Method to format and display the time
|
|
|
|
"""
|
|
|
|
|
2022-08-17 14:39:50 +05:30
|
|
|
days = divmod(duration, 86400)[0]
|
|
|
|
hours = divmod(duration, 3600)[0]
|
|
|
|
minutes = divmod(duration, 60)[0]
|
|
|
|
seconds = round(divmod(duration, 60)[1], 2)
|
|
|
|
if days:
|
|
|
|
return f"{days}day(s) {hours}h {minutes}m {seconds}s"
|
|
|
|
if hours:
|
|
|
|
return f"{hours}h {minutes}m {seconds}s"
|
|
|
|
if minutes:
|
|
|
|
return f"{minutes}m {seconds}s"
|
|
|
|
return f"{seconds}s"
|
|
|
|
|
|
|
|
|
2023-03-21 12:57:48 +01:00
|
|
|
def get_start_and_end(duration: int = 0):
|
2022-10-10 16:23:47 +05:30
|
|
|
"""
|
|
|
|
Method to return start and end time based on duration
|
|
|
|
"""
|
|
|
|
|
2021-08-01 14:27:44 -07:00
|
|
|
today = datetime.utcnow()
|
2021-10-14 16:48:42 +02:00
|
|
|
start = (today + timedelta(0 - duration)).replace(
|
|
|
|
hour=0, minute=0, second=0, microsecond=0
|
|
|
|
)
|
2022-06-21 18:02:50 +02:00
|
|
|
# Add one day to make sure we are handling today's queries
|
|
|
|
end = (today + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
|
2021-08-01 14:27:44 -07:00
|
|
|
return start, end
|
|
|
|
|
|
|
|
|
2022-10-10 16:23:47 +05:30
|
|
|
def snake_to_camel(snake_str):
|
|
|
|
"""
|
|
|
|
Method to convert snake case text to camel case
|
|
|
|
"""
|
|
|
|
split_str = snake_str.split("_")
|
|
|
|
split_str[0] = split_str[0].capitalize()
|
|
|
|
if len(split_str) > 1:
|
|
|
|
split_str[1:] = [u.title() for u in split_str[1:]]
|
|
|
|
return "".join(split_str)
|
2021-08-01 14:27:44 -07:00
|
|
|
|
|
|
|
|
2022-07-27 07:47:25 +02:00
|
|
|
def datetime_to_ts(date: Optional[datetime]) -> Optional[int]:
|
2022-02-13 17:51:25 +01:00
|
|
|
"""
|
2022-04-18 15:13:26 +02:00
|
|
|
Convert a given date to a timestamp as an Int in milliseconds
|
2022-02-13 17:51:25 +01:00
|
|
|
"""
|
2022-07-27 07:47:25 +02:00
|
|
|
return int(date.timestamp() * 1_000) if date else None
|
2022-02-24 01:01:03 +05:30
|
|
|
|
|
|
|
|
2022-06-03 13:42:28 +05:30
|
|
|
def get_formatted_entity_name(name: str) -> Optional[str]:
|
2022-10-10 16:23:47 +05:30
|
|
|
"""
|
|
|
|
Method to get formatted entity name
|
|
|
|
"""
|
|
|
|
|
2022-06-21 18:02:50 +02:00
|
|
|
return (
|
|
|
|
name.replace("[", "").replace("]", "").replace("<default>.", "")
|
|
|
|
if name
|
|
|
|
else None
|
|
|
|
)
|
2022-03-22 18:29:03 +05:30
|
|
|
|
|
|
|
|
2022-06-03 11:43:40 +02:00
|
|
|
def replace_special_with(raw: str, replacement: str) -> str:
|
|
|
|
"""
|
|
|
|
Replace special characters in a string by a hyphen
|
|
|
|
:param raw: raw string to clean
|
|
|
|
:param replacement: string used to replace
|
|
|
|
:return: clean string
|
|
|
|
"""
|
|
|
|
return re.sub(r"[^a-zA-Z0-9]", replacement, raw)
|
2022-06-08 14:33:48 +05:30
|
|
|
|
|
|
|
|
|
|
|
def get_standard_chart_type(raw_chart_type: str) -> str:
|
|
|
|
"""
|
|
|
|
Get standard chart type supported by OpenMetadata based on raw chart type input
|
|
|
|
:param raw_chart_type: raw chart type to be standardize
|
|
|
|
:return: standard chart type
|
|
|
|
"""
|
|
|
|
return om_chart_type_dict.get(raw_chart_type.lower(), ChartType.Other)
|
|
|
|
|
|
|
|
|
2022-10-15 14:56:30 +02:00
|
|
|
def find_in_iter(element: Any, container: Iterable[Any]) -> Optional[Any]:
|
2022-06-21 18:02:50 +02:00
|
|
|
"""
|
|
|
|
If the element is in the container, return it.
|
|
|
|
Otherwise, return None
|
|
|
|
:param element: to find
|
|
|
|
:param container: container with element
|
|
|
|
:return: element or None
|
|
|
|
"""
|
2022-10-15 14:56:30 +02:00
|
|
|
return next((elem for elem in container if elem == element), None)
|
2022-07-19 12:58:58 +02:00
|
|
|
|
|
|
|
|
|
|
|
def find_column_in_table(column_name: str, table: Table) -> Optional[Column]:
|
|
|
|
"""
|
|
|
|
If the column exists in the table, return it
|
|
|
|
"""
|
|
|
|
return next(
|
|
|
|
(col for col in table.columns if col.name.__root__ == column_name), None
|
|
|
|
)
|
2022-08-03 12:01:57 +02:00
|
|
|
|
|
|
|
|
2022-10-15 14:56:30 +02:00
|
|
|
def find_column_in_table_with_index(
|
|
|
|
column_name: str, table: Table
|
|
|
|
) -> Optional[Tuple[int, Column]]:
|
|
|
|
"""Return a column and its index in a Table Entity
|
|
|
|
|
|
|
|
Args:
|
|
|
|
column_name (str): column to find
|
|
|
|
table (Table): Table Entity
|
|
|
|
|
|
|
|
Return:
|
|
|
|
A tuple of Index, Column if the column is found
|
|
|
|
"""
|
|
|
|
col_index, col = next(
|
|
|
|
(
|
|
|
|
(col_index, col)
|
|
|
|
for col_index, col in enumerate(table.columns)
|
|
|
|
if str(col.name.__root__).lower() == column_name.lower()
|
|
|
|
),
|
|
|
|
(None, None),
|
|
|
|
)
|
|
|
|
|
|
|
|
return col_index, col
|
|
|
|
|
|
|
|
|
2022-08-03 12:01:57 +02:00
|
|
|
def list_to_dict(original: Optional[List[str]], sep: str = "=") -> Dict[str, str]:
|
|
|
|
"""
|
|
|
|
Given a list with strings that have a separator,
|
|
|
|
convert that to a dictionary of key-value pairs
|
|
|
|
"""
|
|
|
|
if not original:
|
|
|
|
return {}
|
|
|
|
|
|
|
|
split_original = [
|
|
|
|
(elem.split(sep)[0], elem.split(sep)[1]) for elem in original if sep in elem
|
|
|
|
]
|
|
|
|
return dict(split_original)
|
2022-10-05 16:09:33 +02:00
|
|
|
|
|
|
|
|
|
|
|
def clean_up_starting_ending_double_quotes_in_string(string: str) -> str:
|
|
|
|
"""Remove start and ending double quotes in a string
|
|
|
|
|
|
|
|
Args:
|
|
|
|
string (str): a string
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
TypeError: An error occure checking the type of `string`
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str: a string with no double quotes
|
|
|
|
"""
|
|
|
|
if not isinstance(string, str):
|
|
|
|
raise TypeError(f"{string}, must be of type str, instead got `{type(string)}`")
|
|
|
|
|
|
|
|
return string.strip('"')
|
2022-10-24 17:22:22 +02:00
|
|
|
|
|
|
|
|
|
|
|
def insensitive_replace(raw_str: str, to_replace: str, replace_by: str) -> str:
|
|
|
|
"""Replace `to_replace` by `replace_by` in `raw_str` ignoring the raw_str case.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
raw_str:str: Define the string that will be searched
|
|
|
|
to_replace:str: Specify the string to be replaced
|
|
|
|
replace_by:str: Replace the to_replace:str parameter in the raw_str:str string
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A string where the given to_replace is replaced by replace_by in raw_str, ignoring case
|
|
|
|
"""
|
|
|
|
|
2023-05-03 18:08:54 +05:30
|
|
|
return re.sub(to_replace, replace_by, raw_str, flags=re.IGNORECASE | re.DOTALL)
|
2022-10-24 17:22:22 +02:00
|
|
|
|
|
|
|
|
|
|
|
def insensitive_match(raw_str: str, to_match: str) -> bool:
|
|
|
|
"""Match `to_match` in `raw_str` ignoring the raw_str case.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
raw_str:str: Define the string that will be searched
|
|
|
|
to_match:str: Specify the string to be matched
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
True if `to_match` matches in `raw_str`, ignoring case. Otherwise, false.
|
|
|
|
"""
|
|
|
|
|
2023-05-03 18:08:54 +05:30
|
|
|
return re.match(to_match, raw_str, flags=re.IGNORECASE | re.DOTALL) is not None
|
2022-10-26 11:18:08 +02:00
|
|
|
|
|
|
|
|
|
|
|
def get_entity_tier_from_tags(tags: list[TagLabel]) -> Optional[str]:
|
|
|
|
"""_summary_
|
|
|
|
|
|
|
|
Args:
|
|
|
|
tags (list[TagLabel]): list of tags
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Optional[str]
|
|
|
|
"""
|
2022-11-07 17:08:20 +01:00
|
|
|
if not tags:
|
|
|
|
return None
|
2022-10-26 11:18:08 +02:00
|
|
|
return next(
|
|
|
|
(
|
|
|
|
tag.tagFQN.__root__
|
|
|
|
for tag in tags
|
|
|
|
if tag.tagFQN.__root__.lower().startswith("tier")
|
|
|
|
),
|
|
|
|
None,
|
|
|
|
)
|
2023-03-28 12:59:45 +02:00
|
|
|
|
|
|
|
|
|
|
|
def format_large_string_numbers(number: Union[float, int]) -> str:
|
|
|
|
"""Format large string number to a human readable format.
|
|
|
|
(e.g. 1,000,000 -> 1M, 1,000,000,000 -> 1B, etc)
|
|
|
|
|
|
|
|
Args:
|
|
|
|
number: number
|
|
|
|
"""
|
|
|
|
if number == 0:
|
|
|
|
return "0"
|
|
|
|
units = ["", "K", "M", "B", "T"]
|
|
|
|
constant_k = 1000.0
|
|
|
|
magnitude = int(floor(log(abs(number), constant_k)))
|
|
|
|
return f"{number / constant_k**magnitude:.2f}{units[magnitude]}"
|
2023-04-10 15:18:49 +05:30
|
|
|
|
|
|
|
|
|
|
|
def clean_uri(uri: str) -> str:
|
|
|
|
"""
|
|
|
|
if uri is like http://localhost:9000/
|
|
|
|
then remove the end / and
|
|
|
|
make it http://localhost:9000
|
|
|
|
"""
|
|
|
|
return uri[:-1] if uri.endswith("/") else uri
|