use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.
the class ProgramLifecycleHttpHandler method combineForUpdate.
private ProgramSchedule combineForUpdate(ScheduleDetail scheduleDetail, ProgramSchedule existing) throws BadRequestException {
String description = Objects.firstNonNull(scheduleDetail.getDescription(), existing.getDescription());
ProgramId programId = scheduleDetail.getProgram() == null ? existing.getProgramId() : existing.getProgramId().getParent().program(scheduleDetail.getProgram().getProgramType() == null ? existing.getProgramId().getType() : ProgramType.valueOfSchedulableType(scheduleDetail.getProgram().getProgramType()), Objects.firstNonNull(scheduleDetail.getProgram().getProgramName(), existing.getProgramId().getProgram()));
if (!programId.equals(existing.getProgramId())) {
throw new BadRequestException(String.format("Must update the schedule '%s' with the same program as '%s'. " + "To change the program in a schedule, please delete the schedule and create a new one.", existing.getName(), existing.getProgramId().toString()));
}
Map<String, String> properties = Objects.firstNonNull(scheduleDetail.getProperties(), existing.getProperties());
Trigger trigger = Objects.firstNonNull(scheduleDetail.getTrigger(), existing.getTrigger());
List<? extends Constraint> constraints = Objects.firstNonNull(scheduleDetail.getConstraints(), existing.getConstraints());
Long timeoutMillis = Objects.firstNonNull(scheduleDetail.getTimeoutMillis(), existing.getTimeoutMillis());
return new ProgramSchedule(existing.getName(), description, programId, properties, trigger, constraints, timeoutMillis);
}
use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.
the class RouteConfigHttpHandler method storeRouteConfig.
@PUT
@Path("/routeconfig")
@AuditPolicy(AuditDetail.REQUEST_BODY)
public void storeRouteConfig(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId, @PathParam("app-id") String appId, @PathParam("service-id") String serviceId) throws Exception {
NamespaceId namespace = new NamespaceId(namespaceId);
ProgramId programId = namespace.app(appId).service(serviceId);
Map<String, Integer> routes = parseBody(request, ROUTE_CONFIG_TYPE);
if (routes == null || routes.isEmpty()) {
throw new BadRequestException("Route config contains invalid format or empty content.");
}
List<ProgramId> nonExistingServices = new ArrayList<>();
for (String version : routes.keySet()) {
ProgramId routeProgram = namespace.app(appId, version).service(serviceId);
if (lifecycleService.getProgramSpecification(routeProgram) == null) {
nonExistingServices.add(routeProgram);
}
}
if (nonExistingServices.size() > 0) {
throw new BadRequestException("The following versions of the application/service could not be found : " + nonExistingServices);
}
RouteConfig routeConfig = new RouteConfig(routes);
if (!routeConfig.isValid()) {
throw new BadRequestException("Route Percentage needs to add up to 100.");
}
routeStore.store(programId, routeConfig);
responder.sendStatus(HttpResponseStatus.OK);
}
use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.
the class MonitorHandler method restartInstances.
private void restartInstances(HttpResponder responder, String serviceName, int instanceId, boolean restartAll) throws Exception {
long startTimeMs = System.currentTimeMillis();
boolean isSuccess = true;
if (!serviceManagementMap.containsKey(serviceName)) {
throw new NotFoundException(String.format("Invalid service name %s", serviceName));
}
MasterServiceManager masterServiceManager = serviceManagementMap.get(serviceName);
try {
if (!masterServiceManager.isServiceEnabled()) {
String message = String.format("Failed to restart instance for %s because the service is not enabled.", serviceName);
LOG.debug(message);
isSuccess = false;
throw new ForbiddenException(message);
}
if (restartAll) {
masterServiceManager.restartAllInstances();
} else {
if (instanceId < 0 || instanceId >= masterServiceManager.getInstances()) {
throw new IllegalArgumentException();
}
masterServiceManager.restartInstances(instanceId);
}
responder.sendStatus(HttpResponseStatus.OK);
} catch (IllegalStateException ise) {
String message = String.format("Failed to restart instance for %s because the service may not be ready yet", serviceName);
LOG.debug(message, ise);
isSuccess = false;
throw new ServiceUnavailableException(message);
} catch (IllegalArgumentException iex) {
String message = String.format("Failed to restart instance %d for service: %s because invalid instance id", instanceId, serviceName);
LOG.debug(message, iex);
isSuccess = false;
throw new BadRequestException(message);
} catch (Exception ex) {
LOG.warn(String.format("Exception when trying to restart instances for service %s", serviceName), ex);
isSuccess = false;
throw new Exception(String.format("Error restarting instance %d for service: %s", instanceId, serviceName));
} finally {
long endTimeMs = System.currentTimeMillis();
if (restartAll) {
serviceStore.setRestartAllInstancesRequest(serviceName, startTimeMs, endTimeMs, isSuccess);
} else {
serviceStore.setRestartInstanceRequest(serviceName, startTimeMs, endTimeMs, isSuccess, instanceId);
}
}
}
use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.
the class SecureStoreHandler method create.
@Path("/{key-name}")
@PUT
@AuditPolicy(AuditDetail.REQUEST_BODY)
public void create(HttpRequest httpRequest, HttpResponder httpResponder, @PathParam("namespace-id") String namespace, @PathParam("key-name") String name) throws Exception {
SecureKeyId secureKeyId = new SecureKeyId(namespace, name);
SecureKeyCreateRequest secureKeyCreateRequest = parseBody(httpRequest, SecureKeyCreateRequest.class);
if (secureKeyCreateRequest == null) {
SecureKeyCreateRequest dummy = new SecureKeyCreateRequest("<description>", "<data>", ImmutableMap.of("key", "value"));
throw new BadRequestException("Unable to parse the request. The request body should be of the following format." + " \n" + GSON.toJson(dummy));
}
secureStoreManager.putSecureData(namespace, name, secureKeyCreateRequest.getData(), secureKeyCreateRequest.getDescription(), secureKeyCreateRequest.getProperties());
httpResponder.sendStatus(HttpResponseStatus.OK);
}
use of co.cask.cdap.common.BadRequestException in project cdap by caskdata.
the class DefaultNamespaceAdmin method create.
/**
* Creates a new namespace
*
* @param metadata the {@link NamespaceMeta} for the new namespace to be created
* @throws NamespaceAlreadyExistsException if the specified namespace already exists
*/
@Override
@AuthEnforce(entities = "instanceId", enforceOn = InstanceId.class, actions = Action.ADMIN)
public synchronized void create(final NamespaceMeta metadata) throws Exception {
// TODO: CDAP-1427 - This should be transactional, but we don't support transactions on files yet
Preconditions.checkArgument(metadata != null, "Namespace metadata should not be null.");
NamespaceId namespace = metadata.getNamespaceId();
if (exists(namespace)) {
throw new NamespaceAlreadyExistsException(namespace);
}
// If this namespace has custom mapping then validate the given custom mapping
if (hasCustomMapping(metadata)) {
validateCustomMapping(metadata);
}
// check that the user has configured either both of none of the following configuration: principal and keytab URI
boolean hasValidKerberosConf = false;
if (metadata.getConfig() != null) {
String configuredPrincipal = metadata.getConfig().getPrincipal();
String configuredKeytabURI = metadata.getConfig().getKeytabURI();
if ((!Strings.isNullOrEmpty(configuredPrincipal) && Strings.isNullOrEmpty(configuredKeytabURI)) || (Strings.isNullOrEmpty(configuredPrincipal) && !Strings.isNullOrEmpty(configuredKeytabURI))) {
throw new BadRequestException(String.format("Either neither or both of the following two configurations must be configured. " + "Configured principal: %s, Configured keytabURI: %s", configuredPrincipal, configuredKeytabURI));
}
hasValidKerberosConf = true;
}
// check that if explore as principal is explicitly set to false then user has kerberos configuration
if (!metadata.getConfig().isExploreAsPrincipal() && !hasValidKerberosConf) {
throw new BadRequestException(String.format("No kerberos principal or keytab-uri was provided while '%s' was set to true.", NamespaceConfig.EXPLORE_AS_PRINCIPAL));
}
// Namespace can be created. Grant all the permissions to the user.
Principal principal = authenticationContext.getPrincipal();
privilegesManager.grant(namespace, principal, EnumSet.allOf(Action.class));
// Also grant the user who will execute programs in this namespace all privileges on the namespace
String executionUserName;
if (SecurityUtil.isKerberosEnabled(cConf) && !NamespaceId.SYSTEM.equals(namespace)) {
String namespacePrincipal = metadata.getConfig().getPrincipal();
if (Strings.isNullOrEmpty(namespacePrincipal)) {
executionUserName = new KerberosName(SecurityUtil.getMasterPrincipal(cConf)).getShortName();
} else {
executionUserName = new KerberosName(namespacePrincipal).getShortName();
}
} else {
executionUserName = UserGroupInformation.getCurrentUser().getShortUserName();
}
Principal executionUser = new Principal(executionUserName, Principal.PrincipalType.USER);
privilegesManager.grant(namespace, executionUser, EnumSet.allOf(Action.class));
// store the meta first in the namespace store because namespacedLocationFactory needs to look up location
// mapping from namespace config
nsStore.create(metadata);
try {
UserGroupInformation ugi;
if (NamespaceId.DEFAULT.equals(namespace)) {
ugi = UserGroupInformation.getCurrentUser();
} else {
ugi = impersonator.getUGI(namespace);
}
ImpersonationUtils.doAs(ugi, new Callable<Void>() {
@Override
public Void call() throws Exception {
storageProviderNamespaceAdmin.get().create(metadata);
return null;
}
});
} catch (Throwable t) {
// failed to create namespace in underlying storage so delete the namespace meta stored in the store earlier
deleteNamespaceMeta(metadata.getNamespaceId());
privilegesManager.revoke(namespace);
throw new NamespaceCannotBeCreatedException(namespace, t);
}
LOG.info("Namespace {} created with meta {}", metadata.getNamespaceId(), metadata);
}
Aggregations