Search in sources :

Example 1 with PulsarServerException

use of org.apache.pulsar.broker.PulsarServerException in project incubator-pulsar by apache.

the class MessagingServiceShutdownHook method run.

@Override
public void run() {
    if (service.getConfiguration() != null) {
        LOG.info("messaging service shutdown hook started, lookup port=" + service.getConfiguration().getWebServicePort() + ", broker url=" + service.getBrokerServiceUrl());
    }
    ExecutorService executor = Executors.newSingleThreadExecutor(new DefaultThreadFactory("shutdown-thread"));
    try {
        CompletableFuture<Void> future = new CompletableFuture<>();
        executor.execute(() -> {
            try {
                service.close();
                future.complete(null);
            } catch (PulsarServerException e) {
                future.completeExceptionally(e);
            }
        });
        future.get(service.getConfiguration().getBrokerShutdownTimeoutMs(), TimeUnit.MILLISECONDS);
        LOG.info("Completed graceful shutdown. Exiting");
    } catch (TimeoutException e) {
        LOG.warn("Graceful shutdown timeout expired. Closing now");
    } catch (Exception e) {
        LOG.error("Failed to perform graceful shutdown, Exiting anyway", e);
    } finally {
        immediateFlushBufferedLogs();
        // always put system to halt immediately
        Runtime.getRuntime().halt(0);
    }
}
Also used : DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutorService(java.util.concurrent.ExecutorService) TimeoutException(java.util.concurrent.TimeoutException) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with PulsarServerException

use of org.apache.pulsar.broker.PulsarServerException in project incubator-pulsar by apache.

the class Consumer method updatePermitsAndPendingAcks.

void updatePermitsAndPendingAcks(final List<Entry> entries, SendMessageInfo sentMessages) throws PulsarServerException {
    int permitsToReduce = 0;
    Iterator<Entry> iter = entries.iterator();
    boolean unsupportedVersion = false;
    long totalReadableBytes = 0;
    boolean clientSupportBatchMessages = cnx.isBatchMessageCompatibleVersion();
    while (iter.hasNext()) {
        Entry entry = iter.next();
        ByteBuf metadataAndPayload = entry.getDataBuffer();
        int batchSize = getBatchSizeforEntry(metadataAndPayload, subscription, consumerId);
        if (batchSize == -1) {
            // this would suggest that the message might have been corrupted
            iter.remove();
            PositionImpl pos = (PositionImpl) entry.getPosition();
            entry.release();
            subscription.acknowledgeMessage(pos, AckType.Individual, Collections.emptyMap());
            continue;
        }
        if (pendingAcks != null) {
            pendingAcks.put(entry.getLedgerId(), entry.getEntryId(), batchSize, 0);
        }
        // check if consumer supports batch message
        if (batchSize > 1 && !clientSupportBatchMessages) {
            unsupportedVersion = true;
        }
        totalReadableBytes += metadataAndPayload.readableBytes();
        permitsToReduce += batchSize;
    }
    // reduce permit and increment unackedMsg count with total number of messages in batch-msgs
    int permits = MESSAGE_PERMITS_UPDATER.addAndGet(this, -permitsToReduce);
    incrementUnackedMessages(permitsToReduce);
    if (unsupportedVersion) {
        throw new PulsarServerException("Consumer does not support batch-message");
    }
    if (permits < 0) {
        if (log.isDebugEnabled()) {
            log.debug("[{}-{}] [{}] message permits dropped below 0 - {}", topicName, subscription, consumerId, permits);
        }
    }
    msgOut.recordMultipleEvents(permitsToReduce, totalReadableBytes);
    sentMessages.totalSentMessages = permitsToReduce;
    sentMessages.totalSentMessageBytes = totalReadableBytes;
}
Also used : PulsarServerException(org.apache.pulsar.broker.PulsarServerException) Entry(org.apache.bookkeeper.mledger.Entry) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) ByteBuf(io.netty.buffer.ByteBuf)

Example 3 with PulsarServerException

use of org.apache.pulsar.broker.PulsarServerException in project incubator-pulsar by apache.

the class NamespacesBase method internalUnloadNamespace.

@SuppressWarnings("deprecation")
protected void internalUnloadNamespace() {
    log.info("[{}] Unloading namespace {}", clientAppId());
    validateSuperUserAccess();
    if (namespaceName.isGlobal()) {
        // check cluster ownership for a given global namespace: redirect if peer-cluster owns it
        validateGlobalNamespaceOwnership(namespaceName);
    } else {
        validateClusterOwnership(namespaceName.getCluster());
        validateClusterForProperty(namespaceName.getProperty(), namespaceName.getCluster());
    }
    Policies policies = getNamespacePolicies(namespaceName);
    List<String> boundaries = policies.bundles.getBoundaries();
    for (int i = 0; i < boundaries.size() - 1; i++) {
        String bundle = String.format("%s_%s", boundaries.get(i), boundaries.get(i + 1));
        try {
            pulsar().getAdminClient().namespaces().unloadNamespaceBundle(namespaceName.toString(), bundle);
        } catch (PulsarServerException | PulsarAdminException e) {
            log.error(String.format("[%s] Failed to unload namespace %s", clientAppId(), namespaceName), e);
            throw new RestException(e);
        }
    }
    log.info("[{}] Successfully unloaded all the bundles in namespace {}/{}/{}", clientAppId(), namespaceName);
}
Also used : PulsarServerException(org.apache.pulsar.broker.PulsarServerException) PersistencePolicies(org.apache.pulsar.common.policies.data.PersistencePolicies) RetentionPolicies(org.apache.pulsar.common.policies.data.RetentionPolicies) Policies(org.apache.pulsar.common.policies.data.Policies) RestException(org.apache.pulsar.broker.web.RestException) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException)

Example 4 with PulsarServerException

use of org.apache.pulsar.broker.PulsarServerException in project incubator-pulsar by apache.

the class NamespaceService method registerNamespace.

/**
 * Tried to registers a namespace to this instance
 *
 * @param namespace
 * @param ensureOwned
 * @return
 * @throws PulsarServerException
 * @throws Exception
 */
private boolean registerNamespace(String namespace, boolean ensureOwned) throws PulsarServerException {
    String myUrl = pulsar.getBrokerServiceUrl();
    try {
        NamespaceName nsname = NamespaceName.get(namespace);
        String otherUrl = null;
        NamespaceBundle nsFullBundle = null;
        // all pre-registered namespace is assumed to have bundles disabled
        nsFullBundle = bundleFactory.getFullBundle(nsname);
        // v2 namespace will always use full bundle object
        otherUrl = ownershipCache.tryAcquiringOwnership(nsFullBundle).get().getNativeUrl();
        if (myUrl.equals(otherUrl)) {
            if (nsFullBundle != null) {
                // preload heartbeat namespace
                pulsar.loadNamespaceTopics(nsFullBundle);
            }
            return true;
        }
        String msg = String.format("namespace already owned by other broker : ns=%s expected=%s actual=%s", namespace, myUrl, otherUrl);
        // ignore if not be owned for now
        if (!ensureOwned) {
            LOG.info(msg);
            return false;
        }
        // should not happen
        throw new IllegalStateException(msg);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new PulsarServerException(e);
    }
}
Also used : NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) ServiceUnitNotReadyException(org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) KeeperException(org.apache.zookeeper.KeeperException) PulsarServerException(org.apache.pulsar.broker.PulsarServerException)

Example 5 with PulsarServerException

use of org.apache.pulsar.broker.PulsarServerException in project incubator-pulsar by apache.

the class NamespaceService method searchForCandidateBroker.

private void searchForCandidateBroker(NamespaceBundle bundle, CompletableFuture<Optional<LookupResult>> lookupFuture, boolean authoritative) {
    String candidateBroker = null;
    try {
        // check if this is Heartbeat or SLAMonitor namespace
        candidateBroker = checkHeartbeatNamespace(bundle);
        if (candidateBroker == null) {
            String broker = getSLAMonitorBrokerName(bundle);
            // checking if the broker is up and running
            if (broker != null && isBrokerActive(broker)) {
                candidateBroker = broker;
            }
        }
        if (candidateBroker == null) {
            if (!this.loadManager.get().isCentralized() || pulsar.getLeaderElectionService().isLeader()) {
                Optional<String> availableBroker = getLeastLoadedFromLoadManager(bundle);
                if (!availableBroker.isPresent()) {
                    lookupFuture.complete(Optional.empty());
                    return;
                }
                candidateBroker = availableBroker.get();
            } else {
                if (authoritative) {
                    // leader broker already assigned the current broker as owner
                    candidateBroker = pulsar.getWebServiceAddress();
                } else {
                    // forward to leader broker to make assignment
                    candidateBroker = pulsar.getLeaderElectionService().getCurrentLeader().getServiceUrl();
                }
            }
        }
    } catch (Exception e) {
        LOG.warn("Error when searching for candidate broker to acquire {}: {}", bundle, e.getMessage(), e);
        lookupFuture.completeExceptionally(e);
        return;
    }
    try {
        checkNotNull(candidateBroker);
        if (pulsar.getWebServiceAddress().equals(candidateBroker)) {
            // Load manager decided that the local broker should try to become the owner
            ownershipCache.tryAcquiringOwnership(bundle).thenAccept(ownerInfo -> {
                if (ownerInfo.isDisabled()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Namespace bundle {} is currently being unloaded", bundle);
                    }
                    lookupFuture.completeExceptionally(new IllegalStateException(String.format("Namespace bundle %s is currently being unloaded", bundle)));
                } else {
                    // Found owner for the namespace bundle
                    // Schedule the task to pre-load topics
                    pulsar.loadNamespaceTopics(bundle);
                    lookupFuture.complete(Optional.of(new LookupResult(ownerInfo)));
                }
            }).exceptionally(exception -> {
                LOG.warn("Failed to acquire ownership for namespace bundle {}: ", bundle, exception.getMessage(), exception);
                lookupFuture.completeExceptionally(new PulsarServerException("Failed to acquire ownership for namespace bundle " + bundle, exception));
                return null;
            });
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Redirecting to broker {} to acquire ownership of bundle {}", candidateBroker, bundle);
            }
            // Now setting the redirect url
            createLookupResult(candidateBroker).thenAccept(lookupResult -> lookupFuture.complete(Optional.of(lookupResult))).exceptionally(ex -> {
                lookupFuture.completeExceptionally(ex);
                return null;
            });
        }
    } catch (Exception e) {
        LOG.warn("Error in trying to acquire namespace bundle ownership for {}: {}", bundle, e.getMessage(), e);
        lookupFuture.completeExceptionally(e);
    }
}
Also used : ServiceUnitNotReadyException(org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) URL(java.net.URL) AdminResource(org.apache.pulsar.broker.admin.AdminResource) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) LoadManager(org.apache.pulsar.broker.loadbalance.LoadManager) StringUtils(org.apache.commons.lang3.StringUtils) NamespaceBundles(org.apache.pulsar.common.naming.NamespaceBundles) NamespaceIsolationPolicies(org.apache.pulsar.common.policies.impl.NamespaceIsolationPolicies) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Matcher(java.util.regex.Matcher) Pair(org.apache.commons.lang3.tuple.Pair) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NamespaceOwnershipStatus(org.apache.pulsar.common.policies.data.NamespaceOwnershipStatus) Map(java.util.Map) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) URI(java.net.URI) NamespaceIsolationPolicy(org.apache.pulsar.common.policies.NamespaceIsolationPolicy) Set(java.util.Set) LocalPolicies(org.apache.pulsar.common.policies.data.LocalPolicies) PulsarWebResource.joinPath(org.apache.pulsar.broker.web.PulsarWebResource.joinPath) StatCallback(org.apache.zookeeper.AsyncCallback.StatCallback) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) NamespaceBundleFactory(org.apache.pulsar.common.naming.NamespaceBundleFactory) List(java.util.List) ServiceUnitId(org.apache.pulsar.common.naming.ServiceUnitId) NamespaceBundleFactory.getBundlesData(org.apache.pulsar.common.naming.NamespaceBundleFactory.getBundlesData) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Code(org.apache.zookeeper.KeeperException.Code) TopicName(org.apache.pulsar.common.naming.TopicName) LOCAL_POLICIES_ROOT(org.apache.pulsar.broker.cache.LocalZooKeeperCacheService.LOCAL_POLICIES_ROOT) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ResourceUnit(org.apache.pulsar.broker.loadbalance.ResourceUnit) Hashing(com.google.common.hash.Hashing) PulsarAdmin(org.apache.pulsar.client.admin.PulsarAdmin) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) Lists(com.google.common.collect.Lists) BundlesData(org.apache.pulsar.common.policies.data.BundlesData) ZooKeeperCache.cacheTimeOutInSec(org.apache.pulsar.zookeeper.ZooKeeperCache.cacheTimeOutInSec) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) LookupData(org.apache.pulsar.common.lookup.data.LookupData) PulsarService(org.apache.pulsar.broker.PulsarService) ServiceLookupData(org.apache.pulsar.policies.data.loadbalancer.ServiceLookupData) TimeUnit(java.util.concurrent.TimeUnit) LookupResult(org.apache.pulsar.broker.lookup.LookupResult) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) Codec(org.apache.pulsar.common.util.Codec) SECONDS(java.util.concurrent.TimeUnit.SECONDS) BrokerAssignment(org.apache.pulsar.common.policies.data.BrokerAssignment) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) LookupResult(org.apache.pulsar.broker.lookup.LookupResult) ServiceUnitNotReadyException(org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) KeeperException(org.apache.zookeeper.KeeperException) PulsarServerException(org.apache.pulsar.broker.PulsarServerException)

Aggregations

PulsarServerException (org.apache.pulsar.broker.PulsarServerException)21 KeeperException (org.apache.zookeeper.KeeperException)7 CompletableFuture (java.util.concurrent.CompletableFuture)6 NamespaceName (org.apache.pulsar.common.naming.NamespaceName)6 Policies (org.apache.pulsar.common.policies.data.Policies)5 IOException (java.io.IOException)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)3 ByteBuf (io.netty.buffer.ByteBuf)3 GeneralSecurityException (java.security.GeneralSecurityException)3 Map (java.util.Map)3 Set (java.util.Set)3 ServiceConfiguration (org.apache.pulsar.broker.ServiceConfiguration)3 NamespaceBundle (org.apache.pulsar.common.naming.NamespaceBundle)3 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)2 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 Optional (java.util.Optional)2 PositionImpl (org.apache.bookkeeper.mledger.impl.PositionImpl)2 StringUtils.isNotBlank (org.apache.commons.lang3.StringUtils.isNotBlank)2