use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.
the class ShowMissingDiskStoresFunctionJUnitTest method setUp.
@Before
public void setUp() throws Exception {
cache = Fakes.cache();
system = (InternalDistributedSystem) cache.getDistributedSystem();
pr1 = mock(PartitionedRegion.class);
pr2 = mock(PartitionedRegion.class);
prRoot = mock(DistributedRegion.class);
pa = mock(PartitionAttributes.class);
prc = mock(PartitionRegionConfig.class);
cache = Fakes.cache();
oldCacheInstance = GemFireCacheImpl.setInstanceForTests(cache);
resultSender = new TestResultSender();
context = new FunctionContextImpl("testFunction", null, resultSender);
memberManager = mock(PersistentMemberManager.class);
}
use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.
the class ExecuteFunction66 method cmdExecute.
@Override
public void cmdExecute(Message clientMessage, ServerConnection servConn, long start) throws IOException {
Object function = null;
Object args = null;
MemberMappedArgument memberMappedArg = null;
String[] groups = null;
byte hasResult = 0;
byte functionState = 0;
boolean isReexecute = false;
boolean allMembers = false;
boolean ignoreFailedMembers = false;
int functionTimeout = ConnectionImpl.DEFAULT_CLIENT_FUNCTION_TIMEOUT;
try {
byte[] bytes = clientMessage.getPart(0).getSerializedForm();
functionState = bytes[0];
if (bytes.length >= 5 && servConn.getClientVersion().ordinal() >= Version.GFE_8009.ordinal()) {
functionTimeout = Part.decodeInt(bytes, 1);
}
if (functionState == AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE_REEXECUTE) {
functionState = AbstractExecution.HA_HASRESULT_NO_OPTIMIZEFORWRITE;
isReexecute = true;
} else if (functionState == AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE_REEXECUTE) {
functionState = AbstractExecution.HA_HASRESULT_OPTIMIZEFORWRITE;
isReexecute = true;
}
if (functionState != 1) {
hasResult = (byte) ((functionState & 2) - 1);
} else {
hasResult = functionState;
}
if (hasResult == 1) {
servConn.setAsTrue(REQUIRES_RESPONSE);
servConn.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
}
function = clientMessage.getPart(1).getStringOrObject();
args = clientMessage.getPart(2).getObject();
Part part = clientMessage.getPart(3);
if (part != null) {
memberMappedArg = (MemberMappedArgument) part.getObject();
}
groups = getGroups(clientMessage);
allMembers = getAllMembers(clientMessage);
ignoreFailedMembers = getIgnoreFailedMembers(clientMessage);
} catch (ClassNotFoundException exception) {
logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), exception);
if (hasResult == 1) {
writeChunkedException(clientMessage, exception, servConn);
} else {
writeException(clientMessage, exception, false, servConn);
}
servConn.setAsTrue(RESPONDED);
return;
}
if (function == null) {
final String message = LocalizedStrings.ExecuteFunction_THE_INPUT_FUNCTION_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL.toLocalizedString();
logger.warn(LocalizedMessage.create(LocalizedStrings.TWO_ARG_COLON, new Object[] { servConn.getName(), message }));
sendError(hasResult, clientMessage, message, servConn);
return;
}
// Execute function on the cache
try {
Function functionObject = null;
if (function instanceof String) {
functionObject = FunctionService.getFunction((String) function);
if (functionObject == null) {
final String message = LocalizedStrings.ExecuteFunction_FUNCTION_NAMED_0_IS_NOT_REGISTERED.toLocalizedString(function);
logger.warn("{}: {}", servConn.getName(), message);
sendError(hasResult, clientMessage, message, servConn);
return;
} else {
byte functionStateOnServerSide = AbstractExecution.getFunctionState(functionObject.isHA(), functionObject.hasResult(), functionObject.optimizeForWrite());
if (logger.isDebugEnabled()) {
logger.debug("Function State on server side: {} on client: {}", functionStateOnServerSide, functionState);
}
if (functionStateOnServerSide != functionState) {
String message = LocalizedStrings.FunctionService_FUNCTION_ATTRIBUTE_MISMATCH_CLIENT_SERVER.toLocalizedString(function);
logger.warn("{}: {}", servConn.getName(), message);
sendError(hasResult, clientMessage, message, servConn);
return;
}
}
} else {
functionObject = (Function) function;
}
FunctionStats stats = FunctionStats.getFunctionStats(functionObject.getId());
this.securityService.authorizeDataWrite();
// check if the caller is authorized to do this operation on server
AuthorizeRequest authzRequest = servConn.getAuthzRequest();
ExecuteFunctionOperationContext executeContext = null;
if (authzRequest != null) {
executeContext = authzRequest.executeFunctionAuthorize(functionObject.getId(), null, null, args, functionObject.optimizeForWrite());
}
ChunkedMessage m = servConn.getFunctionResponseMessage();
m.setTransactionId(clientMessage.getTransactionId());
ServerToClientFunctionResultSender resultSender = new ServerToClientFunctionResultSender65(m, MessageType.EXECUTE_FUNCTION_RESULT, servConn, functionObject, executeContext);
InternalDistributedMember localVM = (InternalDistributedMember) servConn.getCache().getDistributedSystem().getDistributedMember();
FunctionContext context = null;
if (memberMappedArg != null) {
context = new FunctionContextImpl(functionObject.getId(), memberMappedArg.getArgumentsForMember(localVM.getId()), resultSender, isReexecute);
} else {
context = new FunctionContextImpl(functionObject.getId(), args, resultSender, isReexecute);
}
HandShake handShake = (HandShake) servConn.getHandshake();
int earlierClientReadTimeout = handShake.getClientReadTimeout();
handShake.setClientReadTimeout(functionTimeout);
try {
if (logger.isDebugEnabled()) {
logger.debug("Executing Function on Server: {} with context: {}", servConn, context);
}
InternalCache cache = servConn.getCache();
HeapMemoryMonitor hmm = ((InternalResourceManager) cache.getResourceManager()).getHeapMonitor();
if (functionObject.optimizeForWrite() && cache != null && hmm.getState().isCritical() && !MemoryThresholds.isLowMemoryExceptionDisabled()) {
Set<DistributedMember> sm = Collections.singleton((DistributedMember) cache.getMyId());
Exception e = new LowMemoryException(LocalizedStrings.ResourceManager_LOW_MEMORY_FOR_0_FUNCEXEC_MEMBERS_1.toLocalizedString(new Object[] { functionObject.getId(), sm }), sm);
sendException(hasResult, clientMessage, e.getMessage(), servConn, e);
return;
}
/**
* if cache is null, then either cache has not yet been created on this node or it is a
* shutdown scenario.
*/
DM dm = null;
if (cache != null) {
dm = cache.getDistributionManager();
}
if (groups != null && groups.length > 0) {
executeFunctionOnGroups(function, args, groups, allMembers, functionObject, resultSender, ignoreFailedMembers);
} else {
executeFunctionaLocally(functionObject, context, (ServerToClientFunctionResultSender65) resultSender, dm, stats);
}
if (!functionObject.hasResult()) {
writeReply(clientMessage, servConn);
}
} catch (FunctionException functionException) {
stats.endFunctionExecutionWithException(functionObject.hasResult());
throw functionException;
} catch (Exception exception) {
stats.endFunctionExecutionWithException(functionObject.hasResult());
throw new FunctionException(exception);
} finally {
handShake.setClientReadTimeout(earlierClientReadTimeout);
}
} catch (IOException ioException) {
logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), ioException);
String message = LocalizedStrings.ExecuteFunction_SERVER_COULD_NOT_SEND_THE_REPLY.toLocalizedString();
sendException(hasResult, clientMessage, message, servConn, ioException);
} catch (InternalFunctionInvocationTargetException internalfunctionException) {
// 4> in case of HA member departed
if (logger.isDebugEnabled()) {
logger.debug(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, new Object[] { function }), internalfunctionException);
}
final String message = internalfunctionException.getMessage();
sendException(hasResult, clientMessage, message, servConn, internalfunctionException);
} catch (Exception e) {
logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), e);
final String message = e.getMessage();
sendException(hasResult, clientMessage, message, servConn, e);
}
}
use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.
the class ExecuteFunction method cmdExecute.
@Override
public void cmdExecute(Message clientMessage, ServerConnection servConn, long start) throws IOException {
Object function = null;
Object args = null;
MemberMappedArgument memberMappedArg = null;
byte hasResult = 0;
try {
hasResult = clientMessage.getPart(0).getSerializedForm()[0];
if (hasResult == 1) {
servConn.setAsTrue(REQUIRES_RESPONSE);
servConn.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
}
function = clientMessage.getPart(1).getStringOrObject();
args = clientMessage.getPart(2).getObject();
Part part = clientMessage.getPart(3);
if (part != null) {
memberMappedArg = (MemberMappedArgument) part.getObject();
}
} catch (ClassNotFoundException exception) {
logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), exception);
if (hasResult == 1) {
writeChunkedException(clientMessage, exception, servConn);
servConn.setAsTrue(RESPONDED);
return;
}
}
if (function == null) {
final String message = LocalizedStrings.ExecuteFunction_THE_INPUT_FUNCTION_FOR_THE_EXECUTE_FUNCTION_REQUEST_IS_NULL.toLocalizedString();
logger.warn("{}: {}", servConn.getName(), message);
sendError(hasResult, clientMessage, message, servConn);
return;
}
// Execute function on the cache
try {
Function functionObject = null;
if (function instanceof String) {
functionObject = FunctionService.getFunction((String) function);
if (functionObject == null) {
final String message = LocalizedStrings.ExecuteFunction_FUNCTION_NAMED_0_IS_NOT_REGISTERED.toLocalizedString(function);
logger.warn("{}: {}", servConn.getName(), message);
sendError(hasResult, clientMessage, message, servConn);
return;
}
} else {
functionObject = (Function) function;
}
FunctionStats stats = FunctionStats.getFunctionStats(functionObject.getId());
this.securityService.authorizeDataWrite();
// check if the caller is authorized to do this operation on server
AuthorizeRequest authzRequest = servConn.getAuthzRequest();
ExecuteFunctionOperationContext executeContext = null;
if (authzRequest != null) {
executeContext = authzRequest.executeFunctionAuthorize(functionObject.getId(), null, null, args, functionObject.optimizeForWrite());
}
ChunkedMessage m = servConn.getFunctionResponseMessage();
m.setTransactionId(clientMessage.getTransactionId());
ResultSender resultSender = new ServerToClientFunctionResultSender(m, MessageType.EXECUTE_FUNCTION_RESULT, servConn, functionObject, executeContext);
InternalDistributedMember localVM = (InternalDistributedMember) servConn.getCache().getDistributedSystem().getDistributedMember();
FunctionContext context = null;
if (memberMappedArg != null) {
context = new FunctionContextImpl(functionObject.getId(), memberMappedArg.getArgumentsForMember(localVM.getId()), resultSender);
} else {
context = new FunctionContextImpl(functionObject.getId(), args, resultSender);
}
HandShake handShake = (HandShake) servConn.getHandshake();
int earlierClientReadTimeout = handShake.getClientReadTimeout();
handShake.setClientReadTimeout(0);
try {
long startExecution = stats.startTime();
stats.startFunctionExecution(functionObject.hasResult());
if (logger.isDebugEnabled()) {
logger.debug("Executing Function on Server: " + servConn.toString() + "with context :" + context.toString());
}
InternalCache cache = servConn.getCache();
HeapMemoryMonitor hmm = ((InternalResourceManager) cache.getResourceManager()).getHeapMonitor();
if (functionObject.optimizeForWrite() && cache != null && hmm.getState().isCritical() && !MemoryThresholds.isLowMemoryExceptionDisabled()) {
Set<DistributedMember> sm = Collections.<DistributedMember>singleton(cache.getMyId());
throw new LowMemoryException(LocalizedStrings.ResourceManager_LOW_MEMORY_FOR_0_FUNCEXEC_MEMBERS_1.toLocalizedString(new Object[] { functionObject.getId(), sm }), sm);
}
functionObject.execute(context);
stats.endFunctionExecution(startExecution, functionObject.hasResult());
} catch (FunctionException functionException) {
stats.endFunctionExecutionWithException(functionObject.hasResult());
throw functionException;
} catch (Exception exception) {
stats.endFunctionExecutionWithException(functionObject.hasResult());
throw new FunctionException(exception);
} finally {
handShake.setClientReadTimeout(earlierClientReadTimeout);
}
} catch (IOException ioException) {
logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), ioException);
String message = LocalizedStrings.ExecuteFunction_SERVER_COULD_NOT_SEND_THE_REPLY.toLocalizedString();
sendException(hasResult, clientMessage, message, servConn, ioException);
} catch (InternalFunctionInvocationTargetException internalfunctionException) {
// 4> in case of HA member departed
if (logger.isDebugEnabled()) {
logger.debug(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, new Object[] { function }), internalfunctionException);
}
final String message = internalfunctionException.getMessage();
sendException(hasResult, clientMessage, message, servConn, internalfunctionException);
} catch (Exception e) {
logger.warn(LocalizedMessage.create(LocalizedStrings.ExecuteFunction_EXCEPTION_ON_SERVER_WHILE_EXECUTIONG_FUNCTION_0, function), e);
final String message = e.getMessage();
sendException(hasResult, clientMessage, message, servConn, e);
}
}
use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.
the class DeployedJarJUnitTest method testDependencyBetweenJars.
@Test
public void testDependencyBetweenJars() throws Exception {
final File parentJarFile = temporaryFolder.newFile("JarClassLoaderJUnitParent.jar");
final File usesJarFile = temporaryFolder.newFile("JarClassLoaderJUnitUses.jar");
// Write out a JAR files.
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("package jcljunit.parent;");
stringBuffer.append("public class JarClassLoaderJUnitParent {");
stringBuffer.append("public String getValueParent() {");
stringBuffer.append("return \"PARENT\";}}");
byte[] jarBytes = this.classBuilder.createJarFromClassContent("jcljunit/parent/JarClassLoaderJUnitParent", stringBuffer.toString());
writeJarBytesToFile(parentJarFile, jarBytes);
ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnitParent.jar", jarBytes);
stringBuffer = new StringBuffer();
stringBuffer.append("package jcljunit.uses;");
stringBuffer.append("public class JarClassLoaderJUnitUses {");
stringBuffer.append("public String getValueUses() {");
stringBuffer.append("return \"USES\";}}");
jarBytes = this.classBuilder.createJarFromClassContent("jcljunit/uses/JarClassLoaderJUnitUses", stringBuffer.toString());
writeJarBytesToFile(usesJarFile, jarBytes);
ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnitUses.jar", jarBytes);
stringBuffer = new StringBuffer();
stringBuffer.append("package jcljunit.function;");
stringBuffer.append("import jcljunit.parent.JarClassLoaderJUnitParent;");
stringBuffer.append("import jcljunit.uses.JarClassLoaderJUnitUses;");
stringBuffer.append("import org.apache.geode.cache.execute.Function;");
stringBuffer.append("import org.apache.geode.cache.execute.FunctionContext;");
stringBuffer.append("public class JarClassLoaderJUnitFunction extends JarClassLoaderJUnitParent implements Function {");
stringBuffer.append("private JarClassLoaderJUnitUses uses = new JarClassLoaderJUnitUses();");
stringBuffer.append("public boolean hasResult() {return true;}");
stringBuffer.append("public void execute(FunctionContext context) {context.getResultSender().lastResult(getValueParent() + \":\" + uses.getValueUses());}");
stringBuffer.append("public String getId() {return \"JarClassLoaderJUnitFunction\";}");
stringBuffer.append("public boolean optimizeForWrite() {return false;}");
stringBuffer.append("public boolean isHA() {return false;}}");
ClassBuilder functionClassBuilder = new ClassBuilder();
functionClassBuilder.addToClassPath(parentJarFile.getAbsolutePath());
functionClassBuilder.addToClassPath(usesJarFile.getAbsolutePath());
jarBytes = functionClassBuilder.createJarFromClassContent("jcljunit/function/JarClassLoaderJUnitFunction", stringBuffer.toString());
ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnitFunction.jar", jarBytes);
Function function = FunctionService.getFunction("JarClassLoaderJUnitFunction");
assertThat(function).isNotNull();
TestResultSender resultSender = new TestResultSender();
FunctionContext functionContext = new FunctionContextImpl(function.getId(), null, resultSender);
function.execute(functionContext);
assertThat((String) resultSender.getResults()).isEqualTo("PARENT:USES");
}
use of org.apache.geode.internal.cache.execute.FunctionContextImpl in project geode by apache.
the class DeployedJarJUnitTest method testFunctions.
@Test
public void testFunctions() throws Exception {
// Test creating a JAR file with a function
String functionString = "import java.util.Properties;" + "import org.apache.geode.cache.Declarable;" + "import org.apache.geode.cache.execute.Function;" + "import org.apache.geode.cache.execute.FunctionContext;" + "public class JarClassLoaderJUnitFunction implements Function {" + "public void init(Properties props) {}" + "public boolean hasResult() {return true;}" + "public void execute(FunctionContext context) {context.getResultSender().lastResult(\"GOODv1\");}" + "public String getId() {return \"JarClassLoaderJUnitFunction\";}" + "public boolean optimizeForWrite() {return false;}" + "public boolean isHA() {return false;}}";
byte[] jarBytes = this.classBuilder.createJarFromClassContent("JarClassLoaderJUnitFunction", functionString);
ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnit.jar", jarBytes);
Function function = FunctionService.getFunction("JarClassLoaderJUnitFunction");
assertThat(function).isNotNull();
TestResultSender resultSender = new TestResultSender();
FunctionContext functionContext = new FunctionContextImpl(function.getId(), null, resultSender);
function.execute(functionContext);
assertThat(resultSender.getResults()).isEqualTo("GOODv1");
// Test updating the function with a new JAR file
functionString = functionString.replace("v1", "v2");
jarBytes = this.classBuilder.createJarFromClassContent("JarClassLoaderJUnitFunction", functionString);
ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnit.jar", jarBytes);
function = FunctionService.getFunction("JarClassLoaderJUnitFunction");
assertThat(function).isNotNull();
resultSender = new TestResultSender();
functionContext = new FunctionContextImpl(function.getId(), null, resultSender);
function.execute(functionContext);
assertThat(resultSender.getResults()).isEqualTo("GOODv2");
// Test returning null for the Id
String functionNullIdString = functionString.replace("return \"JarClassLoaderJUnitFunction\"", "return null");
jarBytes = this.classBuilder.createJarFromClassContent("JarClassLoaderJUnitFunction", functionNullIdString);
ClassPathLoader.getLatest().getJarDeployer().deploy("JarClassLoaderJUnit.jar", jarBytes);
assertThat(FunctionService.getFunction("JarClassLoaderJUnitFunction")).isNull();
// Test removing the JAR
ClassPathLoader.getLatest().getJarDeployer().undeploy("JarClassLoaderJUnit.jar");
assertThat(FunctionService.getFunction("JarClassLoaderJUnitFunction")).isNull();
}
Aggregations