diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8cef181 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +*.iml +*.ipr +*.iws +target/ +/var +pom.xml.versionsBackup +test-output/ +/atlassian-ide-plugin.xml +.idea +.DS_Store +.classpath +.settings +.project +temp-testng-customsuite.xml +test-output +.externalToolBuilders +*~ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..dff5f3a --- /dev/null +++ b/.travis.yml @@ -0,0 +1 @@ +language: java diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..4672098 --- /dev/null +++ b/pom.xml @@ -0,0 +1,456 @@ + + + 4.0.0 + + + com.facebook.airlift + airbase + 95 + + + com.facebook.presto.pinot + pinot-driver + 0.1.0-SNAPSHOT + + pinot-driver + Shaded driver for the presto-pinot connector that exposes only the pinot-common dependancies and some helpers + https://github.com/prestodb/presto-pinot-driver + + + + Apache License 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + repo + + + + + + + + + scm:git:git://github.com/prestodb/presto-pinot-driver.git + scm:git:git://github.com/prestodb/presto-pinot-driver.git + https://github.com/prestodb/presto-pinot-driver + HEAD + + + + ${project.basedir} + + true + true + true + + 1.8.0-151 + 3.3.9 + + org.apache.pinot.\$internal + 0.1.0 + 2.11.2 + + + + + io.netty + netty + 3.10.6.Final + runtime + + + + io.netty + netty-all + 4.1.42.Final + + + + + org.apache.commons + commons-lang3 + 3.5 + + + + org.antlr + antlr4-runtime + + 4.6 + + + + org.apache.pinot + pinot-common + ${dep.pinot.version} + + + org.checkerframework + checker-compat-qual + + + org.slf4j + slf4j-api + + + jline + jline + + + org.slf4j + slf4j-log4j12 + + + commons-logging + commons-logging + + + org.antlr + antlr4-annotations + + + org.apache.kafka + kafka-clients + + + org.codehaus.jackson + jackson-mapper-asl + + + org.apache.kafka + kafka_2.10 + + + commons-beanutils + commons-beanutils-core + + + log4j + log4j + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-annotations + + + javax.validation + validation-api + + + javax.servlet + javax.servlet-api + + + org.glassfish.hk2.external + jakarta.inject + + + jakarta.ws.rs + jakarta.ws.rs-api + + + jakarta.annotation + jakarta.annotation-api + + + + + + org.apache.pinot + pinot-transport + ${dep.pinot.version} + + + org.checkerframework + checker-compat-qual + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + commons-logging + commons-logging + + + org.antlr + antlr4-annotations + + + org.apache.kafka + kafka-clients + + + org.apache.kafka + kafka_2.10 + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-annotations + + + javax.validation + validation-api + + + + + + org.apache.pinot + pinot-core + ${dep.pinot.version} + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + commons-logging + commons-logging + + + org.antlr + antlr4-annotations + + + it.unimi.dsi + fastutil + + + org.apache.kafka + kafka-clients + + + org.apache.kafka + kafka_2.10 + + + org.codehaus.jackson + jackson-mapper-asl + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-annotations + + + javax.validation + validation-api + + + + + + org.apache.thrift + libthrift + 0.12.0 + + + org.apache.commons + commons-lang3 + + + org.apache.httpcomponents + httpcore + + + org.apache.httpcomponents + httpclient + + + + + + com.yammer.metrics + metrics-core + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + jar + + + javadoc + + ** + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.4.3 + + + package + + shade + + + true + true + ${project.build.directory}/pom.xml + true + + + org.apache.pinot:* + com.google.guava:* + org.apache.commons:* + commons-*:* + org.apache.http:* + org.antlr:* + io.netty:* + org.apache.thrift:* + com.yammer.metrics:* + + + + + + org.apache.pinot.pql + ${shadeBase}.org.apache.pinot.pql + + + com.google + ${shadeBase}.com.google + + + org.antlr + ${shadeBase}.org.antlr + + + org.apache.commons + ${shadeBase}.org.apache.commons + + + org.apache.http + ${shadeBase}.org.apache.http + + + org.apache.pinot.transport + ${shadeBase}.org.apache.pinot.transport + + + org.apache.pinot.core + ${shadeBase}.org.apache.pinot.core + + + org.apache.thrift + ${shadeBase}.org.apache.thrift + + + io.netty + ${shadeBase}.io.netty + + + org.jboss + ${shadeBase}.org.jboss + + + com.yammer + ${shadeBase}.com.yammer + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + META-INF/maven/** + + + + + + + + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5 + + forked-path + false + true + false + clean install + true + @{project.version} + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.4 + + true + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.10 + + + default + process-test-classes + + analyze-only + analyze-duplicate + analyze-dep-mgt + + + + + org.apache.commons:commons-lang3:: + + org.antlr:antlr4-runtime:: + + + + + + + + + diff --git a/src/main/java/com/facebook/presto/pinot/PinotScatterGatherQueryClient.java b/src/main/java/com/facebook/presto/pinot/PinotScatterGatherQueryClient.java new file mode 100644 index 0000000..62494b9 --- /dev/null +++ b/src/main/java/com/facebook/presto/pinot/PinotScatterGatherQueryClient.java @@ -0,0 +1,363 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.facebook.presto.pinot; + +import com.yammer.metrics.core.MetricsRegistry; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.util.HashedWheelTimer; +import org.apache.pinot.common.metrics.BrokerMetrics; +import org.apache.pinot.common.request.BrokerRequest; +import org.apache.pinot.common.request.InstanceRequest; +import org.apache.pinot.common.response.ServerInstance; +import org.apache.pinot.common.utils.DataTable; +import org.apache.pinot.core.common.datatable.DataTableFactory; +import org.apache.pinot.pql.parsers.Pql2CompilationException; +import org.apache.pinot.pql.parsers.Pql2Compiler; +import org.apache.pinot.serde.SerDe; +import org.apache.pinot.transport.common.CompositeFuture; +import org.apache.pinot.transport.metrics.NettyClientMetrics; +import org.apache.pinot.transport.netty.PooledNettyClientResourceManager; +import org.apache.pinot.transport.pool.KeyedPool; +import org.apache.pinot.transport.pool.KeyedPoolImpl; +import org.apache.pinot.transport.scattergather.ScatterGather; +import org.apache.pinot.transport.scattergather.ScatterGatherImpl; +import org.apache.pinot.transport.scattergather.ScatterGatherRequest; +import org.apache.pinot.transport.scattergather.ScatterGatherStats; +import org.apache.thrift.protocol.TCompactProtocol; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.function.Function; + +import static java.lang.String.format; + +public class PinotScatterGatherQueryClient +{ + private static final Pql2Compiler REQUEST_COMPILER = new Pql2Compiler(); + private static final String PRESTO_HOST_PREFIX = "presto-pinot-master"; + private static final boolean DEFAULT_EMIT_TABLE_LEVEL_METRICS = true; + + private final String prestoHostId; + private final BrokerMetrics brokerMetrics; + private final ScatterGather scatterGatherer; + + public enum ErrorCode + { + PINOT_INSUFFICIENT_SERVER_RESPONSE(true), + PINOT_INVALID_PQL_GENERATED(false), + PINOT_UNCLASSIFIED_ERROR(false); + + private final boolean retriable; + + ErrorCode(boolean retriable) + { + this.retriable = retriable; + } + + public boolean isRetriable() + { + return retriable; + } + } + + public static class PinotException + extends RuntimeException + { + private final ErrorCode errorCode; + + public PinotException(ErrorCode errorCode, String message, Throwable t) + { + super(message, t); + this.errorCode = errorCode; + } + + public PinotException(ErrorCode errorCode, String message) + { + this(errorCode, message, null); + } + + public ErrorCode getErrorCode() + { + return errorCode; + } + } + + public static class Config + { + private final long idleTimeoutMillis; + private final int threadPoolSize; + private final int minConnectionsPerServer; + private final int maxBacklogPerServer; + private final int maxConnectionsPerServer; + + public Config(long idleTimeoutMillis, int threadPoolSize, int minConnectionsPerServer, int maxBacklogPerServer, int maxConnectionsPerServer) + { + this.idleTimeoutMillis = idleTimeoutMillis; + this.threadPoolSize = threadPoolSize; + this.minConnectionsPerServer = minConnectionsPerServer; + this.maxBacklogPerServer = maxBacklogPerServer; + this.maxConnectionsPerServer = maxConnectionsPerServer; + } + + public long getIdleTimeoutMillis() + { + return idleTimeoutMillis; + } + + public int getThreadPoolSize() + { + return threadPoolSize; + } + + public int getMinConnectionsPerServer() + { + return minConnectionsPerServer; + } + + public int getMaxBacklogPerServer() + { + return maxBacklogPerServer; + } + + public int getMaxConnectionsPerServer() + { + return maxConnectionsPerServer; + } + } + + public PinotScatterGatherQueryClient(Config pinotConfig) + { + prestoHostId = getDefaultPrestoId(); + + MetricsRegistry registry = new MetricsRegistry(); + brokerMetrics = new BrokerMetrics(registry, DEFAULT_EMIT_TABLE_LEVEL_METRICS); + brokerMetrics.initializeGlobalMeters(); + + final NettyClientMetrics clientMetrics = new NettyClientMetrics(registry, "presto_pinot_client_"); + + // Setup Netty Connection Pool + PooledNettyClientResourceManager resourceManager = new PooledNettyClientResourceManager(new NioEventLoopGroup(), new HashedWheelTimer(), clientMetrics); + ExecutorService requestSenderPool = Executors.newFixedThreadPool(pinotConfig.getThreadPoolSize()); + ScheduledThreadPoolExecutor poolTimeoutExecutor = new ScheduledThreadPoolExecutor(50); + KeyedPool connPool = new KeyedPoolImpl<>(pinotConfig.getMinConnectionsPerServer(), pinotConfig.getMaxConnectionsPerServer(), pinotConfig.getIdleTimeoutMillis(), + pinotConfig.getMaxBacklogPerServer(), resourceManager, poolTimeoutExecutor, requestSenderPool, registry); + resourceManager.setPool(connPool); + + // Setup ScatterGather + scatterGatherer = new ScatterGatherImpl(connPool, requestSenderPool); + } + + private static T doWithRetries(int retries, Function caller) + { + PinotException firstError = null; + for (int i = 0; i < retries; ++i) { + try { + return caller.apply(i); + } + catch (PinotException e) { + if (firstError == null) { + firstError = e; + } + if (!e.getErrorCode().isRetriable()) { + throw e; + } + } + } + throw firstError; + } + + private String getDefaultPrestoId() + { + String defaultBrokerId; + try { + defaultBrokerId = PRESTO_HOST_PREFIX + InetAddress.getLocalHost().getHostName(); + } + catch (UnknownHostException e) { + defaultBrokerId = PRESTO_HOST_PREFIX; + } + return defaultBrokerId; + } + + public Map queryPinotServerForDataTable(String pql, String serverHost, List segments, long connectionTimeoutInMillis, boolean ignoreEmptyResponses, int pinotRetryCount) + { + BrokerRequest brokerRequest; + try { + brokerRequest = REQUEST_COMPILER.compileToBrokerRequest(pql); + } + catch (Pql2CompilationException e) { + throw new PinotException(ErrorCode.PINOT_INVALID_PQL_GENERATED, format("Parsing error with on %s, Error = %s", serverHost, e.getMessage()), e); + } + + Map> routingTable = new HashMap<>(); + routingTable.put(serverHost, new ArrayList<>(segments)); + + // Unfortunately the retries will all hit the same server because the routing decision has already been made by the pinot broker + Map serverResponseMap = doWithRetries(pinotRetryCount, (requestId) -> { + ScatterGatherRequest scatterRequest = new ScatterGatherRequestWrapper(brokerRequest, routingTable, requestId, connectionTimeoutInMillis, prestoHostId); + + ScatterGatherStats scatterGatherStats = new ScatterGatherStats(); + CompositeFuture compositeFuture = routeScatterGather(scatterRequest, scatterGatherStats); + return gatherServerResponses(ignoreEmptyResponses, routingTable, compositeFuture, brokerRequest.getQuerySource().getTableName()); + }); + return deserializeServerResponses(serverResponseMap, brokerRequest.getQuerySource().getTableName()); + } + + private Map gatherServerResponses( + boolean ignoreEmptyResponses, + Map> routingTable, + CompositeFuture compositeFuture, + String tableNameWithType) + { + try { + Map serverResponseMap = compositeFuture.get(); + if (!ignoreEmptyResponses) { + if (serverResponseMap.size() != routingTable.size()) { + Map routingTableForLogging = new HashMap<>(); + routingTable.entrySet().forEach(entry -> { + String valueToPrint = entry.getValue().size() > 10 ? format("%d segments", entry.getValue().size()) : entry.getValue().toString(); + routingTableForLogging.put(entry.getKey(), valueToPrint); + }); + throw new PinotException(ErrorCode.PINOT_INSUFFICIENT_SERVER_RESPONSE, String.format("%d of %d servers responded with routing table servers: %s, error: %s", serverResponseMap.size(), routingTable.size(), routingTableForLogging, compositeFuture.getError())); + } + for (Map.Entry entry : serverResponseMap.entrySet()) { + if (entry.getValue().length == 0) { + throw new PinotException(ErrorCode.PINOT_INSUFFICIENT_SERVER_RESPONSE, String.format("Got empty response with from server: %s", entry.getKey().getShortHostName())); + } + } + } + return serverResponseMap; + } + catch (ExecutionException | InterruptedException e) { + Throwable err = e instanceof ExecutionException ? e.getCause() : e; + throw new PinotException(ErrorCode.PINOT_UNCLASSIFIED_ERROR, String.format("Caught exception while fetching responses for table: %s", tableNameWithType), err); + } + } + + /** + * Deserialize the server responses, put the de-serialized data table into the data table map passed in, append + * processing exceptions to the processing exception list passed in. + *

For hybrid use case, multiple responses might be from the same instance. Use response sequence to distinguish + * them. + * + * @param responseMap map from server to response. + * @param tableNameWithType table name with type suffix. + * @return dataTableMap map from server to data table. + */ + private Map deserializeServerResponses( + Map responseMap, + String tableNameWithType) + { + Map dataTableMap = new HashMap<>(); + for (Map.Entry entry : responseMap.entrySet()) { + ServerInstance serverInstance = entry.getKey(); + byte[] value = entry.getValue(); + if (value == null || value.length == 0) { + continue; + } + try { + dataTableMap.put(serverInstance, DataTableFactory.getDataTable(value)); + } + catch (IOException e) { + throw new PinotException(ErrorCode.PINOT_UNCLASSIFIED_ERROR, String.format("Caught exceptions while deserializing response for table: %s from server: %s", tableNameWithType, serverInstance), e); + } + } + return dataTableMap; + } + + private CompositeFuture routeScatterGather(ScatterGatherRequest scatterRequest, ScatterGatherStats scatterGatherStats) + { + try { + return this.scatterGatherer.scatterGather(scatterRequest, scatterGatherStats, true, brokerMetrics); + } + catch (InterruptedException e) { + throw new PinotException(ErrorCode.PINOT_UNCLASSIFIED_ERROR, format("Interrupted while sending request: %s", scatterRequest), e); + } + } + + private static class ScatterGatherRequestWrapper + implements ScatterGatherRequest + { + private final BrokerRequest brokerRequest; + private final Map> routingTable; + private final long requestId; + private final long requestTimeoutMs; + private final String brokerId; + + public ScatterGatherRequestWrapper(BrokerRequest request, Map> routingTable, long requestId, long requestTimeoutMs, String brokerId) + { + brokerRequest = request; + this.routingTable = routingTable; + this.requestId = requestId; + + this.requestTimeoutMs = requestTimeoutMs; + this.brokerId = brokerId; + } + + @Override + public Map> getRoutingTable() + { + return routingTable; + } + + @Override + public byte[] getRequestForService(List segments) + { + InstanceRequest request = new InstanceRequest(); + request.setRequestId(requestId); + request.setEnableTrace(brokerRequest.isEnableTrace()); + request.setQuery(brokerRequest); + request.setSearchSegments(segments); + request.setBrokerId(brokerId); + return new SerDe(new TCompactProtocol.Factory()).serialize(request); + } + + @Override + public long getRequestId() + { + return requestId; + } + + @Override + public long getRequestTimeoutMs() + { + return requestTimeoutMs; + } + + @Override + public BrokerRequest getBrokerRequest() + { + return brokerRequest; + } + + @Override + public String toString() + { + if (routingTable == null) { + return null; + } + + return Arrays.toString(routingTable.entrySet().toArray()); + } + } +}