Search in sources :

Example 76 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class OperationsDashboardHttpHandler method readDashboardDetail.

@GET
@Path("/dashboard")
public void readDashboardDetail(FullHttpRequest request, HttpResponder responder, @QueryParam("start") long startTimeSecs, @QueryParam("duration") int durationTimeSecs, @QueryParam("namespace") Set<String> namespaces) throws Exception {
    if (startTimeSecs < 0) {
        throw new BadRequestException("'start' time cannot be smaller than 0.");
    }
    if (durationTimeSecs < 0) {
        throw new BadRequestException("'duration' cannot be smaller than 0.");
    }
    if (namespaces.isEmpty()) {
        throw new BadRequestException("'namespace' cannot be empty, please provide at least one namespace.");
    }
    long endTimeSecs = startTimeSecs + durationTimeSecs;
    // Get current running timestamp.
    long currentTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    // Find tasks that have been running for up to 30 days before the start timestamp.
    // If there are updates for any of these programs in the selected window, we'll use the record from the window.
    Collection<RunRecordDetail> programsRunningAtStartTime = programHeartbeatService.findRunningAtTimestamp(startTimeSecs, namespaces);
    // end time is exclusive
    Collection<RunRecordDetail> programsInWindow = programHeartbeatService.scan(startTimeSecs, endTimeSecs + 1, namespaces);
    // Get all the ProgramRunId for records in the selected window.
    Set<ProgramRunId> inWindowRunIds = programsInWindow.stream().map(RunRecordDetail::getProgramRunId).collect(Collectors.toSet());
    // If there are records that were running before the start time, but have an update in the window, remove them
    // from the programs running result. This allows us to remove duplicate entries.
    programsRunningAtStartTime = programsRunningAtStartTime.stream().filter(rrd -> !inWindowRunIds.contains(rrd.getProgramRunId())).collect(Collectors.toList());
    // Initialize result set.
    Collection<RunRecordDetail> runRecordMetas = new ArrayList<>();
    // Add all programs running before the start time.
    runRecordMetas.addAll(programsRunningAtStartTime);
    // Add all programs in the window.
    runRecordMetas.addAll(programsInWindow);
    // Sort result by start time.
    runRecordMetas = runRecordMetas.stream().sorted(Comparator.comparingLong(RunRecordDetail::getStartTs)).collect(java.util.stream.Collectors.toList());
    List<DashboardProgramRunRecord> result = new ArrayList<>();
    for (RunRecordDetail runRecordMeta : runRecordMetas) {
        result.add(OperationsDashboardHttpHandler.runRecordToDashboardRecord(runRecordMeta));
    }
    Set<NamespaceId> namespaceIds = namespaces.stream().map(NamespaceId::new).collect(Collectors.toSet());
    // if the end time is in the future, also add scheduled program runs to the result
    // if start time in query is earlier than current time, use currentTime as start when querying future schedules
    long scheduleStartTimeSeconds = startTimeSecs > currentTimeInSeconds ? startTimeSecs : currentTimeInSeconds;
    if (endTimeSecs > currentTimeInSeconds) {
        // end time is exclusive
        result.addAll(getAllScheduledRuns(namespaceIds, scheduleStartTimeSeconds, endTimeSecs + 1));
    }
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(result));
}
Also used : RunRecordDetail(io.cdap.cdap.internal.app.store.RunRecordDetail) ArrayList(java.util.ArrayList) DashboardProgramRunRecord(io.cdap.cdap.proto.ops.DashboardProgramRunRecord) BadRequestException(io.cdap.cdap.common.BadRequestException) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 77 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class ProfileHttpHandler method writeProfile.

private void writeProfile(ProfileId profileId, FullHttpRequest request) throws BadRequestException, IOException, MethodNotAllowedException {
    ProfileCreateRequest profileCreateRequest;
    try (Reader reader = new InputStreamReader(new ByteBufInputStream(request.content()), StandardCharsets.UTF_8)) {
        profileCreateRequest = GSON.fromJson(reader, ProfileCreateRequest.class);
        validateProvisionerProperties(profileCreateRequest);
    } catch (JsonSyntaxException e) {
        throw new BadRequestException("Unable to parse request body. Please make sure it is valid JSON", e);
    }
    String totalProcessingCpusLabel = getTotalProcessingCpusLabel(profileCreateRequest.getProvisioner());
    profileCreateRequest.getProvisioner().setTotalProcessingCpusLabel(totalProcessingCpusLabel);
    Profile profile = new Profile(profileId.getProfile(), profileCreateRequest.getLabel(), profileCreateRequest.getDescription(), profileId.getScope(), profileCreateRequest.getProvisioner());
    profileService.saveProfile(profileId, profile);
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) InputStreamReader(java.io.InputStreamReader) ProfileCreateRequest(io.cdap.cdap.proto.profile.ProfileCreateRequest) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BadRequestException(io.cdap.cdap.common.BadRequestException) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) Profile(io.cdap.cdap.proto.profile.Profile)

Example 78 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class ProgramLifecycleHttpHandler method startPrograms.

/**
 * Starts all programs that are passed into the data. The data is an array of JSON objects
 * where each object must contain the following three elements: appId, programType, and programId
 * (flow name, service name, etc.). In additional, each object can contain an optional runtimeargs element,
 * which is a map of arguments to start the program with.
 * <p>
 * Example input:
 * <pre><code>
 * [{"appId": "App1", "programType": "Service", "programId": "Service1"},
 * {"appId": "App1", "programType": "Mapreduce", "programId": "MapReduce2", "runtimeargs":{"arg1":"val1"}}]
 * </code></pre>
 * </p><p>
 * The response will be an array of JsonObjects each of which will contain the three input parameters
 * as well as a "statusCode" field which maps to the status code for the data in that JsonObjects.
 * </p><p>
 * If an error occurs in the input (for the example above, App2 does not exist), then all JsonObjects for which the
 * parameters have a valid status will have the status field but all JsonObjects for which the parameters do not have
 * a valid status will have an error message and statusCode.
 * </p><p>
 * For example, if there is no App2 in the data above, then the response would be 200 OK with following possible data:
 * </p>
 * <pre><code>
 * [{"appId": "App1", "programType": "Service", "programId": "Service1", "statusCode": 200},
 * {"appId": "App2", "programType": "Mapreduce", "programId": "Mapreduce2",
 *  "statusCode":404, "error": "App: App2 not found"}]
 * </code></pre>
 */
@POST
@Path("/start")
@AuditPolicy({ AuditDetail.REQUEST_BODY, AuditDetail.RESPONSE_BODY })
public void startPrograms(FullHttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId) throws Exception {
    List<BatchProgramStart> programs = validateAndGetBatchInput(request, BATCH_STARTS_TYPE);
    List<BatchProgramResult> output = new ArrayList<>(programs.size());
    for (BatchProgramStart program : programs) {
        ProgramId programId = new ProgramId(namespaceId, program.getAppId(), program.getProgramType(), program.getProgramId());
        try {
            String runId = lifecycleService.run(programId, program.getRuntimeargs(), false).getId();
            output.add(new BatchProgramResult(program, HttpResponseStatus.OK.code(), null, runId));
        } catch (NotFoundException e) {
            output.add(new BatchProgramResult(program, HttpResponseStatus.NOT_FOUND.code(), e.getMessage()));
        } catch (BadRequestException e) {
            output.add(new BatchProgramResult(program, HttpResponseStatus.BAD_REQUEST.code(), e.getMessage()));
        } catch (ConflictException e) {
            output.add(new BatchProgramResult(program, HttpResponseStatus.CONFLICT.code(), e.getMessage()));
        }
    }
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(output));
}
Also used : ConflictException(io.cdap.cdap.common.ConflictException) BatchProgramResult(io.cdap.cdap.proto.BatchProgramResult) ArrayList(java.util.ArrayList) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) NotFoundException(io.cdap.cdap.common.NotFoundException) BadRequestException(io.cdap.cdap.common.BadRequestException) BatchProgramStart(io.cdap.cdap.proto.BatchProgramStart) ProgramId(io.cdap.cdap.proto.id.ProgramId) Path(javax.ws.rs.Path) AuditPolicy(io.cdap.cdap.common.security.AuditPolicy) POST(javax.ws.rs.POST)

Example 79 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class ProgramLifecycleHttpHandler method updateLogLevels.

private void updateLogLevels(FullHttpRequest request, HttpResponder responder, String namespace, String appName, String appVersion, String type, String programName, String runId) throws Exception {
    ProgramType programType = getProgramType(type);
    try {
        // we are decoding the body to Map<String, String> instead of Map<String, LogEntry.Level> here since Gson will
        // serialize invalid enum values to null, which is allowed for log level, instead of throw an Exception.
        lifecycleService.updateProgramLogLevels(new ApplicationId(namespace, appName, appVersion).program(programType, programName), transformLogLevelsMap(decodeArguments(request)), runId);
        responder.sendStatus(HttpResponseStatus.OK);
    } catch (JsonSyntaxException e) {
        throw new BadRequestException("Invalid JSON in body");
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    } catch (SecurityException e) {
        throw new UnauthorizedException("Unauthorized to update the log levels");
    }
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) BadRequestException(io.cdap.cdap.common.BadRequestException) ProgramType(io.cdap.cdap.proto.ProgramType) ApplicationId(io.cdap.cdap.proto.id.ApplicationId)

Example 80 with BadRequestException

use of io.cdap.cdap.common.BadRequestException in project cdap by cdapio.

the class AuthorizationHandler method revoke.

@Path("/privileges/revoke")
@POST
@AuditPolicy(AuditDetail.REQUEST_BODY)
public void revoke(FullHttpRequest httpRequest, HttpResponder httpResponder) throws FeatureDisabledException, BadRequestException, UnknownHostException, AccessException {
    ensureSecurityEnabled();
    RevokeRequest request = parseBody(httpRequest, RevokeRequest.class);
    if (request == null) {
        throw new BadRequestException("Missing request body");
    }
    if (request.getPrincipal() == null && request.getActions() == null && request.getPermissions() == null) {
        permissionManager.revoke(request.getAuthorizable());
    } else {
        permissionManager.revoke(request.getAuthorizable(), request.getPrincipal(), getRequestPermissions(request));
    }
    httpResponder.sendStatus(HttpResponseStatus.OK);
    createLogEntry(httpRequest, HttpResponseStatus.OK);
}
Also used : RevokeRequest(io.cdap.cdap.proto.security.RevokeRequest) BadRequestException(io.cdap.cdap.common.BadRequestException) Path(javax.ws.rs.Path) AuditPolicy(io.cdap.cdap.common.security.AuditPolicy) POST(javax.ws.rs.POST)

Aggregations

BadRequestException (io.cdap.cdap.common.BadRequestException)188 Path (javax.ws.rs.Path)68 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)54 IOException (java.io.IOException)46 JsonSyntaxException (com.google.gson.JsonSyntaxException)44 NotFoundException (io.cdap.cdap.common.NotFoundException)42 ApplicationId (io.cdap.cdap.proto.id.ApplicationId)42 POST (javax.ws.rs.POST)42 HttpResponse (io.cdap.common.http.HttpResponse)36 ByteBufInputStream (io.netty.buffer.ByteBufInputStream)34 URL (java.net.URL)34 ProgramType (io.cdap.cdap.proto.ProgramType)30 InputStreamReader (java.io.InputStreamReader)28 Reader (java.io.Reader)28 ArrayList (java.util.ArrayList)28 AuditPolicy (io.cdap.cdap.common.security.AuditPolicy)26 ProgramId (io.cdap.cdap.proto.id.ProgramId)26 ServiceUnavailableException (io.cdap.cdap.common.ServiceUnavailableException)24 GET (javax.ws.rs.GET)24 ProgramRunId (io.cdap.cdap.proto.id.ProgramRunId)22