Search in sources :

Example 26 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class ProcessManager method restoreFromCheckpoint.

public void restoreFromCheckpoint(ProcessKey processKey, UUID checkpointId) {
    ProcessEntry entry = queueDao.get(processKey);
    checkpointManager.assertProcessAccess(entry);
    if (checkpointId == null) {
        throw new ConcordApplicationException("'checkpointId' is mandatory");
    }
    if (entry.disabled()) {
        throw new ConcordApplicationException("Checkpoint can not be restored as process is disabled -> " + entry.instanceId());
    }
    ProcessStatus s = entry.status();
    if (!RESTORE_ALLOWED_STATUSES.contains(s)) {
        throw new ConcordApplicationException("Unable to restore a checkpoint, the process is " + s);
    }
    ProcessCheckpointManager.CheckpointInfo checkpointInfo = checkpointManager.restoreCheckpoint(processKey, checkpointId);
    if (checkpointInfo == null) {
        throw new ConcordApplicationException("Checkpoint " + checkpointId + " not found");
    }
    Payload payload;
    try {
        payload = payloadManager.createResumePayload(processKey, checkpointInfo.eventName(), null);
    } catch (IOException e) {
        log.error("restore ['{}', '{}'] -> error creating a payload: {}", processKey, checkpointInfo.name(), e);
        throw new ConcordApplicationException("Error creating a payload", e);
    }
    queueManager.restore(processKey, checkpointId, entry.status());
    logManager.info(processKey, "Restoring from checkpoint '{}'", checkpointInfo.name());
    resume(payload);
}
Also used : ProcessCheckpointManager(com.walmartlabs.concord.server.process.state.ProcessCheckpointManager) ProcessStatus(com.walmartlabs.concord.server.sdk.ProcessStatus) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) IOException(java.io.IOException)

Example 27 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class ProcessResource method waitForCompletion.

/**
 * Waits for completion of a process.
 *
 * @param instanceId
 * @param timeout
 * @return
 */
@GET
@ApiOperation("Wait for a process to finish")
@Produces(MediaType.APPLICATION_JSON)
@javax.ws.rs.Path("/{id}/waitForCompletion")
public ProcessEntry waitForCompletion(@ApiParam @PathParam("id") UUID instanceId, @ApiParam @QueryParam("timeout") @DefaultValue("-1") long timeout) {
    log.info("waitForCompletion ['{}', {}] -> waiting...", instanceId, timeout);
    long t1 = System.currentTimeMillis();
    ProcessEntry r;
    while (true) {
        r = get(instanceId);
        ProcessStatus s = r.status();
        if (s == ProcessStatus.FINISHED || s == ProcessStatus.FAILED || s == ProcessStatus.CANCELLED || s == ProcessStatus.TIMED_OUT) {
            return r;
        }
        if (timeout > 0) {
            long t2 = System.currentTimeMillis();
            if (t2 - t1 >= timeout) {
                log.warn("waitForCompletion ['{}', {}] -> timeout, last status: {}", instanceId, timeout, s);
                throw new ConcordApplicationException(Response.status(Status.REQUEST_TIMEOUT).entity(r).build());
            }
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // NOSONAR
            throw new ConcordApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request was interrputed").build());
        }
    }
}
Also used : ProcessStatus(com.walmartlabs.concord.server.sdk.ProcessStatus) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 28 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class ProcessResource method uploadAttachments.

/**
 * Upload process attachments.
 *
 * @param instanceId
 * @param data
 */
@POST
@javax.ws.rs.Path("{id}/attachment")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public void uploadAttachments(@PathParam("id") UUID instanceId, InputStream data) {
    ProcessEntry entry = assertProcess(PartialProcessKey.from(instanceId));
    ProcessKey processKey = new ProcessKey(entry.instanceId(), entry.createdAt());
    Path tmpIn = null;
    Path tmpDir = null;
    try {
        tmpIn = IOUtils.createTempFile("attachments", ".zip");
        Files.copy(data, tmpIn, StandardCopyOption.REPLACE_EXISTING);
        tmpDir = IOUtils.createTempDir("attachments");
        IOUtils.unzip(tmpIn, tmpDir);
        assertAttachmentsPolicy(tmpDir, entry);
        Path finalTmpDir = tmpDir;
        stateManager.tx(tx -> {
            stateManager.deleteDirectory(tx, processKey, path(Constants.Files.JOB_ATTACHMENTS_DIR_NAME, Constants.Files.JOB_STATE_DIR_NAME));
            stateManager.importPath(tx, processKey, Constants.Files.JOB_ATTACHMENTS_DIR_NAME, finalTmpDir, (p, attrs) -> true);
        });
        Map<String, Object> out = OutVariablesUtils.read(tmpDir);
        if (out.isEmpty()) {
            queueDao.removeMeta(processKey, "out");
        } else {
            queueDao.updateMeta(processKey, Collections.singletonMap("out", out));
        }
    } catch (PolicyException e) {
        throw new ConcordApplicationException(e.getMessage(), Status.FORBIDDEN);
    } catch (IOException e) {
        log.error("uploadAttachments ['{}'] -> error", processKey, e);
        throw new ConcordApplicationException("upload error: " + e.getMessage());
    } finally {
        if (tmpDir != null) {
            try {
                IOUtils.deleteRecursively(tmpDir);
            } catch (IOException e) {
                log.warn("uploadAttachments -> cleanup error: {}", e.getMessage());
            }
        }
        if (tmpIn != null) {
            try {
                Files.delete(tmpIn);
            } catch (IOException e) {
                log.warn("uploadAttachments -> cleanup error: {}", e.getMessage());
            }
        }
    }
}
Also used : Path(java.nio.file.Path) PolicyException(com.walmartlabs.concord.server.policy.PolicyException) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) PartialProcessKey(com.walmartlabs.concord.server.sdk.PartialProcessKey) ProcessKey(com.walmartlabs.concord.server.sdk.ProcessKey)

Example 29 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class ProcessResource method get.

/**
 * Returns a process instance details.
 *
 * @deprecated use {@link ProcessResourceV2#get(UUID, Set)}
 */
@GET
@ApiOperation("Get a process' details")
@javax.ws.rs.Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@WithTimer
@Deprecated
public ProcessEntry get(@ApiParam @PathParam("id") UUID instanceId) {
    PartialProcessKey processKey = PartialProcessKey.from(instanceId);
    ProcessEntry e = processQueueManager.get(processKey);
    if (e == null) {
        log.warn("get ['{}'] -> not found", instanceId);
        throw new ConcordApplicationException("Process instance not found", Status.NOT_FOUND);
    }
    return e;
}
Also used : PartialProcessKey(com.walmartlabs.concord.server.sdk.PartialProcessKey) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) WithTimer(com.walmartlabs.concord.server.sdk.metrics.WithTimer) ApiOperation(io.swagger.annotations.ApiOperation)

Example 30 with ConcordApplicationException

use of com.walmartlabs.concord.server.sdk.ConcordApplicationException in project concord by walmartlabs.

the class TriggerResource method refresh.

private void refresh(RepositoryEntry repo) {
    ProcessDefinition pd;
    try {
        pd = repositoryManager.withLock(repo.getUrl(), () -> {
            Repository repository = repositoryManager.fetch(repo.getProjectId(), repo);
            ProjectLoader.Result result = projectLoader.loadProject(repository.path(), importsNormalizerFactory.forProject(repo.getProjectId()), ImportsListener.NOP_LISTENER);
            return result.projectDefinition();
        });
        ProjectValidator.Result result = ProjectValidator.validate(pd);
        if (!result.isValid()) {
            throw new ValidationErrorsException(String.join("\n", result.getErrors()));
        }
    } catch (Exception e) {
        log.error("refresh ['{}'] -> project load error", repo.getId(), e);
        throw new ConcordApplicationException("Refresh failed (repository ID: " + repo.getId() + "): " + e.getMessage(), e);
    }
    triggerManager.refresh(repo.getProjectId(), repo.getId(), pd);
}
Also used : Repository(com.walmartlabs.concord.repository.Repository) RepositoryUtils.assertRepository(com.walmartlabs.concord.server.org.project.RepositoryUtils.assertRepository) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) ProcessDefinition(com.walmartlabs.concord.process.loader.model.ProcessDefinition) ValidationErrorsException(org.sonatype.siesta.ValidationErrorsException) UnauthorizedException(org.apache.shiro.authz.UnauthorizedException) ValidationErrorsException(org.sonatype.siesta.ValidationErrorsException) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException)

Aggregations

ConcordApplicationException (com.walmartlabs.concord.server.sdk.ConcordApplicationException)70 ApiOperation (io.swagger.annotations.ApiOperation)28 UUID (java.util.UUID)22 WithTimer (com.walmartlabs.concord.server.sdk.metrics.WithTimer)21 PartialProcessKey (com.walmartlabs.concord.server.sdk.PartialProcessKey)18 IOException (java.io.IOException)14 ValidationErrorsException (org.sonatype.siesta.ValidationErrorsException)12 GenericOperationResult (com.walmartlabs.concord.server.GenericOperationResult)11 ProcessKey (com.walmartlabs.concord.server.sdk.ProcessKey)11 Validate (org.sonatype.siesta.Validate)11 Path (java.nio.file.Path)10 UserPrincipal (com.walmartlabs.concord.server.security.UserPrincipal)9 OrganizationEntry (com.walmartlabs.concord.server.org.OrganizationEntry)8 EntryPoint (com.walmartlabs.concord.server.process.PayloadManager.EntryPoint)6 ProcessStatus (com.walmartlabs.concord.server.sdk.ProcessStatus)6 UnauthorizedException (org.apache.shiro.authz.UnauthorizedException)6 UserEntry (com.walmartlabs.concord.server.user.UserEntry)5 InputStream (java.io.InputStream)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Form (com.walmartlabs.concord.forms.Form)3