Skip to content

Commit a3c4833

Browse files
authored
Metrics (#147)
* adding metrics updates Signed-off-by: Paige Patton <[email protected]> * setting granularity to 10 * taking out math * lowering day range --------- Signed-off-by: Paige Patton <[email protected]>
1 parent 229f459 commit a3c4833

File tree

5 files changed

+27
-56
lines changed

5 files changed

+27
-56
lines changed

src/krkn_lib/elastic/krkn_elastic.py

+13-15
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from __future__ import annotations
22

3-
import datetime
43
import logging
54
import math
65
import time
@@ -118,19 +117,10 @@ def upload_metrics_to_elasticsearch(
118117
time_start = time.time()
119118
try:
120119
for metric in raw_data:
121-
if (
122-
isinstance(metric["timestamp"], int)
123-
and isinstance(metric["value"], float)
124-
and isinstance(metric["name"], str)
125-
):
126-
127120
result = self.push_metric(
128121
ElasticMetric(
129122
run_uuid=run_uuid,
130-
name=metric["name"],
131-
created_at=datetime.datetime.now(),
132-
timestamp=int(metric["timestamp"]),
133-
value=float(metric["value"]),
123+
**metric
134124
),
135125
index,
136126
)
@@ -141,7 +131,8 @@ def upload_metrics_to_elasticsearch(
141131
)
142132

143133
return int(time.time() - time_start)
144-
except Exception:
134+
except Exception as e:
135+
self.safe_logger.error(f'Upload metric exception: {e}')
145136
return -1
146137

147138
def push_alert(self, alert: ElasticAlert, index: str) -> int:
@@ -159,7 +150,8 @@ def push_alert(self, alert: ElasticAlert, index: str) -> int:
159150
time_start = time.time()
160151
alert.save(using=self.es, index=index)
161152
return int(time.time() - time_start)
162-
except Exception:
153+
except Exception as e:
154+
self.safe_logger.error(f"Push alert exception: {e}")
163155
return -1
164156

165157
def push_metric(self, metric: ElasticMetric, index: str) -> int:
@@ -177,9 +169,12 @@ def push_metric(self, metric: ElasticMetric, index: str) -> int:
177169
time_start = time.time()
178170
metric.save(using=self.es, index=index)
179171
return int(time.time() - time_start)
180-
except Exception:
172+
except Exception as e:
173+
print('error' +str(e))
174+
self.safe_logger.error(f'Exception pushing metric: {e}')
181175
return -1
182176

177+
183178
def push_telemetry(self, telemetry: ChaosRunTelemetry, index: str):
184179
if not index:
185180
raise Exception("index cannot be None or empty")
@@ -189,7 +184,7 @@ def push_telemetry(self, telemetry: ChaosRunTelemetry, index: str):
189184
elastic_chaos.save(using=self.es, index=index)
190185
return int(time.time() - time_start)
191186
except Exception as e:
192-
self.safe_logger.info("Elastic push telemetry error: " + str(e))
187+
self.safe_logger.info(f"Elastic push telemetry error: {e}")
193188
return -1
194189

195190
def search_telemetry(self, run_uuid: str, index: str):
@@ -210,6 +205,7 @@ def search_telemetry(self, run_uuid: str, index: str):
210205
ElasticChaosRunTelemetry(**hit.to_dict()) for hit in result
211206
]
212207
except NotFoundError:
208+
self.safe_logger.error("Search telemetry not found")
213209
return []
214210
return documents
215211

@@ -229,6 +225,7 @@ def search_alert(self, run_uuid: str, index: str) -> list[ElasticAlert]:
229225
result = search.execute()
230226
documents = [ElasticAlert(**hit.to_dict()) for hit in result]
231227
except NotFoundError:
228+
self.safe_logger.error("Search alert not found")
232229
return []
233230
return documents
234231

@@ -248,5 +245,6 @@ def search_metric(self, run_uuid: str, index: str) -> list[ElasticMetric]:
248245
result = search.execute()
249246
documents = [ElasticMetric(**hit.to_dict()) for hit in result]
250247
except NotFoundError:
248+
self.safe_logger.error("Search metric not found")
251249
return []
252250
return documents

src/krkn_lib/models/elastic/models.py

+1-23
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
InnerDoc,
99
Integer,
1010
Keyword,
11-
Long,
1211
Nested,
1312
Text,
1413
Boolean
@@ -38,38 +37,17 @@ def __init__(
3837
self.created_at = created_at
3938

4039

41-
class ElasticMetricValue(InnerDoc):
42-
timestamp = Long()
43-
value = Float()
44-
45-
def __init__(self, timestamp: int, value: float, **kwargs):
46-
super().__init__(**kwargs)
47-
self.timestamp = timestamp
48-
self.value = value
49-
50-
5140
class ElasticMetric(Document):
5241
run_uuid = Keyword()
53-
name = Text()
54-
created_at = Date()
55-
timestamp = Long()
56-
value = Float()
42+
timestamp = Date()
5743

5844
def __init__(
5945
self,
6046
run_uuid: str,
61-
name: str,
62-
created_at: datetime,
63-
timestamp: int,
64-
value: float,
6547
**kwargs,
6648
):
6749
super().__init__(**kwargs)
6850
self.run_uuid = run_uuid
69-
self.name = name
70-
self.created_at = created_at
71-
self.timestamp = timestamp
72-
self.value = value
7351

7452

7553
# Telemetry models

src/krkn_lib/prometheus/krkn_prometheus.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import logging
2-
import math
32
import re
43
import sys
54
import time
@@ -51,6 +50,7 @@ def process_prom_query_in_range(
5150
query: str,
5251
start_time: datetime = None,
5352
end_time: datetime = None,
53+
granularity: int = 10
5454
) -> list[dict[str:any]]:
5555
"""
5656
Executes a query to the Prometheus API in PromQL languag,
@@ -69,10 +69,6 @@ def process_prom_query_in_range(
6969
)
7070
end_time = datetime.now() if end_time is None else end_time
7171

72-
granularity = math.ceil(
73-
(end_time - start_time).total_seconds() / 11000
74-
)
75-
granularity = granularity if granularity > 0 else 1
7672
if self.prom_cli:
7773
try:
7874
return self.prom_cli.custom_query_range(

src/krkn_lib/tests/test_krkn_elastic.py

+11-12
Original file line numberDiff line numberDiff line change
@@ -45,26 +45,24 @@ def test_push_search_alert(self):
4545
def test_push_search_metric(self):
4646
run_uuid = str(uuid.uuid4())
4747
index = "test-push-metric"
48+
timestamp = datetime.datetime.now()
4849
metric_1 = ElasticMetric(
4950
run_uuid=run_uuid,
50-
name="metric_1",
51-
timestamp=100,
52-
value=1.0,
53-
created_at=datetime.datetime.now(),
51+
metricName="metric_1",
52+
timestamp=timestamp,
53+
value=1.0
5454
)
5555
result = self.lib_elastic.push_metric(metric_1, index)
5656
self.assertNotEqual(result, -1)
5757
time.sleep(1)
5858
metrics = self.lib_elastic.search_metric(run_uuid, index)
5959
self.assertEqual(len(metrics), 1)
60-
metric = next(
61-
metric for metric in metrics if metric.name == "metric_1"
62-
)
60+
metric = metrics[0]
61+
6362
self.assertIsNotNone(metric)
64-
self.assertEqual(metric.value, 1.0)
65-
self.assertEqual(metric.timestamp, 100)
63+
self.assertEqual(metric.timestamp, timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f'))
6664
self.assertEqual(metric.run_uuid, run_uuid)
67-
self.assertEqual(metric.name, "metric_1")
65+
self.assertEqual(metric["value"], 1.0)
6866

6967
def test_push_search_telemetry(self):
7068
run_uuid = str(uuid.uuid4())
@@ -100,16 +98,17 @@ def test_upload_metric_to_elasticsearch(self):
10098
len(self.lib_elastic.search_metric(bad_metric_uuid, index)), 0
10199
)
102100

101+
time_now = datetime.datetime.now()
103102
self.lib_elastic.upload_metrics_to_elasticsearch(
104103
run_uuid=good_metric_uuid,
105-
raw_data=[{"name": name, "timestamp": 10, "value": 3.14}],
104+
raw_data=[{"name": name, "timestamp": time_now, "value": 3.14}],
106105
index=index,
107106
)
108107
time.sleep(1)
109108
metric = self.lib_elastic.search_metric(good_metric_uuid, index)
110109
self.assertEqual(len(metric), 1)
111110
self.assertEqual(metric[0].name, name)
112-
self.assertEqual(metric[0].timestamp, 10)
111+
self.assertEqual(metric[0].timestamp, time_now.strftime('%Y-%m-%dT%H:%M:%S.%f'))
113112
self.assertEqual(metric[0].value, 3.14)
114113

115114
def test_search_alert_not_existing(self):

src/krkn_lib/tests/test_krkn_prometheus.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ class TestKrknPrometheus(BaseTest):
1111
def test_process_prom_query(self):
1212
prom_cli = KrknPrometheus(self.url)
1313
query = "node_boot_time_seconds"
14-
start_time = datetime.datetime.now() - datetime.timedelta(days=10)
14+
start_time = datetime.datetime.now() - datetime.timedelta(hours=1)
1515

1616
end_time = datetime.datetime.now()
1717
res = prom_cli.process_prom_query_in_range(query, start_time, end_time)

0 commit comments

Comments
 (0)