Skip to content

Add detailed client information to User-Agent #25889

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions client/trino-cli/src/main/java/io/trino/cli/QueryRunner.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@

import static io.trino.client.ClientSession.stripTransactionId;
import static io.trino.client.StatementClientFactory.newStatementClient;
import static io.trino.client.UserAgentBuilder.createUserAgent;
import static java.util.Objects.requireNonNull;

public class QueryRunner
implements Closeable
{
private static final String USER_AGENT = createUserAgent("trino-cli");

private final AtomicReference<ClientSession> session;
private final boolean debug;
private final OkHttpClient httpClient;
Expand All @@ -37,9 +40,9 @@ public class QueryRunner
public QueryRunner(TrinoUri uri, ClientSession session, boolean debug)
{
this.session = new AtomicReference<>(requireNonNull(session, "session is null"));
this.httpClient = HttpClientFactory.toHttpClientBuilder(uri, session.getSource()).build();
this.httpClient = HttpClientFactory.toHttpClientBuilder(uri, USER_AGENT).build();
this.segmentHttpClient = HttpClientFactory
.unauthenticatedClientBuilder(uri, session.getSource())
.unauthenticatedClientBuilder(uri, USER_AGENT)
.build();
this.debug = debug;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,10 @@
import java.util.function.Function;
import java.util.stream.Stream;

import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.getCausalChain;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.net.HttpHeaders.ACCEPT_ENCODING;
import static com.google.common.net.HttpHeaders.USER_AGENT;
import static io.trino.client.HttpStatusCodes.shouldRetry;
import static io.trino.client.ProtocolHeaders.TRINO_HEADERS;
import static io.trino.client.TrinoJsonCodec.jsonCodec;
Expand All @@ -82,10 +80,6 @@ class StatementClientV1
private static final TrinoJsonCodec<QueryResults> QUERY_RESULTS_CODEC = jsonCodec(QueryResults.class);

private static final Splitter COLLECTION_HEADER_SPLITTER = Splitter.on('=').limit(2).trimResults();
private static final String USER_AGENT_VALUE = StatementClientV1.class.getSimpleName() +
"/" +
firstNonNull(StatementClientV1.class.getPackage().getImplementationVersion(), "unknown");

private final Call.Factory httpCallFactory;
private final String query;
private final AtomicReference<QueryResults> currentResults = new AtomicReference<>();
Expand Down Expand Up @@ -384,9 +378,7 @@ public boolean isClearTransactionId()

private Request.Builder prepareRequest(HttpUrl url)
{
Request.Builder builder = new Request.Builder()
.addHeader(USER_AGENT, USER_AGENT_VALUE)
.url(url);
Request.Builder builder = new Request.Builder().url(url);
user.ifPresent(requestUser -> builder.addHeader(TRINO_HEADERS.requestUser(), requestUser));
originalUser.ifPresent(originalUser -> builder.addHeader(TRINO_HEADERS.requestOriginalUser(), originalUser));
if (compressionDisabled) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.client;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.StandardSystemProperty;
import com.google.common.collect.ImmutableMap;

import java.util.Locale;
import java.util.Map;

import static com.google.common.base.MoreObjects.firstNonNull;

public class UserAgentBuilder
{
private static final Joiner.MapJoiner MAP_JOINER = Joiner.on(" ").withKeyValueSeparator("=");
private static final String LANGUAGE = "lang/java";
private static final String OS_NAME = "os";
private static final String OS_VERSION = "os/version";
private static final String ARCH = "arch";
private static final String VENDOR = "java/vendor";
private static final String VM_NAME = "java/vm";
private static final String LOCALE = "locale";

private UserAgentBuilder() {}

public static String createUserAgent(String product)
{
return createUserAgent(product, getProductVersion());
}

public static String createUserAgent(String product, String version)
{
return createUserAgent(product, version, ImmutableMap.of());
}

public static String createUserAgent(String product, Map<String, String> metadata)
{
return createUserAgent(product, getProductVersion(), metadata);
}

public static String createUserAgent(String product, String version, Map<String, String> metadata)
{
ImmutableMap.Builder<String, String> sourceBuilder = ImmutableMap.builder();
sourceBuilder.put(OS_NAME, sanitize(StandardSystemProperty.OS_NAME.value()));
sourceBuilder.put(OS_VERSION, sanitize(StandardSystemProperty.OS_VERSION.value()));
sourceBuilder.put(ARCH, sanitize(StandardSystemProperty.OS_ARCH.value()));
sourceBuilder.put(LANGUAGE, StandardSystemProperty.JAVA_VM_VERSION.value());
sourceBuilder.put(VM_NAME, sanitize(StandardSystemProperty.JAVA_VM_NAME.value()));
sourceBuilder.put(VENDOR, sanitize(StandardSystemProperty.JAVA_VENDOR.value()));
sourceBuilder.put(LOCALE, Locale.getDefault().toLanguageTag());
sourceBuilder.putAll(metadata);

return String.format("%s/%s", product, version) + " " + MAP_JOINER.join(sourceBuilder.buildOrThrow());
}

@VisibleForTesting
static String sanitize(String value)
{
return value.replaceAll("[^a-zA-Z0-9_.-]+", "_");
}

private static String getProductVersion()
{
String version = UserAgentBuilder.class.getPackage().getImplementationVersion();
return firstNonNull(version, "unknown");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.client;

import com.google.common.base.Splitter;
import com.google.common.base.StandardSystemProperty;
import org.junit.jupiter.api.Test;

import java.util.Locale;
import java.util.Map;

import static io.trino.client.UserAgentBuilder.createUserAgent;
import static io.trino.client.UserAgentBuilder.sanitize;
import static org.assertj.core.api.Assertions.assertThat;

class TestUserAgentBuilder
{
private static final Splitter.MapSplitter MAP_SPLITTER = Splitter.on(' ').omitEmptyStrings().withKeyValueSeparator('=');

@Test
void testUserAgent()
{
String userAgent = createUserAgent("trino-cli", "1.0.0", Map.of("md/lang", "en-US", "md/feature", "experimental"));
assertThat(userAgent).startsWith("trino-cli/1.0.0");

Map<String, String> metadata = MAP_SPLITTER.split(userAgent.substring("trino-cli/1.0.0".length() + 1));
assertThat(metadata)
.containsEntry("lang/java", StandardSystemProperty.JAVA_VM_VERSION.value())
.containsEntry("java/vm", sanitize(StandardSystemProperty.JAVA_VM_NAME.value()))
.containsEntry("java/vendor", sanitize(StandardSystemProperty.JAVA_VENDOR.value()))
.containsEntry("os", sanitize(StandardSystemProperty.OS_NAME.value()))
.containsEntry("os/version", sanitize(StandardSystemProperty.OS_VERSION.value()))
.containsEntry("arch", sanitize(StandardSystemProperty.OS_ARCH.value()))
.containsEntry("locale", Locale.getDefault().toLanguageTag())
.containsEntry("md/lang", "en-US")
.containsEntry("md/feature", "experimental");
}

@Test
void testSanitization()
{
assertThat(sanitize("")).isEmpty();
assertThat(sanitize(" ")).isEqualTo("_");
assertThat(sanitize("a")).isEqualTo("a");
assertThat(sanitize("a b")).isEqualTo("a_b");
assertThat(sanitize("a b c")).isEqualTo("a_b_c");
assertThat(sanitize("a b c")).isEqualTo("a_b_c");
assertThat(sanitize("a -+ b c")).isEqualTo("a_-_b_c");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import java.util.Properties;
import java.util.logging.Logger;

import static io.trino.client.UserAgentBuilder.createUserAgent;
import static io.trino.jdbc.DriverInfo.DRIVER_NAME;
import static io.trino.jdbc.DriverInfo.DRIVER_VERSION;
import static io.trino.jdbc.DriverInfo.DRIVER_VERSION_MAJOR;
Expand All @@ -37,7 +38,8 @@
public class NonRegisteringTrinoDriver
implements Driver, Closeable
{
private static final String USER_AGENT = DRIVER_NAME + "/" + DRIVER_VERSION;
private static final String USER_AGENT = createUserAgent(DRIVER_NAME, DRIVER_VERSION);

private final Dispatcher dispatcher;
private final ConnectionPool pool;

Expand Down
Loading