-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathazure_policy_operations.py
More file actions
248 lines (230 loc) · 10.4 KB
/
Copy pathazure_policy_operations.py
File metadata and controls
248 lines (230 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import json
from datetime import datetime, timedelta
from cloud_governance.common.clouds.azure.compute.compute_operations import ComputeOperations
from cloud_governance.common.clouds.azure.compute.network_operations import NetworkOperations
from cloud_governance.common.clouds.azure.compute.resource_group_operations import ResourceGroupOperations
from cloud_governance.common.clouds.azure.monitor.monitor_management_operations import MonitorManagementOperations
from cloud_governance.common.utils.configs import INSTANCE_IDLE_DAYS, DEFAULT_ROUND_DIGITS, TOTAL_BYTES_IN_KIB
from cloud_governance.policy.helpers.abstract_policy_operations import AbstractPolicyOperations
from cloud_governance.common.logger.init_logger import logger
from cloud_governance.common.utils.utils import Utils
class AzurePolicyOperations(AbstractPolicyOperations):
def __init__(self):
self._cloud_name = 'Azure'
self.compute_operations = ComputeOperations()
self.network_operations = NetworkOperations()
self.resource_group_operations = ResourceGroupOperations()
self.monitor_operations = MonitorManagementOperations()
super().__init__()
def get_tag_name_from_tags(self, tags: dict, tag_name: str):
"""
This method returns the tag value by the tag_name
:param tags:
:type tags:
:param tag_name:
:type tag_name:
:return:
:rtype:
"""
if tags:
for key, value in tags.items():
if Utils.equal_ignore_case(key, tag_name):
return value
return ''
def _delete_resource(self, resource_id: str):
"""
This method deletes the
:param resource_id:
:type resource_id:
:return:
:rtype:
"""
action = "deleted"
try:
if self._policy in ['instance_run', 'instance_idle']:
action = "Stopped"
delete_status = self.compute_operations.stop_vm(resource_id=resource_id)
elif self._policy == 'unattached_volume':
delete_status = self.compute_operations.delete_disk(resource_id=resource_id)
elif self._policy == 'ip_unattached':
delete_status = self.network_operations.release_public_ip(resource_id=resource_id)
elif self._policy == 'unused_nat_gateway':
delete_status = self.network_operations.delete_nat_gateway(resource_id=resource_id)
logger.info(f'{self._policy} {action}: {resource_id}')
except Exception as err:
logger.info(f'Exception raised: {err}: {resource_id}')
def update_resource_day_count_tag(self, resource_id: str, cleanup_days: int, tags: dict):
tags = self._update_tag_value(tags=tags, tag_name='DaysCount', tag_value=str(cleanup_days))
try:
if self._policy in ['instance_run', 'unattached_volume', 'ip_unattached', 'unused_nat_gateway']:
self.resource_group_operations.creates_or_updates_tags(resource_id=resource_id, tags=tags)
except Exception as err:
logger.info(f'Exception raised: {err}: {resource_id}')
def _update_tag_value(self, tags: dict, tag_name: str, tag_value: str):
"""
This method returns the updated tag_list by adding the tag_name and tag_value to the tags
@param tags:
@param tag_name:
@param tag_value:
@return:
"""
if not tags:
tags = {}
if self._dry_run == "yes":
tag_value = 0
tag_value = f'{self.CURRENT_DATE}@{tag_value}'
found = False
updated_tags = {}
if tags:
for key, value in tags.items():
if Utils.equal_ignore_case(key, tag_name):
if value.split("@")[0] != self.CURRENT_DATE:
updated_tags[key] = tag_value
else:
if int(tag_value.split("@")[-1]) == 0 or int(tag_value.split("@")[-1]) == 1:
updated_tags[key] = tag_value
found = True
tags.update(updated_tags)
if not found:
tags.update({tag_name: tag_value})
return tags
def _get_all_instances(self):
"""
This method returns the all instances list
:return:
:rtype:
"""
return self.compute_operations.get_all_instances()
def run_policy_operations(self):
raise NotImplementedError("This method needs to be implemented")
def _get_all_volumes(self) -> list:
"""
This method returns the volumes by state
:return:
:rtype:
"""
volumes = self.compute_operations.get_all_disks()
return volumes
def _get_active_cluster_ids(self):
"""
This method returns the active cluster id's
:return:
:rtype:
"""
active_instances = self._get_all_instances()
cluster_ids = []
for vm in active_instances:
tags = vm.tags if vm.tags else {}
for key, value in tags.items():
if key.startswith('kubernetes.io/cluster'):
cluster_ids.append(key)
break
return cluster_ids
def _get_cluster_tag(self, tags: dict):
"""
This method returns the cluster_tag
:return:
:rtype:
"""
if tags:
for key, value in tags.items():
if key.startswith('kubernetes.io/cluster'):
return key
return ''
def _get_instance_status(self, resource_id: str, vm_name: str):
"""
This method returns the VM status of the Virtual Machine
:param resource_id:
:type resource_id:
:param vm_name:
:type vm_name:
:return:
:rtype:
"""
instance_statuses = self.compute_operations.get_instance_statuses(resource_id=resource_id, vm_name=vm_name)
statuses = instance_statuses.get('statuses', {})
if len(statuses) >= 2:
status = statuses[1].get('display_status', '').lower()
elif len(statuses) == 1:
status = statuses[0].get('display_status', '').lower()
else:
status = 'Unknown Status'
return status
def __get_aggregation_metrics_value(self, metrics: dict, aggregation: str):
"""
This method returns the aggregation value of the metrics
:param metrics:
:type metrics:
:param aggregation:
:type aggregation:
:return:
:rtype:
"""
total_metrics = 0
metric_aggregation_value = 0
for metric in metrics.get('value', []):
metrics_data = metric.get('timeseries', [])
if metrics_data:
total_metrics = len(metrics_data[0].get('data', []))
for metric_data in metrics_data[0].get('data', []):
metric_aggregation_value += metric_data.get(aggregation)
if Utils.equal_ignore_case(aggregation, 'average'):
return round(metric_aggregation_value / total_metrics, DEFAULT_ROUND_DIGITS)
else:
return round(metric_aggregation_value, DEFAULT_ROUND_DIGITS)
def get_cpu_utilization_percentage_metric(self, resource_id: str, days: int = INSTANCE_IDLE_DAYS):
"""
This method returns the cpu utilization percentage
:param days:
:type days:
:param resource_id:
:type resource_id:
:return:
:rtype:
"""
start_date, end_date = Utils.get_start_and_end_datetime(days=days)
timespan = f'{start_date.strftime("%Y-%m-%dT%H:%M:%SZ")}/{end_date.strftime("%Y-%m-%dT%H:%M:%SZ")}'
cpu_metrics = self.monitor_operations.get_resource_metrics(resource_id=resource_id,
metricnames='Percentage CPU',
aggregation='Average',
timespan=timespan)
average_cpu_metrics_value = self.__get_aggregation_metrics_value(metrics=cpu_metrics, aggregation='average')
return average_cpu_metrics_value
def get_network_in_kib_metric(self, resource_id: str, days: int = INSTANCE_IDLE_DAYS):
"""
This method returns the total Network In KiB
:param days:
:type days:
:param resource_id:
:type resource_id:
:return:
:rtype:
"""
start_date, end_date = Utils.get_start_and_end_datetime(days=days)
timespan = f'{start_date.strftime("%Y-%m-%dT%H:%M:%SZ")}/{end_date.strftime("%Y-%m-%dT%H:%M:%SZ")}'
network_in_metrics = self.monitor_operations.get_resource_metrics(resource_id=resource_id,
metricnames='Network In Total',
aggregation='Average',
timespan=timespan)
average_network_in_bytes = self.__get_aggregation_metrics_value(metrics=network_in_metrics,
aggregation='average')
return round(average_network_in_bytes / TOTAL_BYTES_IN_KIB, DEFAULT_ROUND_DIGITS)
def get_network_out_kib_metric(self, resource_id: str, days: int = INSTANCE_IDLE_DAYS):
"""
This method returns the total Network Out KiB
:param days:
:type days:
:param resource_id:
:type resource_id:
:return:
:rtype:
"""
start_date, end_date = Utils.get_start_and_end_datetime(days=days)
timespan = f'{start_date.strftime("%Y-%m-%dT%H:%M:%SZ")}/{end_date.strftime("%Y-%m-%dT%H:%M:%SZ")}'
network_out_metrics = self.monitor_operations.get_resource_metrics(resource_id=resource_id,
metricnames='Network Out Total',
aggregation='Average',
timespan=timespan)
average_network_out_bytes = self.__get_aggregation_metrics_value(metrics=network_out_metrics,
aggregation='average')
return round(average_network_out_bytes / TOTAL_BYTES_IN_KIB, DEFAULT_ROUND_DIGITS)