Search in sources :

Example 1 with BooleanValue

use of org.ow2.authzforce.core.pdp.api.value.BooleanValue in project scheduling by ow2-proactive.

the class RMProxyActiveObject method handleCleaningScript.

/**
 * Execute the given script on the given node.
 * Also register a callback on {@link #cleanCallBack(Future, NodeSet)} method when script has returned.
 * @param nodes           the nodeset on which to start the script
 * @param cleaningScript the script to be executed
 * @param variables
 * @param genericInformation
 * @param taskId
 * @param creds credentials with CredData containing third party credentials
 */
private void handleCleaningScript(NodeSet nodes, Script<?> cleaningScript, VariablesMap variables, Map<String, String> genericInformation, TaskId taskId, Credentials creds) {
    TaskLogger instance = TaskLogger.getInstance();
    try {
        this.nodesTaskId.put(nodes, taskId);
        // create a decrypter to access scheduler and retrieve Third Party User Credentials
        String privateKeyPath = PASchedulerProperties.getAbsolutePath(PASchedulerProperties.SCHEDULER_AUTH_PRIVKEY_PATH.getValueAsString());
        Decrypter decrypter = new Decrypter(Credentials.getPrivateKey(privateKeyPath));
        decrypter.setCredentials(creds);
        HashMap<String, Serializable> dictionary = new HashMap<>();
        dictionary.putAll(variables.getScriptMap());
        dictionary.putAll(variables.getInheritedMap());
        dictionary.putAll(variables.getPropagatedVariables());
        dictionary.putAll(variables.getScopeMap());
        // start handler for binding
        ScriptHandler handler = ScriptLoader.createHandler(nodes.get(0));
        VariablesMap resolvedMap = new VariablesMap();
        resolvedMap.setInheritedMap(VariableSubstitutor.resolveVariables(variables.getInheritedMap(), dictionary));
        resolvedMap.setScopeMap(VariableSubstitutor.resolveVariables(variables.getScopeMap(), dictionary));
        handler.addBinding(SchedulerConstants.VARIABLES_BINDING_NAME, (Serializable) resolvedMap);
        handler.addBinding(SchedulerConstants.GENERIC_INFO_BINDING_NAME, (Serializable) genericInformation);
        // retrieve scheduler URL to bind with schedulerapi, globalspaceapi, and userspaceapi
        String schedulerUrl = PASchedulerProperties.SCHEDULER_REST_URL.getValueAsString();
        logger.debug("Binding schedulerapi...");
        SchedulerNodeClient client = new SchedulerNodeClient(decrypter, schedulerUrl);
        handler.addBinding(SchedulerConstants.SCHEDULER_CLIENT_BINDING_NAME, (Serializable) client);
        logger.debug("Binding globalspaceapi...");
        RemoteSpace globalSpaceClient = new DataSpaceNodeClient(client, IDataSpaceClient.Dataspace.GLOBAL, schedulerUrl);
        handler.addBinding(SchedulerConstants.DS_GLOBAL_API_BINDING_NAME, (Serializable) globalSpaceClient);
        logger.debug("Binding userspaceapi...");
        RemoteSpace userSpaceClient = new DataSpaceNodeClient(client, IDataSpaceClient.Dataspace.USER, schedulerUrl);
        handler.addBinding(SchedulerConstants.DS_USER_API_BINDING_NAME, (Serializable) userSpaceClient);
        logger.debug("Binding credentials...");
        Map<String, String> resolvedThirdPartyCredentials = VariableSubstitutor.filterAndUpdate(decrypter.decrypt().getThirdPartyCredentials(), dictionary);
        handler.addBinding(SchedulerConstants.CREDENTIALS_VARIABLE, (Serializable) resolvedThirdPartyCredentials);
        ScriptResult<?> future = handler.handle(cleaningScript);
        try {
            PAEventProgramming.addActionOnFuture(future, "cleanCallBack", nodes);
        } catch (IllegalArgumentException e) {
            // TODO - linked to PROACTIVE-936 -> IllegalArgumentException is raised if method name is unknown
            // should be replaced by checked exception
            instance.error(taskId, "ERROR : Callback method won't be executed, node won't be released. This is a critical state, check the callback method name", e);
        }
        instance.info(taskId, "Cleaning Script started on node " + nodes.get(0).getNodeInformation().getURL());
    } catch (Exception e) {
        // if active object cannot be created or script has failed
        instance.error(taskId, "Error while starting cleaning script for task " + taskId + " on " + nodes.get(0), e);
        releaseNodes(nodes).booleanValue();
    }
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SchedulerNodeClient(org.ow2.proactive.scheduler.task.client.SchedulerNodeClient) Decrypter(org.ow2.proactive.scheduler.task.utils.Decrypter) LoginException(javax.security.auth.login.LoginException) TaskLogger(org.ow2.proactive.scheduler.util.TaskLogger) RemoteSpace(org.ow2.proactive.scheduler.common.task.dataspaces.RemoteSpace) VariablesMap(org.ow2.proactive.scheduler.task.utils.VariablesMap) DataSpaceNodeClient(org.ow2.proactive.scheduler.task.client.DataSpaceNodeClient) ScriptHandler(org.ow2.proactive.scripting.ScriptHandler)

Example 2 with BooleanValue

use of org.ow2.authzforce.core.pdp.api.value.BooleanValue in project scheduling by ow2-proactive.

the class RMProxyActiveObject method handleCleaningScript.

/**
 * Execute the given script on the given node.
 * Also register a callback on {@link #cleanCallBack(Future, NodeSet)} method when script has returned.
 * @param nodes           the nodeset on which to start the script
 * @param cleaningScript the script to be executed
 * @param variables
 * @param genericInformation
 * @param taskId
 * @param creds credentials with CredData containing third party credentials
 */
private void handleCleaningScript(NodeSet nodes, Script<?> cleaningScript, VariablesMap variables, Map<String, String> genericInformation, TaskId taskId, Credentials creds, Synchronization store, SignalApi signalAPI) {
    TaskLogger instance = TaskLogger.getInstance();
    try {
        this.nodesTaskId.put(nodes, taskId);
        // create a decrypter to access scheduler and retrieve Third Party User Credentials
        String privateKeyPath = PASchedulerProperties.getAbsolutePath(PASchedulerProperties.SCHEDULER_AUTH_PRIVKEY_PATH.getValueAsString());
        Decrypter decrypter = new Decrypter(Credentials.getPrivateKey(privateKeyPath));
        decrypter.setCredentials(creds);
        Node node = nodes.get(0);
        String nodeUrl = node.getNodeInformation().getURL();
        String nodeName = node.getNodeInformation().getName();
        String hostName = node.getVMInformation().getHostName();
        HashMap<String, Serializable> dictionary = new HashMap<>();
        dictionary.putAll(variables.getScriptMap());
        dictionary.putAll(variables.getInheritedMap());
        dictionary.putAll(variables.getPropagatedVariables());
        dictionary.putAll(variables.getScopeMap());
        dictionary.put(SchedulerVars.PA_NODE_URL.toString(), nodeUrl);
        dictionary.put(SchedulerVars.PA_NODE_NAME.toString(), nodeName);
        dictionary.put(SchedulerVars.PA_NODE_HOST.toString(), hostName);
        // start handler for binding
        ScriptHandler handler = ScriptLoader.createHandler(node);
        VariablesMap resolvedMap = new VariablesMap();
        resolvedMap.setInheritedMap(VariableSubstitutor.resolveVariables(variables.getInheritedMap(), dictionary));
        resolvedMap.setScopeMap(VariableSubstitutor.resolveVariables(variables.getScopeMap(), dictionary));
        resolvedMap.put(SchedulerVars.PA_NODE_URL.toString(), nodeUrl);
        resolvedMap.put(SchedulerVars.PA_NODE_NAME.toString(), nodeName);
        resolvedMap.put(SchedulerVars.PA_NODE_HOST.toString(), hostName);
        handler.addBinding(SchedulerConstants.VARIABLES_BINDING_NAME, (Serializable) resolvedMap);
        handler.addBinding(SchedulerConstants.GENERIC_INFO_BINDING_NAME, (Serializable) genericInformation);
        handler.addBinding(SchedulerConstants.SYNCHRONIZATION_API_BINDING_NAME, store);
        handler.addBinding(SchedulerConstants.SIGNAL_API_BINDING_NAME, signalAPI);
        // retrieve scheduler URL to bind with schedulerapi, globalspaceapi, and userspaceapi
        String schedulerUrl = PASchedulerProperties.SCHEDULER_REST_URL.getValueAsString();
        logger.debug("Binding schedulerapi...");
        SchedulerNodeClient client = new SchedulerNodeClient(decrypter, schedulerUrl, taskId.getJobId(), Collections.emptyMap(), Collections.emptyMap());
        handler.addBinding(SchedulerConstants.SCHEDULER_CLIENT_BINDING_NAME, client);
        logger.debug("Binging rmapi...");
        RMNodeClient rmNodeClient = new RMNodeClient(decrypter.decrypt(), schedulerUrl);
        handler.addBinding(SchedulerConstants.RM_CLIENT_BINDING_NAME, rmNodeClient);
        logger.debug("Binding globalspaceapi...");
        RemoteSpace globalSpaceClient = new DataSpaceNodeClient(client, IDataSpaceClient.Dataspace.GLOBAL, schedulerUrl);
        handler.addBinding(SchedulerConstants.DS_GLOBAL_API_BINDING_NAME, (Serializable) globalSpaceClient);
        logger.debug("Binding userspaceapi...");
        RemoteSpace userSpaceClient = new DataSpaceNodeClient(client, IDataSpaceClient.Dataspace.USER, schedulerUrl);
        handler.addBinding(SchedulerConstants.DS_USER_API_BINDING_NAME, (Serializable) userSpaceClient);
        logger.debug("Binding credentials...");
        Map<String, String> resolvedThirdPartyCredentials = VariableSubstitutor.filterAndUpdate(decrypter.decrypt().getThirdPartyCredentials(), dictionary);
        handler.addBinding(SchedulerConstants.CREDENTIALS_VARIABLE, (Serializable) resolvedThirdPartyCredentials);
        ScriptResult<?> future = handler.handle(cleaningScript);
        try {
            PAEventProgramming.addActionOnFuture(future, "cleanCallBack", nodes);
        } catch (IllegalArgumentException e) {
            // TODO - linked to PROACTIVE-936 -> IllegalArgumentException is raised if method name is unknown
            // should be replaced by checked exception
            instance.error(taskId, "ERROR : Callback method won't be executed, node won't be released. This is a critical state, check the callback method name", e);
            instance.close(taskId);
        }
        instance.info(taskId, "Cleaning Script started on node " + nodes.get(0).getNodeInformation().getURL());
    } catch (Exception e) {
        // if active object cannot be created or script has failed
        instance.error(taskId, "Error while starting cleaning script for task " + taskId + " on " + nodes.get(0), e);
        instance.close(taskId);
        releaseNodes(nodes).booleanValue();
    }
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SchedulerNodeClient(org.ow2.proactive.scheduler.task.client.SchedulerNodeClient) Node(org.objectweb.proactive.core.node.Node) RMNodeClient(org.ow2.proactive.resourcemanager.task.client.RMNodeClient) Decrypter(org.ow2.proactive.scheduler.task.utils.Decrypter) LoginException(javax.security.auth.login.LoginException) TaskLogger(org.ow2.proactive.scheduler.util.TaskLogger) RemoteSpace(org.ow2.proactive.scheduler.common.task.dataspaces.RemoteSpace) VariablesMap(org.ow2.proactive.scheduler.task.utils.VariablesMap) DataSpaceNodeClient(org.ow2.proactive.scheduler.task.client.DataSpaceNodeClient) ScriptHandler(org.ow2.proactive.scripting.ScriptHandler)

Example 3 with BooleanValue

use of org.ow2.authzforce.core.pdp.api.value.BooleanValue in project core-pdp-api by authzforce.

the class RegexpMatchFunctionHelper method getCompiledRegexMatchCall.

/**
 * Creates regex-match function call using pre-compiled regex
 *
 * @param argExpressions
 *            input expressions
 * @param remainingArgTypes
 *            types of remaining arguments (after input expressions)
 * @return function call using compiled regex from first argument if constant value; or null if first argument is not constant
 */
public FirstOrderFunctionCall<BooleanValue> getCompiledRegexMatchCall(final List<Expression<?>> argExpressions, final Datatype<?>... remainingArgTypes) {
    // check if first arg = regex is constant value, in which case pre-compile the regex
    final RegularExpression compiledRegex;
    if (argExpressions.isEmpty()) {
        compiledRegex = null;
    } else {
        final Expression<?> input0 = argExpressions.get(0);
        /*
			 * if first arg is constant, pre-compile the regex
			 */
        final Optional<? extends Value> constant = input0.getValue();
        if (constant.isPresent()) {
            // actual constant
            final Value constantValue = constant.get();
            if (!(constantValue instanceof StringValue)) {
                throw new IllegalArgumentException(invalidRegexMsg + constant + "' (invalid datatype: " + input0.getReturnType() + "; expected: " + StandardDatatypes.STRING + ")");
            }
            final String regex = ((StringValue) constantValue).getUnderlyingValue();
            try {
                /*
					 * From Saxon xf:matches() implementation: Matches#evaluateItem() / evalMatches()
					 */
                compiledRegex = Version.platform.compileRegularExpression(XmlUtils.SAXON_PROCESSOR.getUnderlyingConfiguration(), regex, "", "XP20", null);
            } catch (final XPathException e) {
                throw new IllegalArgumentException(invalidRegexMsg + regex + "'", e);
            }
        } else {
            compiledRegex = null;
        }
    }
    if (compiledRegex == null) {
        return null;
    }
    /*
		 * Else compiledRegex != null, so we can optimize: make a new FunctionCall that reuses the compiled regex Although we could remove the first arg from argExpressions since it is already the
		 * compiledRegex, we still need to pass original argExpressions to any subclass of FirstOrderFunctionCall (like below) because it checks all arguments datatypes and so on first.
		 */
    return new CompiledRegexMatchFunctionCall(funcSig, argExpressions, remainingArgTypes, compiledRegex, matchedValueType, indeterminateArg1TypeMessage);
}
Also used : RegularExpression(net.sf.saxon.regex.RegularExpression) XPathException(net.sf.saxon.trans.XPathException) SimpleValue(org.ow2.authzforce.core.pdp.api.value.SimpleValue) AttributeValue(org.ow2.authzforce.core.pdp.api.value.AttributeValue) BooleanValue(org.ow2.authzforce.core.pdp.api.value.BooleanValue) StringValue(org.ow2.authzforce.core.pdp.api.value.StringValue) Value(org.ow2.authzforce.core.pdp.api.value.Value) StringValue(org.ow2.authzforce.core.pdp.api.value.StringValue)

Example 4 with BooleanValue

use of org.ow2.authzforce.core.pdp.api.value.BooleanValue in project core-pdp-api by authzforce.

the class ComparisonFunction method newCall.

@Override
public FirstOrderFunctionCall<BooleanValue> newCall(final List<Expression<?>> argExpressions, final Datatype<?>... remainingArgTypes) {
    return new EagerSinglePrimitiveTypeEval<>(functionSignature, argExpressions, remainingArgTypes) {

        @Override
        protected BooleanValue evaluate(final Deque<AV> args) throws IndeterminateEvaluationException {
            // Now that we have real values, perform the comparison operation
            final AV arg0 = args.poll();
            assert arg0 != null;
            final AV arg1 = args.poll();
            assert arg1 != null;
            final int comparResult;
            try {
                comparResult = arg0.compareTo(arg1);
            } catch (final IllegalArgumentException e) {
                // See BaseTimeValue#compareTo() for example of comparison throwing such exception
                throw new IndeterminateEvaluationException(illegalComparisonMsgPrefix + arg0.getContent() + ", " + arg1.getContent(), XacmlStatusCode.PROCESSING_ERROR.value(), e);
            }
            // Return the result as a BooleanAttributeValue.
            return BooleanValue.valueOf(postCondition.isTrue(comparResult));
        }
    };
}
Also used : IndeterminateEvaluationException(org.ow2.authzforce.core.pdp.api.IndeterminateEvaluationException) Deque(java.util.Deque) EagerSinglePrimitiveTypeEval(org.ow2.authzforce.core.pdp.api.func.BaseFirstOrderFunctionCall.EagerSinglePrimitiveTypeEval)

Example 5 with BooleanValue

use of org.ow2.authzforce.core.pdp.api.value.BooleanValue in project core by authzforce.

the class ConditionEvaluators method getInstance.

/**
 * Instantiates a Condition evaluator from XACML-Schema-derived <code>Condition</code>
 *
 * @param condition
 *            XACML-schema-derived JAXB Condition element
 * @param expressionFactory
 *            expression factory
 * @param xPathCompiler
 *            XPath compiler, defined if XPath support enabled (by PDP configuration and some enclosing Policy(Set) defines a XPathVersion according to XACML standard)
 * @return instance of Condition evaluator
 * @throws java.lang.IllegalArgumentException
 *             if the expression is not a valid boolean Expression
 */
public static BooleanEvaluator getInstance(final Condition condition, final ExpressionFactory expressionFactory, final Optional<XPathCompilerProxy> xPathCompiler) throws IllegalArgumentException {
    if (condition == null) {
        return TRUE_CONDITION;
    }
    /*
		 * condition != null -> condition's Expression is not null (by definition of XACML schema), therefore expressionFactory is needed
		 */
    final ExpressionType exprElt = condition.getExpression().getValue();
    if (expressionFactory == null) {
        throw NULL_EXPR_FACTORY_ARGUMENT_EXCEPTION;
    }
    final Expression<?> expr = expressionFactory.getInstance(exprElt, null, xPathCompiler);
    // make sure it's a boolean expression...
    if (!(expr.getReturnType().equals(StandardDatatypes.BOOLEAN))) {
        throw new IllegalArgumentException("Invalid return datatype (" + expr.getReturnType() + ") for Expression (" + expr.getClass().getSimpleName() + ") in Condition. Expected: Boolean.");
    }
    // WARNING: unchecked cast
    final Expression<BooleanValue> evaluableExpression = (Expression<BooleanValue>) expr;
    /*
		 * Check whether the expression is constant
		 */
    final Optional<BooleanValue> constant = evaluableExpression.getValue();
    if (constant.isPresent()) {
        if (constant.get().getUnderlyingValue()) {
            // constant TRUE
            LOGGER.warn("Condition's expression is equivalent to constant True -> optimization: replacing with constant True condition");
            return TRUE_CONDITION;
        }
        // constant False -> unacceptable
        throw INVALID_CONSTANT_FALSE_EXPRESSION_EXCEPTION;
    }
    // constant == null
    LOGGER.debug("Condition's Expression is not constant (evaluation without context failed)");
    return new BooleanExpressionEvaluator(evaluableExpression);
}
Also used : Expression(org.ow2.authzforce.core.pdp.api.expression.Expression) BooleanValue(org.ow2.authzforce.core.pdp.api.value.BooleanValue) ExpressionType(oasis.names.tc.xacml._3_0.core.schema.wd_17.ExpressionType)

Aggregations

Serializable (java.io.Serializable)2 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 LoginException (javax.security.auth.login.LoginException)2 BooleanValue (org.ow2.authzforce.core.pdp.api.value.BooleanValue)2 RemoteSpace (org.ow2.proactive.scheduler.common.task.dataspaces.RemoteSpace)2 DataSpaceNodeClient (org.ow2.proactive.scheduler.task.client.DataSpaceNodeClient)2 SchedulerNodeClient (org.ow2.proactive.scheduler.task.client.SchedulerNodeClient)2 Decrypter (org.ow2.proactive.scheduler.task.utils.Decrypter)2 VariablesMap (org.ow2.proactive.scheduler.task.utils.VariablesMap)2 TaskLogger (org.ow2.proactive.scheduler.util.TaskLogger)2 ScriptHandler (org.ow2.proactive.scripting.ScriptHandler)2 Date (java.util.Date)1 Deque (java.util.Deque)1 GregorianCalendar (java.util.GregorianCalendar)1 RegularExpression (net.sf.saxon.regex.RegularExpression)1 XPathException (net.sf.saxon.trans.XPathException)1 ExpressionType (oasis.names.tc.xacml._3_0.core.schema.wd_17.ExpressionType)1 ProcessDefinition (org.flowable.engine.repository.ProcessDefinition)1 ProcessDefinitionQuery (org.flowable.engine.repository.ProcessDefinitionQuery)1