-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnewgen_infra_report_final_script.py
More file actions
299 lines (255 loc) · 10.2 KB
/
Copy pathnewgen_infra_report_final_script.py
File metadata and controls
299 lines (255 loc) · 10.2 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import requests
import pandas as pd
from datetime import datetime, timedelta
import time
import os
from openpyxl.styles import Font, Alignment
from openpyxl.utils import get_column_letter
# Configuration
GRAFANA_URL = "https://monitoring.bhartiaxa.com"
API_KEY = "#############"
DATASOURCE_UID = "0wSD8eb7z"
NAMESPACE = "default"
OUTPUT_PATH = "/mnt/c/Users/Parikshit Kudalkar/Downloads"
CONTAINERS = [
"brmsinstanceweb", "brmsinstanceejb", "od110services",
"ibps5sp3uiweb", "ibps5sp3uiejb", "ibps5sp3aiweb", "ibps5sp3aiejb"
]
def format_percentage(value):
"""Format percentage values to XX.XX% format"""
if isinstance(value, (int, float)):
return f"{value:.2f}%"
return value
def ensure_output_directory():
"""Ensure the output directory exists"""
if not os.path.exists(OUTPUT_PATH):
os.makedirs(OUTPUT_PATH)
print(f"Created output directory: {OUTPUT_PATH}")
def fetch_pod_names(container_name):
"""Fetch pod names for the given container with retry logic"""
max_retries = 3
retry_delay = 1
query = f'kube_pod_container_info{{container="{container_name}", namespace="{NAMESPACE}"}}'
for attempt in range(max_retries):
try:
response = requests.get(
f"{GRAFANA_URL}/api/datasources/proxy/uid/{DATASOURCE_UID}/api/v1/query",
headers={"Authorization": f"Bearer {API_KEY}"},
params={"query": query},
timeout=10
)
response.raise_for_status()
pods = [result['metric']['pod'] for result in response.json().get('data', {}).get('result', [])]
return f"({'|'.join(pods)})" if pods else ""
except (requests.exceptions.RequestException, KeyError) as e:
if attempt == max_retries - 1:
print(f"Failed to fetch pods for {container_name}: {str(e)}")
return ""
time.sleep(retry_delay)
return ""
def fetch_metrics(container_name, pod_regex, start_time, end_time):
"""Fetch metrics with improved accuracy and error handling"""
try:
# CPU Query - returns values as decimals (e.g., 0.9479 for 94.79%)
cpu_query = f'''
sum(rate(container_cpu_usage_seconds_total{{
namespace="{NAMESPACE}",
pod=~"{pod_regex}",
container="{container_name}",
image!=""
}}[5m])) by (container)
/
sum(kube_pod_container_resource_limits{{
namespace="{NAMESPACE}",
pod=~"{pod_regex}",
container="{container_name}",
resource="cpu"
}}) by (container)
'''
# Memory Query - returns values as decimals
mem_query = f'''
sum(container_memory_working_set_bytes{{
namespace="{NAMESPACE}",
pod=~"{pod_regex}",
container="{container_name}",
image!=""
}}) by (container)
/
sum(kube_pod_container_resource_limits{{
namespace="{NAMESPACE}",
pod=~"{pod_regex}",
container="{container_name}",
resource="memory"
}}) by (container)
'''
params = {
"start": start_time.timestamp(),
"end": end_time.timestamp(),
"step": "1m"
}
def fetch_data(query):
for attempt in range(3):
try:
response = requests.get(
f"{GRAFANA_URL}/api/datasources/proxy/uid/{DATASOURCE_UID}/api/v1/query_range",
headers={"Authorization": f"Bearer {API_KEY}"},
params={**params, "query": query},
timeout=15
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException:
if attempt == 2:
raise
time.sleep(1)
cpu_data = fetch_data(cpu_query)
mem_data = fetch_data(mem_query)
def process_values(data):
values = []
for result in data.get('data', {}).get('result', []):
for point in result.get('values', []):
try:
val = float(point[1]) * 100 # Convert to percentage
if val >= 0:
values.append(val)
except (ValueError, TypeError):
continue
return values
cpu_values = process_values(cpu_data)
mem_values = process_values(mem_data)
return cpu_values, mem_values
except Exception as e:
print(f"Error fetching metrics for {container_name}: {str(e)}")
return None, None
def generate_report():
"""Generate comprehensive report with accurate metrics"""
end_time = datetime.now()
start_time = end_time - timedelta(hours=6)
report_date = end_time.strftime("%d-%m-%y")
report = []
for container in CONTAINERS:
pod_regex = fetch_pod_names(container)
if not pod_regex:
report.append({
"Date": report_date,
"Container Name": container,
"Max Memory": "N/A",
"Avg Memory": "N/A",
"Max CPU": "N/A",
"Avg CPU": "N/A",
"Data Points": 0
})
continue
cpu_values, mem_values = fetch_metrics(container, pod_regex, start_time, end_time)
if not cpu_values or not mem_values:
report.append({
"Date": report_date,
"Container Name": container,
"Max Memory": "Error",
"Avg Memory": "",
"Max CPU": "",
"Avg CPU": "",
"Data Points": 0
})
continue
stats = {
"Date": report_date,
"Container Name": container,
"Max Memory": max(mem_values),
"Avg Memory": sum(mem_values)/len(mem_values),
"Max CPU": max(cpu_values),
"Avg CPU": sum(cpu_values)/len(cpu_values),
"Data Points": len(cpu_values)
}
report.append(stats)
return report
def save_reports(report_data):
"""Save report to both CSV and Excel with requested naming format"""
try:
df = pd.DataFrame(report_data)
# Reorder columns
column_order = ["Date", "Container Name", "Max Memory", "Avg Memory",
"Max CPU", "Avg CPU", "Data Points"]
df = df[column_order]
# Generate filename with current date
file_date = datetime.now().strftime("%d-%m-%y")
base_filename = f"{file_date}_newgen_infra"
# Ensure output directory exists
ensure_output_directory()
# Format percentage columns for CSV
percentage_cols = ['Max Memory', 'Avg Memory', 'Max CPU', 'Avg CPU']
for col in percentage_cols:
df[col] = df[col].apply(format_percentage)
# Save to CSV
csv_path = os.path.join(OUTPUT_PATH, f"{base_filename}.csv")
df.to_csv(csv_path, index=False)
# Save to Excel with openpyxl
excel_path = os.path.join(OUTPUT_PATH, f"{base_filename}.xlsx")
# Create new workbook
from openpyxl import Workbook
wb = Workbook()
# Remove default sheet if it exists
if len(wb.sheetnames) > 0:
wb.remove(wb.active)
# Create new sheet
ws = wb.create_sheet('Infra Metrics')
# Write headers
headers = df.columns.tolist()
ws.append(headers)
# Write data rows - convert percentages back to decimals for Excel
for _, row in df.iterrows():
excel_row = []
for val, col in zip(row, df.columns):
if col in percentage_cols and isinstance(val, str) and '%' in val:
excel_row.append(float(val.strip('%'))/100) # Convert to decimal
else:
excel_row.append(val)
ws.append(excel_row)
# Format percentage columns (0.00% shows as XX.XX% in Excel)
percentage_format = '0.00%'
for col_idx, col_name in enumerate(df.columns, 1):
if col_name in percentage_cols:
col_letter = get_column_letter(col_idx)
for cell in ws[col_letter][1:]: # Skip header
if cell.value is not None:
cell.number_format = percentage_format
# Set column widths
column_widths = {
'A': 12, # Date
'B': 20, # Container Name
'C': 12, # Max Memory
'D': 12, # Avg Memory
'E': 12, # Max CPU
'F': 12, # Avg CPU
'G': 12 # Data Points
}
for col, width in column_widths.items():
ws.column_dimensions[col].width = width
# Format header row
header_font = Font(bold=True)
header_alignment = Alignment(horizontal='center')
for cell in ws[1]:
cell.font = header_font
cell.alignment = header_alignment
# Save the workbook
wb.save(excel_path)
print(f"\nReports saved to {OUTPUT_PATH}:")
print(f"- CSV file: {os.path.basename(csv_path)}")
print(f"- Excel file: {os.path.basename(excel_path)}")
return df
except Exception as e:
print(f"\nError saving reports: {str(e)}")
print("Please check if the output directory exists and is writable")
return None
if __name__ == "__main__":
print("Generating NewGen Infrastructure Report...")
report_data = generate_report()
df = save_reports(report_data)
if df is not None:
# Format the numeric columns with two decimal places and % sign for display
percentage_cols = ['Max Memory', 'Avg Memory', 'Max CPU', 'Avg CPU']
for col in percentage_cols:
if col in df.columns:
df[col] = df[col].apply(lambda x: f"{float(x.strip('%')):.2f}%" if isinstance(x, str) and '%' in x else x)
print("\nFinal Report:")
print(df.to_string(index=False))