use of io.cdap.cdap.common.NamespaceNotFoundException in project cdap by caskdata.
the class DefaultNamespaceCreatorTest method test.
// NOTE: can't actually delete the default namespace... so everything needs to be tested in a single test case
@Test
public void test() throws Exception {
try {
namespaceAdmin.get(NamespaceId.DEFAULT);
Assert.fail("Default namespace should not exist.");
} catch (NamespaceNotFoundException e) {
// expected
}
// test that it creates the default namespace
BootstrapStepResult result = defaultNamespaceCreator.execute("label", new JsonObject());
BootstrapStepResult expected = new BootstrapStepResult("label", BootstrapStepResult.Status.SUCCEEDED);
Assert.assertEquals(expected, result);
Assert.assertEquals(NamespaceMeta.DEFAULT, namespaceAdmin.get(NamespaceId.DEFAULT));
// test trying to create when it's already there won't error
result = defaultNamespaceCreator.execute("label", new JsonObject());
expected = new BootstrapStepResult("label", BootstrapStepResult.Status.SUCCEEDED);
Assert.assertEquals(expected, result);
Assert.assertEquals(NamespaceMeta.DEFAULT, namespaceAdmin.get(NamespaceId.DEFAULT));
}
use of io.cdap.cdap.common.NamespaceNotFoundException in project cdap by caskdata.
the class LocalApplicationDetailFetcher method list.
/**
* Get a list of {@link ApplicationDetail} for all applications in the given namespace
*
* @param namespace the name of the namespace to get the list of applications
* @return a list of {@link ApplicationDetail} for all applications in the given namespace
* @throws IOException if failed to get the list of {@link ApplicationDetail}
* @throws NamespaceNotFoundException if the given namespace doesn't exit
*/
@Override
public List<ApplicationDetail> list(String namespace) throws IOException, NamespaceNotFoundException {
NamespaceId namespaceId = new NamespaceId(namespace);
List<ApplicationDetail> detailList = Collections.emptyList();
try {
// the existence of the namespace. Does a check here to explicitly throw an exception if nonexistent.
if (!namespaceQueryAdmin.exists(namespaceId)) {
throw new NamespaceNotFoundException(namespaceId);
}
detailList = applicationLifecycleService.getApps(namespaceId);
} catch (Exception e) {
Throwables.propagateIfPossible(e, NamespaceNotFoundException.class, IOException.class);
throw new IOException(e);
}
return detailList;
}
use of io.cdap.cdap.common.NamespaceNotFoundException in project cdap by caskdata.
the class SecureStoreClient method createKey.
/**
* Creates a secure key
*
* @param secureKeyId {@link SecureKeyId} secure key name
* @param keyCreateRequest {@link SecureKeyCreateRequest}
* @throws IOException if a network error occurred
* @throws UnauthenticatedException if the request is not authorized successfully in the gateway server
* @throws SecureKeyAlreadyExistsException if the secure key already exists
* @throws NamespaceNotFoundException if namespace is not found
*/
public void createKey(SecureKeyId secureKeyId, SecureKeyCreateRequest keyCreateRequest) throws IOException, UnauthenticatedException, AlreadyExistsException, NamespaceNotFoundException, UnauthorizedException {
URL url = config.resolveNamespacedURLV3(secureKeyId.getParent(), getSecureKeyPath(secureKeyId));
HttpResponse response = restClient.execute(HttpMethod.PUT, url, GSON.toJson(keyCreateRequest), null, config.getAccessToken(), HttpURLConnection.HTTP_NOT_FOUND, HttpURLConnection.HTTP_CONFLICT);
if (response.getResponseCode() == HttpURLConnection.HTTP_CONFLICT) {
throw new SecureKeyAlreadyExistsException(secureKeyId);
}
if (response.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
throw new NamespaceNotFoundException(secureKeyId.getParent());
}
}
use of io.cdap.cdap.common.NamespaceNotFoundException in project cdap by caskdata.
the class DefaultNamespaceAdmin method delete.
/**
* Deletes the specified namespace
*
* @param namespaceId the {@link Id.Namespace} of the specified namespace
* @throws NamespaceCannotBeDeletedException if the specified namespace cannot be deleted
* @throws NamespaceNotFoundException if the specified namespace does not exist
*/
@Override
@AuthEnforce(entities = "namespaceId", enforceOn = NamespaceId.class, permissions = StandardPermission.DELETE)
public synchronized void delete(@Name("namespaceId") final NamespaceId namespaceId) throws Exception {
// TODO: CDAP-870, CDAP-1427: Delete should be in a single transaction.
NamespaceMeta namespaceMeta = get(namespaceId);
if (checkProgramsRunning(namespaceId)) {
throw new NamespaceCannotBeDeletedException(namespaceId, String.format("Some programs are currently running in namespace " + "'%s', please stop them before deleting namespace", namespaceId));
}
LOG.info("Deleting namespace '{}'.", namespaceId);
try {
// if needed, run master environment specific logic if it is a non-default namespace (see below for more info)
MasterEnvironment masterEnv = MasterEnvironments.getMasterEnvironment();
if (masterEnv != null && !NamespaceId.DEFAULT.equals(namespaceId)) {
masterEnv.onNamespaceDeletion(namespaceId.getNamespace(), namespaceMeta.getConfig().getConfigs());
}
resourceDeleter.get().deleteResources(namespaceMeta);
// namespace in the storage provider (Hive, HBase, etc), since we re-use their default namespace.
if (!NamespaceId.DEFAULT.equals(namespaceId)) {
// Finally delete namespace from MDS and remove from cache
deleteNamespaceMeta(namespaceId);
LOG.info("Namespace '{}' deleted", namespaceId);
} else {
LOG.info("Keeping the '{}' namespace after removing all data.", NamespaceId.DEFAULT);
}
} catch (Exception e) {
LOG.warn("Error while deleting namespace {}", namespaceId, e);
throw new NamespaceCannotBeDeletedException(namespaceId, e);
}
emitNamespaceCountMetric();
}
use of io.cdap.cdap.common.NamespaceNotFoundException in project cdap by caskdata.
the class ArtifactHttpHandler method addArtifact.
@POST
@Path("/namespaces/{namespace-id}/artifacts/{artifact-name}")
@AuditPolicy(AuditDetail.HEADERS)
public BodyConsumer addArtifact(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") final String namespaceId, @PathParam("artifact-name") final String artifactName, @HeaderParam(VERSION_HEADER) final String artifactVersion, @HeaderParam(EXTENDS_HEADER) final String parentArtifactsStr, @HeaderParam(PLUGINS_HEADER) String pluginClasses) throws NamespaceNotFoundException, BadRequestException {
final NamespaceId namespace = validateAndGetNamespace(namespaceId);
// that processes the last http chunk.
if (artifactVersion != null && !artifactVersion.isEmpty()) {
ArtifactId artifactId = validateAndGetArtifactId(namespace, artifactName, artifactVersion);
// If the artifact ID is available, use it to perform an authorization check.
contextAccessEnforcer.enforce(artifactId, StandardPermission.CREATE);
} else {
// If there is no version, we perform an enforceOnParent check in which the entityID is not needed.
contextAccessEnforcer.enforceOnParent(EntityType.ARTIFACT, namespace, StandardPermission.CREATE);
}
final Set<ArtifactRange> parentArtifacts = parseExtendsHeader(namespace, parentArtifactsStr);
final Set<PluginClass> additionalPluginClasses;
if (pluginClasses == null || pluginClasses.isEmpty()) {
additionalPluginClasses = ImmutableSet.of();
} else {
try {
additionalPluginClasses = GSON.fromJson(pluginClasses, PLUGINS_TYPE);
additionalPluginClasses.forEach(PluginClass::validate);
} catch (JsonParseException e) {
throw new BadRequestException(String.format("%s header '%s' is invalid.", PLUGINS_HEADER, pluginClasses), e);
} catch (IllegalArgumentException e) {
throw new BadRequestException(String.format("Invalid PluginClasses '%s'.", pluginClasses), e);
}
}
try {
// copy the artifact contents to local tmp directory
Files.createDirectories(tmpDir.toPath());
File destination = File.createTempFile("artifact-", ".jar", tmpDir);
return new AbstractBodyConsumer(destination) {
@Override
protected void onFinish(HttpResponder responder, File uploadedFile) {
try {
String version = (artifactVersion == null || artifactVersion.isEmpty()) ? getBundleVersion(uploadedFile) : artifactVersion;
ArtifactId artifactId = validateAndGetArtifactId(namespace, artifactName, version);
// add the artifact to the repo
artifactRepository.addArtifact(Id.Artifact.fromEntityId(artifactId), uploadedFile, parentArtifacts, additionalPluginClasses);
responder.sendString(HttpResponseStatus.OK, "Artifact added successfully");
} catch (ArtifactRangeNotFoundException e) {
responder.sendString(HttpResponseStatus.NOT_FOUND, e.getMessage());
} catch (ArtifactAlreadyExistsException e) {
responder.sendString(HttpResponseStatus.CONFLICT, e.getMessage());
} catch (WriteConflictException e) {
responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Conflict while writing artifact, please try again.");
} catch (IOException e) {
LOG.error("Exception while trying to write artifact {}-{}-{}.", namespaceId, artifactName, artifactVersion, e);
responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Error performing IO while writing artifact.");
} catch (BadRequestException e) {
responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage());
} catch (UnauthorizedException e) {
responder.sendString(HttpResponseStatus.FORBIDDEN, e.getMessage());
} catch (Exception e) {
LOG.error("Error while writing artifact {}-{}-{}", namespaceId, artifactName, artifactVersion, e);
responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Error while adding artifact.");
}
}
private String getBundleVersion(File file) throws BadRequestException, IOException {
try (JarFile jarFile = new JarFile(file)) {
Manifest manifest = jarFile.getManifest();
if (manifest == null) {
throw new BadRequestException("Unable to derive version from artifact because it does not contain a manifest. " + "Please package the jar with a manifest, or explicitly specify the artifact version.");
}
Attributes attributes = manifest.getMainAttributes();
String version = attributes == null ? null : attributes.getValue(ManifestFields.BUNDLE_VERSION);
if (version == null) {
throw new BadRequestException("Unable to derive version from artifact because manifest does not contain Bundle-Version attribute. " + "Please include Bundle-Version in the manifest, or explicitly specify the artifact version.");
}
return version;
} catch (ZipException e) {
throw new BadRequestException("Artifact is not in zip format. Please make sure it is a jar file.");
}
}
};
} catch (IOException e) {
LOG.error("Exception creating temp file to place artifact {} contents", artifactName, e);
responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Server error creating temp file for artifact.");
return null;
}
}
Aggregations