Search in sources :

Example 31 with ScriptResult

use of org.ow2.proactive.scripting.ScriptResult in project scheduling by ow2-proactive.

the class ForkedProcessBuilderCreator method createForkedProcessBuilder.

/**
 * Creates a process builder for a given task context.
 *
 * @param context           The task context to execute.
 * @param serializedContext The task context saved to disk.
 * @param outputSink        Standard output sink.
 * @param errorSink         Error sink.
 * @param workingDir        The working directory to execute the process in.
 * @return Returns a process builder, ready to execute.
 * @throws Exception
 */
public OSProcessBuilder createForkedProcessBuilder(TaskContext context, File serializedContext, PrintStream outputSink, PrintStream errorSink, File workingDir) throws Exception {
    String nativeScriptPath = context.getSchedulerHome();
    OSProcessBuilder processBuilder = getOsProcessBuilder(context, workingDir, nativeScriptPath);
    ScriptResult forkEnvironmentScriptResult = executeForkEnvironmentScriptAndExtractVariables(context, outputSink, errorSink, processBuilder);
    processBuilder.command().addAll(forkedJvmTaskExecutionCommandCreator.createForkedJvmTaskExecutionCommand(context, forkEnvironmentScriptResult, serializedContext.getAbsolutePath()));
    processBuilder = processBuilder.directory(workingDir);
    return processBuilder;
}
Also used : ScriptResult(org.ow2.proactive.scripting.ScriptResult) OSProcessBuilder(org.objectweb.proactive.extensions.processbuilder.OSProcessBuilder)

Example 32 with ScriptResult

use of org.ow2.proactive.scripting.ScriptResult in project scheduling by ow2-proactive.

the class RMCore method executeScript.

/**
 * {@inheritDoc}
 */
public <T> List<ScriptResult<T>> executeScript(Script<T> script, String targetType, Set<String> targets) {
    // Depending on the target type, select nodes for script execution
    final TargetType tType = TargetType.valueOf(targetType);
    final HashSet<RMNode> selectedRMNodes = new HashSet<>();
    switch(tType) {
        case NODESOURCE_NAME:
            // If target is a nodesource name select all its nodes
            for (String target : targets) {
                NodeSource nodeSource = this.deployedNodeSources.get(target);
                if (nodeSource != null) {
                    for (RMNode candidateNode : this.allNodes.values()) {
                        if (candidateNode.getNodeSource().equals(nodeSource)) {
                            this.selectCandidateNode(selectedRMNodes, candidateNode);
                        }
                    }
                }
            }
            break;
        case NODE_URL:
            // If target is node url select the node
            for (String target : targets) {
                RMNode candidateNode = this.allNodes.get(target);
                if (candidateNode != null) {
                    this.selectCandidateNode(selectedRMNodes, candidateNode);
                }
            }
            break;
        case HOSTNAME:
            // If target is hostname select first node from that host
            for (String target : targets) {
                for (RMNode node : this.allNodes.values()) {
                    if (node.getHostName().equals(target)) {
                        this.selectCandidateNode(selectedRMNodes, node);
                        break;
                    }
                }
            }
            break;
        default:
            throw new IllegalArgumentException("Unable to execute script, unknown target type: " + targetType);
    }
    // Return a ProActive future on the list of results
    return this.selectionManager.executeScript(script, selectedRMNodes, null);
// To avoid blocking rmcore ao the call is delegated to the selection
// manager ao and each node is unlocked as soon as the script has
// finished it's execution.
}
Also used : NodeSource(org.ow2.proactive.resourcemanager.nodesource.NodeSource) RMNode(org.ow2.proactive.resourcemanager.rmnode.RMNode) TargetType(org.ow2.proactive.resourcemanager.utils.TargetType) HashSet(java.util.HashSet)

Example 33 with ScriptResult

use of org.ow2.proactive.scripting.ScriptResult in project scheduling by ow2-proactive.

the class Script method execute.

/**
 * Execute the script and return the ScriptResult corresponding.
 * This method can add an additional user bindings if needed.
 *
 * @param aBindings the additional user bindings to add if needed. Can be null or empty.
 * @param outputSink where the script output is printed to.
 * @param errorSink where the script error stream is printed to.
 * @return a ScriptResult object.
 */
public ScriptResult<E> execute(Map<String, Object> aBindings, PrintStream outputSink, PrintStream errorSink) {
    try {
        fetchUrlIfNeeded();
    } catch (Throwable t) {
        String stack = Throwables.getStackTraceAsString(t);
        if (t.getMessage() != null) {
            stack = t.getMessage() + System.lineSeparator() + stack;
        }
        return new ScriptResult<>(new Exception(stack));
    }
    ScriptEngine engine = createScriptEngine();
    if (engine == null)
        return new ScriptResult<>(new Exception("No Script Engine Found for name or extension " + scriptEngineLookupName));
    // SCHEDULING-1532: redirect script output to a buffer (keep the latest DEFAULT_OUTPUT_MAX_SIZE)
    BoundedStringWriter outputBoundedWriter = new BoundedStringWriter(outputSink, DEFAULT_OUTPUT_MAX_SIZE);
    BoundedStringWriter errorBoundedWriter = new BoundedStringWriter(errorSink, DEFAULT_OUTPUT_MAX_SIZE);
    engine.getContext().setWriter(new PrintWriter(outputBoundedWriter));
    engine.getContext().setErrorWriter(new PrintWriter(errorBoundedWriter));
    Reader closedInput = new Reader() {

        @Override
        public int read(char[] cbuf, int off, int len) throws IOException {
            throw new IOException("closed");
        }

        @Override
        public void close() throws IOException {
        }
    };
    engine.getContext().setReader(closedInput);
    engine.getContext().setAttribute(ScriptEngine.FILENAME, scriptName, ScriptContext.ENGINE_SCOPE);
    try {
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        // add additional bindings
        if (aBindings != null) {
            for (Entry<String, Object> e : aBindings.entrySet()) {
                bindings.put(e.getKey(), e.getValue());
            }
        }
        prepareBindings(bindings);
        Object evalResult = engine.eval(getReader());
        engine.getContext().getErrorWriter().flush();
        engine.getContext().getWriter().flush();
        // Add output to the script result
        ScriptResult<E> result = this.getResult(evalResult, bindings);
        result.setOutput(outputBoundedWriter.toString());
        return result;
    } catch (javax.script.ScriptException e) {
        // drop exception cause as it might not be serializable
        ScriptException scriptException = new ScriptException(e.getMessage());
        scriptException.setStackTrace(e.getStackTrace());
        return new ScriptResult<>(scriptException);
    } catch (Throwable t) {
        String stack = Throwables.getStackTraceAsString(t);
        if (t.getMessage() != null) {
            stack = t.getMessage() + System.lineSeparator() + stack;
        }
        return new ScriptResult<>(new Exception(stack));
    }
}
Also used : Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) Bindings(javax.script.Bindings) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ScriptEngine(javax.script.ScriptEngine) BoundedStringWriter(org.ow2.proactive.utils.BoundedStringWriter) PrintWriter(java.io.PrintWriter)

Example 34 with ScriptResult

use of org.ow2.proactive.scripting.ScriptResult in project scheduling by ow2-proactive.

the class RMProxyActiveObject method cleanCallBack.

/**
 * Called when a script has returned (call is made as an active object call)
 * <p>
 * Check the nodes to release and release the one that have to (clean script has returned)
 * Take care when renaming this method, method name is linked to
 * {@link #handleCleaningScript(NodeSet, Script, VariablesMap, Map, TaskId, Credentials)}
 */
@ImmediateService
public synchronized void cleanCallBack(Future<ScriptResult<?>> future, NodeSet nodes) {
    String nodeUrl = nodes.get(0).getNodeInformation().getURL();
    ScriptResult<?> sResult = null;
    TaskId taskId = nodesTaskId.get(nodes);
    try {
        sResult = future.get();
    } catch (Exception e) {
        logger.error("Exception occurred while executing cleaning script on node " + nodeUrl + ":", e);
    }
    printCleaningScriptInformations(nodes, sResult, taskId);
    releaseNodes(nodes);
}
Also used : TaskId(org.ow2.proactive.scheduler.common.task.TaskId) LoginException(javax.security.auth.login.LoginException) ImmediateService(org.objectweb.proactive.annotation.ImmediateService)

Aggregations

ScriptResult (org.ow2.proactive.scripting.ScriptResult)18 SelectionScript (org.ow2.proactive.scripting.SelectionScript)10 RMNode (org.ow2.proactive.resourcemanager.rmnode.RMNode)8 Test (org.junit.Test)7 SimpleScript (org.ow2.proactive.scripting.SimpleScript)7 SelectionManager (org.ow2.proactive.resourcemanager.selection.SelectionManager)6 SelectionManagerTest (org.ow2.proactive.resourcemanager.selection.SelectionManagerTest)6 File (java.io.File)5 Serializable (java.io.Serializable)4 InvalidScriptException (org.ow2.proactive.scripting.InvalidScriptException)4 ScriptHandler (org.ow2.proactive.scripting.ScriptHandler)4 IOException (java.io.IOException)3 PrintStream (java.io.PrintStream)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 LoginException (javax.security.auth.login.LoginException)2 ForkEnvironment (org.ow2.proactive.scheduler.common.task.ForkEnvironment)2 RemoteSpace (org.ow2.proactive.scheduler.common.task.dataspaces.RemoteSpace)2