forked from AliceO2Group/AliceO2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetricAggregator.cxx
More file actions
396 lines (360 loc) · 13.9 KB
/
Copy pathMetricAggregator.cxx
File metadata and controls
396 lines (360 loc) · 13.9 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// Copyright 2019-2025 CERN and copyright holders of ALICE O2.
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
// All rights not expressly granted are reserved.
//
// This software is distributed under the terms of the GNU General Public
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
#include "Framework/MetricAggregator.h"
#include "Framework/CommonServices.h"
#include "Framework/DeviceMetricsInfo.h"
#include "Framework/Logger.h"
#include "Framework/Monitoring.h"
#include "Framework/Plugins.h"
#include "Framework/ServiceSpec.h"
#include "Framework/TypeIdHelpers.h"
#include <Monitoring/MonitoringFactory.h>
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace o2::framework;
using Metric = o2::monitoring::Metric;
#define MONITORING_QUEUE_SIZE 100
namespace o2::framework::metricaggregator
{
/// Reads the most recent value from the ring buffer based on the write position and the history offset.
template <typename ValueT>
bool getNumericValue(std::size_t storeIdx,
std::size_t writePos,
std::size_t filledMetrics,
std::size_t historyOffset,
std::vector<MetricsStorage<ValueT>> const& valuesStorage,
std::vector<TimestampsStorage<ValueT>> const& timestampsStorage,
MetricSample& out)
{
if (storeIdx >= valuesStorage.size() || storeIdx >= timestampsStorage.size()) {
return false;
}
auto const& values = valuesStorage[storeIdx];
auto const& timestamps = timestampsStorage[storeIdx];
auto const capacity = values.size();
if (capacity == 0 || capacity <= historyOffset) {
return false;
}
auto const ringIndex = (writePos + capacity - 1 - historyOffset) % capacity;
out.value = static_cast<double>(values[ringIndex]);
out.timestamp = timestamps[ringIndex];
return true;
}
/// Routes the metric extraction request to the correct typed storage array.
bool extractNumericSample(DeviceMetricsInfo const& info,
std::size_t metricIndex,
std::size_t historyOffset,
MetricSample& out)
{
if (metricIndex >= info.metrics.size()) {
return false;
}
auto const& metric = info.metrics[metricIndex];
switch (metric.type) {
case MetricType::Int: {
return getNumericValue(metric.storeIdx,
metric.pos,
metric.filledMetrics,
historyOffset,
info.intMetrics,
info.intTimestamps,
out);
}
case MetricType::Uint64: {
return getNumericValue(metric.storeIdx,
metric.pos,
metric.filledMetrics,
historyOffset,
info.uint64Metrics,
info.uint64Timestamps,
out);
}
case MetricType::Float: {
return getNumericValue(metric.storeIdx,
metric.pos,
metric.filledMetrics,
historyOffset,
info.floatMetrics,
info.floatTimestamps,
out);
}
case MetricType::Enum: {
return getNumericValue(metric.storeIdx,
metric.pos,
metric.filledMetrics,
historyOffset,
info.enumMetrics,
info.enumTimestamps,
out);
}
case MetricType::String:
case MetricType::Unknown:
return false;
}
return false;
}
bool findMetricIndexByName(DeviceMetricsInfo const& info,
std::string_view metricName,
std::size_t& metricIndex)
{
auto const nMetrics = std::min(info.metrics.size(), info.metricLabels.size());
for (std::size_t i = 0; i < nMetrics; ++i) {
auto const& label = info.metricLabels[i];
std::string_view currentName{label.label, label.size};
if (currentName == metricName) {
metricIndex = i;
return true;
}
}
return false;
}
MetricAggregator::MetricAggregator()
{
mBackend = getBackendFromEnv();
if (mBackend == nullptr) {
LOGP(error, "[MetricAggregator] No backend configured, skipping initialization");
return;
}
mMonitoring = o2::monitoring::MonitoringFactory::Get(mBackend);
if (mMonitoring == nullptr) {
LOGP(error, "[MetricAggregator] Failed to create monitoring backend for '{}'", mBackend);
return;
}
mMonitoring->enableBuffering(MONITORING_QUEUE_SIZE);
setPolicy();
LOGP(info, "[MetricAggregator] Initialized with policy '{}'", getPolicy());
}
void MetricAggregator::setPolicy()
{
mPolicy = std::make_unique<AggregationPolicy>();
mPolicy->configureFromEnv();
}
std::string MetricAggregator::getPolicy()
{
std::stringstream ss;
std::string selectionStr;
switch (mPolicy->getSelection()) {
case AggregationSelectionType::All:
selectionStr = "All";
break;
case AggregationSelectionType::Specific:
selectionStr = "Specific";
break;
}
std::string reductionStr;
switch (mPolicy->getReduction()) {
case AggregationMetricType::Sum:
reductionStr = "Sum";
break;
case AggregationMetricType::Average:
reductionStr = "Average";
break;
case AggregationMetricType::Rate:
reductionStr = "Rate";
break;
case AggregationMetricType::Simple:
reductionStr = "Simple";
break;
case AggregationMetricType::Specific:
reductionStr = "Specific";
break;
}
ss << selectionStr << ":" << reductionStr;
return ss.str();
}
void MetricAggregator::mergeMetrics(const std::vector<DeviceMetricsInfo>& metrics,
const DeviceMetricsInfo& driverMetrics,
const std::vector<DeviceSpec>& specs)
{
if (mPolicy->getReduction() == AggregationMetricType::Simple) {
flushMetricsSimple(metrics, driverMetrics, specs);
} else {
flushMetrics(metrics, driverMetrics, specs);
}
}
std::string MetricAggregator::getMetricNameFromPolicy(std::string_view metricName, AggregationMetricType aggregationType)
{
std::string metricNameStr{metricName};
if (aggregationType == AggregationMetricType::Sum) {
metricNameStr += "_sum";
} else if (aggregationType == AggregationMetricType::Rate) {
metricNameStr += "_R";
} else if (aggregationType == AggregationMetricType::Average) {
metricNameStr += "_avg";
}
return metricNameStr;
}
void MetricAggregator::flushMetricsSimple(const std::vector<DeviceMetricsInfo>& deviceMetricsInfo,
const DeviceMetricsInfo& driverMetrics,
const std::vector<DeviceSpec>& specs)
{
auto const nDevices = std::min(deviceMetricsInfo.size(), specs.size());
if (nDevices == 0) {
return;
}
for (std::size_t di = 0; di < nDevices; ++di) {
auto const& deviceId = specs[di].id;
if (mPolicy && !mPolicy->selectDevice(deviceId)) {
continue;
}
auto const& deviceMetrics = deviceMetricsInfo[di];
auto const nMetrics = std::min({deviceMetrics.metrics.size(),
deviceMetrics.metricLabels.size(),
deviceMetrics.changed.size()});
auto monitoring = o2::monitoring::MonitoringFactory::Get(mBackend);
if (monitoring == nullptr) {
LOGP(error, "[MetricAggregator] Failed to create monitoring backend for '{}'", mBackend);
return;
}
monitoring->enableBuffering(MONITORING_QUEUE_SIZE);
monitoring->addGlobalTag("pipeline_id", std::to_string(specs[di].inputTimesliceId));
monitoring->addGlobalTag("dataprocessor_name", specs[di].name);
// FIXME: dpl_instance missing
for (std::size_t mi = 0; mi < nMetrics; ++mi) {
MetricSample sample;
if (!extractNumericSample(deviceMetrics, mi, 0, sample)) {
continue;
}
auto const metricName = std::string(deviceMetrics.metricLabels[mi].label, deviceMetrics.metricLabels[mi].size);
auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(std::chrono::milliseconds(sample.timestamp));
auto metric = o2::monitoring::Metric{metricName, o2::monitoring::Metric::DefaultVerbosity, tp};
metric.addValue(sample.value, "value");
monitoring->send(std::move(metric));
}
monitoring->flushBuffer();
}
}
void MetricAggregator::flushMetrics(const std::vector<DeviceMetricsInfo>& deviceMetrics,
const DeviceMetricsInfo& driverMetrics,
const std::vector<DeviceSpec>& specs)
{
auto const nDevices = std::min(deviceMetrics.size(), specs.size());
if (nDevices == 0) {
mMonitoring->flushBuffer();
return;
}
// Collect all unique metric names across devices to determine which metrics to aggregate.
std::unordered_set<std::string_view> allMetricNames;
for (const auto& deviceMetricsInfo : deviceMetrics) {
auto const nMetrics = std::min(deviceMetricsInfo.metrics.size(), deviceMetricsInfo.metricLabels.size());
for (std::size_t i = 0; i < nMetrics; ++i) {
allMetricNames.insert(std::string_view(deviceMetricsInfo.metricLabels[i].label, deviceMetricsInfo.metricLabels[i].size));
}
}
for (const auto& metricName : allMetricNames) {
try {
auto const metricAggregationType = mPolicy->getAggregationTypeForMetric(metricName);
if (metricAggregationType == AggregationMetricType::Simple) {
continue;
}
// Gather the latest metric values from each valid device
std::vector<MetricSample> deviceSamples;
deviceSamples.reserve(nDevices);
auto metricTimestamp = std::numeric_limits<std::size_t>::max();
for (std::size_t di = 0; di < nDevices; ++di) {
auto const& deviceId = specs[di].id;
if (mPolicy && !mPolicy->selectDevice(deviceId)) {
continue;
}
auto const& deviceMetricsInfo = deviceMetrics[di];
std::size_t deviceMetricIndex = 0;
if (!findMetricIndexByName(deviceMetricsInfo, metricName, deviceMetricIndex)) {
continue;
}
MetricSample latest;
if (!extractNumericSample(deviceMetricsInfo, deviceMetricIndex, 0, latest) || latest.timestamp == 0) {
continue;
}
deviceSamples.push_back(latest);
metricTimestamp = std::min(metricTimestamp, latest.timestamp);
}
if (deviceSamples.empty()) {
continue;
}
const auto handlers = std::unordered_map<AggregationMetricType,
std::function<double(const std::vector<MetricSample>&)>>{
{AggregationMetricType::Sum, [](const auto& windows) {
double sum = 0.0;
for (const auto& window : windows) {
sum += window.value;
}
return sum;
}},
{AggregationMetricType::Average, [](const auto& windows) {
double sum = 0.0;
std::size_t count = 0;
for (const auto& window : windows) {
sum += window.value;
++count;
}
return windows.empty() ? 0.0 : sum / count;
}},
{AggregationMetricType::Rate, [this, &metricName](const auto& windows) {
double sumRate = 0.0;
auto const& previousSamples = mLastSentSamples[std::string{metricName}];
if (mLastSentSamples.empty() || previousSamples.size() != windows.size()) {
return 0.0;
}
for (const auto& window : windows) {
double deltaValue = window.value - previousSamples[&window - &windows[0]].value;
double deltaTimeSec = (window.timestamp - previousSamples[&window - &windows[0]].timestamp) / 1000.0;
if (deltaTimeSec <= 0) {
continue;
}
sumRate += deltaValue / deltaTimeSec;
}
return sumRate;
}}};
double reducedValue = 0.0;
auto handlerIt = handlers.find(metricAggregationType);
if (handlerIt == handlers.end()) {
LOGP(error, "[MetricAggregator] No handler found for aggregation type '{}'", static_cast<int>(metricAggregationType));
continue;
}
reducedValue = handlerIt->second(deviceSamples);
if (reducedValue < 0) {
continue;
}
auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(std::chrono::milliseconds(metricTimestamp));
std::string metricNameWithPolicy = getMetricNameFromPolicy(metricName, metricAggregationType);
auto metric = Metric{metricNameWithPolicy, Metric::DefaultVerbosity, tp};
metric.addValue(reducedValue, "value");
mMonitoring->send(std::move(metric));
mLastSentSamples[std::string{metricName}] = deviceSamples;
} catch (const std::exception& e) {
LOGP(error, "[MetricAggregator] Error determining aggregation type: {}", e.what());
continue;
}
}
mMonitoring->flushBuffer();
}
const char* MetricAggregator::getBackendFromEnv()
{
const char* envBackend = std::getenv("APMON_CONFIG");
if (envBackend == nullptr) {
LOGP(error, "[MetricAggregator] APMON_CONFIG environment variable is not set");
return nullptr;
}
static std::string result = std::string("apmon://") + envBackend;
return result.c_str();
}
} // namespace o2::framework::metricaggregator