Search in sources :

Example 1 with Client

use of org.ow2.proactive.resourcemanager.authentication.Client 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 Client

use of org.ow2.proactive.resourcemanager.authentication.Client in project scheduling by ow2-proactive.

the class SchedulerStateRest method valueOfTaskResultByTag.

/**
 * Returns the value of the task result for a set of tasks of the job
 * <code>jobId</code> filtered by a given tag. <strong>the result is
 * deserialized before sending to the client, if the class is not found the
 * content is replaced by the string 'Unknown value type' </strong>. To get
 * the serialized form of a given result, one has to call the following
 * restful service jobs/{jobid}/tasks/tag/{tasktag}/result/serializedvalue
 *
 * @param sessionId
 *            a valid session id
 * @param jobId
 *            the id of the job
 * @param taskTag
 *            the tag used to filter the tasks.
 * @return the value of the task result
 */
@Override
@GET
@GZIP
@Path("jobs/{jobid}/tasks/tag/{tasktag}/result/value")
@Produces("application/json")
public Map<String, String> valueOfTaskResultByTag(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("tasktag") String taskTag) throws Throwable {
    Scheduler s = checkAccess(sessionId, "jobs/" + jobId + "/tasks/tag/" + taskTag + "/result/value");
    List<TaskResult> taskResults = s.getTaskResultsByTag(jobId, taskTag);
    Map<String, String> result = new HashMap<String, String>(taskResults.size());
    for (TaskResult currentTaskResult : taskResults) {
        result.put(currentTaskResult.getTaskId().getReadableName(), getTaskResultValueAsStringOrExceptionStackTrace(currentTaskResult));
    }
    return result;
}
Also used : HashMap(java.util.HashMap) Scheduler(org.ow2.proactive.scheduler.common.Scheduler) TaskResult(org.ow2.proactive.scheduler.common.task.TaskResult) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) GZIP(org.jboss.resteasy.annotations.GZIP)

Example 3 with Client

use of org.ow2.proactive.resourcemanager.authentication.Client in project scheduling by ow2-proactive.

the class RMRestTest method callGetStatHistory.

private JSONObject callGetStatHistory() throws Exception {
    RMProxyUserInterface rmMock = mock(RMProxyUserInterface.class);
    String sessionId = SharedSessionStoreTestUtils.createValidSession(rmMock);
    AttributeList value = new AttributeList(Collections.singletonList(new Attribute("test", createRrdDb().getBytes())));
    when(rmMock.getMBeanAttributes(Matchers.<ObjectName>any(), Matchers.<String[]>any())).thenReturn(value);
    RMRestInterface client = ProxyFactory.create(RMRestInterface.class, "http://localhost:" + port + "/");
    String statHistory = client.getStatHistory(sessionId, "hhhhh");
    return (JSONObject) new JSONParser().parse(statHistory);
}
Also used : JSONObject(org.json.simple.JSONObject) Attribute(javax.management.Attribute) AttributeList(javax.management.AttributeList) RMProxyUserInterface(org.ow2.proactive.resourcemanager.common.util.RMProxyUserInterface) JSONParser(org.json.simple.parser.JSONParser) Matchers.anyString(org.mockito.Matchers.anyString)

Example 4 with Client

use of org.ow2.proactive.resourcemanager.authentication.Client in project scheduling by ow2-proactive.

the class RMCore method checkNodeAdminPermission.

/**
 * Checks if the client is the node admin.
 *
 * @param rmnode is a node to be checked
 * @param client is a client to be checked
 * @return true if the client is an admin, SecurityException otherwise
 */
private boolean checkNodeAdminPermission(RMNode rmnode, Client client) {
    NodeSource nodeSource = rmnode.getNodeSource();
    String errorMessage = client.getName() + " is not authorized to manage node " + rmnode.getNodeURL() + " from " + rmnode.getNodeSourceName();
    // a node provider
    try {
        // checking if the caller is an administrator
        client.checkPermission(nodeSource.getAdminPermission(), errorMessage);
    } catch (SecurityException ex) {
        // the caller is not an administrator, so checking if it is a node provider
        client.checkPermission(rmnode.getAdminPermission(), errorMessage);
    }
    return true;
}
Also used : NodeSource(org.ow2.proactive.resourcemanager.nodesource.NodeSource)

Example 5 with Client

use of org.ow2.proactive.resourcemanager.authentication.Client in project scheduling by ow2-proactive.

the class SchedulerRestClient method submit.

private JobIdData submit(String sessionId, InputStream job, MediaType mediaType, Map<String, String> variables, Map<String, String> genericInfos) throws NotConnectedRestException {
    String uriTmpl = restEndpointURL + addSlashIfMissing(restEndpointURL) + "scheduler/submit";
    ResteasyClient client = buildResteasyClient(providerFactory);
    ResteasyWebTarget target = client.target(uriTmpl);
    // Generic infos
    if (genericInfos != null) {
        for (String key : genericInfos.keySet()) {
            target = target.queryParamNoTemplate(key, genericInfos.get(key));
        }
    }
    // Multipart form
    MultipartFormDataOutput formData = new MultipartFormDataOutput();
    // Add job to multipart
    formData.addFormData(FILE_KEY, job, mediaType);
    // Add variables to multipart
    if (variables != null && variables.size() > 0) {
        formData.addFormData(VARIABLES_KEY, variables, MediaType.APPLICATION_JSON_TYPE);
    }
    // Multipart form entity
    GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(formData) {
    };
    Response response = target.request().header("sessionid", sessionId).post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE));
    if (response.getStatus() != HttpURLConnection.HTTP_OK) {
        if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new NotConnectedRestException("User not authenticated or session timeout.");
        } else {
            throwException(String.format("Job submission failed status code: %d", response.getStatus()), response);
        }
    }
    return response.readEntity(JobIdData.class);
}
Also used : ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) ResteasyWebTarget(org.jboss.resteasy.client.jaxrs.ResteasyWebTarget) NotConnectedRestException(org.ow2.proactive_grid_cloud_portal.scheduler.exception.NotConnectedRestException) MultipartFormDataOutput(org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput)

Aggregations

Test (org.junit.Test)69 ISchedulerClient (org.ow2.proactive.scheduler.rest.ISchedulerClient)36 Client (org.ow2.proactive.resourcemanager.authentication.Client)31 JobId (org.ow2.proactive.scheduler.common.job.JobId)30 TaskFlowJob (org.ow2.proactive.scheduler.common.job.TaskFlowJob)28 NonTerminatingJob (functionaltests.jobs.NonTerminatingJob)25 SimpleJob (functionaltests.jobs.SimpleJob)25 Job (org.ow2.proactive.scheduler.common.job.Job)25 ResteasyClient (org.jboss.resteasy.client.jaxrs.ResteasyClient)18 ResteasyWebTarget (org.jboss.resteasy.client.jaxrs.ResteasyWebTarget)18 ListFile (org.ow2.proactive_grid_cloud_portal.dataspace.dto.ListFile)18 File (java.io.File)17 RMNode (org.ow2.proactive.resourcemanager.rmnode.RMNode)13 TaskResult (org.ow2.proactive.scheduler.common.task.TaskResult)13 NotConnectedRestException (org.ow2.proactive_grid_cloud_portal.scheduler.exception.NotConnectedRestException)11 Node (org.objectweb.proactive.core.node.Node)9 IOException (java.io.IOException)8 NotConnectedException (org.ow2.proactive.scheduler.common.exception.NotConnectedException)8 JobInfo (org.ow2.proactive.scheduler.common.job.JobInfo)8 NodeSet (org.ow2.proactive.utils.NodeSet)7