boto3-assist 0.1.14__py3-none-any.whl → 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- boto3_assist/boto3session.py +3 -2
- boto3_assist/cloudwatch/cloudwatch_connection.py +84 -0
- boto3_assist/cloudwatch/cloudwatch_connection_tracker.py +17 -0
- boto3_assist/cloudwatch/cloudwatch_log_connection.py +62 -0
- boto3_assist/cloudwatch/cloudwatch_logs.py +39 -0
- boto3_assist/cloudwatch/cloudwatch_query.py +191 -0
- boto3_assist/connection.py +101 -0
- boto3_assist/connection_tracker.py +8 -8
- boto3_assist/dynamodb/dynamodb.py +30 -19
- boto3_assist/dynamodb/dynamodb_connection.py +31 -2
- boto3_assist/dynamodb/dynamodb_index.py +27 -0
- boto3_assist/dynamodb/dynamodb_iservice.py +4 -0
- boto3_assist/dynamodb/dynamodb_model_base.py +6 -7
- boto3_assist/dynamodb/dynamodb_reserved_words.py +6 -3
- boto3_assist/dynamodb/dynamodb_reserved_words.txt +0 -1
- boto3_assist/ec2/ec2_connection.py +3 -0
- boto3_assist/environment_services/environment_loader.py +67 -3
- boto3_assist/environment_services/environment_variables.py +4 -0
- boto3_assist/errors/custom_exceptions.py +34 -0
- boto3_assist/s3/s3.py +476 -0
- boto3_assist/s3/s3_connection.py +120 -0
- boto3_assist/utilities/file_operations.py +105 -0
- boto3_assist/utilities/http_utility.py +42 -0
- boto3_assist/version.py +1 -1
- {boto3_assist-0.1.14.dist-info → boto3_assist-0.2.1.dist-info}/METADATA +1 -3
- boto3_assist-0.2.1.dist-info/RECORD +43 -0
- {boto3_assist-0.1.14.dist-info → boto3_assist-0.2.1.dist-info}/WHEEL +1 -1
- boto3_assist-0.1.14.dist-info/RECORD +0 -32
- {boto3_assist-0.1.14.dist-info → boto3_assist-0.2.1.dist-info}/licenses/LICENSE-EXPLAINED.txt +0 -0
- {boto3_assist-0.1.14.dist-info → boto3_assist-0.2.1.dist-info}/licenses/LICENSE.txt +0 -0
boto3_assist/boto3session.py
CHANGED
|
@@ -45,6 +45,7 @@ class Boto3SessionManager:
|
|
|
45
45
|
self.aws_access_key_id = aws_access_key_id
|
|
46
46
|
self.aws_secret_access_key = aws_secret_access_key
|
|
47
47
|
self.aws_session_token = aws_session_token
|
|
48
|
+
|
|
48
49
|
self.__session: Any = None
|
|
49
50
|
self.__client: Any = None
|
|
50
51
|
self.__resource: Any = None
|
|
@@ -90,7 +91,7 @@ class Boto3SessionManager:
|
|
|
90
91
|
|
|
91
92
|
def __get_aws_session(
|
|
92
93
|
self, aws_profile: Optional[str] = None, aws_region: Optional[str] = None
|
|
93
|
-
) -> boto3.Session:
|
|
94
|
+
) -> boto3.Session | None:
|
|
94
95
|
"""Get a boto3 session for AWS."""
|
|
95
96
|
logger.debug({"profile": aws_profile, "region": aws_region})
|
|
96
97
|
try:
|
|
@@ -153,7 +154,7 @@ class Boto3SessionManager:
|
|
|
153
154
|
)
|
|
154
155
|
return self.__resource
|
|
155
156
|
|
|
156
|
-
def __create_boto3_session(self) -> boto3.Session:
|
|
157
|
+
def __create_boto3_session(self) -> boto3.Session | None:
|
|
157
158
|
try:
|
|
158
159
|
session = boto3.Session(
|
|
159
160
|
profile_name=self.aws_profile,
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Geek Cafe, LLC
|
|
3
|
+
Maintainers: Eric Wilson
|
|
4
|
+
MIT License. See Project Root for the license information.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Optional
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from aws_lambda_powertools import Logger
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
from boto3_assist.cloudwatch.cloudwatch_connection_tracker import (
|
|
14
|
+
CloudWatchConnectionTracker,
|
|
15
|
+
)
|
|
16
|
+
from boto3_assist.connection import Connection
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from mypy_boto3_cloudwatch import CloudWatchClient, CloudWatchServiceResource
|
|
20
|
+
else:
|
|
21
|
+
CloudWatchClient = object
|
|
22
|
+
CloudWatchServiceResource = object
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
logger = Logger()
|
|
26
|
+
tracker: CloudWatchConnectionTracker = CloudWatchConnectionTracker()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class CloudWatchConnection(Connection):
|
|
30
|
+
"""CW Environment"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
*,
|
|
35
|
+
aws_profile: Optional[str] = None,
|
|
36
|
+
aws_region: Optional[str] = None,
|
|
37
|
+
aws_access_key_id: Optional[str] = None,
|
|
38
|
+
aws_secret_access_key: Optional[str] = None,
|
|
39
|
+
) -> None:
|
|
40
|
+
super().__init__(
|
|
41
|
+
service_name="cloudwatch",
|
|
42
|
+
aws_profile=aws_profile,
|
|
43
|
+
aws_region=aws_region,
|
|
44
|
+
aws_access_key_id=aws_access_key_id,
|
|
45
|
+
aws_secret_access_key=aws_secret_access_key,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
self.__client: CloudWatchClient | None = None
|
|
49
|
+
self.__resource: CloudWatchServiceResource | None = None
|
|
50
|
+
|
|
51
|
+
self.raise_on_error: bool = True
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def client(self) -> CloudWatchClient:
|
|
55
|
+
"""CloudWatch Client Connection"""
|
|
56
|
+
if self.__client is None:
|
|
57
|
+
logger.info("Creating CloudWatch Client")
|
|
58
|
+
self.__client = self.session.client
|
|
59
|
+
|
|
60
|
+
if self.raise_on_error and self.__client is None:
|
|
61
|
+
raise RuntimeError("CloudWatch Client is not available")
|
|
62
|
+
return self.__client
|
|
63
|
+
|
|
64
|
+
@client.setter
|
|
65
|
+
def client(self, value: CloudWatchClient):
|
|
66
|
+
logger.info("Setting CloudWatch Client")
|
|
67
|
+
self.__client = value
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def resource(self) -> CloudWatchServiceResource:
|
|
71
|
+
"""CloudWatch Resource Connection"""
|
|
72
|
+
if self.__resource is None:
|
|
73
|
+
logger.info("Creating CloudWatch Resource")
|
|
74
|
+
self.__resource = self.session.resource
|
|
75
|
+
|
|
76
|
+
if self.raise_on_error and self.__resource is None:
|
|
77
|
+
raise RuntimeError("CloudWatch Resource is not available")
|
|
78
|
+
|
|
79
|
+
return self.__resource
|
|
80
|
+
|
|
81
|
+
@resource.setter
|
|
82
|
+
def resource(self, value: CloudWatchServiceResource):
|
|
83
|
+
logger.info("Setting CloudWatch Resource")
|
|
84
|
+
self.__resource = value
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Geek Cafe, LLC
|
|
3
|
+
Maintainers: Eric Wilson
|
|
4
|
+
MIT License. See Project Root for the license information.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from boto3_assist.connection_tracker import ConnectionTracker
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CloudWatchConnectionTracker(ConnectionTracker):
|
|
11
|
+
"""
|
|
12
|
+
Tracks CloudWatch Connection Requests.
|
|
13
|
+
Useful in for performance tuning and debugging.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self) -> None:
|
|
17
|
+
super().__init__("CloudWatch")
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Geek Cafe, LLC
|
|
3
|
+
Maintainers: Eric Wilson
|
|
4
|
+
MIT License. See Project Root for the license information.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Optional
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from aws_lambda_powertools import Logger
|
|
11
|
+
|
|
12
|
+
from boto3_assist.cloudwatch.cloudwatch_connection_tracker import (
|
|
13
|
+
CloudWatchConnectionTracker,
|
|
14
|
+
)
|
|
15
|
+
from boto3_assist.connection import Connection
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from mypy_boto3_logs import CloudWatchLogsClient
|
|
19
|
+
else:
|
|
20
|
+
CloudWatchLogsClient = object
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
logger = Logger()
|
|
24
|
+
tracker: CloudWatchConnectionTracker = CloudWatchConnectionTracker()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class CloudWatchConnection(Connection):
|
|
28
|
+
"""CW Logs Environment"""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
*,
|
|
33
|
+
aws_profile: Optional[str] = None,
|
|
34
|
+
aws_region: Optional[str] = None,
|
|
35
|
+
aws_access_key_id: Optional[str] = None,
|
|
36
|
+
aws_secret_access_key: Optional[str] = None,
|
|
37
|
+
) -> None:
|
|
38
|
+
super().__init__(
|
|
39
|
+
service_name="logs",
|
|
40
|
+
aws_profile=aws_profile,
|
|
41
|
+
aws_region=aws_region,
|
|
42
|
+
aws_access_key_id=aws_access_key_id,
|
|
43
|
+
aws_secret_access_key=aws_secret_access_key,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
self.__client: CloudWatchLogsClient | None = None
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def client(self) -> CloudWatchLogsClient:
|
|
50
|
+
"""CloudWatch Client Connection"""
|
|
51
|
+
if self.__client is None:
|
|
52
|
+
logger.debug("Creating CloudWatch Client")
|
|
53
|
+
self.__client = self.session.client
|
|
54
|
+
|
|
55
|
+
if self.raise_on_error and self.__client is None:
|
|
56
|
+
raise RuntimeError("CloudWatch Client is not available")
|
|
57
|
+
return self.__client
|
|
58
|
+
|
|
59
|
+
@client.setter
|
|
60
|
+
def client(self, value: CloudWatchLogsClient):
|
|
61
|
+
logger.debug("Setting CloudWatch Client")
|
|
62
|
+
self.__client = value
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Geek Cafe, LLC
|
|
3
|
+
Maintainers: Eric Wilson
|
|
4
|
+
MIT License. See Project Root for the license information.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Optional, List, Dict, Any
|
|
8
|
+
from boto3_assist.cloudwatch.cloudwatch_log_connection import CloudWatchConnection
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CloudWatchLogs(CloudWatchConnection):
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
*,
|
|
15
|
+
aws_profile: Optional[str] = None,
|
|
16
|
+
aws_region: Optional[str] = None,
|
|
17
|
+
aws_access_key_id: Optional[str] = None,
|
|
18
|
+
aws_secret_access_key: Optional[str] = None,
|
|
19
|
+
) -> None:
|
|
20
|
+
super().__init__(
|
|
21
|
+
aws_profile=aws_profile,
|
|
22
|
+
aws_region=aws_region,
|
|
23
|
+
aws_access_key_id=aws_access_key_id,
|
|
24
|
+
aws_secret_access_key=aws_secret_access_key,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
def list_log_groups(self):
|
|
28
|
+
"""Retrieve all log groups in the AWS account."""
|
|
29
|
+
log_groups: List[Dict[str, Any]] = []
|
|
30
|
+
paginator = self.client.get_paginator("describe_log_groups")
|
|
31
|
+
for page in paginator.paginate():
|
|
32
|
+
log_groups.extend(page["logGroups"]) # type: ignore[arg-type]
|
|
33
|
+
return log_groups
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main():
|
|
37
|
+
query: CloudWatchLogs = CloudWatchLogs()
|
|
38
|
+
result = query.list_log_groups()
|
|
39
|
+
print(result)
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Geek Cafe, LLC
|
|
3
|
+
Maintainers: Eric Wilson
|
|
4
|
+
MIT License. See Project Root for the license information.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
from datetime import datetime, timedelta, UTC
|
|
9
|
+
from typing import Optional, Dict, Any, List
|
|
10
|
+
from boto3_assist.cloudwatch.cloudwatch_connection import CloudWatchConnection
|
|
11
|
+
from boto3_assist.cloudwatch.cloudwatch_logs import CloudWatchLogs
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CloudWatchQuery(CloudWatchConnection):
|
|
15
|
+
"""Query Cloud Watch"""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
*,
|
|
20
|
+
aws_profile: Optional[str] = None,
|
|
21
|
+
aws_region: Optional[str] = None,
|
|
22
|
+
aws_access_key_id: Optional[str] = None,
|
|
23
|
+
aws_secret_access_key: Optional[str] = None,
|
|
24
|
+
) -> None:
|
|
25
|
+
super().__init__(
|
|
26
|
+
aws_profile=aws_profile,
|
|
27
|
+
aws_region=aws_region,
|
|
28
|
+
aws_access_key_id=aws_access_key_id,
|
|
29
|
+
aws_secret_access_key=aws_secret_access_key,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
self.__cw_logs: CloudWatchLogs | None = None
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def cw_logs(self) -> CloudWatchLogs:
|
|
36
|
+
"""CloudWatch Logs Connection"""
|
|
37
|
+
if self.__cw_logs is None:
|
|
38
|
+
self.__cw_logs = CloudWatchLogs(
|
|
39
|
+
aws_profile=self.aws_profile,
|
|
40
|
+
aws_region=self.aws_region,
|
|
41
|
+
aws_access_key_id=self.aws_access_key_id,
|
|
42
|
+
aws_secret_access_key=self.aws_secret_access_key,
|
|
43
|
+
)
|
|
44
|
+
return self.__cw_logs
|
|
45
|
+
|
|
46
|
+
def get_log_group_size(
|
|
47
|
+
self, log_group_name: str, start_time: datetime, end_time: datetime
|
|
48
|
+
) -> Dict[str, Any]:
|
|
49
|
+
"""
|
|
50
|
+
Get the log group size for a given period of time
|
|
51
|
+
Args:
|
|
52
|
+
log_group_name (str): _description_
|
|
53
|
+
start_time (datetime): _description_
|
|
54
|
+
end_time (datetime): _description_
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
_type_: _description_
|
|
58
|
+
"""
|
|
59
|
+
response = self.client.get_metric_data(
|
|
60
|
+
MetricDataQueries=[
|
|
61
|
+
{
|
|
62
|
+
"Id": "storedBytes",
|
|
63
|
+
"MetricStat": {
|
|
64
|
+
"Metric": {
|
|
65
|
+
"Namespace": "AWS/Logs",
|
|
66
|
+
# "MetricName": "StoredBytes",
|
|
67
|
+
"MetricName": "IncomingBytes",
|
|
68
|
+
"Dimensions": [
|
|
69
|
+
{"Name": "LogGroupName", "Value": log_group_name}
|
|
70
|
+
],
|
|
71
|
+
},
|
|
72
|
+
"Period": 86400, # Daily data
|
|
73
|
+
"Stat": "Sum",
|
|
74
|
+
},
|
|
75
|
+
"ReturnData": True,
|
|
76
|
+
},
|
|
77
|
+
],
|
|
78
|
+
StartTime=start_time,
|
|
79
|
+
EndTime=end_time,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# Extract the total size in bytes for the period
|
|
83
|
+
size: float = 0.0
|
|
84
|
+
if response["MetricDataResults"]:
|
|
85
|
+
# Access the first MetricDataResult
|
|
86
|
+
metric_data_result = response["MetricDataResults"][0]
|
|
87
|
+
# Sum the values if they exist
|
|
88
|
+
size = (
|
|
89
|
+
sum(metric_data_result["Values"]) if metric_data_result["Values"] else 0
|
|
90
|
+
)
|
|
91
|
+
else:
|
|
92
|
+
size = 0
|
|
93
|
+
|
|
94
|
+
size_mb = size / (1024 * 1024)
|
|
95
|
+
size_gb = size_mb / 1024
|
|
96
|
+
resp: Dict[str, Any] = {
|
|
97
|
+
"LogGroupName": log_group_name,
|
|
98
|
+
"Size": {
|
|
99
|
+
"Bytes": size,
|
|
100
|
+
"MB": size_mb,
|
|
101
|
+
"GB": size_gb,
|
|
102
|
+
},
|
|
103
|
+
"StartDate": start_time.isoformat(),
|
|
104
|
+
"EndDate": end_time.isoformat(),
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return resp
|
|
108
|
+
|
|
109
|
+
def get_log_sizes(
|
|
110
|
+
self,
|
|
111
|
+
start_date_time: datetime | None = None,
|
|
112
|
+
end_date_time: datetime | None = None,
|
|
113
|
+
days: int | None = 7,
|
|
114
|
+
top: int = 0,
|
|
115
|
+
) -> List[Dict[str, Any]]:
|
|
116
|
+
"""
|
|
117
|
+
Gets the log sizes for all log groups
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
start_date_time (datetime | None, optional): The Start Date. Defaults to None.
|
|
121
|
+
If None it's set to now in UTC time - the days field
|
|
122
|
+
end_date_time (datetime | None, optional): he Start Date. Defaults to None.
|
|
123
|
+
If None it's set to not in UTC time
|
|
124
|
+
days (int | None, optional): The days offset. Defaults to 7.
|
|
125
|
+
top (int, optional): If greater than zero it will return the top x after sorting
|
|
126
|
+
Defaults to 0.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
list: _description_
|
|
130
|
+
"""
|
|
131
|
+
if not days:
|
|
132
|
+
days = 7
|
|
133
|
+
start_time = start_date_time or (datetime.now(UTC) - timedelta(days=days))
|
|
134
|
+
end_time = end_date_time or datetime.now(UTC)
|
|
135
|
+
|
|
136
|
+
# Step 1: List all log groups
|
|
137
|
+
log_groups = self.cw_logs.list_log_groups()
|
|
138
|
+
log_group_sizes = []
|
|
139
|
+
|
|
140
|
+
# Step 2: Get sizes for each log group
|
|
141
|
+
for log_group in log_groups:
|
|
142
|
+
log_group_name = log_group["logGroupName"]
|
|
143
|
+
|
|
144
|
+
size_info = self.get_log_group_size(log_group_name, start_time, end_time)
|
|
145
|
+
log_group_sizes.append(size_info)
|
|
146
|
+
|
|
147
|
+
# Step 3: Sort by size
|
|
148
|
+
# top_log_groups = sorted(log_group_sizes, key=lambda x: x[1], reverse=True)
|
|
149
|
+
top_log_groups = sorted(
|
|
150
|
+
log_group_sizes,
|
|
151
|
+
key=lambda x: x.get("Size", {}).get("Bytes", 0),
|
|
152
|
+
reverse=True,
|
|
153
|
+
)
|
|
154
|
+
if top and top > 0:
|
|
155
|
+
# find the top x if provided
|
|
156
|
+
top_log_groups = top_log_groups[:top]
|
|
157
|
+
|
|
158
|
+
return top_log_groups
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def main():
|
|
162
|
+
log_group = os.environ.get("LOG_GROUP_QUERY_SAMPLE", "<enter-log-group-here>")
|
|
163
|
+
start = datetime.now() - timedelta(days=7) # Last 30 days
|
|
164
|
+
end = datetime.now()
|
|
165
|
+
cw_query: CloudWatchQuery = CloudWatchQuery()
|
|
166
|
+
result = cw_query.get_log_group_size(log_group, start, end)
|
|
167
|
+
print(result)
|
|
168
|
+
|
|
169
|
+
top = 25
|
|
170
|
+
days = 7
|
|
171
|
+
top_log_groups = cw_query.get_log_sizes(top=top, days=days)
|
|
172
|
+
print(f"Top {top} log groups by size for the last week:")
|
|
173
|
+
|
|
174
|
+
for top_log_group in top_log_groups:
|
|
175
|
+
log_group_name = top_log_group["LogGroupName"]
|
|
176
|
+
size_in_bytes = top_log_group.get("Size", {}).get("Bytes", 0)
|
|
177
|
+
size_in_megs = top_log_group.get("Size", {}).get("MB", 0)
|
|
178
|
+
size_in_gigs = top_log_group.get("Size", {}).get("GB", 0)
|
|
179
|
+
size: str = ""
|
|
180
|
+
if size_in_gigs > 1:
|
|
181
|
+
size = f"{size_in_gigs:.2f} GB"
|
|
182
|
+
elif size_in_megs > 1:
|
|
183
|
+
size = f"{size_in_megs:.2f} MB"
|
|
184
|
+
else:
|
|
185
|
+
size = f"{size_in_bytes} bytes"
|
|
186
|
+
|
|
187
|
+
print(f"{size}: {log_group_name}")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
if __name__ == "__main__":
|
|
191
|
+
main()
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Geek Cafe, LLC
|
|
3
|
+
Maintainers: Eric Wilson
|
|
4
|
+
MIT License. See Project Root for the license information.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
from aws_lambda_powertools import Logger
|
|
10
|
+
from boto3_assist.boto3session import Boto3SessionManager
|
|
11
|
+
from boto3_assist.environment_services.environment_variables import (
|
|
12
|
+
EnvironmentVariables,
|
|
13
|
+
)
|
|
14
|
+
from boto3_assist.cloudwatch.cloudwatch_connection_tracker import (
|
|
15
|
+
CloudWatchConnectionTracker,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
logger = Logger()
|
|
20
|
+
tracker: CloudWatchConnectionTracker = CloudWatchConnectionTracker()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Connection:
|
|
24
|
+
"""Boto 3 Connection"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
*,
|
|
29
|
+
service_name: Optional[str] = None,
|
|
30
|
+
aws_profile: Optional[str] = None,
|
|
31
|
+
aws_region: Optional[str] = None,
|
|
32
|
+
aws_access_key_id: Optional[str] = None,
|
|
33
|
+
aws_secret_access_key: Optional[str] = None,
|
|
34
|
+
) -> None:
|
|
35
|
+
self.aws_profile = aws_profile or EnvironmentVariables.AWS.profile()
|
|
36
|
+
self.aws_region = aws_region or EnvironmentVariables.AWS.region()
|
|
37
|
+
|
|
38
|
+
self.aws_access_key_id = (
|
|
39
|
+
aws_access_key_id or EnvironmentVariables.AWS.DynamoDB.aws_access_key_id()
|
|
40
|
+
)
|
|
41
|
+
self.aws_secret_access_key = (
|
|
42
|
+
aws_secret_access_key
|
|
43
|
+
or EnvironmentVariables.AWS.DynamoDB.aws_secret_access_key()
|
|
44
|
+
)
|
|
45
|
+
self.__session: Boto3SessionManager | None = None
|
|
46
|
+
|
|
47
|
+
self.__service_name: str | None = service_name
|
|
48
|
+
self.raise_on_error: bool = True
|
|
49
|
+
|
|
50
|
+
def setup(self, setup_source: Optional[str] = None) -> None:
|
|
51
|
+
"""
|
|
52
|
+
Setup the environment. Automatically called via init.
|
|
53
|
+
You can run setup at anytime with new parameters.
|
|
54
|
+
Args: setup_source: Optional[str] = None
|
|
55
|
+
Defines the source of the setup. Useful for logging.
|
|
56
|
+
Returns: None
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
logger.debug(
|
|
60
|
+
{
|
|
61
|
+
"metric_filter": f"{self.service_name}_connection_setup",
|
|
62
|
+
"source": f"{self.service_name} Connection",
|
|
63
|
+
"aws_profile": self.aws_profile,
|
|
64
|
+
"aws_region": self.aws_region,
|
|
65
|
+
"setup_source": setup_source,
|
|
66
|
+
}
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
self.__session = Boto3SessionManager(
|
|
70
|
+
service_name=self.service_name,
|
|
71
|
+
aws_profile=self.aws_profile,
|
|
72
|
+
aws_region=self.aws_region,
|
|
73
|
+
aws_access_key_id=self.aws_access_key_id,
|
|
74
|
+
aws_secret_access_key=self.aws_secret_access_key,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
tracker.increment_connection()
|
|
78
|
+
|
|
79
|
+
self.raise_on_error = EnvironmentVariables.AWS.DynamoDB.raise_on_error_setting()
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def service_name(self) -> str:
|
|
83
|
+
"""Service Name"""
|
|
84
|
+
if self.__service_name is None:
|
|
85
|
+
raise RuntimeError("Service Name is not available")
|
|
86
|
+
return self.__service_name
|
|
87
|
+
|
|
88
|
+
@service_name.setter
|
|
89
|
+
def service_name(self, value: str):
|
|
90
|
+
logger.debug("Setting Service Name")
|
|
91
|
+
self.__service_name = value
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def session(self) -> Boto3SessionManager:
|
|
95
|
+
"""Session"""
|
|
96
|
+
if self.__session is None:
|
|
97
|
+
self.setup(setup_source="session init")
|
|
98
|
+
|
|
99
|
+
if self.__session is None:
|
|
100
|
+
raise RuntimeError("Session is not available")
|
|
101
|
+
return self.__session
|
|
@@ -16,7 +16,7 @@ class ConnectionTracker:
|
|
|
16
16
|
|
|
17
17
|
def __init__(self, service_name: str) -> None:
|
|
18
18
|
self.__stack_trace_env_var: str = "BOTO3_ASSIST_CONNECTION_STACK_TRACE"
|
|
19
|
-
self.
|
|
19
|
+
self.__connection_counter: int = 0
|
|
20
20
|
self.__service_name: str = service_name
|
|
21
21
|
self.__issue_stack_trace: bool | None = None
|
|
22
22
|
|
|
@@ -31,7 +31,7 @@ class ConnectionTracker:
|
|
|
31
31
|
|
|
32
32
|
def increment_connection(self) -> None:
|
|
33
33
|
"""Increments the connection counter"""
|
|
34
|
-
self.
|
|
34
|
+
self.__connection_counter += 1
|
|
35
35
|
|
|
36
36
|
if self.connection_count > 1:
|
|
37
37
|
service_message = ""
|
|
@@ -53,27 +53,27 @@ class ConnectionTracker:
|
|
|
53
53
|
|
|
54
54
|
self.__log_warning(
|
|
55
55
|
f"{service_message}"
|
|
56
|
-
f"Your
|
|
56
|
+
f"Your boto3 connection count is {self.connection_count}. "
|
|
57
57
|
"Under most circumstances you should be able to use the same connection "
|
|
58
58
|
"vs. creating a new one. Connections are expensive in terms of time / latency. "
|
|
59
59
|
"If you are seeing perforance issues, check how and where you are creating your "
|
|
60
|
-
"connections. You should be able to pass the
|
|
61
|
-
"and reuse your
|
|
60
|
+
"connections. You should be able to pass the connection to your other objects "
|
|
61
|
+
"and reuse your boto3 connections."
|
|
62
62
|
f"{stack_trace_message}"
|
|
63
63
|
)
|
|
64
64
|
|
|
65
65
|
def decrement_connection(self) -> None:
|
|
66
66
|
"""Decrements the connection counter"""
|
|
67
|
-
self.
|
|
67
|
+
self.__connection_counter -= 1
|
|
68
68
|
|
|
69
69
|
@property
|
|
70
70
|
def connection_count(self) -> int:
|
|
71
71
|
"""Returns the current connection count"""
|
|
72
|
-
return self.
|
|
72
|
+
return self.__connection_counter
|
|
73
73
|
|
|
74
74
|
def reset(self) -> None:
|
|
75
75
|
"""Resets the connection counter"""
|
|
76
|
-
self.
|
|
76
|
+
self.__connection_counter = 0
|
|
77
77
|
|
|
78
78
|
def __log_warning(self, message: str) -> None:
|
|
79
79
|
"""Logs a warning message"""
|