Search in sources :

Example 46 with ConcordApplicationException

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

the class ProcessResource method downloadStateFile.

/**
 * Downloads a single file from the current state snapshot of a process.
 */
@GET
@ApiOperation(value = "Download a single file from a process state snapshot", response = File.class)
@javax.ws.rs.Path("/{id}/state/snapshot/{name:.*}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Validate
public Response downloadStateFile(@ApiParam @PathParam("id") UUID instanceId, @ApiParam @PathParam("name") @NotNull @Size(min = 1) String fileName) {
    ProcessEntry p = assertProcess(PartialProcessKey.from(instanceId));
    ProcessKey processKey = new ProcessKey(p.instanceId(), p.createdAt());
    assertProcessAccess(p, "state");
    StreamingOutput out = output -> {
        Path tmp = stateManager.get(processKey, fileName, ProcessResource::copyToTmp).orElseThrow(() -> new ConcordApplicationException("State file not found: " + fileName, Status.NOT_FOUND));
        try (InputStream in = Files.newInputStream(tmp)) {
            IOUtils.copy(in, output);
        } finally {
            Files.delete(tmp);
        }
    };
    return Response.ok(out).build();
}
Also used : ProcessWaitManager(com.walmartlabs.concord.server.process.waits.ProcessWaitManager) Resource(org.sonatype.siesta.Resource) Size(javax.validation.constraints.Size) ProcessLogAccessManager(com.walmartlabs.concord.server.process.logs.ProcessLogAccessManager) PolicyManager(com.walmartlabs.concord.server.policy.PolicyManager) LoggerFactory(org.slf4j.LoggerFactory) ProcessResult(com.walmartlabs.concord.server.process.ProcessManager.ProcessResult) ApiParam(io.swagger.annotations.ApiParam) MultipartInput(org.jboss.resteasy.plugins.providers.multipart.MultipartInput) ProcessKeyCache(com.walmartlabs.concord.server.process.queue.ProcessKeyCache) ApiOperation(io.swagger.annotations.ApiOperation) ProcessQueueDao(com.walmartlabs.concord.server.process.queue.ProcessQueueDao) WithTimer(com.walmartlabs.concord.server.sdk.metrics.WithTimer) ProcessWaitEntry(com.walmartlabs.concord.server.process.ProcessEntry.ProcessWaitEntry) Path(java.nio.file.Path) PartialProcessKey(com.walmartlabs.concord.server.sdk.PartialProcessKey) ProcessConfiguration(com.walmartlabs.concord.server.cfg.ProcessConfiguration) ProcessLogManager(com.walmartlabs.concord.server.process.logs.ProcessLogManager) IOUtils(com.walmartlabs.concord.common.IOUtils) EncryptedProjectValueManager(com.walmartlabs.concord.server.org.project.EncryptedProjectValueManager) ProcessStatus(com.walmartlabs.concord.server.sdk.ProcessStatus) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) SecretStoreConfiguration(com.walmartlabs.concord.server.cfg.SecretStoreConfiguration) UnauthorizedException(org.apache.shiro.authz.UnauthorizedException) javax.ws.rs(javax.ws.rs) ValidationErrorsException(org.sonatype.siesta.ValidationErrorsException) CheckResult(com.walmartlabs.concord.policyengine.CheckResult) HttpUtils(com.walmartlabs.concord.server.HttpUtils) java.util(java.util) AbstractWaitCondition(com.walmartlabs.concord.server.process.waits.AbstractWaitCondition) ProcessQueueManager(com.walmartlabs.concord.server.process.queue.ProcessQueueManager) AttachmentsRule(com.walmartlabs.concord.policyengine.AttachmentsRule) ProcessKey(com.walmartlabs.concord.server.sdk.ProcessKey) Singleton(javax.inject.Singleton) ConfigurationUtils(com.walmartlabs.concord.common.ConfigurationUtils) StandardCopyOption(java.nio.file.StandardCopyOption) MessageFormat(java.text.MessageFormat) ProcessStateManager.zipTo(com.walmartlabs.concord.server.process.state.ProcessStateManager.zipTo) Inject(javax.inject.Inject) MultipartUtils(com.walmartlabs.concord.server.MultipartUtils) ExpressionUtils(com.walmartlabs.concord.server.events.ExpressionUtils) EntryPoint(com.walmartlabs.concord.server.process.PayloadManager.EntryPoint) HttpServletRequest(javax.servlet.http.HttpServletRequest) Constants(com.walmartlabs.concord.sdk.Constants) PolicyEngine(com.walmartlabs.concord.policyengine.PolicyEngine) Imports(com.walmartlabs.concord.imports.Imports) OffsetDateTimeParam(com.walmartlabs.concord.server.OffsetDateTimeParam) Api(io.swagger.annotations.Api) ZipArchiveOutputStream(org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream) Named(javax.inject.Named) Status(javax.ws.rs.core.Response.Status) ProcessStatusHistoryEntry(com.walmartlabs.concord.server.process.ProcessEntry.ProcessStatusHistoryEntry) ProcessLog(com.walmartlabs.concord.server.process.logs.ProcessLogsDao.ProcessLog) Roles(com.walmartlabs.concord.server.security.Roles) UserPrincipal(com.walmartlabs.concord.server.security.UserPrincipal) ProcessStateManager(com.walmartlabs.concord.server.process.state.ProcessStateManager) Logger(org.slf4j.Logger) Files(java.nio.file.Files) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Validate(org.sonatype.siesta.Validate) PolicyException(com.walmartlabs.concord.server.policy.PolicyException) ProjectAccessManager(com.walmartlabs.concord.server.org.project.ProjectAccessManager) javax.ws.rs.core(javax.ws.rs.core) ProcessFilter(com.walmartlabs.concord.server.process.queue.ProcessFilter) OrganizationManager(com.walmartlabs.concord.server.org.OrganizationManager) java.io(java.io) ProcessStateManager.path(com.walmartlabs.concord.server.process.state.ProcessStateManager.path) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) ResourceAccessLevel(com.walmartlabs.concord.server.org.ResourceAccessLevel) Authorization(io.swagger.annotations.Authorization) Path(java.nio.file.Path) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) PartialProcessKey(com.walmartlabs.concord.server.sdk.PartialProcessKey) ProcessKey(com.walmartlabs.concord.server.sdk.ProcessKey) Validate(org.sonatype.siesta.Validate) ApiOperation(io.swagger.annotations.ApiOperation)

Example 47 with ConcordApplicationException

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

the class ProcessResource method resume.

/**
 * Resumes an existing process.
 */
@POST
@ApiOperation("Resume a process")
@javax.ws.rs.Path("/{id}/resume/{eventName}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@WithTimer
public ResumeProcessResponse resume(@ApiParam @PathParam("id") UUID instanceId, @ApiParam @PathParam("eventName") @NotNull String eventName, @ApiParam @QueryParam("saveAs") String saveAs, @ApiParam Map<String, Object> req) {
    PartialProcessKey processKey = PartialProcessKey.from(instanceId);
    if (saveAs != null && !saveAs.isEmpty() && req != null) {
        req = ConfigurationUtils.toNested(saveAs, req);
    }
    req = ExpressionUtils.escapeMap(req);
    Payload payload;
    try {
        payload = payloadManager.createResumePayload(processKey, eventName, req);
    } catch (IOException e) {
        log.error("resume ['{}', '{}'] -> error creating a payload: {}", instanceId, eventName, e);
        throw new ConcordApplicationException("Error creating a payload", e);
    }
    processManager.resume(payload);
    return new ResumeProcessResponse();
}
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 48 with ConcordApplicationException

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

the class ProcessResource method start.

/**
 * Starts a new process instance.
 *
 * @param in
 * @param parentInstanceId
 * @param sync
 * @return
 * @deprecated use {@link #start(MultipartInput, UUID, boolean, String[], HttpServletRequest)}
 */
@POST
@ApiOperation(value = "Start a new process instance using the supplied payload archive", hidden = true)
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_JSON)
@WithTimer(suffix = "_octetstream")
@Deprecated
public StartProcessResponse start(InputStream in, @QueryParam("parentId") UUID parentInstanceId, @Deprecated @DefaultValue("false") @QueryParam("sync") boolean sync, @QueryParam("out") String[] out) {
    if (sync) {
        throw syncIsForbidden();
    }
    assertPartialKey(parentInstanceId);
    PartialProcessKey processKey = PartialProcessKey.from(UUID.randomUUID());
    UserPrincipal userPrincipal = UserPrincipal.assertCurrent();
    Payload payload;
    try {
        payload = payloadManager.createPayload(processKey, parentInstanceId, userPrincipal.getId(), userPrincipal.getUsername(), in, out);
    } catch (IOException e) {
        log.error("start -> error creating a payload: {}", e.getMessage());
        throw new ConcordApplicationException("Error creating a payload", e);
    }
    return toResponse(processManager.start(payload));
}
Also used : PartialProcessKey(com.walmartlabs.concord.server.sdk.PartialProcessKey) ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) UserPrincipal(com.walmartlabs.concord.server.security.UserPrincipal) WithTimer(com.walmartlabs.concord.server.sdk.metrics.WithTimer) ApiOperation(io.swagger.annotations.ApiOperation)

Example 49 with ConcordApplicationException

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

the class ProcessResourceV2 method get.

/**
 * Returns a process instance's details.
 */
@GET
@ApiOperation("Get a process' details")
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@WithTimer
public ProcessEntry get(@ApiParam @PathParam("id") UUID instanceId, @ApiParam @QueryParam("include") Set<ProcessDataInclude> includes) {
    PartialProcessKey processKey = PartialProcessKey.from(instanceId);
    ProcessEntry e = processQueueManager.get(processKey, includes);
    if (e == null) {
        log.warn("get ['{}'] -> not found", instanceId);
        throw new ConcordApplicationException("Process instance not found", Status.NOT_FOUND);
    }
    if (e.projectId() != null) {
        projectAccessManager.assertAccess(e.orgId(), e.projectId(), null, ResourceAccessLevel.READER, false);
    }
    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 50 with ConcordApplicationException

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

the class ProcessResourceV2 method createProcessFilter.

private ProcessFilter createProcessFilter(UUID orgId, String orgName, UUID projectId, String projectName, UUID repoId, String repoName, OffsetDateTimeParam afterCreatedAt, OffsetDateTimeParam beforeCreatedAt, Set<String> tags, ProcessStatus processStatus, String initiator, UUID parentId, Set<ProcessDataInclude> processData, Integer limit, Integer offset, UriInfo uriInfo) {
    UUID effectiveOrgId = orgId;
    Set<UUID> orgIds = null;
    if (orgId != null) {
        // we got an org ID, use it as it is
        orgIds = Collections.singleton(effectiveOrgId);
    } else if (orgName != null) {
        // we got an org name, validate it first by resolving its ID
        OrganizationEntry org = orgManager.assertExisting(null, orgName);
        effectiveOrgId = org.getId();
        orgIds = Collections.singleton(effectiveOrgId);
    } else {
        // we got a query that is not limited to any specific org
        // let's check if we can return all processes from all orgs or if we should limit it to the user's orgs
        boolean canSeeAllOrgs = Roles.isAdmin() || Permission.isPermitted(Permission.GET_PROCESS_QUEUE_ALL_ORGS);
        if (!canSeeAllOrgs) {
            // non-admin users can only see their org's processes or processes w/o projects
            orgIds = getCurrentUserOrgIds();
        }
    }
    UUID effectiveProjectId = projectId;
    if (effectiveProjectId == null && projectName != null) {
        if (effectiveOrgId == null) {
            throw new ValidationErrorsException("Organization name or ID is required");
        }
        effectiveProjectId = projectDao.getId(effectiveOrgId, projectName);
        if (effectiveProjectId == null) {
            throw new ConcordApplicationException("Project not found: " + projectName, Response.Status.NOT_FOUND);
        }
    }
    if (effectiveProjectId != null) {
        projectAccessManager.assertAccess(effectiveProjectId, effectiveProjectId, null, ResourceAccessLevel.READER, false);
    } else if (effectiveOrgId != null) {
        orgManager.assertAccess(effectiveOrgId, null, false);
    } else {
    // we don't have to do the permissions check when neither the org or the project are specified
    // it is done implicitly by calling getCurrentUserOrgIds for all non-admin users (see above)
    }
    UUID effectiveRepoId = repoId;
    if (effectiveRepoId == null && repoName != null && effectiveProjectId != null) {
        effectiveRepoId = repositoryDao.getId(effectiveProjectId, repoName);
    }
    // collect all metadata filters, we assume that they have "meta." prefix in their query parameter names
    List<MetadataFilter> metaFilters = MetadataUtils.parseMetadataFilters(uriInfo);
    // can't allow seq scans, we don't index PROCESS_QUEUE.META (yet?)
    if (!metaFilters.isEmpty() && effectiveProjectId == null) {
        throw new ValidationErrorsException("Process metadata filters require a project name or an ID to be included in the query.");
    }
    return ProcessFilter.builder().parentId(parentId).projectId(effectiveProjectId).orgIds(orgIds).includeWithoutProject(effectiveOrgId == null && effectiveProjectId == null).afterCreatedAt(unwrap(afterCreatedAt)).beforeCreatedAt(unwrap(beforeCreatedAt)).repoId(effectiveRepoId).repoName(repoName).tags(tags).status(processStatus).initiator(initiator).metaFilters(metaFilters).requirements(FilterUtils.parseJson("requirements", uriInfo)).startAt(FilterUtils.parseDate("startAt", uriInfo)).includes(processData != null ? processData : Collections.emptySet()).limit(limit).offset(offset).build();
}
Also used : ConcordApplicationException(com.walmartlabs.concord.server.sdk.ConcordApplicationException) MetadataFilter(com.walmartlabs.concord.server.process.queue.ProcessFilter.MetadataFilter) UUID(java.util.UUID) OrganizationEntry(com.walmartlabs.concord.server.org.OrganizationEntry) ValidationErrorsException(org.sonatype.siesta.ValidationErrorsException)

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