You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by xi...@apache.org on 2025/03/25 22:22:03 UTC
(pinot) branch master updated: Add BrokerGrpcServer for a streaming response fetching endpoint (#15088)
This is an automated email from the ASF dual-hosted git repository.
xiangfu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git
The following commit(s) were added to refs/heads/master by this push:
new 3a6a2f260a Add BrokerGrpcServer for a streaming response fetching endpoint (#15088)
3a6a2f260a is described below
commit 3a6a2f260a9470166646979f5db8fdb6e27fd304
Author: Xiang Fu <xi...@gmail.com>
AuthorDate: Tue Mar 25 15:21:58 2025 -0700
Add BrokerGrpcServer for a streaming response fetching endpoint (#15088)
* Add BrokerGrpcServer for a streaming response fetching endpoint
* Support JDBC next call using iterator
* Make grpc port auto discovery
---
.../broker/broker/helix/BaseBrokerStarter.java | 25 ++
.../apache/pinot/broker/grpc/BrokerGrpcServer.java | 352 +++++++++++++++++++++
.../pinot/broker/grpc/GrpcRequesterIdentity.java | 92 ++++++
.../java/org/apache/pinot/client/BrokerCache.java | 33 +-
.../pinot/client/BrokerCacheUpdaterPeriodic.java | 12 +-
.../java/org/apache/pinot/client/Connection.java | 2 +-
.../org/apache/pinot/client/ConnectionFactory.java | 38 ++-
.../client/ControllerBasedBrokerSelector.java | 6 -
.../apache/pinot/client/DynamicBrokerSelector.java | 23 +-
.../apache/pinot/client/ExternalViewReader.java | 21 +-
.../org/apache/pinot/client/ResultSetGroup.java | 9 +-
.../apache/pinot/client/UpdatableBrokerCache.java | 2 +-
.../apache/pinot/client/grpc/GrpcConnection.java | 294 +++++++++++++++++
.../pinot/client/grpc/GrpcPreparedStatement.java | 126 ++++++++
.../apache/pinot/client/grpc/GrpcResultSet.java | 134 ++++++++
.../GrpcResultSetGroup.java} | 90 +++---
.../org/apache/pinot/client/grpc/GrpcUtils.java | 100 ++++++
.../pinot/client/DynamicBrokerSelectorTest.java | 5 +
.../org/apache/pinot/client/PinotConnection.java | 31 +-
.../java/org/apache/pinot/client/PinotDriver.java | 14 +-
.../apache/pinot/client/PinotResultMetadata.java | 6 +-
.../org/apache/pinot/client/PinotResultSet.java | 6 +-
.../response/ControllerTenantBrokerResponse.java | 19 ++
.../pinot/client/examples/PinotJdbcExample.java | 95 ++++++
.../PinotGrpcConnection.java} | 88 ++----
.../client/grpc/PinotGrpcConnectionMetaData.java | 209 ++++++++++++
.../client/grpc/PinotGrpcPreparedStatement.java | 277 ++++++++++++++++
.../PinotGrpcResultSet.java} | 156 ++++-----
.../pinot/client/grpc/PinotGrpcStatement.java | 149 +++++++++
.../org/apache/pinot/client/utils/DriverUtils.java | 36 +++
.../common/compression/CompressionFactory.java | 59 ++++
.../pinot/common/compression/Compressor.java | 37 ++-
.../common/compression/DeflateCompressor.java | 57 ++++
.../pinot/common/compression/GzipCompressor.java | 54 ++++
.../pinot/common/compression/Lz4Compressor.java | 59 ++++
.../pinot/common/compression/SnappyCompressor.java | 29 +-
.../pinot/common/compression/ZstdCompressor.java | 69 ++++
.../apache/pinot/common/metrics/BrokerMeter.java | 10 +-
.../apache/pinot/common/metrics/BrokerTimer.java | 4 +-
.../pinot/common/response/BrokerResponse.java | 12 +-
.../common/utils/grpc/BrokerGrpcQueryClient.java | 2 +-
.../pinot/common/utils/helix/HelixHelper.java | 9 +
.../common/compression/DeflateCompressorTest.java | 104 ++++++
.../common/compression/GzipCompressorTest.java | 107 +++++++
.../common/compression/Lz4CompressorTest.java | 94 ++++++
.../common/compression/SnappyCompressorTest.java | 96 ++++++
.../common/compression/ZstdCompressorTest.java | 115 +++++++
.../controller/api/resources/InstanceInfo.java | 8 +-
.../api/resources/PinotBrokerRestletResource.java | 16 +-
.../controller/cursors/ResponseStoreCleaner.java | 4 +-
.../helix/core/PinotHelixResourceManager.java | 2 +-
.../pinot/controller/helix/ControllerTest.java | 1 +
.../pinot/integration/tests/ClusterTest.java | 32 +-
.../CustomDataQueryClusterIntegrationTest.java | 8 +
.../apache/pinot/spi/utils/CommonConstants.java | 12 +
.../org/apache/pinot/tools/QuickStartBase.java | 2 +-
56 files changed, 3150 insertions(+), 302 deletions(-)
diff --git a/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java b/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
index 316bdf42c6..3181d85457 100644
--- a/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
+++ b/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
@@ -43,6 +43,7 @@ import org.apache.helix.store.zk.ZkHelixPropertyStore;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.pinot.broker.broker.AccessControlFactory;
import org.apache.pinot.broker.broker.BrokerAdminApiApplication;
+import org.apache.pinot.broker.grpc.BrokerGrpcServer;
import org.apache.pinot.broker.queryquota.HelixExternalViewBasedQueryQuotaManager;
import org.apache.pinot.broker.requesthandler.BaseSingleStageBrokerRequestHandler;
import org.apache.pinot.broker.requesthandler.BrokerRequestHandler;
@@ -119,6 +120,7 @@ public abstract class BaseBrokerStarter implements ServiceStartable {
protected String _hostname;
protected int _port;
protected int _tlsPort;
+ protected int _grpcPort;
protected String _instanceId;
private volatile boolean _isStarting = false;
private volatile boolean _isShuttingDown = false;
@@ -148,6 +150,7 @@ public abstract class BaseBrokerStarter implements ServiceStartable {
protected HelixExternalViewBasedQueryQuotaManager _queryQuotaManager;
protected MultiStageQueryThrottler _multiStageQueryThrottler;
protected AbstractResponseStore _responseStore;
+ protected BrokerGrpcServer _brokerGrpcServer;
protected FailureDetector _failureDetector;
@Override
@@ -181,6 +184,7 @@ public abstract class BaseBrokerStarter implements ServiceStartable {
}
_port = _listenerConfigs.get(0).getPort();
_tlsPort = ListenerConfigUtil.findLastTlsPort(_listenerConfigs, -1);
+ _grpcPort = _brokerConf.getProperty(CommonConstants.Broker.Grpc.KEY_OF_GRPC_PORT, -1);
_instanceId = _brokerConf.getProperty(Broker.CONFIG_OF_BROKER_ID);
if (_instanceId == null) {
@@ -417,6 +421,14 @@ public abstract class BaseBrokerStarter implements ServiceStartable {
_brokerAdminApplication = createBrokerAdminApp();
_brokerAdminApplication.start(_listenerConfigs);
+ if (BrokerGrpcServer.isEnabled(_brokerConf)) {
+ LOGGER.info("Initializing BrokerGrpcServer");
+ _brokerGrpcServer = new BrokerGrpcServer(_brokerConf, brokerId, _brokerMetrics, _brokerRequestHandler);
+ _brokerGrpcServer.start();
+ } else {
+ LOGGER.info("BrokerGrpcServer is not enabled");
+ }
+
LOGGER.info("Initializing cluster change mediator");
for (ClusterChangeHandler clusterConfigChangeHandler : _clusterConfigChangeHandlers) {
clusterConfigChangeHandler.init(_spectatorHelixManager);
@@ -522,6 +534,14 @@ public abstract class BaseBrokerStarter implements ServiceStartable {
if (_tlsPort > 0) {
HelixHelper.updateTlsPort(instanceConfig, _tlsPort);
}
+ // Update GRPC query engine port
+ if (BrokerGrpcServer.isEnabled(_brokerConf)) {
+ int grpcPort = BrokerGrpcServer.getGrpcPort(_brokerConf);
+ updated |= updatePortIfNeeded(simpleFields, Helix.Instance.GRPC_PORT_KEY, grpcPort);
+ } else {
+ updated |= updatePortIfNeeded(simpleFields, Helix.Instance.GRPC_PORT_KEY, -1);
+ }
+
// Update multi-stage query engine ports
if (_brokerConf.getProperty(Helix.CONFIG_OF_MULTI_STAGE_ENGINE_ENABLED, Helix.DEFAULT_MULTI_STAGE_ENGINE_ENABLED)) {
updated |= updatePortIfNeeded(simpleFields, Helix.Instance.MULTI_STAGE_QUERY_ENGINE_MAILBOX_PORT_KEY,
@@ -649,6 +669,11 @@ public abstract class BaseBrokerStarter implements ServiceStartable {
LOGGER.error("Caught exception while waiting for shutdown delay of {}ms", delayShutdownTimeMs, e);
}
+ if (_brokerGrpcServer != null) {
+ LOGGER.info("Stopping broker grpc server");
+ _brokerGrpcServer.shutdown();
+ }
+
LOGGER.info("Shutting down request handler and broker admin application");
_brokerRequestHandler.shutDown();
_brokerAdminApplication.stop();
diff --git a/pinot-broker/src/main/java/org/apache/pinot/broker/grpc/BrokerGrpcServer.java b/pinot-broker/src/main/java/org/apache/pinot/broker/grpc/BrokerGrpcServer.java
new file mode 100644
index 0000000000..b4e07d4f89
--- /dev/null
+++ b/pinot-broker/src/main/java/org/apache/pinot/broker/grpc/BrokerGrpcServer.java
@@ -0,0 +1,352 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.broker.grpc;
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.protobuf.ByteString;
+import io.grpc.Attributes;
+import io.grpc.Grpc;
+import io.grpc.Server;
+import io.grpc.ServerBuilder;
+import io.grpc.ServerTransportFilter;
+import io.grpc.Status;
+import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
+import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
+import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth;
+import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext;
+import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
+import io.grpc.netty.shaded.io.netty.handler.ssl.SslProvider;
+import io.grpc.stub.StreamObserver;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import java.util.stream.Collectors;
+import nl.altindag.ssl.SSLFactory;
+import org.apache.pinot.broker.api.RequesterIdentity;
+import org.apache.pinot.broker.requesthandler.BrokerRequestHandler;
+import org.apache.pinot.common.compression.CompressionFactory;
+import org.apache.pinot.common.compression.Compressor;
+import org.apache.pinot.common.config.GrpcConfig;
+import org.apache.pinot.common.config.TlsConfig;
+import org.apache.pinot.common.metrics.BrokerMeter;
+import org.apache.pinot.common.metrics.BrokerMetrics;
+import org.apache.pinot.common.proto.Broker;
+import org.apache.pinot.common.proto.PinotQueryBrokerGrpc;
+import org.apache.pinot.common.response.BrokerResponse;
+import org.apache.pinot.common.response.broker.BrokerResponseNative;
+import org.apache.pinot.common.response.broker.ResultTable;
+import org.apache.pinot.common.utils.request.RequestUtils;
+import org.apache.pinot.common.utils.tls.RenewableTlsUtils;
+import org.apache.pinot.common.utils.tls.TlsUtils;
+import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.exception.QueryErrorCode;
+import org.apache.pinot.spi.trace.DefaultRequestContext;
+import org.apache.pinot.spi.trace.RequestContext;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.pinot.sql.parsers.SqlNodeAndOptions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class BrokerGrpcServer extends PinotQueryBrokerGrpc.PinotQueryBrokerImplBase {
+ private static final Logger LOGGER = LoggerFactory.getLogger(BrokerGrpcServer.class);
+
+ private final String _brokerId;
+ private final Server _server;
+ private final int _grpcPort;
+ private final int _secureGrpcPort;
+ private final GrpcConfig _queryClientConfig;
+ private final BrokerMetrics _brokerMetrics;
+ private final BrokerRequestHandler _brokerRequestHandler;
+
+ // Filter to keep track of gRPC connections.
+ private class BrokerGrpcTransportFilter extends ServerTransportFilter {
+ @Override
+ public Attributes transportReady(Attributes transportAttrs) {
+ LOGGER.info("gRPC transportReady: REMOTE_ADDR {}",
+ transportAttrs != null ? transportAttrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR) : "null");
+ _brokerMetrics.addMeteredGlobalValue(BrokerMeter.GRPC_TRANSPORT_READY, 1);
+ return super.transportReady(transportAttrs);
+ }
+
+ @Override
+ public void transportTerminated(Attributes transportAttrs) {
+ // transportTerminated can be called without transportReady before it, e.g. handshake fails
+ // So, don't emit metrics if transportAttrs is null
+ if (transportAttrs != null) {
+ LOGGER.info("gRPC transportTerminated: REMOTE_ADDR {}", transportAttrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR));
+ _brokerMetrics.addMeteredGlobalValue(BrokerMeter.GRPC_TRANSPORT_TERMINATED, 1);
+ }
+ }
+ }
+
+ public BrokerGrpcServer(PinotConfiguration brokerConf, String brokerId, BrokerMetrics brokerMetrics,
+ BrokerRequestHandler brokerRequestHandler) {
+ _brokerMetrics = brokerMetrics;
+ _grpcPort = brokerConf.getProperty(CommonConstants.Broker.Grpc.KEY_OF_GRPC_PORT, -1);
+ _queryClientConfig = createQueryClientConfig(brokerConf);
+ LOGGER.info("gRPC query client config: usePlainText {}", _queryClientConfig.isUsePlainText());
+ _secureGrpcPort = brokerConf.getProperty(CommonConstants.Broker.Grpc.KEY_OF_GRPC_TLS_PORT, -1);
+ if (_secureGrpcPort > 0) {
+ try {
+ TlsConfig tlsConfig = TlsUtils.extractTlsConfig(brokerConf, CommonConstants.Broker.BROKER_TLS_PREFIX);
+ LOGGER.info("Creating Secure gRPC Server in port {}", _secureGrpcPort);
+ _server =
+ NettyServerBuilder.forPort(_secureGrpcPort).sslContext(buildGRpcSslContext(tlsConfig)).addService(this)
+ .addTransportFilter(new BrokerGrpcTransportFilter()).build();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to start secure grpcQueryServer", e);
+ }
+ } else if (_grpcPort > 0) {
+ LOGGER.info("Creating plain text gRPC Server in port {}", _grpcPort);
+ _server =
+ ServerBuilder.forPort(_grpcPort).addService(this).addTransportFilter(new BrokerGrpcTransportFilter()).build();
+ } else {
+ LOGGER.info("Not creating gRPC Server due to the grpc port is {} and secureGrpcPort is {}", _grpcPort,
+ _secureGrpcPort);
+ _server = null;
+ }
+ _brokerId = brokerId;
+ _brokerRequestHandler = brokerRequestHandler;
+ LOGGER.info("Initialized BrokerGrpcServer on port: {}", _grpcPort);
+ }
+
+ public void start() {
+ if (_server == null) {
+ LOGGER.info("BrokerGrpcServer is not configured, nothing to start");
+ return;
+ }
+ LOGGER.info("Starting BrokerGrpcServer");
+ try {
+ _server.start();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void shutdown() {
+ if (_server == null) {
+ LOGGER.info("BrokerGrpcServer is not running, nothing to shutdown");
+ return;
+ }
+ LOGGER.info("Shutting down BrokerGrpcServer");
+ try {
+ _server.shutdown().awaitTermination();
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void submit(Broker.BrokerRequest request,
+ StreamObserver<Broker.BrokerResponse> responseObserver) {
+ if (_server == null) {
+ LOGGER.info("BrokerGrpcServer is not running, nothing to handle request");
+ responseObserver.onError(new RuntimeException("BrokerGrpcServer is not running"));
+ return;
+ }
+ long startTime = System.nanoTime();
+ _brokerMetrics.addMeteredGlobalValue(BrokerMeter.GRPC_QUERIES, 1);
+ _brokerMetrics.addMeteredGlobalValue(BrokerMeter.GRPC_BYTES_RECEIVED, request.getSerializedSize());
+ String query = request.getSql();
+ Map<String, String> metadataMap = request.getMetadataMap();
+ // convert request.getMetadataMap() to JsonNode
+ ObjectNode requestJsonNode = JsonUtils.newObjectNode();
+ requestJsonNode.put(CommonConstants.Broker.Request.SQL, query);
+ for (Map.Entry<String, String> entry : metadataMap.entrySet()) {
+ requestJsonNode.put(entry.getKey(), entry.getValue());
+ }
+
+ SqlNodeAndOptions sqlNodeAndOptions;
+ try {
+ sqlNodeAndOptions = RequestUtils.parseQuery(query, requestJsonNode);
+ } catch (Exception e) {
+ // Do not log or emit metric here because it is pure user error
+ Broker.BrokerResponse errorBlock;
+ try {
+ errorBlock = Broker.BrokerResponse.newBuilder().setPayload(ByteString.copyFrom(
+ new BrokerResponseNative(QueryErrorCode.SQL_PARSING, e.getMessage()).toJsonString().getBytes())).build();
+ } catch (IOException ex) {
+ responseObserver.onCompleted();
+ throw new RuntimeException(ex);
+ }
+ responseObserver.onNext(errorBlock);
+ responseObserver.onCompleted();
+ return;
+ }
+
+ RequesterIdentity requesterIdentify = GrpcRequesterIdentity.fromRequest(request);
+ RequestContext requestContext = new DefaultRequestContext();
+ BrokerResponse brokerResponse;
+ try {
+ brokerResponse =
+ _brokerRequestHandler.handleRequest(requestJsonNode, sqlNodeAndOptions, requesterIdentify, requestContext,
+ null);
+ } catch (Exception e) {
+ _brokerMetrics.addMeteredGlobalValue(BrokerMeter.GRPC_QUERY_EXCEPTIONS, 1);
+ LOGGER.error("Error handling DQL request:\n{}\nException: {}", requestJsonNode, e);
+ responseObserver.onError(
+ Status.INTERNAL.withDescription(e.getMessage()).withCause(e)
+ .asRuntimeException());
+ throw new RuntimeException(e);
+ }
+ ResultTable resultTable = brokerResponse.getResultTable();
+ // Handle empty and error block
+ if (resultTable == null) {
+ if (brokerResponse.getExceptionsSize() > 0) {
+ _brokerMetrics.addMeteredGlobalValue(BrokerMeter.GRPC_QUERY_EXCEPTIONS, 1);
+ }
+ Broker.BrokerResponse emptyOrErrorBlock;
+ try {
+ emptyOrErrorBlock =
+ Broker.BrokerResponse.newBuilder().setPayload(ByteString.copyFrom(brokerResponse.toJsonString().getBytes()))
+ .build();
+ } catch (IOException e) {
+ responseObserver.onCompleted();
+ throw new RuntimeException(e);
+ }
+ responseObserver.onNext(emptyOrErrorBlock);
+ responseObserver.onCompleted();
+ return;
+ }
+ // Handle query response:
+ // First block is metadata
+ try {
+ Broker.BrokerResponse metadataBlock =
+ Broker.BrokerResponse.newBuilder()
+ .setPayload(ByteString.copyFrom(brokerResponse.toMetadataJsonString().getBytes()))
+ .build();
+ responseObserver.onNext(metadataBlock);
+ } catch (IOException e) {
+ responseObserver.onError(e);
+ throw new RuntimeException(e);
+ }
+ // Second block is data schema
+ try {
+ Broker.BrokerResponse schemaBlock =
+ Broker.BrokerResponse.newBuilder().setPayload(ByteString.copyFrom(resultTable.getDataSchema().toBytes()))
+ .build();
+ responseObserver.onNext(schemaBlock);
+ } catch (IOException e) {
+ responseObserver.onError(e);
+ throw new RuntimeException(e);
+ }
+ int blockRowSize =
+ Integer.parseInt(metadataMap.getOrDefault(CommonConstants.Broker.Grpc.BLOCK_ROW_SIZE,
+ String.valueOf(CommonConstants.Broker.Grpc.DEFAULT_BLOCK_ROW_SIZE)));
+
+ String compressionAlgorithm = metadataMap.getOrDefault(CommonConstants.Broker.Grpc.COMPRESSION,
+ CommonConstants.Broker.Grpc.DEFAULT_COMPRESSION);
+ Compressor compressor = CompressionFactory.getCompressor(compressionAlgorithm);
+ // Multiple response blocks are compressed data rows
+ for (int i = 0; i < resultTable.getRows().size(); i += blockRowSize) {
+ try {
+ int rowSize = 0;
+ // Serialize the rows to a byte array
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+
+ for (int j = i; j < Math.min(i + blockRowSize, resultTable.getRows().size()); j++) {
+ String rowString = JsonUtils.objectToJsonNode(resultTable.getRows().get(j)).toString();
+ byte[] bytesToWrite = rowString.getBytes(StandardCharsets.UTF_8);
+ byteArrayOutputStream.write(ByteBuffer.allocate(4).putInt(bytesToWrite.length).array());
+ byteArrayOutputStream.write(bytesToWrite);
+ rowSize += 1;
+ }
+
+ // Compress the byte array using the compressor
+ byte[] serializedData = byteArrayOutputStream.toByteArray();
+ byte[] compressedResultTable = compressor.compress(serializedData);
+ int originalSize = serializedData.length;
+ int compressedSize = compressedResultTable.length;
+ Broker.BrokerResponse dataBlock =
+ Broker.BrokerResponse.newBuilder()
+ .setPayload(ByteString.copyFrom(compressedResultTable))
+ .putMetadata("originalSize", String.valueOf(originalSize))
+ .putMetadata("compressedSize", String.valueOf(compressedSize))
+ .putMetadata("rowSize", String.valueOf(rowSize))
+ .putMetadata("compression", compressionAlgorithm)
+ .build();
+ responseObserver.onNext(dataBlock);
+ } catch (Exception e) {
+ responseObserver.onError(e);
+ throw new RuntimeException(e);
+ }
+ }
+ responseObserver.onCompleted();
+ }
+
+ //TODO: move this method from OSS Pinot class into util, and then re-use this util
+ @VisibleForTesting
+ static SslContext buildGRpcSslContext(TlsConfig tlsConfig)
+ throws Exception {
+ LOGGER.info("Building gRPC SSL context with");
+ if (tlsConfig.getKeyStorePath() == null) {
+ throw new IllegalArgumentException("Must provide key store path for secured gRPC server");
+ } else {
+ SSLFactory sslFactory =
+ RenewableTlsUtils.createSSLFactoryAndEnableAutoRenewalWhenUsingFileStores(tlsConfig);
+ // since tlsConfig.getKeyStorePath() is not null, sslFactory.getKeyManagerFactory().get() should not be null
+ SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(sslFactory.getKeyManagerFactory().get())
+ .sslProvider(SslProvider.valueOf(tlsConfig.getSslProvider()));
+ sslFactory.getTrustManagerFactory().ifPresent(sslContextBuilder::trustManager);
+
+ if (tlsConfig.isClientAuthEnabled()) {
+ sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
+ }
+
+ return GrpcSslContexts.configure(sslContextBuilder).build();
+ }
+ }
+
+ @VisibleForTesting
+ static GrpcConfig createQueryClientConfig(PinotConfiguration brokerConf) {
+ Map<String, Object> target = brokerConf.toMap();
+ target.put(GrpcConfig.CONFIG_USE_PLAIN_TEXT,
+ !brokerConf.getProperty(CommonConstants.Broker.Grpc.KEY_OF_GRPC_TLS_ENABLED, false));
+ Map<String, Object> convertedTlsMap =
+ target.keySet()
+ .stream()
+ .filter(propName -> propName.startsWith(
+ CommonConstants.Broker.Grpc.KEY_OF_GRPC_TLS_PREFIX))
+ .collect(Collectors.toMap(
+ propName -> GrpcConfig.GRPC_TLS_PREFIX + "." + propName.substring(
+ CommonConstants.Broker.Grpc.KEY_OF_GRPC_TLS_PREFIX.length() + 1),
+ target::get
+ ));
+ target.putAll(convertedTlsMap);
+ return new GrpcConfig(target);
+ }
+
+ public static boolean isEnabled(PinotConfiguration brokerConf) {
+ return (brokerConf.getProperty(CommonConstants.Broker.Grpc.KEY_OF_GRPC_PORT, -1) > 0)
+ || (brokerConf.getProperty(CommonConstants.Broker.Grpc.KEY_OF_GRPC_TLS_PORT, -1) > 0);
+ }
+
+ public static int getGrpcPort(PinotConfiguration brokerConf) {
+ int secureGrpcPort = brokerConf.getProperty(CommonConstants.Broker.Grpc.KEY_OF_GRPC_TLS_PORT, -1);
+ if (secureGrpcPort > 0) {
+ return secureGrpcPort;
+ }
+ return brokerConf.getProperty(CommonConstants.Broker.Grpc.KEY_OF_GRPC_PORT, -1);
+ }
+}
diff --git a/pinot-broker/src/main/java/org/apache/pinot/broker/grpc/GrpcRequesterIdentity.java b/pinot-broker/src/main/java/org/apache/pinot/broker/grpc/GrpcRequesterIdentity.java
new file mode 100644
index 0000000000..12755a641a
--- /dev/null
+++ b/pinot-broker/src/main/java/org/apache/pinot/broker/grpc/GrpcRequesterIdentity.java
@@ -0,0 +1,92 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.broker.grpc;
+
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Multimap;
+import java.util.Map;
+import org.apache.pinot.broker.api.RequesterIdentity;
+import org.apache.pinot.common.proto.Broker;
+import org.apache.pinot.common.proto.Server;
+import org.apache.pinot.spi.utils.CommonConstants;
+
+
+public class GrpcRequesterIdentity extends RequesterIdentity {
+ private Multimap<String, String> _metadata;
+
+ public static GrpcRequesterIdentity fromRequest(Server.ServerRequest request) {
+ Multimap<String, String> metadata = ArrayListMultimap.create();
+ for (Map.Entry<String, String> entry : request.getMetadataMap().entrySet()) {
+ metadata.put(entry.getKey(), entry.getValue());
+ }
+ GrpcRequesterIdentity identity = new GrpcRequesterIdentity();
+ identity.setMetadata(metadata);
+ return identity;
+ }
+
+ public static GrpcRequesterIdentity fromRequest(Broker.BrokerRequest request) {
+ Multimap<String, String> metadata = ArrayListMultimap.create();
+ for (Map.Entry<String, String> entry : request.getMetadataMap().entrySet()) {
+ metadata.put(entry.getKey(), entry.getValue());
+ }
+ GrpcRequesterIdentity identity = new GrpcRequesterIdentity();
+ identity.setMetadata(metadata);
+ return identity;
+ }
+
+ public Multimap<String, String> getMetadata() {
+ return _metadata;
+ }
+
+ public void setMetadata(Multimap<String, String> metadata) {
+ _metadata = metadata;
+ }
+
+ /**
+ * Following the same logic of
+ * {@link org.apache.pinot.broker.api.HttpRequesterIdentity} to get client IP
+ * If reverse proxy is used X-Forwarded-For will be populated
+ * If X-Forwarded-For is not present, check if x-real-ip is present
+ * Since X-Forwarded-For can contain comma separated list of values,
+ * we convert it to ";" delimiter to avoid
+ * downstream parsing errors for other fields where "," is being used
+ */
+ @Override
+ public String getClientIp() {
+ if (_metadata != null) {
+ StringBuilder clientIp = new StringBuilder();
+ for (Map.Entry<String, String> entry : _metadata.entries()) {
+ String key = entry.getKey();
+ String value = entry.getValue();
+ if (key.equalsIgnoreCase("x-forwarded-for")) {
+ if (value.contains(",")) {
+ clientIp.append(String.join(";", value.split(",")));
+ } else {
+ clientIp.append(value);
+ }
+ } else if (key.equalsIgnoreCase("x-real-ip")) {
+ clientIp.append(value);
+ }
+ }
+ return clientIp.length() == 0 ? CommonConstants.UNKNOWN : clientIp.toString();
+ } else {
+ return super.getClientIp();
+ }
+ }
+}
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/BrokerCache.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/BrokerCache.java
index c2e1b98caf..3289f61949 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/BrokerCache.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/BrokerCache.java
@@ -22,6 +22,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.type.TypeReference;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.JdkSslContext;
+import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
@@ -59,6 +60,7 @@ public class BrokerCache {
private static class BrokerInstance {
private String _host;
private Integer _port;
+ private Integer _grpcPort;
public String getHost() {
return _host;
@@ -75,6 +77,14 @@ public class BrokerCache {
public void setPort(Integer port) {
_port = port;
}
+
+ public Integer getGrpcPort() {
+ return _grpcPort;
+ }
+
+ public void setGrpcPort(Integer grpcPort) {
+ _grpcPort = grpcPort;
+ }
}
private static final TypeReference<Map<String, List<BrokerInstance>>> RESPONSE_TYPE_REF =
@@ -91,6 +101,7 @@ public class BrokerCache {
private final Map<String, String> _headers;
private final Properties _properties;
private volatile BrokerData _brokerData;
+ private final boolean _useGrpcPort;
public BrokerCache(Properties properties, String controllerUrl) {
String scheme = properties.getProperty(SCHEME, CommonConstants.HTTP_PROTOCOL);
@@ -124,6 +135,7 @@ public class BrokerCache {
ControllerRequestURLBuilder.baseUrl(scheme + "://" + controllerUrl);
_address = controllerRequestURLBuilder.forLiveBrokerTablesGet();
_headers = ConnectionUtils.getHeadersFromProperties(properties);
+ _useGrpcPort = Boolean.parseBoolean(properties.getProperty("useGrpcPort", "false"));
_properties = properties;
}
@@ -147,9 +159,19 @@ public class BrokerCache {
for (Map.Entry<String, List<BrokerInstance>> tableToBrokers : responses.entrySet()) {
List<String> brokersForTable = new ArrayList<>();
tableToBrokers.getValue().forEach(br -> {
- String brokerHostPort = br.getHost() + ":" + br.getPort();
- brokersForTable.add(brokerHostPort);
- brokers.add(brokerHostPort);
+ if (_useGrpcPort) {
+ // Intentionally skip the broker if the grpc port is not set.
+ Integer grpcPort = br.getGrpcPort();
+ if ((grpcPort != null) && (grpcPort > 0)) {
+ String brokerHostPort = br.getHost() + ":" + grpcPort;
+ brokersForTable.add(brokerHostPort);
+ brokers.add(brokerHostPort);
+ }
+ } else {
+ String brokerHostPort = br.getHost() + ":" + br.getPort();
+ brokersForTable.add(brokerHostPort);
+ brokers.add(brokerHostPort);
+ }
});
String tableName = tableToBrokers.getKey();
tableToBrokersMap.put(tableName, brokersForTable);
@@ -203,4 +225,9 @@ public class BrokerCache {
public List<String> getBrokers() {
return _brokerData.getBrokers();
}
+
+ public void close()
+ throws IOException {
+ _client.close();
+ }
}
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/BrokerCacheUpdaterPeriodic.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/BrokerCacheUpdaterPeriodic.java
index c8d8b58049..93f7c47af1 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/BrokerCacheUpdaterPeriodic.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/BrokerCacheUpdaterPeriodic.java
@@ -26,6 +26,7 @@ import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
/**
* Maintains broker cache this is updated periodically
*/
@@ -46,7 +47,8 @@ public class BrokerCacheUpdaterPeriodic implements UpdatableBrokerCache {
properties.getProperty(BROKER_UPDATE_FREQUENCY_MILLIS, DEFAULT_BROKER_UPDATE_FREQUENCY_MILLIS));
}
- public void init() throws Exception {
+ public void init()
+ throws Exception {
_brokerCache.updateBrokerData();
if (_brokerUpdateFreqInMillis > 0) {
@@ -73,11 +75,17 @@ public class BrokerCacheUpdaterPeriodic implements UpdatableBrokerCache {
}
@Override
- public void triggerBrokerCacheUpdate() throws Exception {
+ public void triggerBrokerCacheUpdate()
+ throws Exception {
_brokerCache.updateBrokerData();
}
public void close() {
+ try {
+ _brokerCache.close();
+ } catch (Exception e) {
+ LOGGER.error("Cannot close Broker Cache", e);
+ }
try {
_scheduledExecutorService.shutdown();
} catch (Exception e) {
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/Connection.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/Connection.java
index 429c7be76a..5908ece834 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/Connection.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/Connection.java
@@ -142,7 +142,7 @@ public class Connection {
* @return name of all the tables used in a sql query.
*/
@Nullable
- private static String[] resolveTableName(String query) {
+ public static String[] resolveTableName(String query) {
try {
SqlNodeAndOptions sqlNodeAndOptions = CalciteSqlParser.compileToSqlNodeAndOptions(query);
Set<String> tableNames =
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ConnectionFactory.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ConnectionFactory.java
index 45a92be48b..86e1667513 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ConnectionFactory.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ConnectionFactory.java
@@ -22,6 +22,7 @@ import com.google.common.annotations.VisibleForTesting;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
+import org.apache.pinot.client.grpc.GrpcConnection;
/**
@@ -143,6 +144,20 @@ public class ConnectionFactory {
}
}
+ /**
+ * @param properties
+ * @param controllerUrl url host:port of the controller
+ * @return A connection that connects to brokers as per the given controller
+ */
+ public static GrpcConnection fromControllerGrpc(Properties properties, String controllerUrl) {
+ try {
+ properties.setProperty("useGrpcPort", "true");
+ return new GrpcConnection(properties, new ControllerBasedBrokerSelector(properties, controllerUrl));
+ } catch (Exception e) {
+ throw new PinotClientException(e);
+ }
+ }
+
/**
* Creates a connection to a Pinot cluster, given its Zookeeper URL
*
@@ -153,7 +168,9 @@ public class ConnectionFactory {
*/
public static Connection fromZookeeper(Properties properties, String zkUrl, PinotClientTransport transport) {
try {
- return fromZookeeper(properties, new DynamicBrokerSelector(zkUrl), transport);
+ boolean preferTls = Boolean.parseBoolean(properties.getProperty("preferTLS", "false"));
+ boolean useGrpcPort = Boolean.parseBoolean(properties.getProperty("useGrpcPort", "false"));
+ return fromZookeeper(properties, new DynamicBrokerSelector(zkUrl, preferTls, useGrpcPort), transport);
} catch (Exception e) {
throw new PinotClientException(e);
}
@@ -170,6 +187,21 @@ public class ConnectionFactory {
return new Connection(properties, dynamicBrokerSelector, transport);
}
+ /**
+ * Creates a connection to a Pinot cluster, given its Zookeeper URL
+ *
+ * @param properties The Pinot connection properties
+ * @param zkUrl The URL to the Zookeeper cluster, must include the cluster name e.g host:port/chroot/pinot-cluster
+ * @return A connection that connects to the brokers in the given Helix cluster
+ */
+ public static GrpcConnection fromZookeeperGrpc(Properties properties, String zkUrl) {
+ try {
+ return new GrpcConnection(properties, new DynamicBrokerSelector(zkUrl, false, true));
+ } catch (Exception e) {
+ throw new PinotClientException(e);
+ }
+ }
+
/**
* Creates a connection from properties containing the connection parameters.
*
@@ -225,6 +257,10 @@ public class ConnectionFactory {
return new Connection(properties, brokers, transport);
}
+ public static GrpcConnection fromHostListGrpc(Properties properties, List<String> brokers) {
+ return new GrpcConnection(properties, brokers);
+ }
+
private static PinotClientTransport getDefault(Properties connectionProperties) {
// TODO: This code incorrectly assumes that connection properties are always the same
if (_defaultTransport == null) {
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ControllerBasedBrokerSelector.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ControllerBasedBrokerSelector.java
index cdc2190454..d07b37dd4f 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ControllerBasedBrokerSelector.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ControllerBasedBrokerSelector.java
@@ -32,11 +32,6 @@ public class ControllerBasedBrokerSelector implements BrokerSelector {
private final UpdatableBrokerCache _brokerCache;
private final Properties _properties;
- public ControllerBasedBrokerSelector(String scheme, String controllerHost, int controllerPort)
- throws Exception {
- this(scheme, controllerHost, controllerPort, new Properties());
- }
-
public ControllerBasedBrokerSelector(String scheme, String controllerHost, int controllerPort, Properties properties)
throws Exception {
_properties = properties;
@@ -53,7 +48,6 @@ public class ControllerBasedBrokerSelector implements BrokerSelector {
_brokerCache.init();
}
-
@Override
public String selectBroker(String... tableNames) {
return _brokerCache.getBroker(tableNames);
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/DynamicBrokerSelector.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/DynamicBrokerSelector.java
index 498a68ce0b..ba82c3a8b9 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/DynamicBrokerSelector.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/DynamicBrokerSelector.java
@@ -47,18 +47,26 @@ public class DynamicBrokerSelector implements BrokerSelector, IZkDataListener {
protected final AtomicReference<List<String>> _allBrokerListRef = new AtomicReference<>();
protected final ZkClient _zkClient;
protected final ExternalViewReader _evReader;
- //The preferTlsPort will be mapped to client config in the future, when we support full TLS
+
+ public DynamicBrokerSelector(String zkServers) {
+ this(zkServers, false);
+ }
+
public DynamicBrokerSelector(String zkServers, boolean preferTlsPort) {
+ this(zkServers, preferTlsPort, false);
+ }
+
+ //The preferTlsPort will be mapped to client config in the future, when we support full TLS
+ public DynamicBrokerSelector(String zkServers, boolean preferTlsPort, boolean useGrpcPort) {
_zkClient = getZkClient(zkServers);
_zkClient.setZkSerializer(new BytesPushThroughSerializer());
_zkClient.waitUntilConnected(60, TimeUnit.SECONDS);
_zkClient.subscribeDataChanges(ExternalViewReader.BROKER_EXTERNAL_VIEW_PATH, this);
- _evReader = getEvReader(_zkClient, preferTlsPort);
+ _evReader = getEvReader(_zkClient, preferTlsPort, useGrpcPort);
refresh();
}
- public DynamicBrokerSelector(String zkServers) {
- this(zkServers, false);
- }
+
+
@VisibleForTesting
protected ZkClient getZkClient(String zkServers) {
@@ -75,6 +83,11 @@ public class DynamicBrokerSelector implements BrokerSelector, IZkDataListener {
return new ExternalViewReader(zkClient, preferTlsPort);
}
+ @VisibleForTesting
+ protected ExternalViewReader getEvReader(ZkClient zkClient, boolean preferTlsPort, boolean useGrpcPort) {
+ return new ExternalViewReader(zkClient, preferTlsPort, useGrpcPort);
+ }
+
private void refresh() {
Map<String, List<String>> tableToBrokerListMap = _evReader.getTableToBrokersMap();
_tableToBrokerListMapRef.set(tableToBrokerListMap);
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ExternalViewReader.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ExternalViewReader.java
index 88ed54976c..547de125a1 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ExternalViewReader.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ExternalViewReader.java
@@ -53,6 +53,7 @@ public class ExternalViewReader {
public static final String REALTIME_SUFFIX = "_REALTIME";
public static final String OFFLINE_SUFFIX = "_OFFLINE";
public static final String KEY_PINOT_TLS_PORT = "PINOT_TLS_PORT";
+ public static final String KEY_PINOT_GRPC_PORT = "grpcPort";
public static final String KEY_SIMPLE_FIELDS = "simpleFields";
public static final String KEY_HELIX_HOST = "HELIX_HOST";
public static final String KEY_HELIX_PORT = "HELIX_PORT";
@@ -61,12 +62,21 @@ public class ExternalViewReader {
@VisibleForTesting
boolean _preferTlsPort;
+
+ boolean _useGrpcPort;
+
+ public ExternalViewReader(ZkClient zkClient) {
+ this(zkClient, false);
+ }
+
public ExternalViewReader(ZkClient zkClient, boolean preferTlsPort) {
+ this(zkClient, preferTlsPort, false);
+ }
+
+ public ExternalViewReader(ZkClient zkClient, boolean preferTlsPort, boolean useGrpcPort) {
_preferTlsPort = preferTlsPort;
_zkClient = zkClient;
- }
- public ExternalViewReader(ZkClient zkClient) {
- this(zkClient, false);
+ _useGrpcPort = useGrpcPort;
}
public List<String> getLiveBrokers() {
@@ -108,6 +118,7 @@ public class ExternalViewReader {
if (simpleFields != null) {
JsonNode hostNameNode = simpleFields.get(KEY_HELIX_HOST);
JsonNode tlsPortNode = simpleFields.get(KEY_PINOT_TLS_PORT);
+ JsonNode grpcPortNode = simpleFields.get(KEY_PINOT_GRPC_PORT);
JsonNode helixPortNode = simpleFields.get(KEY_HELIX_PORT);
String[] splitItems = brokerName.split("_");
if (splitItems.length < 3) {
@@ -117,6 +128,10 @@ public class ExternalViewReader {
if (hostNameNode != null && !Strings.isNullOrEmpty(hostNameNode.asText())) {
hostName = hostNameNode.asText();
}
+
+ if (grpcPortNode != null && !Strings.isNullOrEmpty(grpcPortNode.asText()) && _useGrpcPort) {
+ return hostName + ":" + grpcPortNode.asText();
+ }
if (tlsPortNode != null && !Strings.isNullOrEmpty(tlsPortNode.asText()) && _preferTlsPort) {
return hostName + ":" + tlsPortNode.asText();
}
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ResultSetGroup.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ResultSetGroup.java
index e7e05e7fc4..d20765e341 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ResultSetGroup.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ResultSetGroup.java
@@ -31,10 +31,11 @@ public class ResultSetGroup {
private final List<ResultSet> _resultSets;
private final ExecutionStats _executionStats;
private final List<PinotClientException> _exceptions;
+ private final BrokerResponse _brokerResponse;
- ResultSetGroup(BrokerResponse brokerResponse) {
+ public ResultSetGroup(BrokerResponse brokerResponse) {
+ _brokerResponse = brokerResponse;
_resultSets = new ArrayList<>();
-
if (brokerResponse.getResultTable() != null) {
_resultSets.add(new ResultTableResultSet(brokerResponse.getResultTable()));
} else {
@@ -98,6 +99,10 @@ public class ResultSetGroup {
return _exceptions;
}
+ public BrokerResponse getBrokerResponse() {
+ return _brokerResponse;
+ }
+
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/UpdatableBrokerCache.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/UpdatableBrokerCache.java
index b3db7fff4d..4808a988cc 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/UpdatableBrokerCache.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/UpdatableBrokerCache.java
@@ -42,7 +42,7 @@ public interface UpdatableBrokerCache {
/**
* Returns all the brokers currently in the cache
- * @return List of all avaliable brokers
+ * @return List of all available brokers
*/
List<String> getBrokers();
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcConnection.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcConnection.java
new file mode 100644
index 0000000000..068d021c4c
--- /dev/null
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcConnection.java
@@ -0,0 +1,294 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.client.grpc;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.pinot.client.BrokerResponse;
+import org.apache.pinot.client.BrokerSelector;
+import org.apache.pinot.client.Connection;
+import org.apache.pinot.client.PinotClientException;
+import org.apache.pinot.client.ResultSetGroup;
+import org.apache.pinot.client.SimpleBrokerSelector;
+import org.apache.pinot.common.config.GrpcConfig;
+import org.apache.pinot.common.proto.Broker;
+import org.apache.pinot.common.utils.grpc.BrokerGrpcQueryClient;
+import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * A grpc connection to Pinot, normally created through calls to the {@link org.apache.pinot.client.ConnectionFactory}.
+ */
+public class GrpcConnection {
+ public static final String FAIL_ON_EXCEPTIONS = "failOnExceptions";
+ private static final Logger LOGGER = LoggerFactory.getLogger(GrpcConnection.class);
+
+ private final BrokerSelector _brokerSelector;
+ private final boolean _failOnExceptions;
+ private final BrokerStreamingQueryClient _grpcQueryClient;
+
+ public GrpcConnection(Properties properties, List<String> brokerList) {
+ this(properties, new SimpleBrokerSelector(brokerList));
+ LOGGER.info("Created connection to broker list {}", brokerList);
+ }
+
+ public GrpcConnection(Properties properties, BrokerSelector brokerSelector) {
+ _brokerSelector = brokerSelector;
+ // Convert Properties properties to a Map
+ Map<String, Object> propertiesMap = new HashMap<>();
+ properties.forEach((key, value) -> propertiesMap.put(key.toString(), value));
+ _grpcQueryClient = new BrokerStreamingQueryClient(new GrpcConfig(new PinotConfiguration(propertiesMap)));
+ // Default fail Pinot query if response contains any exception.
+ _failOnExceptions = Boolean.parseBoolean(properties.getProperty(FAIL_ON_EXCEPTIONS, "TRUE"));
+ }
+
+ /**
+ * Creates a prepared statement, to escape query parameters.
+ *
+ * @param query The query for which to create a prepared statement
+ * @return A prepared statement for this connection
+ */
+ public GrpcPreparedStatement prepareStatement(String query) {
+ return new GrpcPreparedStatement(this, query);
+ }
+
+ /**
+ * Executes a query.
+ *
+ * @param query The query to execute
+ * @return The result of the query
+ * @throws PinotClientException If an exception occurs while processing the query
+ */
+ public ResultSetGroup execute(String query)
+ throws PinotClientException, IOException {
+ return execute(query, new HashMap<>());
+ }
+
+ /**
+ * Executes a query.
+ *
+ * @param query The query to execute
+ * @param metadataMap The query metadata
+ * @return The result of the query
+ * @throws PinotClientException If an exception occurs while processing the query
+ */
+ public ResultSetGroup execute(String query, Map<String, String> metadataMap)
+ throws PinotClientException, IOException {
+ BrokerResponse brokerResponse = BrokerResponse.fromJson(getJsonResponse(query, metadataMap));
+ if (!brokerResponse.getExceptions().isEmpty() && _failOnExceptions) {
+ throw new PinotClientException("Query had processing exceptions: \n" + brokerResponse.getExceptions());
+ }
+ return new ResultSetGroup(brokerResponse);
+ }
+
+ /**
+ * Executes a query.
+ *
+ * @param query The query to execute
+ * @return The result of the query
+ * @throws PinotClientException If an exception occurs while processing the query
+ */
+ public GrpcResultSetGroup executeGrpc(String query)
+ throws PinotClientException, IOException {
+ return executeGrpc(query, new HashMap<>());
+ }
+
+ /**
+ * Executes a query.
+ *
+ * @param query The query to execute
+ * @param metadataMap The query metadata
+ * @return The result of the query
+ * @throws PinotClientException If an exception occurs while processing the query
+ */
+ public GrpcResultSetGroup executeGrpc(String query, Map<String, String> metadataMap)
+ throws PinotClientException, IOException {
+ Iterator<Broker.BrokerResponse> brokerResponseIterator = executeWithIterator(query, metadataMap);
+ return new GrpcResultSetGroup(brokerResponseIterator);
+ }
+
+ /**
+ * Executes a query asynchronously.
+ *
+ * @param query The query to execute
+ * @return A future containing the result of the query
+ * @throws PinotClientException If an exception occurs while processing the query
+ */
+ public CompletableFuture<ResultSetGroup> executeAsync(String query)
+ throws PinotClientException {
+ return executeAsync(query, new HashMap<>());
+ }
+
+ /**
+ * Executes a query asynchronously.
+ *
+ * @param query The query to execute
+ * @return A future containing the result of the query
+ * @throws PinotClientException If an exception occurs while processing the query
+ */
+ public CompletableFuture<ResultSetGroup> executeAsync(String query, Map<String, String> metadataMap)
+ throws PinotClientException {
+ return CompletableFuture.supplyAsync(() -> {
+ try {
+ return new ResultSetGroup(BrokerResponse.fromJson(getJsonResponse(query, metadataMap)));
+ } catch (IOException e) {
+ throw new PinotClientException("Failed to execute query: " + query, e);
+ }
+ });
+ }
+
+ /**
+ * Executes a query.
+ *
+ * @param query The query to execute
+ * @param metadataMap The query metadata
+ * @return The JsonNode result of the query
+ * @throws PinotClientException If an exception occurs while processing the query
+ */
+ public JsonNode getJsonResponse(String query, Map<String, String> metadataMap)
+ throws IOException {
+ Iterator<org.apache.pinot.common.proto.Broker.BrokerResponse> response = executeWithIterator(query, metadataMap);
+ // Process metadata
+ ObjectNode brokerResponseJson = JsonUtils.newObjectNode();
+ if (response.hasNext()) {
+ brokerResponseJson.setAll(GrpcUtils.extractMetadataJson(response.next()));
+ }
+ // Directly return when there is exception
+ if (brokerResponseJson.has("exceptions") && !brokerResponseJson.get("exceptions").isEmpty()) {
+ return brokerResponseJson;
+ }
+ // Process schema
+ JsonNode schemaJsonNode = null;
+ if (response.hasNext()) {
+ schemaJsonNode = GrpcUtils.extractSchemaJson(response.next());
+ }
+ // Process rows
+ ArrayNode rows = JsonUtils.newArrayNode();
+ while (response.hasNext()) {
+ rows.addAll(GrpcUtils.extractRowsJson(response.next()));
+ }
+ if (schemaJsonNode != null && rows != null) {
+ ObjectNode resultTable = JsonUtils.newObjectNode();
+ resultTable.putIfAbsent("dataSchema", schemaJsonNode);
+ resultTable.putIfAbsent("rows", rows);
+ brokerResponseJson.putIfAbsent("resultTable", resultTable);
+ }
+
+ return brokerResponseJson;
+ }
+
+ /**
+ * Executes a query asynchronously.
+ *
+ * @param query The query to execute
+ * @return A future containing the result of the query
+ * @throws PinotClientException If an exception occurs while processing the query
+ */
+ public Iterator<Broker.BrokerResponse> executeWithIterator(String query)
+ throws PinotClientException {
+ return executeWithIterator(query, new HashMap<>());
+ }
+
+ /**
+ * Executes a query asynchronously.
+ *
+ * @param query The query to execute
+ * @return A future containing the result of the query
+ * @throws PinotClientException If an exception occurs while processing the query
+ */
+ public Iterator<Broker.BrokerResponse> executeWithIterator(String query, Map<String, String> metadata)
+ throws PinotClientException {
+ String[] tableNames = Connection.resolveTableName(query);
+ String brokerHostPort = _brokerSelector.selectBroker(tableNames);
+ if (brokerHostPort == null) {
+ throw new PinotClientException("Could not find broker to query " + ((tableNames == null) ? "with no tables"
+ : "for table(s): " + Arrays.asList(tableNames)));
+ }
+ String brokerHost = brokerHostPort.split(":")[0];
+ int brokerPort = Integer.parseInt(brokerHostPort.split(":")[1]);
+ Broker.BrokerRequest brokerRequest =
+ Broker.BrokerRequest.newBuilder().setSql(query).putAllMetadata(metadata).build();
+ return _grpcQueryClient.submit(brokerHost, brokerPort, brokerRequest);
+ }
+
+ /**
+ * Close the connection for further processing
+ *
+ * @throws PinotClientException when connection is already closed
+ */
+ public void close()
+ throws PinotClientException {
+ _grpcQueryClient.shutdown();
+ _brokerSelector.close();
+ }
+
+ /**
+ * Provides access to the underlying grpc clients for this connection.
+ * There may be client metrics useful for monitoring and other observability goals.
+ *
+ * @return pinot client.
+ */
+ public BrokerStreamingQueryClient getGrpcQueryClient() {
+ return _grpcQueryClient;
+ }
+
+ public List<String> getBrokerList() {
+ return _brokerSelector.getBrokers();
+ }
+
+ public static class BrokerStreamingQueryClient {
+ private final Map<String, BrokerGrpcQueryClient> _grpcQueryClientMap = new ConcurrentHashMap<>();
+ private final GrpcConfig _config;
+
+ public BrokerStreamingQueryClient(GrpcConfig config) {
+ _config = config;
+ }
+
+ public Iterator<Broker.BrokerResponse> submit(String brokerHost, int brokerGrpcPort,
+ Broker.BrokerRequest brokerRequest) {
+ BrokerGrpcQueryClient client = getOrCreateGrpcQueryClient(brokerHost, brokerGrpcPort);
+ return client.submit(brokerRequest);
+ }
+
+ private BrokerGrpcQueryClient getOrCreateGrpcQueryClient(String brokerHost, int brokerGrpcPort) {
+ String hostnamePort = String.format("%s_%d", brokerHost, brokerGrpcPort);
+ return _grpcQueryClientMap.computeIfAbsent(hostnamePort,
+ k -> new BrokerGrpcQueryClient(brokerHost, brokerGrpcPort, _config));
+ }
+
+ public void shutdown() {
+ for (BrokerGrpcQueryClient client : _grpcQueryClientMap.values()) {
+ client.close();
+ }
+ }
+ }
+}
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcPreparedStatement.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcPreparedStatement.java
new file mode 100644
index 0000000000..0147e29deb
--- /dev/null
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcPreparedStatement.java
@@ -0,0 +1,126 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.client.grpc;
+
+import java.io.IOException;
+import java.util.Iterator;
+import org.apache.pinot.common.proto.Broker;
+
+
+/**
+ * A prepared statement, which is used to escape query parameters sent to Pinot.
+ */
+public class GrpcPreparedStatement {
+ private final GrpcConnection _connection;
+ private final String _statement;
+ private final String[] _parameters;
+
+ public GrpcPreparedStatement(GrpcConnection connection, String query) {
+ _connection = connection;
+ _statement = query;
+ _parameters = new String[getQuestionMarkCount(query)];
+ }
+
+ private int getQuestionMarkCount(String query) {
+ int questionMarkCount = 0;
+ int index = query.indexOf('?');
+ while (index != -1) {
+ questionMarkCount++;
+ index = query.indexOf('?', index + 1);
+ }
+ return questionMarkCount;
+ }
+
+ private String fillStatementWithParameters() {
+ String statement = _statement;
+ for (String parameter : _parameters) {
+ statement = statement.replaceFirst("\\?", parameter);
+ }
+ return statement;
+ }
+
+ /**
+ * Executes this prepared statement.
+ *
+ * @return The query results
+ */
+ public GrpcResultSetGroup execute()
+ throws IOException {
+ return _connection.executeGrpc(fillStatementWithParameters());
+ }
+
+ /**
+ * Executes this prepared statement asynchronously.
+ *
+ * @return The query results
+ */
+ public Iterator<Broker.BrokerResponse> executeWithIterator() {
+ return _connection.executeWithIterator(fillStatementWithParameters());
+ }
+
+ /**
+ * Replaces the given parameter by its value.
+ *
+ * @param parameterIndex The index of the parameter to replace
+ * @param value The value of the parameter to replace
+ */
+ public void setString(int parameterIndex, String value) {
+ _parameters[parameterIndex] = "'" + value.replace("'", "''") + "'";
+ }
+
+ /**
+ * Replaces the given parameter by its value.
+ *
+ * @param parameterIndex The index of the parameter to replace
+ * @param value The value of the parameter to replace
+ */
+ public void setInt(int parameterIndex, int value) {
+ _parameters[parameterIndex] = String.valueOf(value);
+ }
+
+ /**
+ * Replaces the given parameter by its value.
+ *
+ * @param parameterIndex The index of the parameter to replace
+ * @param value The value of the parameter to replace
+ */
+ public void setLong(int parameterIndex, long value) {
+ _parameters[parameterIndex] = String.valueOf(value);
+ }
+
+ /**
+ * Replaces the given parameter by its value.
+ *
+ * @param parameterIndex The index of the parameter to replace
+ * @param value The value of the parameter to replace
+ */
+ public void setFloat(int parameterIndex, float value) {
+ _parameters[parameterIndex] = String.valueOf(value);
+ }
+
+ /**
+ * Replaces the given parameter by its value.
+ *
+ * @param parameterIndex The index of the parameter to replace
+ * @param value The value of the parameter to replace
+ */
+ public void setDouble(int parameterIndex, double value) {
+ _parameters[parameterIndex] = String.valueOf(value);
+ }
+}
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcResultSet.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcResultSet.java
new file mode 100644
index 0000000000..271e1e734d
--- /dev/null
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcResultSet.java
@@ -0,0 +1,134 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.client.grpc;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pinot.client.AbstractResultSet;
+import org.apache.pinot.client.TextTable;
+import org.apache.pinot.common.proto.Broker;
+import org.apache.pinot.common.utils.DataSchema;
+
+
+/**
+ * ResultSet which contains the ResultTable from the broker response of a sql query.
+ */
+public class GrpcResultSet extends AbstractResultSet {
+ private final List<String> _columnNamesArray;
+ private final List<String> _columnDataTypesArray;
+ private final ArrayNode _currentBatchRows;
+
+ public GrpcResultSet(DataSchema schema, Broker.BrokerResponse brokerResponse) {
+ _columnNamesArray = new ArrayList<>(schema.size());
+ _columnDataTypesArray = new ArrayList<>(schema.size());
+ for (int i = 0; i < schema.size(); i++) {
+ _columnNamesArray.add(schema.getColumnName(i));
+ _columnDataTypesArray.add(schema.getColumnDataType(i).toString());
+ }
+ try {
+ _currentBatchRows = GrpcUtils.extractRowsJson(brokerResponse);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public int getRowCount() {
+ return _currentBatchRows.size();
+ }
+
+ @Override
+ public int getColumnCount() {
+ return _columnNamesArray.size();
+ }
+
+ @Override
+ public String getColumnName(int columnIndex) {
+ return _columnNamesArray.get(columnIndex);
+ }
+
+ @Override
+ public String getColumnDataType(int columnIndex) {
+ return _columnDataTypesArray.get(columnIndex);
+ }
+
+ @Override
+ public String getString(int rowIndex, int columnIndex) {
+ JsonNode jsonValue = _currentBatchRows.get(rowIndex).get(columnIndex);
+ if (jsonValue.isTextual()) {
+ return jsonValue.textValue();
+ } else {
+ return jsonValue.toString();
+ }
+ }
+
+ public List<String> getAllColumns() {
+ return _columnNamesArray;
+ }
+
+ public List<String> getAllColumnsDataTypes() {
+ return _columnDataTypesArray;
+ }
+
+ @Override
+ public int getGroupKeyLength() {
+ return 0;
+ }
+
+ @Override
+ public String getGroupKeyString(int rowIndex, int groupKeyColumnIndex) {
+ throw new AssertionError("No group key string for result table");
+ }
+
+ @Override
+ public String getGroupKeyColumnName(int groupKeyColumnIndex) {
+ throw new AssertionError("No group key column name for result table");
+ }
+
+ @Override
+ public String toString() {
+ int numColumns = getColumnCount();
+ TextTable table = new TextTable();
+ String[] columnNames = new String[numColumns];
+ String[] columnDataTypes = new String[numColumns];
+ for (int c = 0; c < numColumns; c++) {
+ columnNames[c] = _columnNamesArray.get(c);
+ columnDataTypes[c] = _columnDataTypesArray.get(c);
+ }
+ table.addHeader(columnNames);
+ table.addHeader(columnDataTypes);
+
+ int numRows = getRowCount();
+ for (int r = 0; r < numRows; r++) {
+ String[] columnValues = new String[numColumns];
+ for (int c = 0; c < numColumns; c++) {
+ try {
+ columnValues[c] = getString(r, c);
+ } catch (Exception e) {
+ columnNames[c] = "ERROR";
+ }
+ }
+ table.addRow(columnValues);
+ }
+ return table.toString();
+ }
+}
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ResultSetGroup.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcResultSetGroup.java
similarity index 51%
copy from pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ResultSetGroup.java
copy to pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcResultSetGroup.java
index e7e05e7fc4..04f2c00c16 100644
--- a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/ResultSetGroup.java
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcResultSetGroup.java
@@ -16,47 +16,61 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.pinot.client;
+package org.apache.pinot.client.grpc;
import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.io.IOException;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
+import org.apache.pinot.client.ExecutionStats;
+import org.apache.pinot.client.PinotClientException;
+import org.apache.pinot.client.ResultSet;
+import org.apache.pinot.common.proto.Broker;
+import org.apache.pinot.common.utils.DataSchema;
/**
* A Pinot result set group, containing the results given back by Pinot for a given query.
*/
-public class ResultSetGroup {
- private final List<ResultSet> _resultSets;
+public class GrpcResultSetGroup {
+ private final DataSchema _schema;
private final ExecutionStats _executionStats;
private final List<PinotClientException> _exceptions;
+ private final Iterator<Broker.BrokerResponse> _brokerResponseIterator;
+ private ResultSet _currentResultSet;
- ResultSetGroup(BrokerResponse brokerResponse) {
- _resultSets = new ArrayList<>();
+ public GrpcResultSetGroup(Iterator<Broker.BrokerResponse> brokerResponseIterator)
+ throws IOException {
- if (brokerResponse.getResultTable() != null) {
- _resultSets.add(new ResultTableResultSet(brokerResponse.getResultTable()));
+ // Process metadata
+ ObjectNode brokerResponseJson = GrpcUtils.extractMetadataJson(brokerResponseIterator.next());
+ _executionStats = GrpcUtils.extractExecutionStats(brokerResponseJson);
+ _exceptions = getPinotClientExceptions(brokerResponseJson.get("exceptions"));
+ // Process schema
+ if (brokerResponseIterator.hasNext()) {
+ _schema = GrpcUtils.extractSchema(brokerResponseIterator.next());
} else {
+ _schema = new DataSchema(new String[0], new DataSchema.ColumnDataType[0]);
+ }
+ _brokerResponseIterator = brokerResponseIterator;
+ }
- if (brokerResponse.getSelectionResults() != null) {
- _resultSets.add(new SelectionResultSet(brokerResponse.getSelectionResults()));
- }
+ public boolean hasNextResultSet() {
+ return _brokerResponseIterator.hasNext();
+ }
- int aggregationResultCount = brokerResponse.getAggregationResultsSize();
- for (int i = 0; i < aggregationResultCount; i++) {
- JsonNode aggregationResult = brokerResponse.getAggregationResults().get(i);
- if (aggregationResult.has("value")) {
- _resultSets.add(new AggregationResultSet(aggregationResult));
- } else if (aggregationResult.has("groupByResult")) {
- _resultSets.add(new GroupByResultSet(aggregationResult));
- } else {
- throw new PinotClientException("Unrecognized result group, neither a value nor group by result");
- }
- }
- }
- _executionStats = brokerResponse.getExecutionStats();
- _exceptions = getPinotClientExceptions(brokerResponse.getExceptions());
+ /**
+ * Obtains the next result set from the iterator
+ *
+ * @return The result set
+ */
+ @Nullable
+ public ResultSet getNextResultSet() {
+ _currentResultSet = new GrpcResultSet(_schema, _brokerResponseIterator.next());
+ return _currentResultSet;
}
private static List<PinotClientException> getPinotClientExceptions(
@@ -70,26 +84,6 @@ public class ResultSetGroup {
return exceptions;
}
- /**
- * Returns the number of result sets in this result set group, or 0 if there are no result sets; there is one result
- * set per aggregation function in the original query and one result set in the case of a selection query.
- *
- * @return The number of result sets in this result set
- */
- public int getResultSetCount() {
- return _resultSets.size();
- }
-
- /**
- * Obtains the result set at the given index, starting from zero.
- *
- * @param index The index for which to obtain the result set
- * @return The result set at the given index
- */
- public ResultSet getResultSet(int index) {
- return _resultSets.get(index);
- }
-
public ExecutionStats getExecutionStats() {
return _executionStats;
}
@@ -101,10 +95,10 @@ public class ResultSetGroup {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
- for (ResultSet resultSet : _resultSets) {
- sb.append(resultSet);
- sb.append("\n");
- }
+ sb.append(_schema);
+ sb.append("\n");
+ sb.append(_currentResultSet);
+ sb.append("\n");
sb.append(_executionStats.toString());
sb.append("\n");
for (PinotClientException exception : _exceptions) {
diff --git a/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcUtils.java b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcUtils.java
new file mode 100644
index 0000000000..b604d0109a
--- /dev/null
+++ b/pinot-clients/pinot-java-client/src/main/java/org/apache/pinot/client/grpc/GrpcUtils.java
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.client.grpc;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.Iterator;
+import java.util.Map;
+import org.apache.pinot.client.ExecutionStats;
+import org.apache.pinot.common.compression.CompressionFactory;
+import org.apache.pinot.common.compression.Compressor;
+import org.apache.pinot.common.proto.Broker;
+import org.apache.pinot.common.utils.DataSchema;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.JsonUtils;
+
+
+public class GrpcUtils {
+
+ private GrpcUtils() {
+ }
+
+ public static ObjectNode extractMetadataJson(Broker.BrokerResponse brokerResponse)
+ throws IOException {
+ ObjectNode metadata = JsonUtils.newObjectNode();
+ JsonNode jsonNode = JsonUtils.bytesToJsonNode(brokerResponse.getPayload().toByteArray());
+ Iterator<String> fieldNamesIterator = jsonNode.fieldNames();
+ while (fieldNamesIterator.hasNext()) {
+ String fieldName = fieldNamesIterator.next();
+ metadata.set(fieldName, jsonNode.get(fieldName));
+ }
+ metadata.set("metadataMap", JsonUtils.objectToJsonNode(brokerResponse.getMetadataMap()));
+ return metadata;
+ }
+
+ public static DataSchema extractSchema(Broker.BrokerResponse brokerResponse)
+ throws IOException {
+ return DataSchema.fromBytes(brokerResponse.getPayload().asReadOnlyByteBuffer());
+ }
+
+ public static JsonNode extractSchemaJson(Broker.BrokerResponse brokerResponse)
+ throws IOException {
+ DataSchema schema = DataSchema.fromBytes(brokerResponse.getPayload().asReadOnlyByteBuffer());
+ return JsonUtils.objectToJsonNode(schema);
+ }
+
+ public static ArrayNode extractRowsJson(Broker.BrokerResponse brokerResponse)
+ throws IOException {
+ Map<String, String> metadataMap = brokerResponse.getMetadataMap();
+ String compressionAlgorithm = metadataMap.getOrDefault(CommonConstants.Broker.Grpc.COMPRESSION,
+ CommonConstants.Broker.Grpc.DEFAULT_COMPRESSION);
+ Compressor compressor = CompressionFactory.getCompressor(compressionAlgorithm);
+
+ byte[] respBytes = brokerResponse.getPayload().toByteArray();
+ int rowSize = Integer.parseInt(brokerResponse.getMetadataOrThrow("rowSize"));
+ byte[] uncompressedPayload;
+ try {
+ uncompressedPayload = compressor.decompress(respBytes);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ ArrayNode jsonRows = JsonUtils.newArrayNode();
+ int bytesRead = 0;
+ ByteBuffer byteBuffer = ByteBuffer.wrap(uncompressedPayload);
+ for (int i = 0; i < rowSize; i++) {
+ int nextRowSize = byteBuffer.getInt(bytesRead);
+ bytesRead += 4;
+ byte[] rowBytes = new byte[nextRowSize];
+ byteBuffer.position(bytesRead);
+ byteBuffer.get(rowBytes);
+ bytesRead += nextRowSize;
+ String rowString = new String(rowBytes);
+ jsonRows.add(JsonUtils.stringToJsonNode(rowString));
+ }
+ return jsonRows;
+ }
+
+ public static ExecutionStats extractExecutionStats(JsonNode executionStatsJson) {
+ return ExecutionStats.fromJson(executionStatsJson);
+ }
+}
diff --git a/pinot-clients/pinot-java-client/src/test/java/org/apache/pinot/client/DynamicBrokerSelectorTest.java b/pinot-clients/pinot-java-client/src/test/java/org/apache/pinot/client/DynamicBrokerSelectorTest.java
index 986b4773c7..e00f954279 100644
--- a/pinot-clients/pinot-java-client/src/test/java/org/apache/pinot/client/DynamicBrokerSelectorTest.java
+++ b/pinot-clients/pinot-java-client/src/test/java/org/apache/pinot/client/DynamicBrokerSelectorTest.java
@@ -67,6 +67,11 @@ public class DynamicBrokerSelectorTest {
return _mockExternalViewReader;
}
+ @Override
+ protected ExternalViewReader getEvReader(ZkClient zkClient, boolean preferTlsPort, boolean useGrpcPort) {
+ return _mockExternalViewReader;
+ }
+
@Override
protected ZkClient getZkClient(String zkServers) {
return _mockZkClient;
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotConnection.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotConnection.java
index 1e6a667ce7..48d719babb 100644
--- a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotConnection.java
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotConnection.java
@@ -31,6 +31,7 @@ import org.apache.pinot.client.base.AbstractBaseConnection;
import org.apache.pinot.client.controller.PinotControllerTransport;
import org.apache.pinot.client.controller.PinotControllerTransportFactory;
import org.apache.pinot.client.controller.response.ControllerTenantBrokerResponse;
+import org.apache.pinot.client.utils.DriverUtils;
import org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
@@ -73,39 +74,11 @@ public class PinotConnection extends AbstractBaseConnection {
for (String possibleQueryOption: POSSIBLE_QUERY_OPTIONS) {
Object property = properties.getProperty(possibleQueryOption);
if (property != null) {
- _queryOptions.put(possibleQueryOption, parseOptionValue(property));
+ _queryOptions.put(possibleQueryOption, DriverUtils.parseOptionValue(property));
}
}
}
- private Object parseOptionValue(Object value) {
- if (value instanceof String) {
- String str = (String) value;
-
- try {
- Long numVal = Long.valueOf(str);
- if (numVal != null) {
- return numVal;
- }
- } catch (NumberFormatException e) {
- }
-
- try {
- Double numVal = Double.valueOf(str);
- if (numVal != null) {
- return numVal;
- }
- } catch (NumberFormatException e) {
- }
-
- Boolean boolVal = Boolean.valueOf(str.toLowerCase());
- if (boolVal != null) {
- return boolVal;
- }
- }
-
- return value;
- }
public org.apache.pinot.client.Connection getSession() {
return _session;
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotDriver.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotDriver.java
index 93ba1ab551..e7249dba9a 100644
--- a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotDriver.java
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotDriver.java
@@ -37,6 +37,7 @@ import javax.net.ssl.SSLContext;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.pinot.client.controller.PinotControllerTransport;
import org.apache.pinot.client.controller.PinotControllerTransportFactory;
+import org.apache.pinot.client.grpc.PinotGrpcConnection;
import org.apache.pinot.client.utils.DriverUtils;
import org.apache.pinot.common.utils.tls.TlsUtils;
import org.apache.pinot.spi.utils.CommonConstants;
@@ -46,6 +47,8 @@ import org.slf4j.LoggerFactory;
public class PinotDriver implements Driver {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(PinotDriver.class);
private static final String URI_SCHEME = "pinot";
+ private static final String GRPC_URI_SCHEME = "pinotgrpc";
+
public static final String INFO_TENANT = "tenant";
public static final String DEFAULT_TENANT = "DefaultTenant";
public static final String INFO_SCHEME = "scheme";
@@ -118,13 +121,18 @@ public class PinotDriver implements Driver {
pinotControllerTransportFactory.setHeaders(headers);
}
- pinotClientTransport = factory.withConnectionProperties(info).buildTransport();
pinotControllerTransport = pinotControllerTransportFactory
.withConnectionProperties(info)
.buildTransport();
String controllerUrl = DriverUtils.getControllerFromURL(url);
+ String scheme = DriverUtils.getPinotScheme(url);
String tenant = info.getProperty(INFO_TENANT, DEFAULT_TENANT);
- return new PinotConnection(info, controllerUrl, pinotClientTransport, tenant, pinotControllerTransport);
+ if (scheme.equalsIgnoreCase("pinot")) {
+ pinotClientTransport = factory.withConnectionProperties(info).buildTransport();
+ return new PinotConnection(info, controllerUrl, pinotClientTransport, tenant, pinotControllerTransport);
+ } else {
+ return new PinotGrpcConnection(info, controllerUrl, tenant, pinotControllerTransport);
+ }
} catch (Exception e) {
closeResourcesSafely(pinotClientTransport, pinotControllerTransport);
throw new SQLException(String.format("Failed to connect to url : %s", url), e);
@@ -167,7 +175,7 @@ public class PinotDriver implements Driver {
throws SQLException {
String cleanURI = url.substring(5);
URI uri = URI.create(cleanURI);
- return uri.getScheme().contentEquals(URI_SCHEME);
+ return uri.getScheme().contentEquals(URI_SCHEME) || uri.getScheme().contentEquals(GRPC_URI_SCHEME);
}
@Override
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultMetadata.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultMetadata.java
index 3f7df2167d..ce8ecbc08a 100644
--- a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultMetadata.java
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultMetadata.java
@@ -26,9 +26,9 @@ import org.apache.pinot.client.utils.DriverUtils;
public class PinotResultMetadata extends AbstractBaseResultSetMetadata {
- private int _totalColumns;
- private Map<Integer, String> _columns = new HashMap<>();
- private Map<Integer, String> _columnDataTypes = new HashMap<>();
+ private final int _totalColumns;
+ private final Map<Integer, String> _columns = new HashMap<>();
+ private final Map<Integer, String> _columnDataTypes;
public PinotResultMetadata(int totalColumns, Map<String, Integer> columnsNameToIndex,
Map<Integer, String> columnDataTypes) {
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultSet.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultSet.java
index 838fbf37e2..f62b52e497 100644
--- a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultSet.java
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultSet.java
@@ -49,9 +49,9 @@ public class PinotResultSet extends AbstractBaseResultSet {
private org.apache.pinot.client.ResultSet _resultSet;
private int _totalRows;
private int _currentRow;
- private int _totalColumns;
- private Map<String, Integer> _columns = new HashMap<>();
- private Map<Integer, String> _columnDataTypes = new HashMap<>();
+ private final int _totalColumns;
+ private final Map<String, Integer> _columns = new HashMap<>();
+ private final Map<Integer, String> _columnDataTypes = new HashMap<>();
private boolean _closed;
private boolean _wasNull = false;
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/controller/response/ControllerTenantBrokerResponse.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/controller/response/ControllerTenantBrokerResponse.java
index 1b537aad42..96afe7ab33 100644
--- a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/controller/response/ControllerTenantBrokerResponse.java
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/controller/response/ControllerTenantBrokerResponse.java
@@ -66,6 +66,25 @@ public class ControllerTenantBrokerResponse {
return brokerList;
}
+ public List<String> getBrokerGrpcConnections() {
+ List<String> brokerList = new ArrayList<>();
+ for (JsonNode broker : _brokers) {
+ if (!broker.has("grpcPort")) {
+ continue;
+ }
+ String hostName = broker.get("host").textValue();
+ Integer grpcPort = broker.get("grpcPort").intValue();
+ String brokerIP = hostName;
+ if (hostName.contains("_")) {
+ String[] hostNamePart = hostName.split("_");
+ brokerIP = hostNamePart[hostNamePart.length - 1];
+ }
+ String brokerIPPort = String.format("%s:%d", brokerIP, grpcPort);
+ brokerList.add(brokerIPPort);
+ }
+ return brokerList;
+ }
+
public static class ControllerTenantBrokerResponseFuture
extends ControllerResponseFuture<ControllerTenantBrokerResponse> {
public ControllerTenantBrokerResponseFuture(Future<Response> response, String url) {
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/examples/PinotJdbcExample.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/examples/PinotJdbcExample.java
new file mode 100644
index 0000000000..acd2dc78fd
--- /dev/null
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/examples/PinotJdbcExample.java
@@ -0,0 +1,95 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.client.examples;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.List;
+import java.util.Properties;
+import org.apache.pinot.client.ConnectionFactory;
+import org.apache.pinot.client.ResultSetGroup;
+import org.apache.pinot.client.grpc.GrpcConnection;
+
+
+public class PinotJdbcExample {
+
+ private PinotJdbcExample() {
+ }
+
+ public static void testPinotJdbcForQuickStart(String jdbcUrl, final String query) {
+ try (Connection connection = DriverManager.getConnection(jdbcUrl);
+ Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query)) {
+
+ System.out.println("Connected to Apache Pinot with JDBC Url: " + jdbcUrl);
+ System.out.println("Running query: " + query);
+
+ // Print results
+ ResultSetMetaData metaData = resultSet.getMetaData();
+ int columnCount = metaData.getColumnCount();
+ while (resultSet.next()) {
+ System.out.print("Row Id: " + resultSet.getRow() + "\t");
+ for (int i = 1; i <= columnCount; i++) {
+ System.out.print(metaData.getColumnName(i) + ": " + resultSet.getString(i) + "\t");
+ }
+ System.out.println();
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static void testQuery(GrpcConnection grpcConnection, String query) {
+ try {
+ ResultSetGroup resultSetGroup = grpcConnection.execute(query);
+ for (int i = 0; i < resultSetGroup.getResultSetCount(); i++) {
+ org.apache.pinot.client.ResultSet resultSet = resultSetGroup.getResultSet(i);
+ for (int rowId = 0; rowId < resultSet.getRowCount(); rowId++) {
+ System.out.print("Row Id: " + rowId + "\t");
+ for (int colId = 0; colId < resultSet.getColumnCount(); colId++) {
+ System.out.print(resultSet.getString(rowId, colId) + "\t");
+ }
+ System.out.println();
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ grpcConnection.close();
+ }
+
+ public static void main(String[] args)
+ throws IOException {
+ Properties properties = new Properties();
+
+ String query;
+ // query = "SELECT count(*) FROM airlineStats";
+ query = "SELECT * FROM airlineStats limit 1000";
+ testPinotJdbcForQuickStart("jdbc:pinot://localhost:9000", query);
+ testPinotJdbcForQuickStart("jdbc:pinotgrpc://localhost:9000?blockRowSize=100", query);
+
+ testQuery(ConnectionFactory.fromControllerGrpc(properties, "localhost:9000"), query);
+ testQuery(ConnectionFactory.fromZookeeperGrpc(properties, "localhost:2123/QuickStartCluster"), query);
+ testQuery(ConnectionFactory.fromHostListGrpc(properties, List.of("localhost:8010")), query);
+ }
+}
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotConnection.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcConnection.java
similarity index 65%
copy from pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotConnection.java
copy to pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcConnection.java
index 1e6a667ce7..f3a0c221f4 100644
--- a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotConnection.java
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcConnection.java
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.pinot.client;
+package org.apache.pinot.client.grpc;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
@@ -31,29 +31,30 @@ import org.apache.pinot.client.base.AbstractBaseConnection;
import org.apache.pinot.client.controller.PinotControllerTransport;
import org.apache.pinot.client.controller.PinotControllerTransportFactory;
import org.apache.pinot.client.controller.response.ControllerTenantBrokerResponse;
+import org.apache.pinot.client.utils.DriverUtils;
+import org.apache.pinot.spi.utils.CommonConstants;
import org.apache.pinot.spi.utils.CommonConstants.Broker.Request.QueryOptionKey;
-public class PinotConnection extends AbstractBaseConnection {
-
+public class PinotGrpcConnection extends AbstractBaseConnection {
+ public static final String BROKER_LIST = "brokers";
protected static final String[] POSSIBLE_QUERY_OPTIONS = {
- QueryOptionKey.ENABLE_NULL_HANDLING,
- QueryOptionKey.USE_MULTISTAGE_ENGINE
+ QueryOptionKey.ENABLE_NULL_HANDLING,
+ QueryOptionKey.USE_MULTISTAGE_ENGINE,
};
- private org.apache.pinot.client.Connection _session;
- private boolean _closed;
- private String _controllerURL;
+
+ protected static final String[] POSSIBLE_METADATA_MAP_OPTIONS = {
+ CommonConstants.Broker.Grpc.BLOCK_ROW_SIZE,
+ CommonConstants.Broker.Grpc.COMPRESSION,
+ };
+ private GrpcConnection _session;
private PinotControllerTransport _controllerTransport;
+ private boolean _closed;
+ private final String _controllerURL;
private final Map<String, Object> _queryOptions = new HashMap<String, Object>();
+ private final Map<String, String> _metadataMap = new HashMap<>();
- public static final String BROKER_LIST = "brokers";
-
- PinotConnection(String controllerURL, PinotClientTransport transport, String tenant,
- PinotControllerTransport controllerTransport) {
- this(new Properties(), controllerURL, transport, tenant, controllerTransport);
- }
-
- PinotConnection(Properties properties, String controllerURL, PinotClientTransport transport, String tenant,
+ public PinotGrpcConnection(Properties properties, String controllerURL, String tenant,
PinotControllerTransport controllerTransport) {
_closed = false;
_controllerURL = controllerURL;
@@ -66,48 +67,25 @@ public class PinotConnection extends AbstractBaseConnection {
if (properties.containsKey(BROKER_LIST)) {
brokers = Arrays.asList(properties.getProperty(BROKER_LIST).split(";"));
} else {
- brokers = getBrokerList(controllerURL, tenant);
+ brokers = getBrokerGrpcList(controllerURL, tenant);
}
- _session = new org.apache.pinot.client.Connection(properties, brokers, transport);
+ _session = new GrpcConnection(properties, brokers);
- for (String possibleQueryOption: POSSIBLE_QUERY_OPTIONS) {
+ for (String possibleQueryOption : POSSIBLE_QUERY_OPTIONS) {
Object property = properties.getProperty(possibleQueryOption);
if (property != null) {
- _queryOptions.put(possibleQueryOption, parseOptionValue(property));
+ _queryOptions.put(possibleQueryOption, DriverUtils.parseOptionValue(property));
}
}
- }
-
- private Object parseOptionValue(Object value) {
- if (value instanceof String) {
- String str = (String) value;
-
- try {
- Long numVal = Long.valueOf(str);
- if (numVal != null) {
- return numVal;
- }
- } catch (NumberFormatException e) {
- }
-
- try {
- Double numVal = Double.valueOf(str);
- if (numVal != null) {
- return numVal;
- }
- } catch (NumberFormatException e) {
- }
-
- Boolean boolVal = Boolean.valueOf(str.toLowerCase());
- if (boolVal != null) {
- return boolVal;
+ for (String possibleMetadataMapOption : POSSIBLE_METADATA_MAP_OPTIONS) {
+ Object property = properties.getProperty(possibleMetadataMapOption);
+ if (property != null) {
+ _metadataMap.put(possibleMetadataMapOption, property.toString());
}
}
-
- return value;
}
- public org.apache.pinot.client.Connection getSession() {
+ public GrpcConnection getSession() {
return _session;
}
@@ -115,10 +93,14 @@ public class PinotConnection extends AbstractBaseConnection {
return _queryOptions;
}
- private List<String> getBrokerList(String controllerURL, String tenant) {
+ public Map<String, String> getMetadataMap() {
+ return _metadataMap;
+ }
+
+ private List<String> getBrokerGrpcList(String controllerURL, String tenant) {
ControllerTenantBrokerResponse controllerTenantBrokerResponse =
_controllerTransport.getBrokersFromController(controllerURL, tenant);
- return controllerTenantBrokerResponse.getBrokers();
+ return controllerTenantBrokerResponse.getBrokerGrpcConnections();
}
@Override
@@ -145,14 +127,14 @@ public class PinotConnection extends AbstractBaseConnection {
public Statement createStatement()
throws SQLException {
validateState();
- return new PinotStatement(this);
+ return new PinotGrpcStatement(this);
}
@Override
public PreparedStatement prepareStatement(String sql)
throws SQLException {
validateState();
- return new PinotPreparedStatement(this, sql);
+ return new PinotGrpcPreparedStatement(this, sql);
}
@Override
@@ -164,6 +146,6 @@ public class PinotConnection extends AbstractBaseConnection {
@Override
public DatabaseMetaData getMetaData()
throws SQLException {
- return new PinotConnectionMetaData(this, _controllerURL, _controllerTransport);
+ return new PinotGrpcConnectionMetaData(this, _controllerURL, _controllerTransport);
}
}
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcConnectionMetaData.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcConnectionMetaData.java
new file mode 100644
index 0000000000..65ecd3bc8a
--- /dev/null
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcConnectionMetaData.java
@@ -0,0 +1,209 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.client.grpc;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.apache.pinot.client.PinotMeta;
+import org.apache.pinot.client.PinotResultSet;
+import org.apache.pinot.client.ResultTableResultSet;
+import org.apache.pinot.client.base.AbstractBaseConnectionMetaData;
+import org.apache.pinot.client.controller.PinotControllerTransport;
+import org.apache.pinot.client.controller.response.SchemaResponse;
+import org.apache.pinot.client.controller.response.TableResponse;
+import org.apache.pinot.client.utils.DriverUtils;
+import org.apache.pinot.spi.utils.JsonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.pinot.client.utils.Constants.*;
+
+
+public class PinotGrpcConnectionMetaData extends AbstractBaseConnectionMetaData {
+ private static final Logger LOGGER = LoggerFactory.getLogger(PinotGrpcConnectionMetaData.class);
+
+ private final PinotGrpcConnection _connection;
+ private final PinotControllerTransport _controllerTransport;
+ private final String _controllerURL;
+
+ public PinotGrpcConnectionMetaData(PinotGrpcConnection connection) {
+ this(connection, null, null);
+ }
+
+ public PinotGrpcConnectionMetaData(PinotGrpcConnection connection, String controllerURL,
+ PinotControllerTransport controllerTransport) {
+ _connection = connection;
+ _controllerURL = controllerURL;
+ _controllerTransport = controllerTransport;
+ }
+
+ @Override
+ public String getURL()
+ throws SQLException {
+ return DriverUtils.getURIFromBrokers(_connection.getSession().getBrokerList());
+ }
+
+ @Override
+ public String getDatabaseProductName()
+ throws SQLException {
+ return PRODUCT_NAME;
+ }
+
+ @Override
+ public String getDatabaseProductVersion()
+ throws SQLException {
+ return PINOT_VERSION;
+ }
+
+ @Override
+ public String getDriverName()
+ throws SQLException {
+ return DRIVER_NAME;
+ }
+
+ @Override
+ public String getDriverVersion()
+ throws SQLException {
+ return DRIVER_VERSION;
+ }
+
+ @Override
+ public int getDriverMajorVersion() {
+ return Integer.parseInt(DRIVER_VERSION.split(".")[0]);
+ }
+
+ @Override
+ public int getDriverMinorVersion() {
+ return Integer.parseInt(DRIVER_VERSION.split(".")[1]);
+ }
+
+ @Override
+ public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)
+ throws SQLException {
+ try {
+ PinotMeta pinotMeta = new PinotMeta();
+ pinotMeta.setColumnNames(TABLE_COLUMNS);
+ pinotMeta.setColumnDataTypes(TABLE_COLUMNS_DTYPES);
+
+ TableResponse tableResponse = _controllerTransport.getAllTables(_controllerURL);
+ if (tableResponse.getNumTables() == 0) {
+ LOGGER.warn("No tables found in database");
+ }
+ for (String table : tableResponse.getAllTables()) {
+ Object[] row = new Object[]{null, null, table, TABLE_TYPE, table, "", "", "", "", ""};
+ pinotMeta.addRow(Arrays.asList(row));
+ }
+
+ JsonNode resultTable = JsonUtils.objectToJsonNode(pinotMeta);
+ return PinotResultSet.fromResultTable(new ResultTableResultSet(resultTable));
+ } catch (Exception e) {
+ throw new SQLException(e);
+ }
+ }
+
+ @Override
+ public ResultSet getSchemas()
+ throws SQLException {
+ return PinotResultSet.empty();
+ }
+
+ @Override
+ public ResultSet getCatalogs()
+ throws SQLException {
+ return PinotResultSet.empty();
+ }
+
+ @Override
+ public ResultSet getTableTypes()
+ throws SQLException {
+ PinotMeta pinotMeta = new PinotMeta();
+ pinotMeta.setColumnNames(TABLE_TYPES_COLUMNS);
+ pinotMeta.setColumnDataTypes(TABLE_TYPES_COLUMNS_DTYPES);
+
+ List<Object> row = new ArrayList<>();
+ row.add(TABLE_TYPE);
+ pinotMeta.addRow(row);
+
+ JsonNode resultTable = JsonUtils.objectToJsonNode(pinotMeta);
+ return PinotResultSet.fromResultTable(new ResultTableResultSet(resultTable));
+ }
+
+ @Override
+ public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern)
+ throws SQLException {
+
+ if (tableNamePattern != null && tableNamePattern.equals("%")) {
+ LOGGER.warn("driver does not support pattern [{}] for table name", tableNamePattern);
+ return PinotResultSet.empty();
+ }
+
+ SchemaResponse schemaResponse = _controllerTransport.getTableSchema(tableNamePattern, _controllerURL);
+ PinotMeta pinotMeta = new PinotMeta();
+ pinotMeta.setColumnNames(TABLE_SCHEMA_COLUMNS);
+ pinotMeta.setColumnDataTypes(TABLE_SCHEMA_COLUMNS_DTYPES);
+
+ int ordinalPosition = 1;
+ if (schemaResponse.getDimensions() != null) {
+ for (JsonNode columns : schemaResponse.getDimensions()) {
+ appendColumnMeta(pinotMeta, tableNamePattern, ordinalPosition, columns);
+ ordinalPosition++;
+ }
+ }
+
+ if (schemaResponse.getMetrics() != null) {
+ for (JsonNode columns : schemaResponse.getMetrics()) {
+ appendColumnMeta(pinotMeta, tableNamePattern, ordinalPosition, columns);
+ ordinalPosition++;
+ }
+ }
+
+ if (schemaResponse.getDateTimeFieldSpecs() != null) {
+ for (JsonNode columns : schemaResponse.getDateTimeFieldSpecs()) {
+ appendColumnMeta(pinotMeta, tableNamePattern, ordinalPosition, columns);
+ ordinalPosition++;
+ }
+ }
+
+ JsonNode resultTable = JsonUtils.objectToJsonNode(pinotMeta);
+ return PinotResultSet.fromResultTable(new ResultTableResultSet(resultTable));
+ }
+
+ private void appendColumnMeta(PinotMeta pinotMeta, String tableName, int ordinalPosition, JsonNode columns) {
+ String columnName = columns.get("name").textValue();
+ String columnDataType = columns.get("dataType").textValue();
+ Integer columnsSQLDataType = DriverUtils.getSQLDataType(columnDataType);
+
+ Object[] row = new Object[]{
+ null, null, tableName, columnName, columnsSQLDataType, columnDataType, -1, -1, -1, -1, 1, null, null, -1, -1,
+ -1, ordinalPosition, "NO", null, null, null, -1, "NO", "NO"
+ };
+ pinotMeta.addRow(Arrays.asList(row));
+ }
+
+ @Override
+ public Connection getConnection()
+ throws SQLException {
+ return _connection;
+ }
+}
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcPreparedStatement.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcPreparedStatement.java
new file mode 100644
index 0000000000..db1d1b4da6
--- /dev/null
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcPreparedStatement.java
@@ -0,0 +1,277 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.client.grpc;
+
+import java.io.IOException;
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.sql.Date;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.Iterator;
+import org.apache.commons.codec.binary.Hex;
+import org.apache.pinot.client.PinotClientException;
+import org.apache.pinot.client.base.AbstractBasePreparedStatement;
+import org.apache.pinot.client.utils.DateTimeUtils;
+import org.apache.pinot.client.utils.DriverUtils;
+import org.apache.pinot.common.proto.Broker;
+
+
+public class PinotGrpcPreparedStatement extends AbstractBasePreparedStatement {
+ private static final String LIMIT_STATEMENT = "LIMIT";
+
+ private PinotGrpcConnection _connection;
+ private GrpcConnection _session;
+ private Iterator<Broker.BrokerResponse> _brokerResponseIterator;
+ private GrpcPreparedStatement _preparedStatement;
+ private String _query;
+ private boolean _closed;
+ private ResultSet _resultSet;
+ private int _maxRows = Integer.MAX_VALUE;
+
+ public PinotGrpcPreparedStatement(PinotGrpcConnection connection, String query) {
+ _connection = connection;
+ _session = connection.getSession();
+ _closed = false;
+ _query = query;
+ if (!DriverUtils.queryContainsLimitStatement(_query)) {
+ _query += " " + LIMIT_STATEMENT + " " + _maxRows;
+ }
+ _query = DriverUtils.enableQueryOptions(_query, _connection.getQueryOptions());
+ _preparedStatement = new GrpcPreparedStatement(_session, _query);
+ }
+
+ @Override
+ protected void validateState()
+ throws SQLException {
+ if (isClosed()) {
+ throw new SQLException("Connection is already closed!");
+ }
+ }
+
+ @Override
+ public void setNull(int parameterIndex, int sqlType)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setString(parameterIndex - 1, "NULL");
+ }
+
+ @Override
+ public void setBoolean(int parameterIndex, boolean x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setString(parameterIndex - 1, String.valueOf(x));
+ }
+
+ @Override
+ public void setShort(int parameterIndex, short x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setInt(parameterIndex - 1, x);
+ }
+
+ @Override
+ public void setInt(int parameterIndex, int x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setInt(parameterIndex - 1, x);
+ }
+
+ @Override
+ public void setLong(int parameterIndex, long x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setLong(parameterIndex - 1, x);
+ }
+
+ @Override
+ public void setFloat(int parameterIndex, float x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setFloat(parameterIndex - 1, x);
+ }
+
+ @Override
+ public void setDouble(int parameterIndex, double x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setDouble(parameterIndex - 1, x);
+ }
+
+ @Override
+ public void setString(int parameterIndex, String x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setString(parameterIndex - 1, x);
+ }
+
+ @Override
+ public void setBytes(int parameterIndex, byte[] x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setString(parameterIndex - 1, Hex.encodeHexString(x));
+ }
+
+ @Override
+ public void setDate(int parameterIndex, Date x)
+ throws SQLException {
+ _preparedStatement.setString(parameterIndex - 1, DateTimeUtils.dateToString(x));
+ }
+
+ @Override
+ public void setTime(int parameterIndex, Time x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setString(parameterIndex - 1, DateTimeUtils.timeToString(x));
+ }
+
+ @Override
+ public void setTimestamp(int parameterIndex, Timestamp x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setString(parameterIndex - 1, DateTimeUtils.timeStampToString(x));
+ }
+
+ @Override
+ public void setBigDecimal(int parameterIndex, BigDecimal x)
+ throws SQLException {
+ validateState();
+ _preparedStatement.setString(parameterIndex - 1, x.toString());
+ }
+
+ @Override
+ public void clearParameters()
+ throws SQLException {
+ validateState();
+ _preparedStatement = new GrpcPreparedStatement(_session, _query);
+ }
+
+ @Override
+ public boolean execute()
+ throws SQLException {
+ _resultSet = executeQuery();
+ return _resultSet != null;
+ }
+
+ @Override
+ public ResultSet executeQuery(String sql)
+ throws SQLException {
+ validateState();
+ try {
+ _brokerResponseIterator =
+ _session.executeWithIterator(DriverUtils.enableQueryOptions(sql, _connection.getQueryOptions()));
+ _resultSet = new PinotGrpcResultSet(_brokerResponseIterator);
+ return _resultSet;
+ } catch (PinotClientException | IOException e) {
+ throw new SQLException(String.format("Failed to execute query : %s", sql), e);
+ }
+ }
+
+ @Override
+ public ResultSet executeQuery()
+ throws SQLException {
+ validateState();
+ try {
+ _brokerResponseIterator = _preparedStatement.executeWithIterator();
+ _resultSet = new PinotGrpcResultSet(_brokerResponseIterator);
+ return _resultSet;
+ } catch (PinotClientException | IOException e) {
+ throw new SQLException(String.format("Failed to execute query : %s", _query), e);
+ }
+ }
+
+ @Override
+ public boolean execute(String sql)
+ throws SQLException {
+ _resultSet = executeQuery(sql);
+ return _resultSet != null;
+ }
+
+ @Override
+ public boolean execute(String sql, int autoGeneratedKeys)
+ throws SQLException {
+ return execute(sql);
+ }
+
+ @Override
+ public boolean execute(String sql, int[] columnIndexes)
+ throws SQLException {
+ return execute(sql);
+ }
+
+ @Override
+ public boolean execute(String sql, String[] columnNames)
+ throws SQLException {
+ return execute(sql);
+ }
+
+ @Override
+ public ResultSet getResultSet()
+ throws SQLException {
+ return _resultSet;
+ }
+
+ @Override
+ public void close()
+ throws SQLException {
+ _preparedStatement = null;
+ _connection = null;
+ _session = null;
+ _closed = true;
+ }
+
+ @Override
+ public Connection getConnection()
+ throws SQLException {
+ validateState();
+ return _connection;
+ }
+
+ @Override
+ public int getFetchSize()
+ throws SQLException {
+ return _maxRows;
+ }
+
+ @Override
+ public void setFetchSize(int rows)
+ throws SQLException {
+ _maxRows = rows;
+ }
+
+ @Override
+ public int getMaxRows()
+ throws SQLException {
+ return _maxRows;
+ }
+
+ @Override
+ public void setMaxRows(int max)
+ throws SQLException {
+ _maxRows = max;
+ }
+
+ @Override
+ public boolean isClosed()
+ throws SQLException {
+ return _closed;
+ }
+}
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultSet.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcResultSet.java
similarity index 77%
copy from pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultSet.java
copy to pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcResultSet.java
index 838fbf37e2..efc50eb005 100644
--- a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/PinotResultSet.java
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcResultSet.java
@@ -16,10 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.pinot.client;
+package org.apache.pinot.client.grpc;
-import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.ByteArrayInputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
@@ -34,67 +36,57 @@ import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.Map;
import org.apache.commons.codec.binary.Hex;
+import org.apache.pinot.client.PinotResultMetadata;
import org.apache.pinot.client.base.AbstractBaseResultSet;
import org.apache.pinot.client.utils.DateTimeUtils;
-import org.apache.pinot.spi.utils.JsonUtils;
+import org.apache.pinot.common.proto.Broker;
+import org.apache.pinot.common.utils.DataSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class PinotResultSet extends AbstractBaseResultSet {
+public class PinotGrpcResultSet extends AbstractBaseResultSet {
public static final String NULL_STRING = "null";
- private static final Logger LOG = LoggerFactory.getLogger(PinotResultSet.class);
- private org.apache.pinot.client.ResultSet _resultSet;
- private int _totalRows;
- private int _currentRow;
- private int _totalColumns;
- private Map<String, Integer> _columns = new HashMap<>();
- private Map<Integer, String> _columnDataTypes = new HashMap<>();
+ private static final Logger LOG = LoggerFactory.getLogger(PinotGrpcResultSet.class);
+
+ private final Iterator<Broker.BrokerResponse> _brokerResponseIterator;
+ private final int _totalColumns;
+ private final Map<String, Integer> _columns = new HashMap<>();
+ private final Map<Integer, String> _columnDataTypes = new HashMap<>();
+
+ private ArrayNode _currentRowBatch;
+ private int _currentBatchSize;
+
+ private int _currentBatchIndex = -1;
+ private int _currentRow = 0;
+
private boolean _closed;
private boolean _wasNull = false;
- public PinotResultSet(org.apache.pinot.client.ResultSet resultSet) {
- _resultSet = resultSet;
- _totalRows = _resultSet.getRowCount();
- _totalColumns = _resultSet.getColumnCount();
- _currentRow = -1;
+ public PinotGrpcResultSet(Iterator<Broker.BrokerResponse> brokerResponseIterator)
+ throws IOException {
+ _brokerResponseIterator = brokerResponseIterator;
_closed = false;
+ ObjectNode metadata = GrpcUtils.extractMetadataJson(_brokerResponseIterator.next());
+ DataSchema dataSchema = GrpcUtils.extractSchema(_brokerResponseIterator.next());
+ _totalColumns = dataSchema.size();
for (int i = 0; i < _totalColumns; i++) {
- _columns.put(_resultSet.getColumnName(i), i + 1);
- _columnDataTypes.put(i + 1, _resultSet.getColumnDataType(i));
+ _columns.put(dataSchema.getColumnName(i), i + 1);
+ _columnDataTypes.put(i + 1, dataSchema.getColumnDataType(i).name());
}
}
- public PinotResultSet() {
- _totalRows = 0;
- _currentRow = -1;
+ public PinotGrpcResultSet() {
+ _brokerResponseIterator = null;
+ _currentBatchSize = 0;
_totalColumns = 0;
}
- public static PinotResultSet empty() {
- return new PinotResultSet();
- }
-
- public static PinotResultSet fromJson(String jsonText) {
- try {
- JsonNode brokerResponse = JsonUtils.stringToJsonNode(jsonText);
- ResultSet resultSet = new ResultTableResultSet(brokerResponse.get("resultTable"));
- return new PinotResultSet(resultSet);
- } catch (Exception e) {
- LOG.error("Error encountered while creating result set from JSON", e);
- return empty();
- }
- }
-
- public static PinotResultSet fromResultTable(ResultSet resultSet) {
- try {
- return new PinotResultSet(resultSet);
- } catch (Exception e) {
- LOG.error("Error encountered while creating result set from Result Table", e);
- return empty();
- }
+ public static PinotGrpcResultSet empty() {
+ return new PinotGrpcResultSet();
}
protected void validateState()
@@ -117,39 +109,26 @@ public class PinotResultSet extends AbstractBaseResultSet {
public boolean absolute(int row)
throws SQLException {
validateState();
-
- if (row >= 0 && row < _totalRows) {
- _currentRow = row;
- return true;
- } else if (row < 0 && Math.abs(row) <= _totalRows) {
- _currentRow = _totalRows + row;
- return true;
- }
-
- return false;
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
public void afterLast()
throws SQLException {
validateState();
-
- _currentRow = _totalRows;
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
public void beforeFirst()
throws SQLException {
validateState();
-
- _currentRow = -1;
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
public void close()
throws SQLException {
- _resultSet = null;
- _totalRows = 0;
_currentRow = -1;
_columns.clear();
_closed = true;
@@ -176,9 +155,7 @@ public class PinotResultSet extends AbstractBaseResultSet {
public boolean first()
throws SQLException {
validateState();
-
- _currentRow = 0;
- return true;
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
@@ -280,7 +257,6 @@ public class PinotResultSet extends AbstractBaseResultSet {
public int getRow()
throws SQLException {
validateState();
-
return _currentRow;
}
@@ -295,8 +271,7 @@ public class PinotResultSet extends AbstractBaseResultSet {
public String getString(int columnIndex)
throws SQLException {
validateColumn(columnIndex);
-
- String val = _resultSet.getString(_currentRow, columnIndex - 1);
+ String val = _currentRowBatch.get(_currentBatchIndex).get(columnIndex - 1).asText();
if (checkIsNull(val)) {
return null;
}
@@ -405,16 +380,14 @@ public class PinotResultSet extends AbstractBaseResultSet {
public boolean isAfterLast()
throws SQLException {
validateState();
-
- return (_currentRow >= _totalRows);
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
public boolean isBeforeFirst()
throws SQLException {
validateState();
-
- return (_currentRow < 0);
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
@@ -427,25 +400,21 @@ public class PinotResultSet extends AbstractBaseResultSet {
public boolean isFirst()
throws SQLException {
validateState();
-
- return _currentRow == 0;
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
public boolean isLast()
throws SQLException {
validateState();
-
- return _currentRow == _totalRows - 1;
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
public boolean last()
throws SQLException {
validateState();
-
- _currentRow = _totalRows - 1;
- return true;
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
@@ -453,33 +422,40 @@ public class PinotResultSet extends AbstractBaseResultSet {
throws SQLException {
validateState();
+ if (_currentBatchIndex == _currentBatchSize - 1) {
+ if (_brokerResponseIterator.hasNext()) {
+ System.out.println("Try to fetch next batch of rows from broker response iterator.");
+ try {
+ _currentRowBatch = GrpcUtils.extractRowsJson(_brokerResponseIterator.next());
+ _currentBatchIndex = 0;
+ _currentBatchSize = _currentRowBatch.size();
+ _currentRow++;
+ return true;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ return false;
+ }
+ }
+
+ _currentBatchIndex++;
_currentRow++;
- boolean hasNext = _currentRow < _totalRows;
- return hasNext;
+ return _currentBatchIndex < _currentBatchSize;
}
@Override
public boolean previous()
throws SQLException {
validateState();
-
- if (!isBeforeFirst()) {
- _currentRow--;
- return true;
- }
- return false;
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
public boolean relative(int rows)
throws SQLException {
validateState();
- int nextRow = _currentRow + rows;
- if (nextRow >= 0 && nextRow < _totalRows) {
- _currentRow = nextRow;
- return true;
- }
- return false;
+ throw new SQLDataException("Absolute row number not supported");
}
@Override
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcStatement.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcStatement.java
new file mode 100644
index 0000000000..a5650122d7
--- /dev/null
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/grpc/PinotGrpcStatement.java
@@ -0,0 +1,149 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.client.grpc;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Iterator;
+import java.util.Map;
+import org.apache.pinot.client.PinotClientException;
+import org.apache.pinot.client.base.AbstractBaseStatement;
+import org.apache.pinot.client.utils.DriverUtils;
+import org.apache.pinot.common.proto.Broker;
+
+
+public class PinotGrpcStatement extends AbstractBaseStatement {
+ private static final String LIMIT_STATEMENT = "LIMIT";
+
+ private final PinotGrpcConnection _connection;
+ private final org.apache.pinot.client.grpc.GrpcConnection _session;
+ private boolean _closed;
+ private ResultSet _resultSet;
+ private int _maxRows = 1000000;
+
+ public PinotGrpcStatement(PinotGrpcConnection connection) {
+ _connection = connection;
+ _session = connection.getSession();
+ _closed = false;
+ _resultSet = null;
+ }
+
+ @Override
+ public void close()
+ throws SQLException {
+ _closed = true;
+ }
+
+ @Override
+ protected void validateState()
+ throws SQLException {
+ if (isClosed()) {
+ throw new SQLException("Statement is already closed!");
+ }
+ }
+
+ @Override
+ public ResultSet executeQuery(String sql)
+ throws SQLException {
+ validateState();
+ try {
+ if (!DriverUtils.queryContainsLimitStatement(sql)) {
+ sql += " " + LIMIT_STATEMENT + " " + _maxRows;
+ }
+ Map<String, Object> queryOptions = _connection.getQueryOptions();
+ String enabledSql = DriverUtils.enableQueryOptions(sql, queryOptions);
+ Iterator<Broker.BrokerResponse> brokerResponseIterator =
+ _session.executeWithIterator(enabledSql, _connection.getMetadataMap());
+ _resultSet = new PinotGrpcResultSet(brokerResponseIterator);
+ return _resultSet;
+ } catch (PinotClientException | IOException e) {
+ throw new SQLException(String.format("Failed to execute query : %s", sql), e);
+ }
+ }
+
+ @Override
+ public boolean execute(String sql)
+ throws SQLException {
+ _resultSet = executeQuery(sql);
+ return _resultSet != null;
+ }
+
+ @Override
+ public boolean execute(String sql, int autoGeneratedKeys)
+ throws SQLException {
+ return execute(sql);
+ }
+
+ @Override
+ public boolean execute(String sql, int[] columnIndexes)
+ throws SQLException {
+ return execute(sql);
+ }
+
+ @Override
+ public boolean execute(String sql, String[] columnNames)
+ throws SQLException {
+ return execute(sql);
+ }
+
+ @Override
+ public ResultSet getResultSet()
+ throws SQLException {
+ return _resultSet;
+ }
+
+ @Override
+ public Connection getConnection()
+ throws SQLException {
+ validateState();
+ return _connection;
+ }
+
+ @Override
+ public int getFetchSize()
+ throws SQLException {
+ return _maxRows;
+ }
+
+ @Override
+ public void setFetchSize(int rows)
+ throws SQLException {
+ _maxRows = rows;
+ }
+
+ @Override
+ public int getMaxRows()
+ throws SQLException {
+ return _maxRows;
+ }
+
+ @Override
+ public void setMaxRows(int max)
+ throws SQLException {
+ _maxRows = max;
+ }
+
+ @Override
+ public boolean isClosed()
+ throws SQLException {
+ return _closed;
+ }
+}
diff --git a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/utils/DriverUtils.java b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/utils/DriverUtils.java
index c21b567378..c06bafcff4 100644
--- a/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/utils/DriverUtils.java
+++ b/pinot-clients/pinot-jdbc-client/src/main/java/org/apache/pinot/client/utils/DriverUtils.java
@@ -118,6 +118,15 @@ public class DriverUtils {
return controllerUrl;
}
+
+ public static String getPinotScheme(String url) {
+ if (url.regionMatches(true, 0, SCHEME, 0, SCHEME.length())) {
+ url = url.substring(5);
+ }
+ URI uri = URI.create(url);
+ return uri.getScheme();
+ }
+
public static Map<String, String> getURLParams(String url) {
if (url.regionMatches(true, 0, SCHEME, 0, SCHEME.length())) {
url = url.substring(SCHEME.length());
@@ -250,4 +259,31 @@ public class DriverUtils {
optionBuilder.append(";\n");
return optionBuilder.toString();
}
+
+ public static Object parseOptionValue(Object value) {
+ if (value instanceof String) {
+ String str = (String) value;
+ try {
+ Long numVal = Long.valueOf(str);
+ if (numVal != null) {
+ return numVal;
+ }
+ } catch (NumberFormatException e) {
+ }
+
+ try {
+ Double numVal = Double.valueOf(str);
+ if (numVal != null) {
+ return numVal;
+ }
+ } catch (NumberFormatException e) {
+ }
+
+ Boolean boolVal = Boolean.valueOf(str.toLowerCase());
+ if (boolVal != null) {
+ return boolVal;
+ }
+ }
+ return value;
+ }
}
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/compression/CompressionFactory.java b/pinot-common/src/main/java/org/apache/pinot/common/compression/CompressionFactory.java
new file mode 100644
index 0000000000..2b5d596679
--- /dev/null
+++ b/pinot-common/src/main/java/org/apache/pinot/common/compression/CompressionFactory.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+public class CompressionFactory {
+ private CompressionFactory() {
+ }
+
+ public static String[] getCompressionTypes() {
+ return new String[]{
+ "LZ4", "LZ4_FAST", "LZ4_HIGH",
+ "ZSTD", "ZSTANDARD",
+ "DEFLATE",
+ "GZIP",
+ "SNAPPY",
+ "PASS_THROUGH", "NONE"
+ };
+ }
+
+ public static Compressor getCompressor(String type) {
+ switch (type.toUpperCase()) {
+ case "LZ4":
+ case "LZ4_FAST":
+ return Lz4Compressor.FAST_INSTANCE;
+ case "LZ4_HIGH":
+ return Lz4Compressor.HIGH_INSTANCE;
+ case "ZSTD":
+ case "ZSTANDARD":
+ return ZstdCompressor.DEFAULT_INSTANCE;
+ case "DEFLATE":
+ return DeflateCompressor.INSTANCE;
+ case "GZIP":
+ return GzipCompressor.INSTANCE;
+ case "SNAPPY":
+ return SnappyCompressor.INSTANCE;
+ case "PASS_THROUGH":
+ case "NONE":
+ return NoCompressor.INSTANCE;
+ default:
+ throw new IllegalArgumentException("Unknown compression type: " + type);
+ }
+ }
+}
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java b/pinot-common/src/main/java/org/apache/pinot/common/compression/Compressor.java
similarity index 58%
copy from pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java
copy to pinot-common/src/main/java/org/apache/pinot/common/compression/Compressor.java
index 6397a833a2..b8390aee2b 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/compression/Compressor.java
@@ -16,28 +16,31 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.pinot.controller.api.resources;
+package org.apache.pinot.common.compression;
-public class InstanceInfo {
- private final String _instanceName;
- private final String _host;
- private final Integer _port;
+/**
+ * Compressor interface for bytes compress/decompress.
+ * Note that the compress method will also encode the size of original bytes as the first
+ */
+public interface Compressor {
- public InstanceInfo(String instanceName, String host, Integer port) {
- _instanceName = instanceName;
- _host = host;
- _port = port;
- }
+ byte[] compress(byte[] input)
+ throws Exception;
- public String getInstanceName() {
- return _instanceName;
- }
+ byte[] decompress(byte[] input)
+ throws Exception;
+}
+
+class NoCompressor implements Compressor {
+ public static final Compressor INSTANCE = new NoCompressor();
- public String getHost() {
- return _host;
+ @Override
+ public byte[] compress(byte[] input) {
+ return input;
}
- public Integer getPort() {
- return _port;
+ @Override
+ public byte[] decompress(byte[] input) {
+ return input;
}
}
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/compression/DeflateCompressor.java b/pinot-common/src/main/java/org/apache/pinot/common/compression/DeflateCompressor.java
new file mode 100644
index 0000000000..cb91a8dea6
--- /dev/null
+++ b/pinot-common/src/main/java/org/apache/pinot/common/compression/DeflateCompressor.java
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+import java.io.ByteArrayOutputStream;
+import java.util.zip.Deflater;
+import java.util.zip.Inflater;
+
+
+public class DeflateCompressor implements Compressor {
+ public static final DeflateCompressor INSTANCE = new DeflateCompressor();
+
+ @Override
+ public byte[] compress(byte[] input)
+ throws Exception {
+ Deflater deflater = new Deflater();
+ deflater.setInput(input);
+ deflater.finish();
+ byte[] buffer = new byte[1024];
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ while (!deflater.finished()) {
+ int count = deflater.deflate(buffer);
+ bos.write(buffer, 0, count);
+ }
+ return bos.toByteArray();
+ }
+
+ @Override
+ public byte[] decompress(byte[] input)
+ throws Exception {
+ Inflater inflater = new Inflater();
+ inflater.setInput(input);
+ byte[] buffer = new byte[1024];
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ while (!inflater.finished()) {
+ int count = inflater.inflate(buffer);
+ bos.write(buffer, 0, count);
+ }
+ return bos.toByteArray();
+ }
+}
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/compression/GzipCompressor.java b/pinot-common/src/main/java/org/apache/pinot/common/compression/GzipCompressor.java
new file mode 100644
index 0000000000..fd5417dced
--- /dev/null
+++ b/pinot-common/src/main/java/org/apache/pinot/common/compression/GzipCompressor.java
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+
+public class GzipCompressor implements Compressor {
+ public static final GzipCompressor INSTANCE = new GzipCompressor();
+
+ @Override
+ public byte[] compress(byte[] input)
+ throws Exception {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ try (GZIPOutputStream gos = new GZIPOutputStream(bos)) {
+ gos.write(input);
+ }
+ return bos.toByteArray();
+ }
+
+ @Override
+ public byte[] decompress(byte[] input)
+ throws Exception {
+ ByteArrayInputStream bis = new ByteArrayInputStream(input);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ try (GZIPInputStream gis = new GZIPInputStream(bis)) {
+ byte[] buffer = new byte[1024];
+ int len;
+ while ((len = gis.read(buffer)) > 0) {
+ bos.write(buffer, 0, len);
+ }
+ }
+ return bos.toByteArray();
+ }
+}
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/compression/Lz4Compressor.java b/pinot-common/src/main/java/org/apache/pinot/common/compression/Lz4Compressor.java
new file mode 100644
index 0000000000..aad76dc277
--- /dev/null
+++ b/pinot-common/src/main/java/org/apache/pinot/common/compression/Lz4Compressor.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import net.jpountz.lz4.LZ4Compressor;
+import net.jpountz.lz4.LZ4Factory;
+import net.jpountz.lz4.LZ4FastDecompressor;
+
+
+public class Lz4Compressor implements Compressor {
+ private static final LZ4Factory FACTORY = LZ4Factory.fastestInstance();
+ public static final Lz4Compressor FAST_INSTANCE = new Lz4Compressor(false);
+ public static final Lz4Compressor HIGH_INSTANCE = new Lz4Compressor(true);
+
+ private final LZ4Compressor _compressor;
+
+ private Lz4Compressor(boolean highCompression) {
+ _compressor = highCompression ? FACTORY.highCompressor() : FACTORY.fastCompressor();
+ }
+
+ @Override
+ public byte[] compress(byte[] input) {
+ int maxCompressedLength = _compressor.maxCompressedLength(input.length);
+ ByteBuffer buffer = ByteBuffer.allocate(4 + maxCompressedLength);
+ buffer.putInt(input.length); // Store original length
+ int compressedSize = _compressor.compress(input, 0, input.length, buffer.array(), 4, maxCompressedLength);
+ System.out.println("original size = " + input.length + ", compressed size = " + compressedSize);
+ // Return only the valid portion of the array
+ return Arrays.copyOfRange(buffer.array(), 0, 4 + compressedSize);
+ }
+
+ @Override
+ public byte[] decompress(byte[] input) {
+ LZ4FastDecompressor decompressor = FACTORY.fastDecompressor();
+ ByteBuffer buffer = ByteBuffer.wrap(input);
+ int originalLength = buffer.getInt(); // Retrieve original length
+ byte[] restored = new byte[originalLength];
+ decompressor.decompress(input, 4, restored, 0, originalLength);
+ return restored;
+ }
+}
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java b/pinot-common/src/main/java/org/apache/pinot/common/compression/SnappyCompressor.java
similarity index 63%
copy from pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java
copy to pinot-common/src/main/java/org/apache/pinot/common/compression/SnappyCompressor.java
index 6397a833a2..89f47fc213 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/compression/SnappyCompressor.java
@@ -16,28 +16,23 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.pinot.controller.api.resources;
+package org.apache.pinot.common.compression;
-public class InstanceInfo {
- private final String _instanceName;
- private final String _host;
- private final Integer _port;
+import org.xerial.snappy.Snappy;
- public InstanceInfo(String instanceName, String host, Integer port) {
- _instanceName = instanceName;
- _host = host;
- _port = port;
- }
- public String getInstanceName() {
- return _instanceName;
- }
+public class SnappyCompressor implements Compressor {
+ public static final SnappyCompressor INSTANCE = new SnappyCompressor();
- public String getHost() {
- return _host;
+ @Override
+ public byte[] compress(byte[] input)
+ throws Exception {
+ return Snappy.compress(input);
}
- public Integer getPort() {
- return _port;
+ @Override
+ public byte[] decompress(byte[] input)
+ throws Exception {
+ return Snappy.uncompress(input);
}
}
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/compression/ZstdCompressor.java b/pinot-common/src/main/java/org/apache/pinot/common/compression/ZstdCompressor.java
new file mode 100644
index 0000000000..d25b427f59
--- /dev/null
+++ b/pinot-common/src/main/java/org/apache/pinot/common/compression/ZstdCompressor.java
@@ -0,0 +1,69 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+import com.github.luben.zstd.Zstd;
+import com.github.luben.zstd.ZstdException;
+import java.nio.ByteBuffer;
+
+
+public class ZstdCompressor implements Compressor {
+ public static final ZstdCompressor DEFAULT_INSTANCE = new ZstdCompressor();
+
+ private final int _level;
+
+ public ZstdCompressor() {
+ this(Zstd.defaultCompressionLevel());
+ }
+
+ public ZstdCompressor(int level) {
+ _level = level;
+ }
+
+ @Override
+ public byte[] compress(byte[] input) {
+ try {
+ int compressedSize = (int) Zstd.compressBound(input.length);
+ ByteBuffer buffer = ByteBuffer.allocate(4 + compressedSize);
+ buffer.putInt(input.length); // Store original length
+ int actualCompressedSize =
+ (int) Zstd.compressByteArray(buffer.array(), 4, compressedSize, input, 0, input.length, _level, true);
+ return java.util.Arrays.copyOfRange(buffer.array(), 0, 4 + actualCompressedSize);
+ } catch (ZstdException e) {
+ throw new RuntimeException("Failed to compress data using Zstd", e);
+ }
+ }
+
+ @Override
+ public byte[] decompress(byte[] input) {
+ try {
+ ByteBuffer buffer = ByteBuffer.wrap(input);
+ int originalLength = buffer.getInt(); // Retrieve original length
+ byte[] output = new byte[originalLength];
+ long decompressedSize = Zstd.decompressByteArray(output, 0, originalLength, input, 4, input.length - 4);
+ if (decompressedSize != originalLength) {
+ throw new RuntimeException(
+ "Decompressed size mismatch: expected " + originalLength + " but got " + decompressedSize);
+ }
+ return output;
+ } catch (ZstdException e) {
+ throw new RuntimeException("Failed to decompress data using Zstd", e);
+ }
+ }
+}
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
index 22be35405f..d8562beade 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerMeter.java
@@ -189,7 +189,15 @@ public enum BrokerMeter implements AbstractMetrics.Meter {
/**
* The number of bytes stored in the response store. Only the size of the result table is tracked.
*/
- CURSOR_RESPONSE_STORE_SIZE("bytes", true);
+ CURSOR_RESPONSE_STORE_SIZE("bytes", true),
+
+ // GRPC related metrics
+ GRPC_QUERIES("grpcQueries", true),
+ GRPC_QUERY_EXCEPTIONS("grpcExceptions", true),
+ GRPC_BYTES_RECEIVED("grpcBytesReceived", true),
+ GRPC_BYTES_SENT("grpcBytesSent", true),
+ GRPC_TRANSPORT_READY("grpcTransport", true),
+ GRPC_TRANSPORT_TERMINATED("grpcTransport", true);
private final String _brokerMeterName;
private final String _unit;
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerTimer.java b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerTimer.java
index 2e70cf69bb..d3befeed86 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerTimer.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/metrics/BrokerTimer.java
@@ -55,7 +55,9 @@ public enum BrokerTimer implements AbstractMetrics.Timer {
// processing from realtime servers
REALTIME_TOTAL_CPU_TIME_NS(false),
// How long it took the server to start.
- STARTUP_SUCCESS_DURATION_MS(true);
+ STARTUP_SUCCESS_DURATION_MS(true),
+ // GRPC query execution time
+ GRPC_QUERY_EXECUTION_MS(true);
private final String _timerName;
private final boolean _global;
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/response/BrokerResponse.java b/pinot-common/src/main/java/org/apache/pinot/common/response/BrokerResponse.java
index 90cc107b45..252ddbe4b3 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/response/BrokerResponse.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/response/BrokerResponse.java
@@ -19,6 +19,7 @@
package org.apache.pinot.common.response;
import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
@@ -34,7 +35,6 @@ import org.apache.pinot.spi.utils.JsonUtils;
* Interface for broker response.
*/
public interface BrokerResponse {
-
/**
* Convert the broker response to JSON String.
*/
@@ -51,6 +51,16 @@ public interface BrokerResponse {
JsonUtils.objectToOutputStream(this, outputStream);
}
+ /**
+ * Convert the broker response metadata to JSON String.
+ */
+ default String toMetadataJsonString()
+ throws IOException {
+ ObjectNode objectNode = (ObjectNode) JsonUtils.objectToJsonNode(this);
+ objectNode.remove("resultTable");
+ return JsonUtils.objectToString(objectNode);
+ }
+
/**
* Returns the result table.
*/
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/utils/grpc/BrokerGrpcQueryClient.java b/pinot-common/src/main/java/org/apache/pinot/common/utils/grpc/BrokerGrpcQueryClient.java
index 7d8e96f2fb..94eb73967c 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/utils/grpc/BrokerGrpcQueryClient.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/utils/grpc/BrokerGrpcQueryClient.java
@@ -37,7 +37,7 @@ public class BrokerGrpcQueryClient extends BaseGrpcQueryClient<Broker.BrokerRequ
}
@Override
- Iterator<Broker.BrokerResponse> submit(Broker.BrokerRequest request) {
+ public Iterator<Broker.BrokerResponse> submit(Broker.BrokerRequest request) {
return _blockingStub.submit(request);
}
}
diff --git a/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/HelixHelper.java b/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/HelixHelper.java
index c5071e4939..e8a32bbf8e 100644
--- a/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/HelixHelper.java
+++ b/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/HelixHelper.java
@@ -610,6 +610,15 @@ public class HelixHelper {
return true;
}
+ /**
+ * Return the grpcPort for a given Pinot instance config
+ * @param instanceConfig the instance config to fetch
+ * @return the grpc port, -1 if not found
+ */
+ public static String getGrpcPort(InstanceConfig instanceConfig) {
+ return instanceConfig.getRecord().getStringField(CommonConstants.Helix.Instance.GRPC_PORT_KEY, "-1");
+ }
+
/**
* Adds default tags to the instance config if no tag exists, returns {@code true} if the default tags are added,
* {@code false} otherwise.
diff --git a/pinot-common/src/test/java/org/apache/pinot/common/compression/DeflateCompressorTest.java b/pinot-common/src/test/java/org/apache/pinot/common/compression/DeflateCompressorTest.java
new file mode 100644
index 0000000000..8c296b213f
--- /dev/null
+++ b/pinot-common/src/test/java/org/apache/pinot/common/compression/DeflateCompressorTest.java
@@ -0,0 +1,104 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+import java.util.Random;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+
+public class DeflateCompressorTest {
+ private DeflateCompressor _compressor;
+
+ @BeforeMethod
+ public void setUp() {
+ _compressor = new DeflateCompressor();
+ }
+
+ @Test
+ public void testRoundTripWithSampleData()
+ throws Exception {
+ String inputStr = "Hello, World!";
+ byte[] input = inputStr.getBytes();
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Decompressed data should match original input");
+ }
+
+ @Test
+ public void testEmptyInput()
+ throws Exception {
+ byte[] input = new byte[0];
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Decompressed empty data should be empty");
+ }
+
+ @Test
+ public void testLargeInput()
+ throws Exception {
+ byte[] input = new byte[10000];
+ new Random().nextBytes(input);
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Decompressed large data should match original");
+ }
+
+ @Test(expectedExceptions = Exception.class)
+ public void testDecompressInvalidDataThrowsException()
+ throws Exception {
+ byte[] invalidData = new byte[]{0x01, 0x02, 0x03};
+ _compressor.decompress(invalidData);
+ }
+
+ @Test
+ public void testBinaryData()
+ throws Exception {
+ byte[] input = new byte[500];
+ new Random().nextBytes(input);
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Decompressed binary data should match original");
+ }
+
+ @Test
+ public void testInputSizeLargerThanBuffer()
+ throws Exception {
+ byte[] input = new byte[1500];
+ new Random().nextBytes(input);
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Data larger than buffer size should decompress correctly");
+ }
+
+ @Test
+ public void testCompressedDataIsSmallerForCompressibleData()
+ throws Exception {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 1000; i++) {
+ sb.append("repeated string ");
+ }
+ byte[] input = sb.toString().getBytes();
+ byte[] compressed = _compressor.compress(input);
+ assertTrue(compressed.length < input.length, "Compressed data should be smaller for compressible input");
+ }
+}
diff --git a/pinot-common/src/test/java/org/apache/pinot/common/compression/GzipCompressorTest.java b/pinot-common/src/test/java/org/apache/pinot/common/compression/GzipCompressorTest.java
new file mode 100644
index 0000000000..50b7e0f0f6
--- /dev/null
+++ b/pinot-common/src/test/java/org/apache/pinot/common/compression/GzipCompressorTest.java
@@ -0,0 +1,107 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+import java.util.Random;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+
+public class GzipCompressorTest {
+ private GzipCompressor _compressor;
+
+ @BeforeMethod
+ public void setUp() {
+ _compressor = new GzipCompressor();
+ }
+
+ @Test
+ public void testRoundTripWithSampleData()
+ throws Exception {
+ String inputStr = "Test GZIP compression";
+ byte[] input = inputStr.getBytes();
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Decompressed data should match original");
+ }
+
+ @Test
+ public void testEmptyInput()
+ throws Exception {
+ byte[] input = new byte[0];
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Empty input should remain empty after round trip");
+ }
+
+ @Test
+ public void testLargeInput()
+ throws Exception {
+ byte[] input = new byte[100_000]; // 100KB
+ new Random().nextBytes(input);
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Large input should survive round trip");
+ }
+
+ @Test(expectedExceptions = Exception.class)
+ public void testDecompressInvalidData()
+ throws Exception {
+ byte[] invalidPayload = {0x01, 0x02, 0x03}; // Not valid GZIP
+ _compressor.decompress(invalidPayload);
+ }
+
+ @Test
+ public void testBinaryData()
+ throws Exception {
+ byte[] input = new byte[2048];
+ new Random().nextBytes(input);
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Random binary data should match after round trip");
+ }
+
+ @Test
+ public void testCompressionReducesSizeForRepetitiveData()
+ throws Exception {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 1000; i++) {
+ sb.append("Repeating pattern ABC123 ");
+ }
+ byte[] input = sb.toString().getBytes();
+ byte[] compressed = _compressor.compress(input);
+ assertTrue(compressed.length < input.length,
+ "Compressed size should be smaller for repetitive content");
+ }
+
+ @Test
+ public void testPartialReadHandling()
+ throws Exception {
+ // Create input that will produce multi-chunk output
+ byte[] input = new byte[2048];
+ new Random().nextBytes(input);
+
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Should handle multi-chunk reads properly");
+ }
+}
diff --git a/pinot-common/src/test/java/org/apache/pinot/common/compression/Lz4CompressorTest.java b/pinot-common/src/test/java/org/apache/pinot/common/compression/Lz4CompressorTest.java
new file mode 100644
index 0000000000..5a938a00c8
--- /dev/null
+++ b/pinot-common/src/test/java/org/apache/pinot/common/compression/Lz4CompressorTest.java
@@ -0,0 +1,94 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+import java.nio.charset.StandardCharsets;
+import net.jpountz.lz4.LZ4Exception;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+
+public class Lz4CompressorTest {
+ private Lz4Compressor _fastCompressor;
+ private Lz4Compressor _highCompressor;
+
+ @BeforeClass
+ public void setUp() {
+ _fastCompressor = Lz4Compressor.FAST_INSTANCE;
+ _highCompressor = Lz4Compressor.HIGH_INSTANCE;
+ }
+
+ @Test
+ public void testFastCompressionAndDecompression() {
+ testCompressionAndDecompression(_fastCompressor);
+ }
+
+ @Test
+ public void testHighCompressionAndDecompression() {
+ testCompressionAndDecompression(_highCompressor);
+ }
+
+ private void testCompressionAndDecompression(Lz4Compressor compressor) {
+ String originalString = "This is a performance-optimized LZ4 compression test.";
+ byte[] originalBytes = originalString.getBytes(StandardCharsets.UTF_8);
+
+ byte[] compressedBytes = compressor.compress(originalBytes);
+ Assert.assertNotNull(compressedBytes, "Compressed data should not be null");
+ Assert.assertTrue(compressedBytes.length > 4, "Compressed data should not be empty");
+
+ byte[] decompressedBytes = compressor.decompress(compressedBytes);
+ Assert.assertNotNull(decompressedBytes, "Decompressed data should not be null");
+ Assert.assertEquals(decompressedBytes.length, originalBytes.length,
+ "Decompressed data length should match original");
+ Assert.assertEquals(new String(decompressedBytes, StandardCharsets.UTF_8), originalString,
+ "Decompressed content should match original");
+ }
+
+ @Test
+ public void testEmptyCompression() {
+ byte[] emptyBytes = new byte[0];
+ byte[] compressedBytes = _fastCompressor.compress(emptyBytes);
+ Assert.assertNotNull(compressedBytes, "Compressed empty data should not be null");
+ Assert.assertTrue(compressedBytes.length > 4, "Compressed data should contain length metadata");
+
+ byte[] decompressedBytes = _fastCompressor.decompress(compressedBytes);
+ Assert.assertNotNull(decompressedBytes, "Decompressed empty data should not be null");
+ Assert.assertEquals(decompressedBytes.length, 0, "Decompressed empty data should be empty");
+ }
+
+ @Test(expectedExceptions = LZ4Exception.class)
+ public void testInvalidDecompression() {
+ byte[] invalidData = new byte[]{0, 0, 0, 10, 1, 2, 3, 4, 5}; // Invalid compressed data with fake length
+ _fastCompressor.decompress(invalidData);
+ }
+
+ @Test
+ public void testCompressionRatioForCompressibleData() {
+ byte[] input = "REPEATING_PATTERN_LZ4_TEST_1234567890 ".repeat(1638).getBytes(StandardCharsets.UTF_8);
+ byte[] compressedFast = _fastCompressor.compress(input);
+ byte[] compressedHigh = _highCompressor.compress(input);
+
+ System.out.println("Fast compression size: " + compressedFast.length + " vs Original size: " + input.length);
+ System.out.println("High compression size: " + compressedHigh.length + " vs Original size: " + input.length);
+
+ Assert.assertTrue(compressedFast.length < input.length, "Fast compressed data should be smaller than original");
+ Assert.assertTrue(compressedHigh.length <= compressedFast.length, "High compression should produce smaller output");
+ }
+}
diff --git a/pinot-common/src/test/java/org/apache/pinot/common/compression/SnappyCompressorTest.java b/pinot-common/src/test/java/org/apache/pinot/common/compression/SnappyCompressorTest.java
new file mode 100644
index 0000000000..40dda784e7
--- /dev/null
+++ b/pinot-common/src/test/java/org/apache/pinot/common/compression/SnappyCompressorTest.java
@@ -0,0 +1,96 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+import java.util.Random;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+
+public class SnappyCompressorTest {
+ private SnappyCompressor _compressor;
+
+ @BeforeMethod
+ public void setUp() {
+ _compressor = new SnappyCompressor();
+ }
+
+ @Test
+ public void testRoundTripWithSampleData()
+ throws Exception {
+ String inputStr = "Snappy compression test 123";
+ byte[] input = inputStr.getBytes();
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Round-trip should return original data");
+ }
+
+ @Test
+ public void testEmptyInput()
+ throws Exception {
+ byte[] input = new byte[0];
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Empty input should remain empty");
+ }
+
+ @Test
+ public void testLargeRandomData()
+ throws Exception {
+ byte[] input = new byte[100_000]; // 100KB
+ new Random().nextBytes(input);
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Large random input should match after decompression");
+ }
+
+ @Test(expectedExceptions = Exception.class)
+ public void testInvalidCompressedData()
+ throws Exception {
+ byte[] invalidData = new byte[]{0x01, 0x02, 0x03}; // Random invalid data
+ _compressor.decompress(invalidData);
+ }
+
+ @Test
+ public void testBinaryDataRoundTrip()
+ throws Exception {
+ byte[] input = new byte[8192]; // 8KB
+ new Random().nextBytes(input);
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Binary data should survive round-trip");
+ }
+
+ @Test
+ public void testCompressionRatioForRepeatedData()
+ throws Exception {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 5000; i++) {
+ sb.append("Repeating pattern ABCDEF123456 "); // Highly redundant
+ }
+ byte[] input = sb.toString().getBytes();
+ byte[] compressed = _compressor.compress(input);
+
+ assertTrue(compressed.length < input.length * 0.75,
+ "Compressed size should be significantly smaller for redundant data");
+ }
+}
diff --git a/pinot-common/src/test/java/org/apache/pinot/common/compression/ZstdCompressorTest.java b/pinot-common/src/test/java/org/apache/pinot/common/compression/ZstdCompressorTest.java
new file mode 100644
index 0000000000..53a198cc2c
--- /dev/null
+++ b/pinot-common/src/test/java/org/apache/pinot/common/compression/ZstdCompressorTest.java
@@ -0,0 +1,115 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.pinot.common.compression;
+
+import java.util.Random;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertThrows;
+import static org.testng.Assert.assertTrue;
+
+
+public class ZstdCompressorTest {
+ private ZstdCompressor _compressor;
+
+ @BeforeMethod
+ public void setUp() {
+ _compressor = new ZstdCompressor();
+ }
+
+ @Test
+ public void testRoundTripWithSampleData() {
+ String inputStr = "Zstandard compression test 123";
+ byte[] input = inputStr.getBytes();
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Decompressed data should match original");
+ }
+
+ @Test
+ public void testEmptyInput() {
+ byte[] input = new byte[0];
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Empty input should remain empty after round trip");
+ }
+
+ @Test
+ public void testLargeRandomData() {
+ byte[] input = new byte[10_000_000]; // 10MB
+ new Random().nextBytes(input);
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Large random input should match after decompression");
+ }
+
+ @Test(expectedExceptions = RuntimeException.class)
+ public void testInvalidCompressedData() {
+ byte[] invalidData = new byte[]{0x01, 0x02, 0x03};
+ _compressor.decompress(invalidData);
+ }
+
+ @Test
+ public void testBinaryDataRoundTrip() {
+ byte[] input = new byte[65_535]; // Zstd's special case size
+ new Random().nextBytes(input);
+ byte[] compressed = _compressor.compress(input);
+ byte[] decompressed = _compressor.decompress(compressed);
+ assertEquals(decompressed, input, "Binary data should survive round trip");
+ }
+
+ @Test
+ public void testCompressionRatioForRedundantData() {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 5000; i++) {
+ sb.append("Repeating pattern ZSTD-COMPRESSION-TEST-123 ");
+ }
+ byte[] input = sb.toString().getBytes();
+ byte[] compressed = _compressor.compress(input);
+ assertTrue(compressed.length < input.length * 0.2,
+ "Compressed size should be <20% of original for redundant data");
+ }
+
+ @Test
+ public void testCorruptedDataThrowsException() {
+ byte[] original = "Important data for corruption test".getBytes();
+ byte[] compressed = _compressor.compress(original);
+
+ // Corrupt the middle byte
+ compressed[compressed.length / 2] ^= (byte) 0xFF;
+
+ assertThrows(RuntimeException.class, () -> _compressor.decompress(compressed));
+ }
+
+ @Test
+ public void testDecompressWithTruncatedData() {
+ byte[] original = "Data for truncation test".getBytes();
+ byte[] compressed = _compressor.compress(original);
+
+ // Create truncated array
+ byte[] truncated = new byte[compressed.length - 5];
+ System.arraycopy(compressed, 0, truncated, 0, truncated.length);
+
+ assertThrows(RuntimeException.class, () -> {
+ _compressor.decompress(truncated);
+ });
+ }
+}
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java
index 6397a833a2..b12efdd6b0 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/InstanceInfo.java
@@ -22,11 +22,13 @@ public class InstanceInfo {
private final String _instanceName;
private final String _host;
private final Integer _port;
+ private final Integer _grpcPort;
- public InstanceInfo(String instanceName, String host, Integer port) {
+ public InstanceInfo(String instanceName, String host, Integer port, Integer grpcPort) {
_instanceName = instanceName;
_host = host;
_port = port;
+ _grpcPort = grpcPort;
}
public String getInstanceName() {
@@ -40,4 +42,8 @@ public class InstanceInfo {
public Integer getPort() {
return _port;
}
+
+ public Integer getGrpcPort() {
+ return _grpcPort;
+ }
}
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotBrokerRestletResource.java b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotBrokerRestletResource.java
index 08f9b0d662..2a82174879 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotBrokerRestletResource.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotBrokerRestletResource.java
@@ -49,6 +49,7 @@ import javax.ws.rs.core.Response;
import org.apache.helix.model.InstanceConfig;
import org.apache.pinot.common.exception.TableNotFoundException;
import org.apache.pinot.common.utils.DatabaseUtils;
+import org.apache.pinot.common.utils.helix.HelixHelper;
import org.apache.pinot.controller.api.access.AccessType;
import org.apache.pinot.controller.api.access.Authenticate;
import org.apache.pinot.controller.api.exception.ControllerApplicationException;
@@ -64,15 +65,18 @@ import static org.apache.pinot.spi.utils.CommonConstants.DATABASE;
import static org.apache.pinot.spi.utils.CommonConstants.SWAGGER_AUTHORIZATION_KEY;
-@Api(tags = Constants.BROKER_TAG, authorizations = {@Authorization(value = SWAGGER_AUTHORIZATION_KEY),
- @Authorization(value = DATABASE)})
+@Api(tags = Constants.BROKER_TAG, authorizations = {
+ @Authorization(value = SWAGGER_AUTHORIZATION_KEY),
+ @Authorization(value = DATABASE)
+})
@SwaggerDefinition(securityDefinition = @SecurityDefinition(apiKeyAuthDefinitions = {
@ApiKeyAuthDefinition(name = HttpHeaders.AUTHORIZATION, in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER,
key = SWAGGER_AUTHORIZATION_KEY,
description = "The format of the key is ```\"Basic <token>\" or \"Bearer <token>\"```"),
@ApiKeyAuthDefinition(name = DATABASE, in = ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = DATABASE,
description = "Database context passed through http header. If no context is provided 'default' database "
- + "context will be considered.")}))
+ + "context will be considered.")
+}))
@Path("/")
public class PinotBrokerRestletResource {
public static final Logger LOGGER = LoggerFactory.getLogger(PinotBrokerRestletResource.class);
@@ -187,7 +191,8 @@ public class PinotBrokerRestletResource {
Set<InstanceConfig> tenantBrokers =
new HashSet<>(_pinotHelixResourceManager.getAllInstancesConfigsForBrokerTenant(tenantName));
Set<InstanceInfo> instanceInfoSet = tenantBrokers.stream()
- .map(x -> new InstanceInfo(x.getInstanceName(), x.getHostName(), Integer.parseInt(x.getPort())))
+ .map(x -> new InstanceInfo(x.getInstanceName(), x.getHostName(), Integer.parseInt(x.getPort()),
+ Integer.parseInt(HelixHelper.getGrpcPort(x))))
.collect(Collectors.toSet());
applyStateChanges(instanceInfoSet, state);
return ImmutableList.copyOf(instanceInfoSet);
@@ -224,7 +229,8 @@ public class PinotBrokerRestletResource {
Set<InstanceConfig> tenantBrokers =
new HashSet<>(_pinotHelixResourceManager.getBrokerInstancesConfigsFor(tableNamesWithType.get(0)));
Set<InstanceInfo> instanceInfoSet = tenantBrokers.stream()
- .map(x -> new InstanceInfo(x.getInstanceName(), x.getHostName(), Integer.parseInt(x.getPort())))
+ .map(x -> new InstanceInfo(x.getInstanceName(), x.getHostName(), Integer.parseInt(x.getPort()),
+ Integer.parseInt(HelixHelper.getGrpcPort(x))))
.collect(Collectors.toSet());
applyStateChanges(instanceInfoSet, state);
return ImmutableList.copyOf(instanceInfoSet);
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java b/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java
index 220533d235..e2a5fc2646 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/cursors/ResponseStoreCleaner.java
@@ -45,6 +45,7 @@ import org.apache.pinot.common.http.MultiHttpRequestResponse;
import org.apache.pinot.common.metrics.ControllerMetrics;
import org.apache.pinot.common.response.CursorResponse;
import org.apache.pinot.common.response.broker.CursorResponseNative;
+import org.apache.pinot.common.utils.helix.HelixHelper;
import org.apache.pinot.controller.ControllerConf;
import org.apache.pinot.controller.LeadControllerManager;
import org.apache.pinot.controller.api.resources.InstanceInfo;
@@ -127,7 +128,8 @@ public class ResponseStoreCleaner extends ControllerPeriodicTask<Void> {
Map<String, InstanceInfo> brokers = new HashMap<>();
for (InstanceConfig broker : brokerList) {
brokers.put(getInstanceKey(broker.getHostName(), broker.getPort()),
- new InstanceInfo(broker.getInstanceName(), broker.getHostName(), Integer.parseInt(broker.getPort())));
+ new InstanceInfo(broker.getInstanceName(), broker.getHostName(), Integer.parseInt(broker.getPort()),
+ Integer.parseInt(HelixHelper.getGrpcPort(broker))));
}
try {
diff --git a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java
index c8478c25c5..1a23ab510f 100644
--- a/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java
+++ b/pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java
@@ -4455,7 +4455,7 @@ public class PinotHelixResourceManager {
if ("ONLINE".equalsIgnoreCase(brokerEntry.getValue()) && instanceConfigMap.containsKey(brokerEntry.getKey())) {
InstanceConfig instanceConfig = instanceConfigMap.get(brokerEntry.getKey());
hosts.add(new InstanceInfo(instanceConfig.getInstanceName(), instanceConfig.getHostName(),
- Integer.parseInt(instanceConfig.getPort())));
+ Integer.parseInt(instanceConfig.getPort()), Integer.parseInt(HelixHelper.getGrpcPort(instanceConfig))));
}
}
if (!hosts.isEmpty()) {
diff --git a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerTest.java b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerTest.java
index 293f649fa9..5590cdff06 100644
--- a/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerTest.java
+++ b/pinot-controller/src/test/java/org/apache/pinot/controller/helix/ControllerTest.java
@@ -121,6 +121,7 @@ public class ControllerTest {
protected int _nextControllerPort = 20000;
protected int _nextBrokerPort = _nextControllerPort + 1000;
+ protected int _nextBrokerGrpcPort = _nextBrokerPort + 500;
protected int _nextServerPort = _nextBrokerPort + 1000;
protected int _nextMinionPort = _nextServerPort + 1000;
diff --git a/pinot-integration-test-base/src/test/java/org/apache/pinot/integration/tests/ClusterTest.java b/pinot-integration-test-base/src/test/java/org/apache/pinot/integration/tests/ClusterTest.java
index b810d45f65..43fc3181b4 100644
--- a/pinot-integration-test-base/src/test/java/org/apache/pinot/integration/tests/ClusterTest.java
+++ b/pinot-integration-test-base/src/test/java/org/apache/pinot/integration/tests/ClusterTest.java
@@ -28,6 +28,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutorService;
@@ -48,6 +49,8 @@ import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.pinot.broker.broker.helix.BaseBrokerStarter;
import org.apache.pinot.broker.broker.helix.HelixBrokerStarter;
+import org.apache.pinot.client.ConnectionFactory;
+import org.apache.pinot.client.grpc.GrpcConnection;
import org.apache.pinot.common.exception.HttpErrorStatusException;
import org.apache.pinot.common.utils.FileUploadDownloadClient;
import org.apache.pinot.common.utils.URIUtils;
@@ -99,6 +102,7 @@ public abstract class ClusterTest extends ControllerTest {
protected final List<BaseBrokerStarter> _brokerStarters = new ArrayList<>();
protected final List<Integer> _brokerPorts = new ArrayList<>();
protected String _brokerBaseApiUrl;
+ protected String _brokerGrpcEndpoint;
protected final List<BaseServerStarter> _serverStarters = new ArrayList<>();
protected int _serverGrpcPort;
@@ -126,6 +130,10 @@ public abstract class ClusterTest extends ControllerTest {
return _brokerBaseApiUrl;
}
+ protected String getBrokerGrpcEndpoint() {
+ return _brokerGrpcEndpoint;
+ }
+
public String getMinionBaseApiUrl() {
return _minionBaseApiUrl;
}
@@ -174,6 +182,13 @@ public abstract class ClusterTest extends ControllerTest {
brokerConf.setProperty(Broker.CONFIG_OF_BROKER_TIMEOUT_MS, 60 * 1000L);
brokerConf.setProperty(Broker.CONFIG_OF_DELAY_SHUTDOWN_TIME_MS, 0);
brokerConf.setProperty(CommonConstants.CONFIG_OF_TIMEZONE, "UTC");
+
+ int brokerGrpcPort = NetUtils.findOpenPort(_nextBrokerGrpcPort);
+ brokerConf.setProperty(Broker.Grpc.KEY_OF_GRPC_PORT, brokerGrpcPort);
+ if (_brokerGrpcEndpoint == null) {
+ _brokerGrpcEndpoint = "localhost:" + brokerGrpcPort;
+ }
+ _nextBrokerGrpcPort = brokerGrpcPort + 1;
overrideBrokerConf(brokerConf);
return brokerConf;
}
@@ -330,6 +345,7 @@ public abstract class ClusterTest extends ControllerTest {
_brokerStarters.clear();
_brokerPorts.clear();
_brokerBaseApiUrl = null;
+ _brokerGrpcEndpoint = null;
}
protected void stopServer() {
@@ -510,11 +526,23 @@ public abstract class ClusterTest extends ControllerTest {
return JsonUtils.stringToJsonNode(sendGetRequest(getBrokerBaseApiUrl() + "/" + uri));
}
+ public JsonNode queryGrpcEndpoint(String query, Map<String, String> metadataMap)
+ throws IOException {
+ GrpcConnection grpcConnection =
+ ConnectionFactory.fromHostListGrpc(new Properties(), List.of(getBrokerGrpcEndpoint()));
+ return grpcConnection.getJsonResponse(query, metadataMap);
+ }
+
/**
- * Queries the broker's sql query endpoint (/query/sql)
+ * Queries the broker's query endpoint (/query/sql), picking http or grpc randomly.
*/
public JsonNode postQuery(@Language("sql") String query)
throws Exception {
+ if (System.currentTimeMillis() % 2 == 0) {
+ return queryGrpcEndpoint(query,
+ Map.of(Broker.Request.QUERY_OPTIONS,
+ Broker.Request.QueryOptionKey.USE_MULTISTAGE_ENGINE + "=" + useMultiStageQueryEngine()));
+ }
return postQuery(query, getBrokerQueryApiUrl(getBrokerBaseApiUrl(), useMultiStageQueryEngine()), null,
getExtraQueryProperties());
}
@@ -576,7 +604,7 @@ public abstract class ClusterTest extends ControllerTest {
}
public JsonNode cancelQuery(String clientQueryId)
- throws Exception {
+ throws Exception {
URI cancelURI = URI.create(getControllerRequestURLBuilder().forCancelQueryByClientId(clientQueryId));
Object o = _httpClient.sendDeleteRequest(cancelURI);
return null; // TODO
diff --git a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/CustomDataQueryClusterIntegrationTest.java b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/CustomDataQueryClusterIntegrationTest.java
index 2d4569f012..5c3b9b2cf9 100644
--- a/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/CustomDataQueryClusterIntegrationTest.java
+++ b/pinot-integration-tests/src/test/java/org/apache/pinot/integration/tests/custom/CustomDataQueryClusterIntegrationTest.java
@@ -157,6 +157,14 @@ public abstract class CustomDataQueryClusterIntegrationTest extends BaseClusterI
return super.getBrokerBaseApiUrl();
}
+ @Override
+ protected String getBrokerGrpcEndpoint() {
+ if (_sharedClusterTestSuite != this) {
+ return _sharedClusterTestSuite.getBrokerGrpcEndpoint();
+ }
+ return super.getBrokerGrpcEndpoint();
+ }
+
@Override
public int getControllerPort() {
if (_sharedClusterTestSuite != this) {
diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
index 6ab5a0458b..bc9042738b 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
@@ -727,6 +727,18 @@ public class CommonConstants {
public static final int DEFAULT_STATS_MANAGER_THREADPOOL_SIZE = 2;
}
+ public static class Grpc {
+ public static final String KEY_OF_GRPC_PORT = "pinot.broker.grpc.port";
+ public static final String KEY_OF_GRPC_TLS_ENABLED = "pinot.broker.grpc.tls.enabled";
+ public static final String KEY_OF_GRPC_TLS_PORT = "pinot.broker.grpc.tls.port";
+ public static final String KEY_OF_GRPC_TLS_PREFIX = "pinot.broker.grpctls";
+
+ public static final String BLOCK_ROW_SIZE = "blockRowSize";
+ public static final int DEFAULT_BLOCK_ROW_SIZE = 10_000;
+ public static final String COMPRESSION = "compression";
+ public static final String DEFAULT_COMPRESSION = "ZSTD";
+ }
+
public static final String PREFIX_OF_CONFIG_OF_PINOT_FS_FACTORY = "pinot.broker.storage.factory";
public static final String USE_MSE_TO_FILL_EMPTY_RESPONSE_SCHEMA =
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/QuickStartBase.java b/pinot-tools/src/main/java/org/apache/pinot/tools/QuickStartBase.java
index 388192d623..48c4fdac0c 100644
--- a/pinot-tools/src/main/java/org/apache/pinot/tools/QuickStartBase.java
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/QuickStartBase.java
@@ -292,7 +292,7 @@ public abstract class QuickStartBase {
}
protected Map<String, String> getClusterConfigOverrides() {
- return Map.of();
+ return Map.of("pinot.broker.grpc.port", "8010");
}
protected String[] getDefaultBatchTableDirectories() {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org