Search in sources :

Example 1 with NamespaceAlreadyExistsException

use of co.cask.cdap.common.NamespaceAlreadyExistsException 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);
}
Also used : Action(co.cask.cdap.proto.security.Action) NamespaceCannotBeCreatedException(co.cask.cdap.common.NamespaceCannotBeCreatedException) KerberosName(org.apache.hadoop.security.authentication.util.KerberosName) NamespaceCannotBeCreatedException(co.cask.cdap.common.NamespaceCannotBeCreatedException) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) BadRequestException(co.cask.cdap.common.BadRequestException) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) NamespaceCannotBeDeletedException(co.cask.cdap.common.NamespaceCannotBeDeletedException) DatasetManagementException(co.cask.cdap.api.dataset.DatasetManagementException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) NamespaceAlreadyExistsException(co.cask.cdap.common.NamespaceAlreadyExistsException) BadRequestException(co.cask.cdap.common.BadRequestException) NamespaceId(co.cask.cdap.proto.id.NamespaceId) NamespaceAlreadyExistsException(co.cask.cdap.common.NamespaceAlreadyExistsException) Principal(co.cask.cdap.proto.security.Principal) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation) AuthEnforce(co.cask.cdap.common.security.AuthEnforce)

Example 2 with NamespaceAlreadyExistsException

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

the class AbstractNamespaceClient method create.

@Override
public void create(NamespaceMeta metadata) throws Exception {
    URL url = resolve(String.format("namespaces/%s", metadata.getName()));
    HttpResponse response = execute(HttpRequest.put(url).withBody(GSON.toJson(metadata)).build());
    String responseBody = response.getResponseBodyAsString();
    if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
        if (responseBody.equals(String.format("Namespace '%s' already exists.", metadata.getName()))) {
            throw new NamespaceAlreadyExistsException(metadata.getNamespaceId());
        }
        return;
    }
    if (response.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST) {
        throw new BadRequestException("Bad request: " + responseBody);
    }
    throw new IOException(String.format("Cannot create namespace %s. Reason: %s", metadata.getName(), responseBody));
}
Also used : HttpResponse(co.cask.common.http.HttpResponse) BadRequestException(co.cask.cdap.common.BadRequestException) NamespaceAlreadyExistsException(co.cask.cdap.common.NamespaceAlreadyExistsException) IOException(java.io.IOException) URL(java.net.URL)

Example 3 with NamespaceAlreadyExistsException

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

the class DefaultNamespaceAdminTest method testNamespaces.

@Test
public void testNamespaces() throws Exception {
    String namespace = "namespace";
    NamespaceId namespaceId = new NamespaceId(namespace);
    NamespaceMeta.Builder builder = new NamespaceMeta.Builder();
    int initialCount = namespaceAdmin.list().size();
    // TEST_NAMESPACE_META1 is already created in AppFabricTestBase#beforeClass
    Assert.assertTrue(namespaceAdmin.exists(new NamespaceId(TEST_NAMESPACE1)));
    // It should be present in cache too
    Assert.assertNotNull(getFromCache(new NamespaceId(TEST_NAMESPACE1)));
    try {
        namespaceAdmin.create(TEST_NAMESPACE_META1);
        Assert.fail("Should not create duplicate namespace.");
    } catch (NamespaceAlreadyExistsException e) {
        Assert.assertEquals(TEST_NAMESPACE_META1.getNamespaceId(), e.getId());
    }
    // "random" namespace should not exist
    try {
        namespaceAdmin.get(new NamespaceId("random"));
        Assert.fail("Namespace 'random' should not exist.");
    } catch (NamespaceNotFoundException e) {
        Assert.assertEquals(new NamespaceId("random"), e.getId());
    }
    try {
        namespaceAdmin.create(null);
        Assert.fail("Namespace with null metadata should fail.");
    } catch (IllegalArgumentException e) {
        Assert.assertEquals("Namespace metadata should not be null.", e.getMessage());
    }
    Assert.assertEquals(initialCount, namespaceAdmin.list().size());
    Assert.assertFalse(namespaceAdmin.exists(new NamespaceId(namespace)));
    try {
        namespaceAdmin.create(builder.build());
        Assert.fail("Namespace with no name should fail");
    } catch (IllegalArgumentException e) {
        Assert.assertEquals("Namespace id cannot be null.", e.getMessage());
    }
    Assert.assertEquals(initialCount, namespaceAdmin.list().size());
    Assert.assertFalse(namespaceAdmin.exists(namespaceId));
    // namespace with default fields
    namespaceAdmin.create(builder.setName(namespace).build());
    Assert.assertEquals(initialCount + 1, namespaceAdmin.list().size());
    Assert.assertTrue(namespaceAdmin.exists(namespaceId));
    // it should be loaded in cache too since exists calls get
    Assert.assertNotNull(getFromCache(namespaceId));
    try {
        NamespaceMeta namespaceMeta = namespaceAdmin.get(namespaceId);
        Assert.assertEquals(namespaceId.getNamespace(), namespaceMeta.getName());
        Assert.assertEquals("", namespaceMeta.getDescription());
        namespaceAdmin.delete(namespaceId);
        // it should be deleted from the cache too
        Assert.assertNull(getFromCache(namespaceId));
    } catch (NotFoundException e) {
        Assert.fail(String.format("Namespace '%s' should be found since it was just created.", namespaceId.getNamespace()));
    }
    namespaceAdmin.create(builder.setDescription("describes " + namespace).build());
    Assert.assertEquals(initialCount + 1, namespaceAdmin.list().size());
    Assert.assertTrue(namespaceAdmin.exists(namespaceId));
    try {
        NamespaceMeta namespaceMeta = namespaceAdmin.get(namespaceId);
        // it should be loaded in cache too
        Assert.assertNotNull(getFromCache(namespaceId));
        Assert.assertEquals(namespaceId.getNamespace(), namespaceMeta.getName());
        Assert.assertEquals("describes " + namespaceId.getNamespace(), namespaceMeta.getDescription());
        namespaceAdmin.delete(namespaceId);
        // it should be deleted from the cache
        Assert.assertNull(getFromCache(namespaceId));
    } catch (NotFoundException e) {
        Assert.fail(String.format("Namespace '%s' should be found since it was just created.", namespaceId.getNamespace()));
    }
    // Verify NotFoundException's contents as well, instead of just checking namespaceService.exists = false
    verifyNotFound(namespaceId);
}
Also used : NamespaceMeta(co.cask.cdap.proto.NamespaceMeta) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) NotFoundException(co.cask.cdap.common.NotFoundException) NamespaceId(co.cask.cdap.proto.id.NamespaceId) NamespaceAlreadyExistsException(co.cask.cdap.common.NamespaceAlreadyExistsException) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) Test(org.junit.Test)

Aggregations

NamespaceAlreadyExistsException (co.cask.cdap.common.NamespaceAlreadyExistsException)3 BadRequestException (co.cask.cdap.common.BadRequestException)2 NamespaceNotFoundException (co.cask.cdap.common.NamespaceNotFoundException)2 NamespaceId (co.cask.cdap.proto.id.NamespaceId)2 IOException (java.io.IOException)2 DatasetManagementException (co.cask.cdap.api.dataset.DatasetManagementException)1 NamespaceCannotBeCreatedException (co.cask.cdap.common.NamespaceCannotBeCreatedException)1 NamespaceCannotBeDeletedException (co.cask.cdap.common.NamespaceCannotBeDeletedException)1 NotFoundException (co.cask.cdap.common.NotFoundException)1 AuthEnforce (co.cask.cdap.common.security.AuthEnforce)1 NamespaceMeta (co.cask.cdap.proto.NamespaceMeta)1 Action (co.cask.cdap.proto.security.Action)1 Principal (co.cask.cdap.proto.security.Principal)1 UnauthorizedException (co.cask.cdap.security.spi.authorization.UnauthorizedException)1 HttpResponse (co.cask.common.http.HttpResponse)1 URL (java.net.URL)1 ExecutionException (java.util.concurrent.ExecutionException)1 UserGroupInformation (org.apache.hadoop.security.UserGroupInformation)1 KerberosName (org.apache.hadoop.security.authentication.util.KerberosName)1 Test (org.junit.Test)1