Skip to content

Commit 174864a

Browse files
authored
Merge pull request #92 from naved001/log-everything
2 parents 616a196 + 40e1cb5 commit 174864a

File tree

4 files changed

+27
-9
lines changed

4 files changed

+27
-9
lines changed

openshift_metrics/merge.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Merges metrics from files and produces reports by pod and by namespace
33
"""
44

5+
import logging
56
import os
67
import argparse
78
from datetime import datetime, UTC
@@ -13,6 +14,9 @@
1314
from openshift_metrics import utils, invoice
1415
from openshift_metrics.metrics_processor import MetricsProcessor
1516

17+
logging.basicConfig(level=logging.INFO)
18+
logger = logging.getLogger(__name__)
19+
1620
def compare_dates(date_str1, date_str2):
1721
"""Returns true is date1 is earlier than date2"""
1822
date1 = datetime.strptime(date_str1, "%Y-%m-%d")
@@ -96,14 +100,15 @@ def main():
96100
elif compare_dates(report_end_date, metrics_from_file["end_date"]):
97101
report_end_date = metrics_from_file["end_date"]
98102

99-
print(report_start_date)
100-
print(report_end_date)
103+
logger.info(f"Generating report from {report_start_date} to {report_end_date}")
104+
101105
report_start_date = datetime.strptime(report_start_date, "%Y-%m-%d")
102106
report_end_date = datetime.strptime(report_end_date, "%Y-%m-%d")
103107

104108
report_month = datetime.strftime(report_start_date, "%Y-%m")
105109

106110
if args.use_nerc_rates:
111+
logger.info("Using nerc rates.")
107112
nerc_data = nerc_rates.load_from_url()
108113
rates = invoice.Rates(
109114
cpu=Decimal(nerc_data.get_value_at("CPU SU Rate", report_month)),
@@ -130,7 +135,7 @@ def main():
130135
pod_report_file = f"Pod NERC OpenShift {report_month}.csv"
131136

132137
if report_start_date.month != report_end_date.month:
133-
print("Warning: The report spans multiple months")
138+
logger.warning("The report spans multiple months")
134139
report_month += " to " + datetime.strftime(report_end_date, "%Y-%m")
135140

136141
condensed_metrics_dict = processor.condense_metrics(

openshift_metrics/openshift_prometheus_metrics.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,15 @@
1818
import os
1919
import sys
2020
import json
21+
import logging
2122

2223
from openshift_metrics import utils
2324
from openshift_metrics.prometheus_client import PrometheusClient
2425
from openshift_metrics.metrics_processor import MetricsProcessor
2526

27+
logging.basicConfig(level=logging.INFO)
28+
logger = logging.getLogger(__name__)
29+
2630
CPU_REQUEST = 'kube_pod_resource_request{unit="cores"} unless on(pod, namespace) kube_pod_status_unschedulable'
2731
MEMORY_REQUEST = 'kube_pod_resource_request{unit="bytes"} unless on(pod, namespace) kube_pod_status_unschedulable'
2832
GPU_REQUEST = 'kube_pod_resource_request{resource=~"nvidia.com.*"} unless on(pod, namespace) kube_pod_status_unschedulable'
@@ -71,8 +75,7 @@ def main():
7175
else:
7276
output_file = f"metrics-{report_start_date}-to-{report_end_date}.json"
7377

74-
print(f"Generating report starting {report_start_date} and ending {report_end_date} in {output_file}")
75-
78+
logger.info(f"Generating report starting {report_start_date} and ending {report_end_date} in {output_file}")
7679

7780
token = os.environ.get("OPENSHIFT_TOKEN")
7881
prom_client = PrometheusClient(openshift_url, token)
@@ -98,6 +101,7 @@ def main():
98101
node_labels = prom_client.query_metric(KUBE_NODE_LABELS, report_start_date, report_end_date)
99102
metrics_dict["gpu_metrics"] = MetricsProcessor.insert_node_labels(node_labels, gpu_request_metrics)
100103
except utils.EmptyResultError:
104+
logger.info(f"No GPU metrics found for the period {report_start_date} to {report_end_date}")
101105
pass
102106

103107
month_year = datetime.strptime(report_start_date, "%Y-%m-%d").strftime("%Y-%m")
@@ -108,6 +112,7 @@ def main():
108112
s3_location = f"data_{month_year}/metrics-{report_start_date}-to-{report_end_date}.json"
109113

110114
with open(output_file, "w") as file:
115+
logger.info(f"Writing metrics to {output_file}")
111116
json.dump(metrics_dict, file)
112117

113118
if args.upload_to_s3:

openshift_metrics/prometheus_client.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
import requests
22
import time
3+
import logging
34

45
from urllib3.util.retry import Retry
56
from requests.adapters import HTTPAdapter
67
from openshift_metrics.utils import EmptyResultError
78

9+
logging.basicConfig(level=logging.INFO)
10+
logger = logging.getLogger(__name__)
11+
812
class PrometheusClient:
913
def __init__(self, prometheus_url: str, token: str, step_min: int=15):
1014
self.prometheus_url = prometheus_url
@@ -22,7 +26,7 @@ def query_metric(self, metric, start_date, end_date):
2226
session = requests.Session()
2327
session.mount("https://", HTTPAdapter(max_retries=retries))
2428

25-
print(f"Retrieving metric: {metric}")
29+
logger.info(f"Retrieving metric: {metric}")
2630

2731
for _ in range(3):
2832
response = session.get(url, headers=headers, verify=True)
@@ -33,7 +37,7 @@ def query_metric(self, metric, start_date, end_date):
3337
data = response.json()["data"]["result"]
3438
if data:
3539
break
36-
print("Empty result set")
40+
logger.warning("Empty result set")
3741
time.sleep(3)
3842

3943
if not data:

openshift_metrics/utils.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,14 @@
1717
import csv
1818
import requests
1919
import boto3
20+
import logging
2021

2122
from openshift_metrics import invoice
2223
from decimal import Decimal
2324

25+
logging.basicConfig(level=logging.INFO)
26+
logger = logging.getLogger(__name__)
27+
2428

2529
class EmptyResultError(Exception):
2630
"""Raise when no results are retrieved for a query"""
@@ -69,7 +73,7 @@ def upload_to_s3(file, bucket, location):
6973
aws_access_key_id=s3_key_id,
7074
aws_secret_access_key=s3_secret,
7175
)
72-
76+
logger.info(f"Uploading {file} to s3://{bucket}/{location}")
7377
response = s3.upload_file(file, Bucket=bucket, Key=location)
7478

7579

@@ -104,7 +108,7 @@ def get_namespace_attributes():
104108

105109
def csv_writer(rows, file_name):
106110
"""Writes rows as csv to file_name"""
107-
print(f"Writing csv to {file_name}")
111+
logger.info(f"Writing report to {file_name}")
108112
with open(file_name, "w") as csvfile:
109113
csvwriter = csv.writer(csvfile)
110114
csvwriter.writerows(rows)

0 commit comments

Comments
 (0)