Search in sources :

Example 16 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method doPerformAction.

private void doPerformAction(HttpRequest request, HttpResponder responder, String namespaceId, String appId, String appVersion, String type, String programId, String action) throws Exception {
    ApplicationId applicationId = new ApplicationId(namespaceId, appId, appVersion);
    if (SCHEDULES.equals(type)) {
        ScheduleId scheduleId = applicationId.schedule(programId);
        lifecycleService.suspendResumeSchedule(scheduleId, action);
        responder.sendJson(HttpResponseStatus.OK, "OK");
        return;
    }
    ProgramType programType;
    try {
        programType = ProgramType.valueOfCategoryName(type);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(String.format("Unknown program type '%s'", type), e);
    }
    ProgramId program = applicationId.program(programType, programId);
    Map<String, String> args = decodeArguments(request);
    // we have already validated that the action is valid
    switch(action.toLowerCase()) {
        case "start":
            lifecycleService.start(program, args, false);
            break;
        case "debug":
            if (!isDebugAllowed(programType)) {
                throw new NotImplementedException(String.format("debug action is not implemented for program type %s", programType));
            }
            lifecycleService.start(program, args, true);
            break;
        case "stop":
            lifecycleService.stop(program);
            break;
        default:
            throw new NotFoundException(String.format("%s action was not found", action));
    }
    responder.sendStatus(HttpResponseStatus.OK);
}
Also used : NotImplementedException(co.cask.cdap.common.NotImplementedException) BadRequestException(co.cask.cdap.common.BadRequestException) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) NotFoundException(co.cask.cdap.common.NotFoundException) ProgramType(co.cask.cdap.proto.ProgramType) ApplicationId(co.cask.cdap.proto.id.ApplicationId) ScheduleId(co.cask.cdap.proto.id.ScheduleId) ProgramId(co.cask.cdap.proto.id.ProgramId)

Example 17 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method readScheduleDetailBody.

private ScheduleDetail readScheduleDetailBody(HttpRequest request, String scheduleName, boolean isUpdate, Function<JsonElement, ScheduleDetail> toScheduleDetail) throws BadRequestException, IOException {
    // TODO: remove backward compatibility with ScheduleSpecification, use fromJson(ScheduleDetail.class)
    JsonElement json;
    try (Reader reader = new InputStreamReader(new ChannelBufferInputStream(request.getContent()), Charsets.UTF_8)) {
        // The schedule spec in the request body does not contain the program information
        json = GSON.fromJson(reader, JsonElement.class);
    } catch (IOException e) {
        throw new IOException("Error reading request body", e);
    } catch (JsonSyntaxException e) {
        throw new BadRequestException("Request body is invalid json: " + e.getMessage());
    }
    if (!json.isJsonObject()) {
        throw new BadRequestException("Expected a json object in the request body but received " + GSON.toJson(json));
    }
    ScheduleDetail scheduleDetail;
    if (((JsonObject) json).get("schedule") != null) {
        // field only exists in legacy ScheduleSpec/UpdateDetail
        try {
            scheduleDetail = toScheduleDetail.apply(json);
        } catch (JsonSyntaxException e) {
            throw new BadRequestException("Error parsing request body as a schedule " + (isUpdate ? "update details" : "specification") + " (in backward compatibility mode): " + e.getMessage());
        } catch (IllegalArgumentException e) {
            throw new BadRequestException(e);
        }
    } else {
        try {
            scheduleDetail = GSON.fromJson(json, ScheduleDetail.class);
        } catch (JsonSyntaxException e) {
            throw new BadRequestException("Error parsing request body as a schedule specification: " + e.getMessage());
        }
    }
    // If the schedule name is present in the request body, it should match the name in path params
    if (scheduleDetail.getName() != null && !scheduleName.equals(scheduleDetail.getName())) {
        throw new BadRequestException(String.format("Schedule name in the body of the request (%s) does not match the schedule name in the path parameter (%s)", scheduleDetail.getName(), scheduleName));
    }
    return scheduleDetail;
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) InputStreamReader(java.io.InputStreamReader) JsonElement(com.google.gson.JsonElement) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BadRequestException(co.cask.cdap.common.BadRequestException) ChannelBufferInputStream(org.jboss.netty.buffer.ChannelBufferInputStream) IOException(java.io.IOException) ScheduleDetail(co.cask.cdap.proto.ScheduleDetail)

Example 18 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method getStatus.

/**
   * Returns status of a type specified by the type{flows,workflows,mapreduce,spark,services,schedules}.
   */
@GET
@Path("/apps/{app-id}/versions/{version-id}/{program-type}/{program-id}/status")
public void getStatus(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId, @PathParam("app-id") String appId, @PathParam("version-id") String versionId, @PathParam("program-type") String type, @PathParam("program-id") String programId) throws Exception {
    ApplicationId applicationId = new ApplicationId(namespaceId, appId, versionId);
    if (SCHEDULES.equals(type)) {
        JsonObject json = new JsonObject();
        ScheduleId scheduleId = applicationId.schedule(programId);
        json.addProperty("status", lifecycleService.getScheduleStatus(scheduleId).toString());
        responder.sendJson(HttpResponseStatus.OK, json);
        return;
    }
    ProgramType programType;
    try {
        programType = ProgramType.valueOfCategoryName(type);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e);
    }
    ProgramId program = applicationId.program(programType, programId);
    ProgramStatus programStatus = lifecycleService.getProgramStatus(program);
    Map<String, String> status = ImmutableMap.of("status", programStatus.name());
    responder.sendJson(HttpResponseStatus.OK, status);
}
Also used : JsonObject(com.google.gson.JsonObject) BadRequestException(co.cask.cdap.common.BadRequestException) ProgramType(co.cask.cdap.proto.ProgramType) ApplicationId(co.cask.cdap.proto.id.ApplicationId) ScheduleId(co.cask.cdap.proto.id.ScheduleId) ProgramId(co.cask.cdap.proto.id.ProgramId) ProgramStatus(co.cask.cdap.proto.ProgramStatus) BatchProgramStatus(co.cask.cdap.proto.BatchProgramStatus) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 19 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class MonitorHandler method updateServiceLogLevels.

/**
   * Update log levels for this service.
   */
@Path("system/services/{service-name}/loglevels")
@PUT
public void updateServiceLogLevels(HttpRequest request, HttpResponder responder, @PathParam("service-name") String serviceName) throws Exception {
    if (!serviceManagementMap.containsKey(serviceName)) {
        throw new NotFoundException(String.format("Invalid service name %s", serviceName));
    }
    MasterServiceManager masterServiceManager = serviceManagementMap.get(serviceName);
    if (!masterServiceManager.isServiceEnabled()) {
        throw new ForbiddenException(String.format("Failed to update log levels for service %s " + "because the service is not enabled", serviceName));
    }
    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.
        masterServiceManager.updateServiceLogLevels(transformLogLevelsMap(decodeArguments(request)));
        responder.sendStatus(HttpResponseStatus.OK);
    } catch (IllegalStateException ise) {
        throw new ServiceUnavailableException(String.format("Failed to update log levels for service %s " + "because the service may not be ready yet", serviceName));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    } catch (JsonSyntaxException e) {
        throw new BadRequestException("Invalid Json in the body");
    }
}
Also used : ForbiddenException(co.cask.cdap.common.ForbiddenException) JsonSyntaxException(com.google.gson.JsonSyntaxException) MasterServiceManager(co.cask.cdap.common.twill.MasterServiceManager) NotFoundException(co.cask.cdap.common.NotFoundException) BadRequestException(co.cask.cdap.common.BadRequestException) ServiceUnavailableException(co.cask.cdap.common.ServiceUnavailableException) Path(javax.ws.rs.Path) PUT(javax.ws.rs.PUT)

Example 20 with BadRequestException

use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method doAddSchedule.

private void doAddSchedule(HttpRequest request, HttpResponder responder, String namespace, String appName, String appVersion, String scheduleName) throws Exception {
    final ApplicationId applicationId = new ApplicationId(namespace, appName, appVersion);
    ScheduleDetail scheduleFromRequest = readScheduleDetailBody(request, scheduleName, false, new Function<JsonElement, ScheduleDetail>() {

        @Override
        public ScheduleDetail apply(@Nullable JsonElement input) {
            ScheduleSpecification scheduleSpec = GSON.fromJson(input, ScheduleSpecification.class);
            return toScheduleDetail(applicationId, scheduleSpec);
        }
    });
    if (scheduleFromRequest.getProgram() == null) {
        throw new BadRequestException("No program was specified for the schedule");
    }
    if (scheduleFromRequest.getProgram().getProgramType() == null) {
        throw new BadRequestException("No program type was specified for the schedule");
    }
    if (scheduleFromRequest.getProgram().getProgramName() == null) {
        throw new BadRequestException("No program name was specified for the schedule");
    }
    if (scheduleFromRequest.getTrigger() == null) {
        throw new BadRequestException("No trigger was specified for the schedule");
    }
    ProgramType programType = ProgramType.valueOfSchedulableType(scheduleFromRequest.getProgram().getProgramType());
    String programName = scheduleFromRequest.getProgram().getProgramName();
    ProgramId programId = applicationId.program(programType, programName);
    if (lifecycleService.getProgramSpecification(programId) == null) {
        throw new NotFoundException(programId);
    }
    String description = Objects.firstNonNull(scheduleFromRequest.getDescription(), "");
    Map<String, String> properties = Objects.firstNonNull(scheduleFromRequest.getProperties(), EMPTY_PROPERTIES);
    List<? extends Constraint> constraints = Objects.firstNonNull(scheduleFromRequest.getConstraints(), NO_CONSTRAINTS);
    long timeoutMillis = Objects.firstNonNull(scheduleFromRequest.getTimeoutMillis(), Schedulers.JOB_QUEUE_TIMEOUT_MILLIS);
    ProgramSchedule schedule = new ProgramSchedule(scheduleName, description, programId, properties, scheduleFromRequest.getTrigger(), constraints, timeoutMillis);
    programScheduler.addSchedule(schedule);
    responder.sendStatus(HttpResponseStatus.OK);
}
Also used : NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) NotFoundException(co.cask.cdap.common.NotFoundException) ProgramId(co.cask.cdap.proto.id.ProgramId) ProgramSchedule(co.cask.cdap.internal.app.runtime.schedule.ProgramSchedule) JsonElement(com.google.gson.JsonElement) BadRequestException(co.cask.cdap.common.BadRequestException) ScheduleDetail(co.cask.cdap.proto.ScheduleDetail) ProgramType(co.cask.cdap.proto.ProgramType) ApplicationId(co.cask.cdap.proto.id.ApplicationId) ScheduleSpecification(co.cask.cdap.api.schedule.ScheduleSpecification)

Aggregations

BadRequestException (co.cask.cdap.common.BadRequestException)82 Path (javax.ws.rs.Path)29 NotFoundException (co.cask.cdap.common.NotFoundException)25 HttpResponse (co.cask.common.http.HttpResponse)17 JsonSyntaxException (com.google.gson.JsonSyntaxException)17 URL (java.net.URL)17 POST (javax.ws.rs.POST)17 NamespaceId (co.cask.cdap.proto.id.NamespaceId)16 IOException (java.io.IOException)15 ChannelBufferInputStream (org.jboss.netty.buffer.ChannelBufferInputStream)13 AuditPolicy (co.cask.cdap.common.security.AuditPolicy)12 HttpRequest (co.cask.common.http.HttpRequest)12 InputStreamReader (java.io.InputStreamReader)11 Reader (java.io.Reader)11 NamespaceNotFoundException (co.cask.cdap.common.NamespaceNotFoundException)9 ApplicationId (co.cask.cdap.proto.id.ApplicationId)8 ArtifactNotFoundException (co.cask.cdap.common.ArtifactNotFoundException)7 ProgramType (co.cask.cdap.proto.ProgramType)7 ProgramId (co.cask.cdap.proto.id.ProgramId)6 Test (org.junit.Test)6