|
19 | 19 | #include "absl/types/optional.h" |
20 | 20 | #include "absl/types/variant.h" |
21 | 21 | #include <opentelemetry/common/attribute_value.h> |
| 22 | +#include <opentelemetry/sdk/common/attribute_utils.h> |
| 23 | +#include <opentelemetry/sdk/instrumentationscope/instrumentation_scope.h> |
22 | 24 | #include <opentelemetry/sdk/resource/resource.h> |
23 | 25 | #include <opentelemetry/sdk/resource/semantic_conventions.h> |
24 | 26 | #include <numeric> |
| 27 | +#include <string> |
25 | 28 | #include <unordered_map> |
| 29 | +#include <unordered_set> |
26 | 30 |
|
27 | 31 | namespace google { |
28 | 32 | namespace cloud { |
@@ -229,6 +233,52 @@ MonitoredResource ToMonitoredResource( |
229 | 233 | return provider.Process(attributes); |
230 | 234 | } |
231 | 235 |
|
| 236 | +opentelemetry::sdk::metrics::ResourceMetrics |
| 237 | +GetCopyWithServiceResourceLabelsAsMetricLabels( |
| 238 | + opentelemetry::sdk::metrics::ResourceMetrics const& data) { |
| 239 | + if (!data.resource_) { |
| 240 | + return data; |
| 241 | + } |
| 242 | + |
| 243 | + std::unordered_set<std::string> const& kOtelServiceKeys{ |
| 244 | + sc::kServiceName, sc::kServiceNamespace, sc::kServiceInstanceId}; |
| 245 | + |
| 246 | + std::unordered_map<std::string, |
| 247 | + opentelemetry::sdk::common::OwnedAttributeValue> |
| 248 | + service_labels; |
| 249 | + auto resource_attributes = data.resource_->GetAttributes(); |
| 250 | + for (auto it = resource_attributes.begin(); it != resource_attributes.end(); |
| 251 | + ++it) { |
| 252 | + if (kOtelServiceKeys.find(it->first) != kOtelServiceKeys.end()) { |
| 253 | + service_labels[it->first] = it->second; |
| 254 | + } |
| 255 | + } |
| 256 | + |
| 257 | + if (service_labels.empty()) { |
| 258 | + return data; |
| 259 | + } |
| 260 | + |
| 261 | + opentelemetry::sdk::metrics::ResourceMetrics data_copy = data; |
| 262 | + for (opentelemetry::sdk::metrics::ScopeMetrics& scope_metrics : |
| 263 | + data_copy.scope_metric_data_) { |
| 264 | + for (opentelemetry::sdk::metrics::MetricData& metric : |
| 265 | + scope_metrics.metric_data_) { |
| 266 | + for (opentelemetry::sdk::metrics::PointDataAttributes& pda : |
| 267 | + metric.point_data_attr_) { |
| 268 | + auto& attributes = pda.attributes; |
| 269 | + for (auto it = service_labels.begin(); it != service_labels.end(); |
| 270 | + ++it) { |
| 271 | + if (attributes.find(it->first) == attributes.end()) { |
| 272 | + attributes[it->first] = it->second; |
| 273 | + } |
| 274 | + } |
| 275 | + } |
| 276 | + } |
| 277 | + } |
| 278 | + |
| 279 | + return data_copy; |
| 280 | +} |
| 281 | + |
232 | 282 | GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END |
233 | 283 | } // namespace otel_internal |
234 | 284 | } // namespace cloud |
|
0 commit comments