Search in sources :

Example 1 with NamespaceNotFoundException

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));
}
Also used : JsonObject(com.google.gson.JsonObject) BootstrapStepResult(io.cdap.cdap.proto.bootstrap.BootstrapStepResult) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) Test(org.junit.Test)

Example 2 with NamespaceNotFoundException

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;
}
Also used : ApplicationDetail(io.cdap.cdap.proto.ApplicationDetail) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) IOException(java.io.IOException) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) IOException(java.io.IOException) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) NotFoundException(io.cdap.cdap.common.NotFoundException)

Example 3 with NamespaceNotFoundException

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());
    }
}
Also used : SecureKeyAlreadyExistsException(io.cdap.cdap.common.SecureKeyAlreadyExistsException) HttpResponse(io.cdap.common.http.HttpResponse) URL(java.net.URL) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException)

Example 4 with NamespaceNotFoundException

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();
}
Also used : MasterEnvironment(io.cdap.cdap.master.spi.environment.MasterEnvironment) NamespaceMeta(io.cdap.cdap.proto.NamespaceMeta) NamespaceCannotBeDeletedException(io.cdap.cdap.common.NamespaceCannotBeDeletedException) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) NamespaceCannotBeDeletedException(io.cdap.cdap.common.NamespaceCannotBeDeletedException) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) NamespaceCannotBeCreatedException(io.cdap.cdap.common.NamespaceCannotBeCreatedException) NamespaceAlreadyExistsException(io.cdap.cdap.common.NamespaceAlreadyExistsException) DatasetManagementException(io.cdap.cdap.api.dataset.DatasetManagementException) IOException(java.io.IOException) BadRequestException(io.cdap.cdap.common.BadRequestException) AuthEnforce(io.cdap.cdap.common.security.AuthEnforce)

Example 5 with NamespaceNotFoundException

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;
    }
}
Also used : ArtifactRangeNotFoundException(io.cdap.cdap.common.ArtifactRangeNotFoundException) HttpResponder(io.cdap.http.HttpResponder) ArtifactId(io.cdap.cdap.proto.id.ArtifactId) ArtifactRange(io.cdap.cdap.api.artifact.ArtifactRange) Attributes(java.util.jar.Attributes) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) JarFile(java.util.jar.JarFile) Manifest(java.util.jar.Manifest) ArtifactRangeNotFoundException(io.cdap.cdap.common.ArtifactRangeNotFoundException) ZipException(java.util.zip.ZipException) ArtifactAlreadyExistsException(io.cdap.cdap.common.ArtifactAlreadyExistsException) JsonParseException(com.google.gson.JsonParseException) InvalidArtifactRangeException(io.cdap.cdap.api.artifact.InvalidArtifactRangeException) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) PluginNotExistsException(io.cdap.cdap.internal.app.runtime.plugin.PluginNotExistsException) WriteConflictException(io.cdap.cdap.internal.app.runtime.artifact.WriteConflictException) CapabilityNotAvailableException(io.cdap.cdap.internal.capability.CapabilityNotAvailableException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) BadRequestException(io.cdap.cdap.common.BadRequestException) ArtifactNotFoundException(io.cdap.cdap.common.ArtifactNotFoundException) ArtifactAlreadyExistsException(io.cdap.cdap.common.ArtifactAlreadyExistsException) AbstractBodyConsumer(io.cdap.cdap.common.http.AbstractBodyConsumer) WriteConflictException(io.cdap.cdap.internal.app.runtime.artifact.WriteConflictException) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) BadRequestException(io.cdap.cdap.common.BadRequestException) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) PluginClass(io.cdap.cdap.api.plugin.PluginClass) JarFile(java.util.jar.JarFile) File(java.io.File) Path(javax.ws.rs.Path) AuditPolicy(io.cdap.cdap.common.security.AuditPolicy) POST(javax.ws.rs.POST)

Aggregations

NamespaceNotFoundException (io.cdap.cdap.common.NamespaceNotFoundException)24 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)12 IOException (java.io.IOException)10 NotFoundException (io.cdap.cdap.common.NotFoundException)8 HttpResponse (io.cdap.common.http.HttpResponse)6 NamespaceMeta (io.cdap.cdap.proto.NamespaceMeta)5 Path (javax.ws.rs.Path)5 BadRequestException (io.cdap.cdap.common.BadRequestException)4 NamespaceCannotBeDeletedException (io.cdap.cdap.common.NamespaceCannotBeDeletedException)4 UnauthorizedException (io.cdap.cdap.security.spi.authorization.UnauthorizedException)4 GET (javax.ws.rs.GET)4 Test (org.junit.Test)4 NamespaceAlreadyExistsException (io.cdap.cdap.common.NamespaceAlreadyExistsException)3 URL (java.net.URL)3 ArtifactRange (io.cdap.cdap.api.artifact.ArtifactRange)2 DatasetManagementException (io.cdap.cdap.api.dataset.DatasetManagementException)2 SecureStoreMetadata (io.cdap.cdap.api.security.store.SecureStoreMetadata)2 NamespaceCannotBeCreatedException (io.cdap.cdap.common.NamespaceCannotBeCreatedException)2 ArtifactDetail (io.cdap.cdap.internal.app.runtime.artifact.ArtifactDetail)2 ApplicationId (io.cdap.cdap.proto.id.ApplicationId)2