Search in sources :

Example 1 with ClusterDataImpl

use of org.apache.pulsar.common.policies.data.ClusterDataImpl in project pulsar by apache.

the class PulsarWebResource method checkLocalOrGetPeerReplicationCluster.

public static CompletableFuture<ClusterDataImpl> checkLocalOrGetPeerReplicationCluster(PulsarService pulsarService, NamespaceName namespace) {
    if (!namespace.isGlobal()) {
        return CompletableFuture.completedFuture(null);
    }
    NamespaceName heartbeatNamespace = pulsarService.getHeartbeatNamespaceV2();
    if (namespace.equals(heartbeatNamespace)) {
        return CompletableFuture.completedFuture(null);
    }
    final CompletableFuture<ClusterDataImpl> validationFuture = new CompletableFuture<>();
    final String localCluster = pulsarService.getConfiguration().getClusterName();
    pulsarService.getPulsarResources().getNamespaceResources().getPoliciesAsync(namespace).thenAccept(policiesResult -> {
        if (policiesResult.isPresent()) {
            Policies policies = policiesResult.get();
            if (policies.replication_clusters.isEmpty()) {
                String msg = String.format("Namespace does not have any clusters configured : local_cluster=%s ns=%s", localCluster, namespace.toString());
                log.warn(msg);
                validationFuture.completeExceptionally(new RestException(Status.PRECONDITION_FAILED, msg));
            } else if (!policies.replication_clusters.contains(localCluster)) {
                ClusterDataImpl ownerPeerCluster = getOwnerFromPeerClusterList(pulsarService, policies.replication_clusters);
                if (ownerPeerCluster != null) {
                    // found a peer that own this namespace
                    validationFuture.complete(ownerPeerCluster);
                    return;
                }
                String msg = String.format("Namespace missing local cluster name in clusters list: local_cluster=%s ns=%s clusters=%s", localCluster, namespace.toString(), policies.replication_clusters);
                log.warn(msg);
                validationFuture.completeExceptionally(new RestException(Status.PRECONDITION_FAILED, msg));
            } else {
                validationFuture.complete(null);
            }
        } else {
            String msg = String.format("Namespace %s not found", namespace.toString());
            log.warn(msg);
            validationFuture.completeExceptionally(new RestException(Status.NOT_FOUND, "Namespace not found"));
        }
    }).exceptionally(ex -> {
        String msg = String.format("Failed to validate global cluster configuration : cluster=%s ns=%s  emsg=%s", localCluster, namespace, ex.getMessage());
        log.error(msg);
        validationFuture.completeExceptionally(new RestException(ex));
        return null;
    });
    return validationFuture;
}
Also used : Constants(org.apache.pulsar.common.naming.Constants) ClusterDataImpl(org.apache.pulsar.common.policies.data.ClusterDataImpl) PulsarResources(org.apache.pulsar.broker.resources.PulsarResources) URL(java.net.URL) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) BookieResources(org.apache.pulsar.broker.resources.BookieResources) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) StringUtils(org.apache.commons.lang3.StringUtils) NamespaceBundles(org.apache.pulsar.common.naming.NamespaceBundles) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Pair(org.apache.commons.lang3.tuple.Pair) TopicOperation(org.apache.pulsar.common.policies.data.TopicOperation) PolicyOperation(org.apache.pulsar.common.policies.data.PolicyOperation) NamespaceOperation(org.apache.pulsar.common.policies.data.NamespaceOperation) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) LocalPoliciesResources(org.apache.pulsar.broker.resources.LocalPoliciesResources) IsolationPolicyResources(org.apache.pulsar.broker.resources.NamespaceResources.IsolationPolicyResources) Context(javax.ws.rs.core.Context) AsyncResponse(javax.ws.rs.container.AsyncResponse) Range(com.google.common.collect.Range) Set(java.util.Set) CompletionException(java.util.concurrent.CompletionException) BrokerService(org.apache.pulsar.broker.service.BrokerService) Sets(com.google.common.collect.Sets) AuthenticationDataSource(org.apache.pulsar.broker.authentication.AuthenticationDataSource) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) LookupOptions(org.apache.pulsar.broker.namespace.LookupOptions) Response(javax.ws.rs.core.Response) BoundType(com.google.common.collect.BoundType) PolicyName(org.apache.pulsar.common.policies.data.PolicyName) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) NamespaceResources(org.apache.pulsar.broker.resources.NamespaceResources) UriInfo(javax.ws.rs.core.UriInfo) TenantOperation(org.apache.pulsar.common.policies.data.TenantOperation) PulsarServiceNameResolver(org.apache.pulsar.client.impl.PulsarServiceNameResolver) TopicResources(org.apache.pulsar.broker.resources.TopicResources) TopicName(org.apache.pulsar.common.naming.TopicName) CompletableFuture(java.util.concurrent.CompletableFuture) NamespaceService(org.apache.pulsar.broker.namespace.NamespaceService) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) PolicyPath(org.apache.pulsar.common.policies.path.PolicyPath) BundlesData(org.apache.pulsar.common.policies.data.BundlesData) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) TenantInfo(org.apache.pulsar.common.policies.data.TenantInfo) Status(javax.ws.rs.core.Response.Status) ClusterResources(org.apache.pulsar.broker.resources.ClusterResources) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) ResourceGroupResources(org.apache.pulsar.broker.resources.ResourceGroupResources) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PulsarService(org.apache.pulsar.broker.PulsarService) DynamicConfigurationResources(org.apache.pulsar.broker.resources.DynamicConfigurationResources) ExecutionException(java.util.concurrent.ExecutionException) Policies(org.apache.pulsar.common.policies.data.Policies) TenantResources(org.apache.pulsar.broker.resources.TenantResources) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) ServletContext(javax.servlet.ServletContext) AuthorizationService(org.apache.pulsar.broker.authorization.AuthorizationService) SECONDS(java.util.concurrent.TimeUnit.SECONDS) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) CompletableFuture(java.util.concurrent.CompletableFuture) Policies(org.apache.pulsar.common.policies.data.Policies) ClusterDataImpl(org.apache.pulsar.common.policies.data.ClusterDataImpl)

Example 2 with ClusterDataImpl

use of org.apache.pulsar.common.policies.data.ClusterDataImpl in project pulsar by apache.

the class TopicsTest method setup.

@Override
@BeforeMethod
protected void setup() throws Exception {
    super.internalSetup();
    topics = spy(new Topics());
    topics.setPulsar(pulsar);
    doReturn(TopicDomain.persistent.value()).when(topics).domain();
    doReturn("test-app").when(topics).clientAppId();
    doReturn(mock(AuthenticationDataHttps.class)).when(topics).clientAuthData();
    admin.clusters().createCluster(testLocalCluster, new ClusterDataImpl());
    admin.tenants().createTenant(testTenant, new TenantInfoImpl(Sets.newHashSet("role1", "role2"), Sets.newHashSet(testLocalCluster)));
    admin.namespaces().createNamespace(testTenant + "/" + testNamespace, Sets.newHashSet(testLocalCluster));
}
Also used : Topics(org.apache.pulsar.broker.rest.Topics) AuthenticationDataHttps(org.apache.pulsar.broker.authentication.AuthenticationDataHttps) ClusterDataImpl(org.apache.pulsar.common.policies.data.ClusterDataImpl) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 3 with ClusterDataImpl

use of org.apache.pulsar.common.policies.data.ClusterDataImpl in project pulsar by apache.

the class TopicsAuthTest method setup.

@Override
@BeforeMethod
protected void setup() throws Exception {
    // enable auth&auth and use JWT at broker
    conf.setAuthenticationEnabled(true);
    conf.setAuthorizationEnabled(true);
    conf.getProperties().setProperty("tokenSecretKey", "data:;base64," + Base64.getEncoder().encodeToString(SECRET_KEY.getEncoded()));
    Set<String> superUserRoles = new HashSet<>();
    superUserRoles.add("admin");
    conf.setSuperUserRoles(superUserRoles);
    Set<String> providers = new HashSet<>();
    providers.add(AuthenticationProviderToken.class.getName());
    conf.setAuthenticationProviders(providers);
    super.internalSetup();
    PulsarAdminBuilder pulsarAdminBuilder = PulsarAdmin.builder().serviceHttpUrl(brokerUrl != null ? brokerUrl.toString() : brokerUrlTls.toString()).authentication(AuthenticationToken.class.getName(), ADMIN_TOKEN);
    admin = Mockito.spy(pulsarAdminBuilder.build());
    admin.clusters().createCluster(testLocalCluster, new ClusterDataImpl());
    admin.tenants().createTenant(testTenant, new TenantInfoImpl(Sets.newHashSet("role1", "role2"), Sets.newHashSet(testLocalCluster)));
    admin.namespaces().createNamespace(testTenant + "/" + testNamespace, Sets.newHashSet(testLocalCluster));
    admin.namespaces().grantPermissionOnNamespace(testTenant + "/" + testNamespace, "producer", EnumSet.of(AuthAction.produce));
    admin.namespaces().grantPermissionOnNamespace(testTenant + "/" + testNamespace, "consumer", EnumSet.of(AuthAction.consume));
}
Also used : PulsarAdminBuilder(org.apache.pulsar.client.admin.PulsarAdminBuilder) AuthenticationToken(org.apache.pulsar.client.impl.auth.AuthenticationToken) AuthenticationProviderToken(org.apache.pulsar.broker.authentication.AuthenticationProviderToken) ClusterDataImpl(org.apache.pulsar.common.policies.data.ClusterDataImpl) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) HashSet(java.util.HashSet) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 4 with ClusterDataImpl

use of org.apache.pulsar.common.policies.data.ClusterDataImpl in project pulsar by apache.

the class PulsarWorkerService method initInBroker.

@Override
public void initInBroker(ServiceConfiguration brokerConfig, WorkerConfig workerConfig, PulsarResources pulsarResources, InternalConfigurationData internalConf) throws Exception {
    String namespace = workerConfig.getPulsarFunctionsNamespace();
    String[] a = workerConfig.getPulsarFunctionsNamespace().split("/");
    String tenant = a[0];
    String cluster = workerConfig.getPulsarFunctionsCluster();
    // create tenant for function worker service
    try {
        NamedEntity.checkName(tenant);
        pulsarResources.getTenantResources().createTenant(tenant, new TenantInfoImpl(Sets.newHashSet(workerConfig.getSuperUserRoles()), Sets.newHashSet(cluster)));
        LOG.info("Created tenant {} for function worker", tenant);
    } catch (AlreadyExistsException e) {
        LOG.debug("Failed to create already existing property {} for function worker service", cluster, e);
    } catch (IllegalArgumentException e) {
        LOG.error("Failed to create property with invalid name {} for function worker service", cluster, e);
        throw e;
    } catch (Exception e) {
        LOG.error("Failed to create property {} for function worker", cluster, e);
        throw e;
    }
    // create cluster for function worker service
    try {
        NamedEntity.checkName(cluster);
        ClusterDataImpl clusterData = ClusterDataImpl.builder().serviceUrl(workerConfig.getPulsarWebServiceUrl()).brokerServiceUrl(workerConfig.getPulsarServiceUrl()).build();
        pulsarResources.getClusterResources().createCluster(cluster, clusterData);
        LOG.info("Created cluster {} for function worker", cluster);
    } catch (AlreadyExistsException e) {
        LOG.debug("Failed to create already existing cluster {} for function worker service", cluster, e);
    } catch (IllegalArgumentException e) {
        LOG.error("Failed to create cluster with invalid name {} for function worker service", cluster, e);
        throw e;
    } catch (Exception e) {
        LOG.error("Failed to create cluster {} for function worker service", cluster, e);
        throw e;
    }
    // create namespace for function worker service
    try {
        Policies policies = createFunctionsNamespacePolicies(workerConfig.getPulsarFunctionsCluster());
        policies.bundles = getBundles(brokerConfig.getDefaultNumberOfNamespaceBundles());
        pulsarResources.getNamespaceResources().createPolicies(NamespaceName.get(namespace), policies);
        LOG.info("Created namespace {} for function worker service", namespace);
    } catch (AlreadyExistsException e) {
        LOG.debug("Failed to create already existing namespace {} for function worker service", namespace);
    } catch (Exception e) {
        LOG.error("Failed to create namespace {}", namespace, e);
        throw e;
    }
    URI dlogURI;
    try {
        // initializing dlog namespace for function worker
        if (workerConfig.isInitializedDlogMetadata()) {
            String metadataStoreUrl = removeIdentifierFromMetadataURL(internalConf.getMetadataStoreUrl());
            dlogURI = WorkerUtils.newDlogNamespaceURI(metadataStoreUrl);
        } else {
            dlogURI = WorkerUtils.initializeDlogNamespace(internalConf);
        }
    } catch (IOException ioe) {
        LOG.error("Failed to initialize dlog namespace with zookeeper {} at at metadata service uri {} for " + "storing function packages", internalConf.getMetadataStoreUrl(), internalConf.getBookkeeperMetadataServiceUri(), ioe);
        throw ioe;
    }
    init(workerConfig, dlogURI, false);
    LOG.info("Function worker service setup completed");
}
Also used : InactiveTopicPolicies(org.apache.pulsar.common.policies.data.InactiveTopicPolicies) RetentionPolicies(org.apache.pulsar.common.policies.data.RetentionPolicies) Policies(org.apache.pulsar.common.policies.data.Policies) AlreadyExistsException(org.apache.pulsar.metadata.api.MetadataStoreException.AlreadyExistsException) IOException(java.io.IOException) ClusterDataImpl(org.apache.pulsar.common.policies.data.ClusterDataImpl) URI(java.net.URI) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) AlreadyExistsException(org.apache.pulsar.metadata.api.MetadataStoreException.AlreadyExistsException) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Example 5 with ClusterDataImpl

use of org.apache.pulsar.common.policies.data.ClusterDataImpl in project pulsar by yahoo.

the class PulsarWorkerService method initInBroker.

@Override
public void initInBroker(ServiceConfiguration brokerConfig, WorkerConfig workerConfig, PulsarResources pulsarResources, InternalConfigurationData internalConf) throws Exception {
    String namespace = workerConfig.getPulsarFunctionsNamespace();
    String[] a = workerConfig.getPulsarFunctionsNamespace().split("/");
    String tenant = a[0];
    String cluster = workerConfig.getPulsarFunctionsCluster();
    // create tenant for function worker service
    try {
        NamedEntity.checkName(tenant);
        pulsarResources.getTenantResources().createTenant(tenant, new TenantInfoImpl(Sets.newHashSet(workerConfig.getSuperUserRoles()), Sets.newHashSet(cluster)));
        LOG.info("Created tenant {} for function worker", tenant);
    } catch (AlreadyExistsException e) {
        LOG.debug("Failed to create already existing property {} for function worker service", cluster, e);
    } catch (IllegalArgumentException e) {
        LOG.error("Failed to create property with invalid name {} for function worker service", cluster, e);
        throw e;
    } catch (Exception e) {
        LOG.error("Failed to create property {} for function worker", cluster, e);
        throw e;
    }
    // create cluster for function worker service
    try {
        NamedEntity.checkName(cluster);
        ClusterDataImpl clusterData = ClusterDataImpl.builder().serviceUrl(workerConfig.getPulsarWebServiceUrl()).brokerServiceUrl(workerConfig.getPulsarServiceUrl()).build();
        pulsarResources.getClusterResources().createCluster(cluster, clusterData);
        LOG.info("Created cluster {} for function worker", cluster);
    } catch (AlreadyExistsException e) {
        LOG.debug("Failed to create already existing cluster {} for function worker service", cluster, e);
    } catch (IllegalArgumentException e) {
        LOG.error("Failed to create cluster with invalid name {} for function worker service", cluster, e);
        throw e;
    } catch (Exception e) {
        LOG.error("Failed to create cluster {} for function worker service", cluster, e);
        throw e;
    }
    // create namespace for function worker service
    try {
        Policies policies = createFunctionsNamespacePolicies(workerConfig.getPulsarFunctionsCluster());
        policies.bundles = getBundles(brokerConfig.getDefaultNumberOfNamespaceBundles());
        pulsarResources.getNamespaceResources().createPolicies(NamespaceName.get(namespace), policies);
        LOG.info("Created namespace {} for function worker service", namespace);
    } catch (AlreadyExistsException e) {
        LOG.debug("Failed to create already existing namespace {} for function worker service", namespace);
    } catch (Exception e) {
        LOG.error("Failed to create namespace {}", namespace, e);
        throw e;
    }
    URI dlogURI = null;
    if (brokerConfig.isMetadataStoreBackedByZookeeper()) {
        try {
            // initializing dlog namespace for function worker
            if (workerConfig.isInitializedDlogMetadata()) {
                String metadataStoreUrl = removeIdentifierFromMetadataURL(internalConf.getMetadataStoreUrl());
                dlogURI = WorkerUtils.newDlogNamespaceURI(metadataStoreUrl);
            } else {
                dlogURI = WorkerUtils.initializeDlogNamespace(internalConf);
            }
        } catch (IOException ioe) {
            LOG.error("Failed to initialize dlog namespace with zookeeper {} at at metadata service uri {} for " + "storing function packages", internalConf.getMetadataStoreUrl(), internalConf.getBookkeeperMetadataServiceUri(), ioe);
            throw ioe;
        }
    }
    init(workerConfig, dlogURI, false);
    LOG.info("Function worker service setup completed");
}
Also used : InactiveTopicPolicies(org.apache.pulsar.common.policies.data.InactiveTopicPolicies) RetentionPolicies(org.apache.pulsar.common.policies.data.RetentionPolicies) Policies(org.apache.pulsar.common.policies.data.Policies) AlreadyExistsException(org.apache.pulsar.metadata.api.MetadataStoreException.AlreadyExistsException) IOException(java.io.IOException) ClusterDataImpl(org.apache.pulsar.common.policies.data.ClusterDataImpl) URI(java.net.URI) TenantInfoImpl(org.apache.pulsar.common.policies.data.TenantInfoImpl) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) AlreadyExistsException(org.apache.pulsar.metadata.api.MetadataStoreException.AlreadyExistsException) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) IOException(java.io.IOException)

Aggregations

ClusterDataImpl (org.apache.pulsar.common.policies.data.ClusterDataImpl)24 TenantInfoImpl (org.apache.pulsar.common.policies.data.TenantInfoImpl)12 CompletableFuture (java.util.concurrent.CompletableFuture)10 ClusterData (org.apache.pulsar.common.policies.data.ClusterData)10 Map (java.util.Map)9 BeforeMethod (org.testng.annotations.BeforeMethod)8 List (java.util.List)7 AsyncResponse (javax.ws.rs.container.AsyncResponse)7 Response (javax.ws.rs.core.Response)7 Status (javax.ws.rs.core.Response.Status)7 RestException (org.apache.pulsar.broker.web.RestException)7 MetadataStoreException (org.apache.pulsar.metadata.api.MetadataStoreException)7 IOException (java.io.IOException)6 Collections (java.util.Collections)6 NamespaceIsolationDataImpl (org.apache.pulsar.common.policies.data.NamespaceIsolationDataImpl)6 URI (java.net.URI)5 Optional (java.util.Optional)5 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)5 Policies (org.apache.pulsar.common.policies.data.Policies)5 ApiOperation (io.swagger.annotations.ApiOperation)4