-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement basic AWS client functions
- Loading branch information
Raul Martinez
committed
Sep 3, 2023
1 parent
3b97829
commit 0262fb6
Showing
9 changed files
with
792 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
""""AWS boto functions for pi_reports""" | ||
|
||
from datetime import datetime | ||
from typing import Any, List, Literal | ||
|
||
from boto3.session import Session | ||
from mypy_boto3_pi.client import PIClient | ||
from mypy_boto3_pi.type_defs import GetResourceMetricsResponseTypeDef, MetricQueryTypeDef | ||
from mypy_boto3_rds.client import RDSClient | ||
from mypy_boto3_rds.type_defs import DBInstanceMessageTypeDef | ||
|
||
from aws_pi_reports.time import parse_time | ||
|
||
|
||
class PIAwsClient: | ||
"""PI AWS Client""" | ||
|
||
def __init__(self, session: Session) -> None: | ||
self._session: Session = session | ||
self._pi_client: PIClient = self._session.client("pi") # pyright: ignore[reportUnknownMemberType] | ||
|
||
def pi_get_resource_metrics( | ||
self, | ||
service_type: Literal["DOCDB", "RDS"], | ||
identifier: str, | ||
metric_queries: List[MetricQueryTypeDef], | ||
start_time: datetime, | ||
end_time: datetime, | ||
period_in_seconds: int = 3600, | ||
max_results: int = 100, | ||
next_token: str = "", | ||
period_alignment: Literal["END_TIME", "START_TIME"] = "END_TIME", | ||
) -> GetResourceMetricsResponseTypeDef: | ||
result: GetResourceMetricsResponseTypeDef = self._pi_client.get_resource_metrics( | ||
ServiceType=service_type, | ||
Identifier=identifier, | ||
MetricQueries=metric_queries, | ||
StartTime=start_time, | ||
EndTime=end_time, | ||
PeriodInSeconds=period_in_seconds, | ||
MaxResults=max_results, | ||
NextToken=next_token, | ||
PeriodAlignment=period_alignment, | ||
) | ||
return result | ||
|
||
|
||
class RDSAwsCClient: | ||
"""RDS AWS Client""" | ||
|
||
def __init__( | ||
self, | ||
session: Session, | ||
) -> None: | ||
self._session: Session = session | ||
self._rds_client: RDSClient = self._session.client("rds") # pyright: ignore[reportUnknownMemberType] | ||
|
||
def _rds_get_attribute(self, db_instance_identifier: str, attr_name: str) -> Any: | ||
response: DBInstanceMessageTypeDef = self._rds_client.describe_db_instances(DBInstanceIdentifier=db_instance_identifier) | ||
return response["DBInstances"][0][attr_name] # type: ignore # pyright: ignore[reportUnknownVariableType] | ||
|
||
def rds_get_database_instance_resource_id(self, db_instance_identifier: str) -> str: | ||
return str(self._rds_get_attribute(db_instance_identifier=db_instance_identifier, attr_name="DbiResourceId")) | ||
|
||
|
||
class AWSClient(PIAwsClient, RDSAwsCClient): | ||
"""AWS Client""" | ||
|
||
def __init__(self, aws_profile: str = "", aws_region: str = "") -> None: | ||
self._session: Session = Session(profile_name=aws_profile, region_name=aws_region) | ||
super().__init__(session=self._session) # Initialize all supers with session | ||
|
||
def get_resource_metrics_for_db_instance( | ||
self, | ||
db_instance_identifier: str, | ||
service_type: Literal["DOCDB", "RDS"], | ||
metric_queries: List[MetricQueryTypeDef], | ||
time: datetime, | ||
time_delta: str, | ||
period_in_seconds: int = 3600, | ||
max_results: int = 100, | ||
next_token: str = "", | ||
period_alignment: Literal["END_TIME", "START_TIME"] = "END_TIME", | ||
) -> GetResourceMetricsResponseTypeDef: | ||
start_time, end_time = parse_time(time, time_delta) | ||
|
||
if service_type == "RDS": | ||
resource_identifier: str = self.rds_get_database_instance_resource_id(db_instance_identifier=db_instance_identifier) | ||
else: | ||
raise NotImplementedError(f"Service type {service_type} not implemented") | ||
|
||
return self.pi_get_resource_metrics( | ||
service_type=service_type, | ||
identifier=resource_identifier, | ||
metric_queries=metric_queries, | ||
start_time=start_time, | ||
end_time=end_time, | ||
period_in_seconds=period_in_seconds, | ||
max_results=max_results, | ||
next_token=next_token, | ||
period_alignment=period_alignment, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,18 @@ | ||
"""cli for RDS reports""" | ||
|
||
import inspect | ||
from types import FrameType | ||
from typing import Union | ||
|
||
import typer | ||
|
||
app = typer.Typer( | ||
help="""Performance Insights Reports for RDS | ||
""" | ||
) | ||
|
||
|
||
@app.command() | ||
def counter_metrics() -> None: | ||
frame: Union[FrameType, None] = inspect.currentframe() | ||
f_name = frame.f_code.co_name if frame else "unknown_function" | ||
print(f"Executing {f_name}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
"""Reports module""" | ||
from __future__ import annotations | ||
|
||
from abc import ABC, abstractmethod | ||
|
||
|
||
class Report(ABC): | ||
""" | ||
Base Report interface with methods to be implemented by concrete reports | ||
""" | ||
|
||
# @property | ||
# @abstractmethod | ||
# def product(self) -> None: | ||
# pass | ||
|
||
@abstractmethod | ||
def read_report_input(self) -> None: | ||
pass | ||
|
||
@abstractmethod | ||
def processs_report_input(self) -> None: | ||
pass | ||
|
||
@abstractmethod | ||
def processs_queries_output(self) -> None: | ||
pass | ||
|
||
@abstractmethod | ||
def report(self) -> None: | ||
pass | ||
|
||
|
||
class StandardRDSReport(Report): | ||
""" | ||
Standard RDS Report | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
{ | ||
"metric-queries":[ | ||
{ | ||
"Metric":"os.cpuUtilization.user.avg" | ||
}, | ||
{ | ||
"Metric":"os.cpuUtilization.idle.avg" | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.API.html |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import re | ||
from datetime import datetime, timedelta | ||
from typing import Dict, Tuple, Union | ||
|
||
duration_regex_str = "^((?P<weeks>[-+\\d]+?)w|(?P<days>[-+\\d]+?)d|(?P<hours>[-+\\d]+?)h|(?P<minutes>[-+\\d]+?)m)$" | ||
duration_regex = re.compile(r"{duration_regex_str}") | ||
|
||
|
||
def parse_time(time: datetime, duration: str) -> Tuple[datetime, datetime]: | ||
parts: Union[re.Match[str], None] = duration_regex.match(duration) | ||
if not parts: | ||
raise SyntaxError(f"Invalid duration string: {duration}. Expected format: {duration_regex_str}") | ||
groups = parts.groupdict() | ||
time_params: Dict[str, int] = {} | ||
name = next(iter(groups)) | ||
value: int = int(groups[name]) | ||
time_params[name] = abs(value) | ||
return (time, time + timedelta(**time_params)) if value > 0 else (time - timedelta(**time_params), time) |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters