Skip to content

Commit 6d2ef39

Browse files
committed
Address feedback from Gemini code assistant
1 parent 43bdb07 commit 6d2ef39

6 files changed

Lines changed: 137 additions & 31 deletions

File tree

‎google/cloud/storage/grpc_plugin.h‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,21 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
6666
* telemetry).
6767
*
6868
* The exporter connects to Cloud Monitoring using the client's credentials, CA
69-
* certificates file, and proxy configuration. Telemetry is exported when the
70-
* client's endpoint host belongs to the client's universe domain, the client
71-
* does not use `google::cloud::MakeInsecureCredentials()`, and any universe
72-
* domain specified in the credentials matches the client's universe domain.
73-
* Setting this option to `true` does not override these requirements.
69+
* certificates file, and proxy configuration. Telemetry is exported only when
70+
* the client's endpoint host belongs to the client's universe domain, the
71+
* client does not use `google::cloud::MakeInsecureCredentials()`,
72+
* `google::cloud::MakeApiKeyCredentials()`, or
73+
* `google::cloud::MakeGDCHServiceAccountCredentials()`, and the credentials'
74+
* universe domain matches the client's universe domain. Credentials files
75+
* without a `universe_domain` field count as `googleapis.com`, and export is
76+
* disabled when a credentials' universe domain cannot be determined. These
77+
* requirements apply to `EnableGrpcMetricsOption`, `EnableOTelMetricsOption`,
78+
* and `EnableOTelDebugMetricsOption`; setting any of them to `true` does not
79+
* override them.
80+
*
81+
* Clients with the same `google::cloud::AuthorityOption` share one Cloud
82+
* Monitoring exporter for the life of the process, configured by the first such
83+
* client.
7484
*
7585
* Monitored resource attributes from the host (project, zone, and instance)
7686
* are used when the client authenticates through the host's metadata server.

‎google/cloud/storage/internal/grpc/enable_metrics.cc‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,18 @@ void EnableGrpcMetrics(
3737
Options const& storage_options,
3838
std::function<opentelemetry::sdk::resource::Resource()> const&
3939
detect_resource) {
40-
auto options = DefaultOptionsGrpc(storage_options);
40+
Options const options = DefaultOptionsGrpc(storage_options);
4141
// Avoid querying the metadata server for GCP resource attributes when metrics
42-
// export is disabled.
42+
// export is disabled or does not use host resource attributes.
4343
if (!AnyMetricsEnabled(options)) return;
44-
if (DetectMetricsExportMode(options) == MetricsExportMode::kDisabled) return;
44+
MetricsExportMode const mode = DetectMetricsExportMode(options);
45+
if (mode == MetricsExportMode::kDisabled) return;
46+
opentelemetry::sdk::resource::Resource const resource =
47+
mode == MetricsExportMode::kWithHostResource
48+
? detect_resource()
49+
: opentelemetry::sdk::resource::Resource::GetEmpty();
4550
std::optional<ExporterConfig> config =
46-
MakeMeterProviderConfig(detect_resource(), options);
51+
MakeMeterProviderConfig(resource, options);
4752
if (!config) return;
4853
EnableGrpcMetricsImpl(std::move(*config));
4954
}

‎google/cloud/storage/internal/grpc/enable_metrics.h‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ void EnableGrpcMetrics(Options const& storage_options);
3434
* Overload of `EnableGrpcMetrics` that takes an explicit resource detector for
3535
* testing.
3636
*
37-
* Invokes @p detect_resource only when metrics export is enabled for
38-
* @p storage_options, avoiding an unnecessary metadata server query otherwise.
37+
* Invokes @p detect_resource only when `DetectMetricsExportMode()` returns
38+
* `MetricsExportMode::kWithHostResource`, avoiding an unnecessary metadata
39+
* server query otherwise.
3940
*/
4041
void EnableGrpcMetrics(
4142
Options const& storage_options,

‎google/cloud/storage/internal/grpc/metrics_exporter_impl_test.cc‎

Lines changed: 88 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ auto TestOptions(Options opts = {}) {
9191
ScopedEnvironment("GCP_STORAGE_CPP_ENABLE_OTEL_METRICS", std::nullopt);
9292
auto debug_env = ScopedEnvironment(
9393
"GCP_STORAGE_CPP_ENABLE_OTEL_DEBUG_METRICS", std::nullopt);
94+
ScopedEnvironment const emulator_env(
95+
"CLOUD_STORAGE_EXPERIMENTAL_GRPC_TESTBENCH_ENDPOINT", std::nullopt);
96+
ScopedEnvironment const universe_env("GOOGLE_CLOUD_UNIVERSE_DOMAIN",
97+
std::nullopt);
9498
// Use the credentials of the host. Only for those does the resource passed
9599
// to `MakeMeterProviderConfig()` supply the monitoring project.
96100
opts.set<storage_experimental::EnableGrpcMetricsOption>(true)
@@ -1183,20 +1187,29 @@ INSTANTIATE_TEST_SUITE_P(
11831187
// Credentials that carry no universe are not compared.
11841188
CredentialsUniverseTestCase{"AccessTokenInOtherUniverse",
11851189
AccessTokenCredentials(), "ud.net", true},
1186-
CredentialsUniverseTestCase{"ApiKeyInOtherUniverse",
1187-
MakeApiKeyCredentials("test-only-api-key"),
1188-
"ud.net", true},
11891190
CredentialsUniverseTestCase{"ComputeEngineInOtherUniverse",
11901191
MakeComputeEngineCredentials(), "ud.net",
11911192
true},
11921193
CredentialsUniverseTestCase{
11931194
"ImpersonationFromAccessTokenInOtherUniverse",
11941195
ImpersonationFrom(AccessTokenCredentials()), "ud.net", true},
1196+
// Credentials not supported for Cloud Monitoring export.
1197+
CredentialsUniverseTestCase{"ApiKeyInDefaultUniverse",
1198+
MakeApiKeyCredentials("test-only-api-key"),
1199+
std::nullopt, false},
1200+
CredentialsUniverseTestCase{"ApiKeyInOtherUniverse",
1201+
MakeApiKeyCredentials("test-only-api-key"),
1202+
"ud.net", false},
1203+
CredentialsUniverseTestCase{
1204+
"GdchServiceAccountInDefaultUniverse",
1205+
MakeGDCHServiceAccountCredentials(
1206+
"{}", "https://test-only-audience.example.com"),
1207+
std::nullopt, false},
11951208
CredentialsUniverseTestCase{
11961209
"GdchServiceAccountInOtherUniverse",
11971210
MakeGDCHServiceAccountCredentials(
11981211
"{}", "https://test-only-audience.example.com"),
1199-
"ud.net", true},
1212+
"ud.net", false},
12001213
// Credentials that failed to load are passed on like any other. Each
12011214
// export then fails with the stored error.
12021215
CredentialsUniverseTestCase{
@@ -1402,6 +1415,27 @@ TEST_F(GrpcMetricsExporterConfigTest, LogsUnknownCredentialsUniverseDomain) {
14021415
"credentials"))));
14031416
}
14041417

1418+
/// @test Verify the log line reports unsupported credentials when export is
1419+
/// disabled for API key or GDCH credentials.
1420+
TEST_F(GrpcMetricsExporterConfigTest, LogsUnsupportedCredentials) {
1421+
for (std::shared_ptr<Credentials> const& credentials : {
1422+
MakeApiKeyCredentials("test-only-api-key"),
1423+
MakeGDCHServiceAccountCredentials(
1424+
"{}", "https://test-only-audience.example.com"),
1425+
}) {
1426+
ScopedLog log;
1427+
std::optional<ExporterConfig> const config = MakeMeterProviderConfig(
1428+
EmptyResource(),
1429+
DefaultOptionsGrpc(
1430+
EnabledOptionsWithProject().set<UnifiedCredentialsOption>(
1431+
credentials)));
1432+
EXPECT_FALSE(config.has_value());
1433+
EXPECT_THAT(log.ExtractLines(),
1434+
Contains(AllOf(HasSubstr("metrics export is disabled"),
1435+
HasSubstr("unsupported credentials"))));
1436+
}
1437+
}
1438+
14051439
/// @test Verify nothing is logged about a skipped exporter when the exporter
14061440
/// is created.
14071441
TEST_F(GrpcMetricsExporterConfigTest, DoesNotLogWhenExporting) {
@@ -1468,6 +1502,10 @@ INSTANTIATE_TEST_SUITE_P(
14681502
.set<storage_experimental::EnableGrpcMetricsOption>(false)
14691503
.set<storage_experimental::EnableOTelMetricsOption>(true)
14701504
.set<EndpointOption>("storage.ud.net")},
1505+
ResourceDetectionTestCase{
1506+
"ApiKeyCredentials",
1507+
Unified(MakeApiKeyCredentials("test-only-api-key"))
1508+
.set<storage_experimental::EnableGrpcMetricsOption>(true)},
14711509
ResourceDetectionTestCase{
14721510
"OTelDebugMetricsCredentialsForOtherUniverse",
14731511
Unified(ServiceAccountFor("ud.net"))
@@ -1554,12 +1592,32 @@ TEST_F(GrpcMetricsExporterConfigTest,
15541592
}
15551593
}
15561594

1557-
/// @test Verify the resource is detected once for a client that exports
1558-
/// metrics, and the exporter is created. The authority is unique to this test
1559-
/// because the registry of exporters is process-wide.
1595+
/// @test Verify the resource is detected once for a client using metadata
1596+
/// credentials, and the exporter is created. The authority is unique to this
1597+
/// test because the registry of exporters is process-wide.
15601598
TEST_F(GrpcMetricsExporterConfigTest, DetectsResourceOnceWhenExporting) {
15611599
std::string const authority = "test-only-detects-resource.example.com";
15621600
int detections = 0;
1601+
EnableGrpcMetrics(
1602+
EnabledOptionsWithProject()
1603+
.set<UnifiedCredentialsOption>(MakeComputeEngineCredentials())
1604+
.set<AuthorityOption>(authority),
1605+
[&detections] {
1606+
++detections;
1607+
return HostResource();
1608+
});
1609+
ScopedProviderShutdown const provider_shutdown(FindMeterProvider(authority));
1610+
EXPECT_EQ(detections, 1);
1611+
EXPECT_THAT(FindMeterProvider(authority), NotNull());
1612+
}
1613+
1614+
/// @test Verify `EnableGrpcMetrics()` skips GCP resource detection and still
1615+
/// creates an exporter when the client uses non-host credentials.
1616+
TEST_F(GrpcMetricsExporterConfigTest,
1617+
SkipsResourceDetectionForNonHostCredentials) {
1618+
std::string const authority =
1619+
"test-only-skips-detection-non-host.example.com";
1620+
int detections = 0;
15631621
EnableGrpcMetrics(EnabledOptionsWithProject()
15641622
.set<UnifiedCredentialsOption>(AccessTokenCredentials())
15651623
.set<AuthorityOption>(authority),
@@ -1568,10 +1626,32 @@ TEST_F(GrpcMetricsExporterConfigTest, DetectsResourceOnceWhenExporting) {
15681626
return HostResource();
15691627
});
15701628
ScopedProviderShutdown const provider_shutdown(FindMeterProvider(authority));
1571-
EXPECT_EQ(detections, 1);
1629+
EXPECT_EQ(detections, 0);
15721630
EXPECT_THAT(FindMeterProvider(authority), NotNull());
15731631
}
15741632

1633+
/// @test Verify clients sharing an authority reuse the first client's
1634+
/// `MeterProvider` even when later clients supply different credentials.
1635+
TEST_F(GrpcMetricsExporterConfigTest,
1636+
ReusesFirstExporterPerAuthorityAcrossCredentials) {
1637+
std::string const authority =
1638+
"test-only-reuses-provider-across-credentials.example.com";
1639+
EnableGrpcMetrics(EnabledOptionsWithProject()
1640+
.set<UnifiedCredentialsOption>(AccessTokenCredentials())
1641+
.set<AuthorityOption>(authority),
1642+
[] { return HostResource(); });
1643+
std::shared_ptr<opentelemetry::metrics::MeterProvider> const first =
1644+
FindMeterProvider(authority);
1645+
ScopedProviderShutdown const provider_shutdown(first);
1646+
ASSERT_THAT(first, NotNull());
1647+
1648+
EnableGrpcMetrics(EnabledOptions()
1649+
.set<UnifiedCredentialsOption>(ServiceAccount())
1650+
.set<AuthorityOption>(authority),
1651+
[] { return HostResource(); });
1652+
EXPECT_THAT(FindMeterProvider(authority), Eq(first));
1653+
}
1654+
15751655
} // namespace
15761656
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
15771657
} // namespace storage_internal

‎google/cloud/storage/internal/grpc/metrics_exporter_options.cc‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@
4444
#include <string_view>
4545
#include <type_traits>
4646
#include <variant>
47-
#include <vector>
4847

4948
namespace google {
5049
namespace cloud {
@@ -67,18 +66,18 @@ void Forward(Options const& from, Options& to) {
6766
// Returns true if @p host is a DNS name: non-empty labels of letters, digits
6867
// and `-`, separated by `.`.
6968
bool IsHostName(std::string_view host) {
70-
std::vector<std::string_view> const labels = absl::StrSplit(host, '.');
71-
return std::all_of(labels.begin(), labels.end(), [](std::string_view label) {
72-
return !label.empty() &&
73-
std::all_of(label.begin(), label.end(), [](unsigned char c) {
74-
return absl::ascii_isalnum(c) || c == '-';
75-
});
76-
});
69+
for (std::string_view const label : absl::StrSplit(host, '.')) {
70+
if (label.empty()) return false;
71+
for (unsigned char const c : label) {
72+
if (!absl::ascii_isalnum(c) && c != '-') return false;
73+
}
74+
}
75+
return true;
7776
}
7877

7978
// Extracts the DNS host from supported Storage gRPC targets (`google-c2p`
8079
// targets and scheme-less `host` or `host:port` endpoints). Returns an empty
81-
// view for other gRPC target formats (such as `unix:` or `dns:` URIs, IP
80+
// view for other gRPC target formats (such as `unix:` or `dns:` URIs, IPv6
8281
// literals, or targets with paths).
8382
std::string_view EndpointHost(std::string_view endpoint) {
8483
for (std::string_view prefix : {kC2pPrefix, kC2pExperimentalPrefix}) {
@@ -104,6 +103,7 @@ std::string_view EndpointHost(std::string_view endpoint) {
104103

105104
struct CredentialsSummary {
106105
bool insecure = false;
106+
bool unsupported = false;
107107
bool from_host = false;
108108
// False when a credential source carries a universe domain that could not
109109
// be read or parsed.
@@ -174,14 +174,18 @@ CredentialsSummary Summarize(Credentials const& credentials) {
174174
void visit(internal::ExternalAccountConfig const& cfg) override {
175175
FromCredentialsFile(cfg.json_object());
176176
}
177-
void visit(internal::ApiKeyConfig const&) override {}
177+
void visit(internal::ApiKeyConfig const&) override {
178+
summary.unsupported = true;
179+
}
178180
void visit(internal::ComputeEngineCredentialsConfig const&) override {
179181
summary.from_host = true;
180182
}
181183
void visit(internal::AuthorizedUserConfig const& cfg) override {
182184
FromCredentialsFile(cfg.json_object());
183185
}
184-
void visit(internal::GDCHServiceAccountConfig const&) override {}
186+
void visit(internal::GDCHServiceAccountConfig const&) override {
187+
summary.unsupported = true;
188+
}
185189
};
186190

187191
Visitor visitor;
@@ -300,6 +304,11 @@ MetricsExportMode DetectMetricsExportMode(Options const& options) {
300304
" insecure credentials";
301305
return MetricsExportMode::kDisabled;
302306
}
307+
if (summary.unsupported) {
308+
GCP_LOG(INFO) << "gRPC metrics export is disabled: the client uses"
309+
" unsupported credentials";
310+
return MetricsExportMode::kDisabled;
311+
}
303312
if (!summary.universe_domain_known) {
304313
GCP_LOG(INFO) << "gRPC metrics export is disabled: cannot determine the"
305314
" universe domain of the credentials, universe_domain="

‎google/cloud/storage/internal/grpc/metrics_exporter_options.h‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ enum class MetricsExportMode {
7272
*
7373
* - The client's endpoint must be a `google-c2p` target or `host[:port]` whose
7474
* host is a subdomain of the client's universe domain.
75-
* - The client must not use `MakeInsecureCredentials()`.
75+
* - The client must not use `MakeInsecureCredentials()`,
76+
* `MakeApiKeyCredentials()`, or `MakeGDCHServiceAccountCredentials()`.
7677
* - If the credentials specify a universe domain, it must match the client's
7778
* universe domain; if it cannot be determined, export is disabled.
7879
*

0 commit comments

Comments
 (0)