Skip to content

Commit

Permalink
Support Remote function execution
Browse files Browse the repository at this point in the history
  • Loading branch information
rongrong committed Sep 15, 2020
1 parent 3825bdb commit aaeff3f
Show file tree
Hide file tree
Showing 12 changed files with 323 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
package com.facebook.presto.functionNamespace;

import com.facebook.presto.common.CatalogSchemaName;
import com.facebook.presto.common.Page;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.function.QualifiedFunctionName;
import com.facebook.presto.common.type.TypeManager;
import com.facebook.presto.functionNamespace.execution.SqlFunctionExecutors;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.function.FunctionHandle;
Expand All @@ -30,6 +33,7 @@
import com.facebook.presto.spi.function.SqlFunctionId;
import com.facebook.presto.spi.function.SqlInvokedFunction;
import com.facebook.presto.spi.function.SqlInvokedScalarFunctionImplementation;
import com.facebook.presto.spi.function.ThriftScalarFunctionImplementation;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
Expand All @@ -38,13 +42,14 @@
import javax.annotation.concurrent.GuardedBy;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static com.facebook.presto.spi.StandardErrorCode.GENERIC_USER_ERROR;
import static com.facebook.presto.spi.function.FunctionImplementationType.SQL;
import static com.facebook.presto.spi.function.FunctionKind.SCALAR;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
Expand Down Expand Up @@ -175,6 +180,19 @@ public final ScalarFunctionImplementation getScalarFunctionImplementation(Functi
return implementationByHandle.getUnchecked((SqlFunctionHandle) functionHandle);
}

@Override
public CompletableFuture<Block> executeFunction(FunctionHandle functionHandle, Page input, List<Integer> channels, TypeManager typeManager)
{
checkArgument(functionHandle instanceof SqlFunctionHandle, format("Expect SqlFunctionHandle, got %s", functionHandle.getClass()));
FunctionMetadata functionMetadata = getFunctionMetadata(functionHandle);
return sqlFunctionExecutors.executeFunction(
getScalarFunctionImplementation(functionHandle),
input,
channels,
functionMetadata.getArgumentTypes().stream().map(typeManager::getType).collect(toImmutableList()),
typeManager.getType(functionMetadata.getReturnType()));
}

protected String getCatalogName()
{
return catalogName;
Expand Down Expand Up @@ -240,8 +258,18 @@ protected FunctionImplementationType getFunctionImplementationType(SqlInvokedFun
protected ScalarFunctionImplementation sqlInvokedFunctionToImplementation(SqlInvokedFunction function)
{
FunctionImplementationType implementationType = getFunctionImplementationType(function);
checkArgument(implementationType.equals(SQL));
return new SqlInvokedScalarFunctionImplementation(function.getBody());
switch (implementationType) {
case SQL:
return new SqlInvokedScalarFunctionImplementation(function.getBody());
case THRIFT:
checkArgument(function.getFunctionHandle().isPresent(), "Need functionHandle to get function implementation");
return new ThriftScalarFunctionImplementation(function.getFunctionHandle().get(), function.getRoutineCharacteristics().getLanguage());
case BUILTIN:
throw new IllegalStateException(
format("SqlInvokedFunction %s has BUILTIN implementation type but %s cannot manage BUILTIN functions", function.getSignature().getName(), this.getClass()));
default:
throw new IllegalStateException(format("Unknown function implementation type: %s", implementationType));
}
}

private Collection<SqlInvokedFunction> fetchFunctions(QualifiedFunctionName functionName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,23 @@
*/
package com.facebook.presto.functionNamespace.execution;

import com.facebook.presto.common.Page;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.functionNamespace.execution.thrift.ThriftSqlFunctionExecutor;
import com.facebook.presto.spi.function.FunctionImplementationType;
import com.facebook.presto.spi.function.RoutineCharacteristics.Language;
import com.facebook.presto.spi.function.ScalarFunctionImplementation;
import com.facebook.presto.spi.function.ThriftScalarFunctionImplementation;
import com.google.inject.Inject;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

public class SqlFunctionExecutors
Expand All @@ -44,4 +53,10 @@ public FunctionImplementationType getFunctionImplementationType(Language languag
{
return supportedLanguages.get(language);
}

public CompletableFuture<Block> executeFunction(ScalarFunctionImplementation functionImplementation, Page input, List<Integer> channels, List<Type> argumentTypes, Type returnType)
{
checkArgument(functionImplementation instanceof ThriftScalarFunctionImplementation, format("Only support ThriftScalarFunctionImplementation, got %s", functionImplementation.getClass()));
return thriftSqlFunctionExecutor.executeFunction((ThriftScalarFunctionImplementation) functionImplementation, input, channels, argumentTypes, returnType);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package com.facebook.presto.metadata;

import com.facebook.presto.common.CatalogSchemaName;
import com.facebook.presto.common.Page;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.block.BlockEncodingSerde;
import com.facebook.presto.common.block.BlockSerdeUtil;
Expand Down Expand Up @@ -239,6 +240,7 @@
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

import static com.facebook.presto.common.function.OperatorType.tryGetOperatorType;
import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature;
Expand Down Expand Up @@ -849,6 +851,12 @@ else if (function instanceof SqlInvokedFunction) {
}
}

@Override
public final CompletableFuture<Block> executeFunction(FunctionHandle functionHandle, Page input, List<Integer> channels, TypeManager typeManager)
{
throw new IllegalStateException("Builtin function execution should be handled by the engine.");
}

public WindowFunctionSupplier getWindowFunctionImplementation(FunctionHandle functionHandle)
{
checkArgument(functionHandle instanceof BuiltInFunctionHandle, "Expect BuiltInFunctionHandle");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
import com.facebook.presto.Session;
import com.facebook.presto.SystemSessionProperties;
import com.facebook.presto.common.CatalogSchemaName;
import com.facebook.presto.common.Page;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.block.BlockEncodingSerde;
import com.facebook.presto.common.function.OperatorType;
import com.facebook.presto.common.function.QualifiedFunctionName;
Expand Down Expand Up @@ -68,6 +70,7 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

Expand Down Expand Up @@ -340,6 +343,13 @@ public ScalarFunctionImplementation getScalarFunctionImplementation(FunctionHand
return functionNamespaceManager.get().getScalarFunctionImplementation(functionHandle);
}

public CompletableFuture<Block> executeFunction(FunctionHandle functionHandle, Page inputPage, List<Integer> channels)
{
Optional<FunctionNamespaceManager<?>> functionNamespaceManager = getServingFunctionNamespaceManager(functionHandle.getFunctionNamespace());
checkState(functionNamespaceManager.isPresent(), format("FunctionHandle %s should have a serving function namespace", functionHandle));
return functionNamespaceManager.get().executeFunction(functionHandle, inputPage, channels, typeManager);
}

public WindowFunctionSupplier getWindowFunctionImplementation(FunctionHandle functionHandle)
{
return builtInFunctionNamespaceManager.getWindowFunctionImplementation(functionHandle);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
/*
* 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.operator;

import com.facebook.presto.common.Page;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.metadata.FunctionManager;
import com.facebook.presto.spi.plan.PlanNodeId;
import com.facebook.presto.spi.relation.CallExpression;
import com.facebook.presto.spi.relation.ConstantExpression;
import com.facebook.presto.spi.relation.InputReferenceExpression;
import com.facebook.presto.spi.relation.RowExpression;
import com.google.common.collect.ImmutableList;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.lang.String.format;
import static java.lang.Thread.currentThread;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.CompletableFuture.completedFuture;

public class RemoteProjectOperator
implements Operator
{
private final OperatorContext operatorContext;
private final FunctionManager functionManager;
private final List<RowExpression> projections;

private final CompletableFuture<Block>[] result;

private boolean finishing;

private RemoteProjectOperator(OperatorContext operatorContext, FunctionManager functionManager, List<RowExpression> projections)
{
this.operatorContext = requireNonNull(operatorContext, "operatorContext is null");
this.functionManager = requireNonNull(functionManager, "functionManager is null");
this.projections = ImmutableList.copyOf(requireNonNull(projections, "projections is null"));
this.result = new CompletableFuture[projections.size()];
}

@Override
public OperatorContext getOperatorContext()
{
return operatorContext;
}

@Override
public boolean needsInput()
{
return !finishing && !processingPage();
}

@Override
public void addInput(Page page)
{
checkState(!finishing, "Operator is already finishing");
checkState(!processingPage(), "Still processing previous input");
requireNonNull(page, "page is null");
for (int channel = 0; channel < projections.size(); channel++) {
RowExpression projection = projections.get(channel);
if (projection instanceof InputReferenceExpression) {
result[channel] = completedFuture(page.getBlock(((InputReferenceExpression) projection).getField()));
}
else if (projection instanceof CallExpression) {
CallExpression remoteCall = (CallExpression) projection;
result[channel] = functionManager.executeFunction(
remoteCall.getFunctionHandle(),
page,
remoteCall.getArguments().stream()
.map(InputReferenceExpression.class::cast)
.map(InputReferenceExpression::getField)
.collect(toImmutableList()));
}
else {
checkState(projection instanceof ConstantExpression, format("Does not expect expression type %s", projection.getClass()));
}
}
}

@Override
public Page getOutput()
{
if (resultReady()) {
Block[] blocks = new Block[result.length];
Page output;
try {
for (int i = 0; i < blocks.length; i++) {
blocks[i] = result[i].get();
}
output = new Page(blocks);
Arrays.fill(result, null);
return output;
}
catch (InterruptedException ie) {
currentThread().interrupt();
throw new RuntimeException(ie);
}
catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause != null) {
throwIfUnchecked(cause);
throw new RuntimeException(cause);
}
throw new RuntimeException(e);
}
}
return null;
}

@Override
public void finish()
{
finishing = true;
}

@Override
public boolean isFinished()
{
return finishing && !processingPage();
}

private boolean processingPage()
{
// Array result will be filled with nulls when getOutput() produce output.
// If result has non-null values that means input page is in processing.
for (int i = 0; i < result.length; i++) {
if (result[i] != null) {
return true;
}
}
return false;
}

private boolean resultReady()
{
for (int i = 0; i < result.length; i++) {
if (result[i] == null || !result[i].isDone()) {
return false;
}
}
return true;
}

public static class RemoteProjectOperatorFactory
implements OperatorFactory
{
private final int operatorId;
private final PlanNodeId planNodeId;
private final FunctionManager functionManager;
private final List<RowExpression> projections;
private boolean closed;

public RemoteProjectOperatorFactory(int operatorId, PlanNodeId planNodeId, FunctionManager functionManager, List<RowExpression> projections)
{
this.operatorId = operatorId;
this.planNodeId = requireNonNull(planNodeId, "planNodeId is null");
this.functionManager = requireNonNull(functionManager, "functionManager is null");
this.projections = ImmutableList.copyOf(requireNonNull(projections, "projections is null"));
}
@Override
public Operator createOperator(DriverContext driverContext)
{
checkState(!closed, "Factory is already closed");
OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, RemoteProjectOperator.class.getSimpleName());
return new RemoteProjectOperator(operatorContext, functionManager, projections);
}

@Override
public void noMoreOperators()
{
closed = true;
}

@Override
public OperatorFactory duplicate()
{
return new RemoteProjectOperatorFactory(operatorId, planNodeId, functionManager, projections);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -947,6 +947,9 @@ protected Object visitFunctionCall(FunctionCall node, Object context)
optimize);
result = functionInterpreter.visitor.process(function, context);
break;
case THRIFT:
// do not interpret remote functions on coordinator
return new FunctionCall(node.getName(), node.getWindow(), node.isDistinct(), node.isIgnoreNulls(), toExpressions(argumentValues, argumentTypes));
default:
throw new IllegalArgumentException(format("Unsupported function implementation type: %s", functionMetadata.getImplementationType()));
}
Expand Down
Loading

0 comments on commit aaeff3f

Please sign in to comment.