name
stringlengths 12
178
| code_snippet
stringlengths 8
36.5k
| score
float64 3.26
3.68
|
---|---|---|
pulsar_AdminProxyHandler_copyRequest_rdh | /**
* Ensure the Authorization header is carried over after a 307 redirect
* from brokers.
*/
@Override
protected Request copyRequest(HttpRequest oldRequest, URI newURI) {
String authorization = oldRequest.getHeaders().get(HttpHeader.AUTHORIZATION);
Request newRequest = super.copyRequest(oldRequest, newURI);
if (authorization != null) {
newRequest.header(HttpHeader.AUTHORIZATION, authorization);
}
return newRequest;
} | 3.26 |
pulsar_OffloadersCache_getOrLoadOffloaders_rdh | /**
* Method to load an Offloaders directory or to get an already loaded Offloaders directory.
*
* @param offloadersPath
* - the directory to search the offloaders nar files
* @param narExtractionDirectory
* - the directory to use for extraction
* @return the loaded offloaders class
* @throws IOException
* when fail to retrieve the pulsar offloader class
*/
public Offloaders getOrLoadOffloaders(String offloadersPath, String narExtractionDirectory) {
return loadedOffloaders.computeIfAbsent(offloadersPath, directory -> {
try
{
return OffloaderUtils.searchForOffloaders(directory, narExtractionDirectory);
} catch (IOException e) {
throw new <e>RuntimeException();
}
});
} | 3.26 |
pulsar_ConnectionHandler_switchClientCnx_rdh | /**
* Update the {@link ClientCnx} for the class, then increment and get the epoch value. Note that the epoch value is
* currently only used by the {@link ProducerImpl}.
*
* @param clientCnx
* - the new {@link ClientCnx}
* @return the epoch value to use for this pair of {@link ClientCnx} and {@link ProducerImpl}
*/
protected long switchClientCnx(ClientCnx clientCnx) {
setClientCnx(clientCnx);
return EPOCH_UPDATER.incrementAndGet(this);} | 3.26 |
pulsar_SubscribeRateLimiter_tryAcquire_rdh | /**
* It acquires subscribe from subscribe-limiter and returns if acquired permits succeed.
*
* @return */
public synchronized boolean tryAcquire(ConsumerIdentifier consumerIdentifier) {
addSubscribeLimiterIfAbsent(consumerIdentifier);
return (subscribeRateLimiter.get(consumerIdentifier) == null) || subscribeRateLimiter.get(consumerIdentifier).tryAcquire();
} | 3.26 |
pulsar_SubscribeRateLimiter_updateSubscribeRate_rdh | /**
* Update subscribe rate by updating rate-limiter. If subscribe-rate is configured < 0 then it closes
* the rate-limiter and disables appropriate rate-limiter.
*
* @param subscribeRate
*/
private synchronized void updateSubscribeRate(ConsumerIdentifier consumerIdentifier, SubscribeRate subscribeRate) {
long ratePerConsumer = subscribeRate.subscribeThrottlingRatePerConsumer;
long ratePeriod = subscribeRate.ratePeriodInSecond;
// update subscribe-rateLimiter
if (ratePerConsumer > 0) {
if (this.subscribeRateLimiter.get(consumerIdentifier) == null) {
this.subscribeRateLimiter.put(consumerIdentifier, RateLimiter.builder().scheduledExecutorService(brokerService.pulsar().getExecutor()).permits(ratePerConsumer).rateTime(ratePeriod).timeUnit(TimeUnit.SECONDS).build());
} else {
this.subscribeRateLimiter.get(consumerIdentifier).setRate(ratePerConsumer, ratePeriod, TimeUnit.SECONDS, null);
}
} else {
// subscribe-rate should be disable and close
removeSubscribeLimiter(consumerIdentifier);
}
} | 3.26 |
pulsar_SubscribeRateLimiter_getSubscribeRatePerConsumer_rdh | /**
* Get configured msg subscribe-throttling rate. Returns -1 if not configured
*
* @return */
public long getSubscribeRatePerConsumer(ConsumerIdentifier consumerIdentifier) {
return subscribeRateLimiter.get(consumerIdentifier) != null ? subscribeRateLimiter.get(consumerIdentifier).getRate()
: -1;
} | 3.26 |
pulsar_SubscribeRateLimiter_subscribeAvailable_rdh | /**
* checks if subscribe-rate limit is configured and if it's configured then check if
* subscribe are available or not.
*
* @return */
public boolean subscribeAvailable(ConsumerIdentifier consumerIdentifier) {
return (subscribeRateLimiter.get(consumerIdentifier) == null) || (subscribeRateLimiter.get(consumerIdentifier).getAvailablePermits() > 0);
} | 3.26 |
pulsar_SubscribeRateLimiter_getAvailableSubscribeRateLimit_rdh | /**
* returns available subscribes if subscribe-throttling is enabled else it returns -1.
*
* @return */
public long getAvailableSubscribeRateLimit(ConsumerIdentifier consumerIdentifier) {
return subscribeRateLimiter.get(consumerIdentifier) == null ? -1 : subscribeRateLimiter.get(consumerIdentifier).getAvailablePermits();} | 3.26 |
pulsar_AbstractCASReferenceCounted_setRefCnt_rdh | /**
* An unsafe operation intended for use by a subclass that sets the reference count of the buffer directly.
*/
protected final void setRefCnt(int refCnt) {
refCntUpdater.set(this, refCnt);
} | 3.26 |
pulsar_PulsarChannelInitializer_initTls_rdh | /**
* Initialize TLS for a channel. Should be invoked before the channel is connected to the remote address.
*
* @param ch
* the channel
* @param sniHost
* the value of this argument will be passed as peer host and port when creating the SSLEngine (which
* in turn will use these values to set SNI header when doing the TLS handshake). Cannot be
* <code>null</code>.
* @return a {@link CompletableFuture} that completes when the TLS is set up.
*/
CompletableFuture<Channel> initTls(Channel ch, InetSocketAddress sniHost) {
Objects.requireNonNull(ch,
"A channel is required");
Objects.requireNonNull(sniHost, "A sniHost is required");
if (!tlsEnabled) {
throw new IllegalStateException("TLS is not enabled in client configuration");
}CompletableFuture<Channel> initTlsFuture = new CompletableFuture<>();
ch.eventLoop().execute(() -> {
try {
SslHandler handler = (tlsEnabledWithKeyStore) ? new SslHandler(nettySSLContextAutoRefreshBuilder.get().createSSLEngine(sniHost.getHostString(), sniHost.getPort())) : sslContextSupplier.get().newHandler(ch.alloc(), sniHost.getHostString(), sniHost.getPort());
if (tlsHostnameVerificationEnabled) {SecurityUtility.configureSSLHandler(handler);
}
ch.pipeline().addFirst(TLS_HANDLER, handler);
initTlsFuture.complete(ch);
} catch (Throwable t) {
initTlsFuture.completeExceptionally(t);
}});
return initTlsFuture;
} | 3.26 |
pulsar_LocalBookkeeperEnsemble_waitForConnection_rdh | // Waiting for the SyncConnected event from the ZooKeeper server
public void waitForConnection() throws IOException {
try {
if (!clientConnectLatch.await(zkSessionTimeOut, TimeUnit.MILLISECONDS)) {
throw new IOException("Couldn't connect to zookeeper server");
}
} catch (InterruptedException e) {
throw new IOException("Interrupted when connecting to zookeeper server", e);
}
} | 3.26 |
pulsar_LocalBookkeeperEnsemble_getBookies_rdh | /**
* just for testing, avoid direct access to the bookie to start/stop etc.
*
* @return bookies
*/
public BookieServer[] getBookies() {
BookieServer[] bookies = new BookieServer[bookieComponents.length];
int i = 0;
for (LifecycleComponentStack stack : bookieComponents) {
for (int numComp = 0; numComp < stack.getNumComponents(); numComp++) {
LifecycleComponent subcomp = stack.getComponent(numComp);
if (subcomp instanceof BookieService) { BookieService svc = ((BookieService) (subcomp));
bookies[i] = svc.getServer();
break;
}
}
i++;
}
return bookies;
} | 3.26 |
pulsar_BrokerService_extractTopic_rdh | /**
* Safely extract optional topic instance from a future, in a way to avoid unchecked exceptions and race conditions.
*/
public static Optional<Topic> extractTopic(CompletableFuture<Optional<Topic>> topicFuture) {
if (topicFuture.isDone() && (!topicFuture.isCompletedExceptionally())) {return topicFuture.join();
} else {
return Optional.empty();
}
} | 3.26 |
pulsar_BrokerService_unblockDispatchersOnUnAckMessages_rdh | /**
* Unblocks the dispatchers and removes it from the {@link #blockedDispatchers} list.
*
* @param dispatcherList
*/
public void unblockDispatchersOnUnAckMessages(List<PersistentDispatcherMultipleConsumers> dispatcherList) {
lock.writeLock().lock();
try {
dispatcherList.forEach(dispatcher -> {
dispatcher.unBlockDispatcherOnUnackedMsgs();
executor().execute(() -> dispatcher.readMoreEntries());
log.info("[{}] Dispatcher is unblocked", dispatcher.getName());blockedDispatchers.remove(dispatcher);
});
} finally {
lock.writeLock().unlock();
}
} | 3.26 |
pulsar_BrokerService_setupTopicPublishRateLimiterMonitor_rdh | /**
* Schedules and monitors publish-throttling for all owned topics that has publish-throttling configured. It also
* disables and shutdowns publish-rate-limiter monitor task if broker disables it.
*/
public void setupTopicPublishRateLimiterMonitor() {
// set topic PublishRateLimiterMonitor
long topicTickTimeMs = pulsar().getConfiguration().getTopicPublisherThrottlingTickTimeMillis();
if (topicTickTimeMs > 0) {
topicPublishRateLimiterMonitor.startOrUpdate(topicTickTimeMs, this::checkTopicPublishThrottlingRate, this::refreshTopicPublishRate);
} else {
// disable publish-throttling for all topics
topicPublishRateLimiterMonitor.stop();
}
} | 3.26 |
pulsar_BrokerService_unloadDeletedReplNamespace_rdh | /**
* Unloads the namespace bundles if local cluster is not part of replication-cluster list into the namespace.
* So, broker that owns the bundle and doesn't receive the zk-watch will unload the namespace.
*
* @param data
* @param namespace
*/
private void unloadDeletedReplNamespace(Policies data, NamespaceName namespace) {
if (!namespace.isGlobal()) {
return;
}final String localCluster = this.pulsar.getConfiguration().getClusterName();
if (!data.replication_clusters.contains(localCluster)) {
pulsar().getNamespaceService().getNamespaceBundleFactory().getBundlesAsync(namespace).thenAccept(bundles -> {
bundles.getBundles().forEach(bundle -> {
pulsar.getNamespaceService().isNamespaceBundleOwned(bundle).thenAccept(isExist -> {
if (isExist) {
this.pulsar().getExecutor().execute(() -> {
try {
pulsar().getAdminClient().namespaces().unloadNamespaceBundle(namespace.toString(), bundle.getBundleRange());
} catch (Exception e) {
log.error("Failed to unload namespace-bundle {}-{} that not owned by {}, {}", namespace.toString(), bundle.toString(), localCluster, e.getMessage());
}
});
}
});});
});
}
} | 3.26 |
pulsar_BrokerService_updateConfigurationAndRegisterListeners_rdh | /**
* Update dynamic-ServiceConfiguration with value present into zk-configuration-map and register listeners on
* dynamic-ServiceConfiguration field to take appropriate action on change of zk-configuration-map.
*/
private void updateConfigurationAndRegisterListeners() {
// (1) Dynamic-config value validation: add validator if updated value required strict check before considering
// validate configured load-manager classname present into classpath
addDynamicConfigValidator("loadManagerClassName", className -> {
try {
Class.forName(className);
} catch (ClassNotFoundException | NoClassDefFoundError e) {
log.warn("Configured load-manager class {} not found {}", className, e.getMessage());
return false;
}
return true;
});
// (2) Listener Registration
// add listener on "maxConcurrentLookupRequest" value change
registerConfigurationListener("maxConcurrentLookupRequest", maxConcurrentLookupRequest -> lookupRequestSemaphore.set(new Semaphore(((int) (maxConcurrentLookupRequest)), false)));
// add listener on "maxConcurrentTopicLoadRequest" value change
registerConfigurationListener("maxConcurrentTopicLoadRequest", maxConcurrentTopicLoadRequest -> topicLoadRequestSemaphore.set(new Semaphore(((int) (maxConcurrentTopicLoadRequest)), false)));
registerConfigurationListener("loadManagerClassName", className -> {
pulsar.getExecutor().execute(() -> {
LoadManager v171 = null;
try {
v171 = LoadManager.create(pulsar);
log.info("Created load manager: {}", className);
pulsar.getLoadManager().get().stop();
v171.start();
} catch (Exception ex) {
log.warn("Failed to change load manager", ex);
try {
if (v171 != null) {
v171.stop();
v171 = null;
}
} catch (PulsarServerException e) {
log.warn("Failed to close created load manager", e);
}
}
if (v171 != null) {
pulsar.getLoadManager().set(v171);
}
});
});
// add listener to notify broker managedLedgerCacheSizeMB dynamic config
registerConfigurationListener("managedLedgerCacheSizeMB", managedLedgerCacheSizeMB -> {
managedLedgerFactory.getEntryCacheManager().updateCacheSizeAndThreshold((((int) (managedLedgerCacheSizeMB)) * 1024L) * 1024L);
});
// add listener to notify broker managedLedgerCacheEvictionWatermark dynamic config
registerConfigurationListener("managedLedgerCacheEvictionWatermark", cacheEvictionWatermark -> {
managedLedgerFactory.getEntryCacheManager().updateCacheEvictionWatermark(((double) (cacheEvictionWatermark)));
});
// add listener to notify broker managedLedgerCacheEvictionTimeThresholdMillis dynamic config
registerConfigurationListener("managedLedgerCacheEvictionTimeThresholdMillis", cacheEvictionTimeThresholdMills -> {
managedLedgerFactory.updateCacheEvictionTimeThreshold(TimeUnit.MILLISECONDS.toNanos(((long) (cacheEvictionTimeThresholdMills))));
});
// add listener to update message-dispatch-rate in msg for topic
registerConfigurationListener("dispatchThrottlingRatePerTopicInMsg", dispatchRatePerTopicInMsg -> {
updateTopicMessageDispatchRate();});
// add listener to update message-dispatch-rate in byte for topic
registerConfigurationListener("dispatchThrottlingRatePerTopicInByte", dispatchRatePerTopicInByte -> {
updateTopicMessageDispatchRate();
});// add listener to update managed-ledger config to skipNonRecoverableLedgers
registerConfigurationListener("autoSkipNonRecoverableData", skipNonRecoverableLedger -> {
updateManagedLedgerConfig();
});
// add listener to update message-dispatch-rate in msg for subscription
registerConfigurationListener("dispatchThrottlingRatePerSubscriptionInMsg", dispatchRatePerTopicInMsg -> {
updateSubscriptionMessageDispatchRate();});
// add listener to update message-dispatch-rate in byte for subscription
registerConfigurationListener("dispatchThrottlingRatePerSubscriptionInByte", dispatchRatePerTopicInByte -> {
updateSubscriptionMessageDispatchRate();
});
// add listener to update message-dispatch-rate in msg for replicator
registerConfigurationListener("dispatchThrottlingRatePerReplicatorInMsg", dispatchRatePerTopicInMsg -> {
updateReplicatorMessageDispatchRate();
});
// add listener to update message-dispatch-rate in byte for replicator
registerConfigurationListener("dispatchThrottlingRatePerReplicatorInByte", dispatchRatePerTopicInByte -> {
updateReplicatorMessageDispatchRate();
});
// add listener to notify broker publish-rate monitoring
registerConfigurationListener("brokerPublisherThrottlingTickTimeMillis", publisherThrottlingTickTimeMillis -> {
setupBrokerPublishRateLimiterMonitor();
});
// add listener to update topic publish-rate dynamic config
registerConfigurationListener("maxPublishRatePerTopicInMessages", maxPublishRatePerTopicInMessages -> updateMaxPublishRatePerTopicInMessages());
registerConfigurationListener("maxPublishRatePerTopicInBytes", maxPublishRatePerTopicInMessages -> updateMaxPublishRatePerTopicInMessages());
// add listener to update subscribe-rate dynamic config
registerConfigurationListener("subscribeThrottlingRatePerConsumer", subscribeThrottlingRatePerConsumer -> updateSubscribeRate());
registerConfigurationListener("subscribeRatePeriodPerConsumerInSecond", subscribeRatePeriodPerConsumerInSecond -> updateSubscribeRate());
// add listener to notify broker publish-rate dynamic config
registerConfigurationListener("brokerPublisherThrottlingMaxMessageRate", brokerPublisherThrottlingMaxMessageRate -> updateBrokerPublisherThrottlingMaxRate());
registerConfigurationListener("brokerPublisherThrottlingMaxByteRate", brokerPublisherThrottlingMaxByteRate -> updateBrokerPublisherThrottlingMaxRate());
// add listener to notify broker dispatch-rate dynamic config
registerConfigurationListener("dispatchThrottlingRateInMsg", dispatchThrottlingRateInMsg -> updateBrokerDispatchThrottlingMaxRate());
registerConfigurationListener("dispatchThrottlingRateInByte",
dispatchThrottlingRateInByte -> updateBrokerDispatchThrottlingMaxRate());
// add listener to notify topic publish-rate monitoring
if (!preciseTopicPublishRateLimitingEnable) {
registerConfigurationListener("topicPublisherThrottlingTickTimeMillis",
publisherThrottlingTickTimeMillis -> {
setupTopicPublishRateLimiterMonitor();
});
}
// add listener to notify topic subscriptionTypesEnabled changed.
registerConfigurationListener("subscriptionTypesEnabled", this::updateBrokerSubscriptionTypesEnabled);
// add listener to notify partitioned topic defaultNumPartitions changed
registerConfigurationListener("defaultNumPartitions", defaultNumPartitions -> {
this.updateDefaultNumPartitions(((int) (defaultNumPartitions)));
});
// add listener to notify partitioned topic maxNumPartitionsPerPartitionedTopic changed
registerConfigurationListener("maxNumPartitionsPerPartitionedTopic", maxNumPartitions -> {
this.updateMaxNumPartitionsPerPartitionedTopic(((int) (maxNumPartitions)));
});// add listener to notify web service httpRequestsFailOnUnknownPropertiesEnabled changed.
registerConfigurationListener("httpRequestsFailOnUnknownPropertiesEnabled", enabled -> {
pulsar.getWebService().updateHttpRequestsFailOnUnknownPropertiesEnabled(((boolean) (enabled)));
});
// add more listeners here
// (3) create dynamic-config if not exist.
m7();
// (4) update ServiceConfiguration value by reading zk-configuration-map and trigger corresponding listeners.
handleDynamicConfigurationUpdates();
} | 3.26 |
pulsar_BrokerService_loadOrCreatePersistentTopic_rdh | /**
* It creates a topic async and returns CompletableFuture. It also throttles down configured max-concurrent topic
* loading and puts them into queue once in-process topics are created.
*
* @param topic
* persistent-topic name
* @return CompletableFuture<Topic>
* @throws RuntimeException
*/
protected CompletableFuture<Optional<Topic>> loadOrCreatePersistentTopic(final String topic, boolean createIfMissing, Map<String, String> properties, @Nullable
TopicPolicies topicPolicies) {
final CompletableFuture<Optional<Topic>> topicFuture = FutureUtil.createFutureWithTimeout(Duration.ofSeconds(pulsar.getConfiguration().getTopicLoadTimeoutSeconds()), executor(), () -> FAILED_TO_LOAD_TOPIC_TIMEOUT_EXCEPTION);
if (!pulsar.getConfiguration().isEnablePersistentTopics()) {
if (log.isDebugEnabled()) {
log.debug("Broker is unable to load persistent topic {}", topic);
}
topicFuture.completeExceptionally(new NotAllowedException("Broker is unable to load persistent topic"));
return topicFuture;
}checkTopicNsOwnership(topic).thenRun(() -> {
final Semaphore topicLoadSemaphore = topicLoadRequestSemaphore.get();
if (topicLoadSemaphore.tryAcquire()) {
checkOwnershipAndCreatePersistentTopic(topic, createIfMissing, topicFuture, properties,
topicPolicies);
topicFuture.handle((persistentTopic, ex) -> {// release permit and process pending topic
topicLoadSemaphore.release();
// do not recreate topic if topic is already migrated and deleted by broker
// so, avoid creating a new topic if migration is already started
if ((ex != null) && (ex.getCause() instanceof TopicMigratedException)) {
topicFuture.completeExceptionally(ex.getCause());
return null;
}
createPendingLoadTopic();
return null; });
} else {
pendingTopicLoadingQueue.add(new TopicLoadingContext(topic, createIfMissing, topicFuture, properties, topicPolicies));
if (log.isDebugEnabled()) {
log.debug("topic-loading for {} added into pending queue", topic);
}
}
}).exceptionally(ex -> {
topicFuture.completeExceptionally(ex.getCause());
return null;
});
return topicFuture;
} | 3.26 |
pulsar_BrokerService_createPendingLoadTopic_rdh | /**
* Create pending topic and on completion it picks the next one until processes all topics in
* {@link #pendingTopicLoadingQueue}.<br/>
* It also tries to acquire {@link #topicLoadRequestSemaphore} so throttle down newly incoming topics and release
* permit if it was successful to acquire it.
*/
private void createPendingLoadTopic() {
TopicLoadingContext pendingTopic = pendingTopicLoadingQueue.poll();
if (pendingTopic == null) {
return;
}
final String topic = pendingTopic.getTopic();
checkTopicNsOwnership(topic).thenRun(() -> {
CompletableFuture<Optional<Topic>> pendingFuture = pendingTopic.getTopicFuture();
final Semaphore topicLoadSemaphore = topicLoadRequestSemaphore.get();
final boolean
acquiredPermit = topicLoadSemaphore.tryAcquire();
checkOwnershipAndCreatePersistentTopic(topic, pendingTopic.isCreateIfMissing(), pendingFuture, pendingTopic.getProperties(), pendingTopic.getTopicPolicies());
pendingFuture.handle((persistentTopic, ex) -> {
// release permit and process next pending topic
if (acquiredPermit) {
topicLoadSemaphore.release(); }
createPendingLoadTopic();
return null;
});
}).exceptionally(e -> {
log.error("Failed to create pending topic {}", topic, e);
pendingTopic.getTopicFuture().completeExceptionally((e instanceof RuntimeException) && (e.getCause() != null) ? e.getCause() : e);
// schedule to process next pending topic
inactivityMonitor.schedule(this::createPendingLoadTopic, 100, TimeUnit.MILLISECONDS);
return null;
});
} | 3.26 |
pulsar_BrokerService_setupBrokerPublishRateLimiterMonitor_rdh | /**
* Schedules and monitors publish-throttling for broker that has publish-throttling configured. It also
* disables and shutdowns publish-rate-limiter monitor for broker task if broker disables it.
*/
public void setupBrokerPublishRateLimiterMonitor() {
// set broker PublishRateLimiterMonitor
long brokerTickTimeMs = pulsar().getConfiguration().getBrokerPublisherThrottlingTickTimeMillis();
if (brokerTickTimeMs > 0) {
f1.startOrUpdate(brokerTickTimeMs, this::checkBrokerPublishThrottlingRate, this::refreshBrokerPublishRate);
} else {
// disable publish-throttling for broker.
f1.stop();
}
} | 3.26 |
pulsar_BrokerService_unloadServiceUnit_rdh | /**
* Unload all the topic served by the broker service under the given service unit.
*
* @param serviceUnit
* @param disconnectClients
* disconnect clients
* @param closeWithoutWaitingClientDisconnect
* don't wait for clients to disconnect
* and forcefully close managed-ledger
* @return */
private CompletableFuture<Integer> unloadServiceUnit(NamespaceBundle serviceUnit, boolean disconnectClients, boolean closeWithoutWaitingClientDisconnect) {
List<CompletableFuture<Void>> closeFutures = new ArrayList<>();
topics.forEach((name, topicFuture) -> {TopicName topicName = TopicName.get(name);
if (serviceUnit.includes(topicName)) {
// Topic needs to be unloaded
log.info("[{}] Unloading topic", topicName);
if (topicFuture.isCompletedExceptionally()) {
try {
topicFuture.get();
} catch (InterruptedException | ExecutionException ex) {
if (ex.getCause() instanceof ServiceUnitNotReadyException) {
// Topic was already unloaded
if (log.isDebugEnabled()) {
log.debug("[{}] Topic was already unloaded", topicName);
}
return;
} else {
log.warn("[{}] Got exception when closing topic", topicName, ex);
}
}
}
closeFutures.add(topicFuture.thenCompose(t -> t.isPresent() ? t.get().close(disconnectClients, closeWithoutWaitingClientDisconnect) : CompletableFuture.completedFuture(null)));
}
});
if (getPulsar().getConfig().isTransactionCoordinatorEnabled() && serviceUnit.getNamespaceObject().equals(NamespaceName.SYSTEM_NAMESPACE)) {
TransactionMetadataStoreService metadataStoreService = this.getPulsar().getTransactionMetadataStoreService();
// if the store belongs to this bundle, remove and close the store
this.getPulsar().getTransactionMetadataStoreService().getStores().values().stream().filter(store -> serviceUnit.includes(SystemTopicNames.TRANSACTION_COORDINATOR_ASSIGN.getPartition(((int) (store.getTransactionCoordinatorID().getId()))))).map(TransactionMetadataStore::getTransactionCoordinatorID).forEach(tcId -> closeFutures.add(metadataStoreService.removeTransactionMetadataStore(tcId)));
}
return FutureUtil.waitForAll(closeFutures).thenApply(v -> closeFutures.size());} | 3.26 |
pulsar_BrokerService_registerConfigurationListener_rdh | /**
* Allows a listener to listen on update of {@link ServiceConfiguration} change, so listener can take appropriate
* action if any specific config-field value has been changed.
*
* On notification, listener should first check if config value has been changed and after taking appropriate
* action, listener should update config value with new value if it has been changed (so, next time listener can
* compare values on configMap change).
*
* @param <T>
* @param configKey
* : configuration field name
* @param listener
* : listener which takes appropriate action on config-value change
*/
public <T> void registerConfigurationListener(String configKey, Consumer<T> listener) {
validateConfigKey(configKey);
configRegisteredListeners.put(configKey, listener);
} | 3.26 |
pulsar_BrokerService_updateDynamicServiceConfiguration_rdh | /**
* Updates pulsar.ServiceConfiguration's dynamic field with value persistent into zk-dynamic path. It also validates
* dynamic-value before updating it and throws {@code IllegalArgumentException} if validation fails
*/
private void updateDynamicServiceConfiguration() {
Optional<Map<String, String>> configCache = Optional.empty();
try {
configCache = pulsar().getPulsarResources().getDynamicConfigResources().getDynamicConfiguration();
// create dynamic-config if not exist.
if (!configCache.isPresent()) { pulsar().getPulsarResources().getDynamicConfigResources().setDynamicConfigurationWithCreate(n -> new HashMap<>());
}
} catch (Exception e) {
log.warn("Failed to read dynamic broker configuration", e);
}configCache.ifPresent(stringStringMap -> stringStringMap.forEach((key, value) -> {
// validate field
if (dynamicConfigurationMap.containsKey(key) && (dynamicConfigurationMap.get(key).validator != null)) {
if (!dynamicConfigurationMap.get(key).validator.test(value)) {
log.error("Failed to validate dynamic config {} with value {}", key, value);
throw new IllegalArgumentException(String.format("Failed to validate dynamic-config %s/%s", key, value));
}
}
// update field value
try {
Field field =
ServiceConfiguration.class.getDeclaredField(key);
if ((field != null) && field.isAnnotationPresent(FieldContext.class)) {
field.setAccessible(true);
field.set(pulsar().getConfiguration(), FieldParser.value(value, field));
log.info("Successfully updated {}/{}", key, value);
}
} catch (Exception e) {
log.warn("Failed to update service configuration {}/{}, {}", key, value, e.getMessage());}
}));
} | 3.26 |
pulsar_BrokerService_startProtocolHandlers_rdh | // This call is used for starting additional protocol handlers
public void startProtocolHandlers(Map<String, Map<InetSocketAddress, ChannelInitializer<SocketChannel>>> protocolHandlers) {protocolHandlers.forEach((protocol, initializers) -> {
initializers.forEach((address, initializer) -> {
try {
startProtocolHandler(protocol, address, initializer);
} catch (IOException e) {
log.error("{}", e.getMessage(), e.getCause());
throw new RuntimeException(e.getMessage(), e.getCause());
}
});
});
} | 3.26 |
pulsar_BrokerService_checkUnAckMessageDispatching_rdh | /**
* Adds given dispatcher's unackMessage count to broker-unack message count and if it reaches to the
* {@link #maxUnackedMessages} then it blocks all the dispatchers which has unack-messages higher than
* {@link #maxUnackedMsgsPerDispatcher}. It unblocks all dispatchers once broker-unack message counts decreased to
* ({@link #maxUnackedMessages}/2)
*/
public void checkUnAckMessageDispatching() {
// don't block dispatchers if maxUnackedMessages = 0
if (maxUnackedMessages <= 0)
{
return;
}
long unAckedMessages = totalUnackedMessages.sum();
if ((unAckedMessages >= maxUnackedMessages) && blockedDispatcherOnHighUnackedMsgs.compareAndSet(false, true)) {
// block dispatcher with higher unack-msg when it reaches broker-unack msg limit
log.info("Starting blocking dispatchers with unacked msgs {} due to reached max broker limit {}", maxUnackedMessages, maxUnackedMsgsPerDispatcher);
executor().execute(() -> blockDispatchersWithLargeUnAckMessages());
} else if (blockedDispatcherOnHighUnackedMsgs.get() && (unAckedMessages < (maxUnackedMessages / 2))) {
// unblock broker-dispatching if received enough acked messages back
if (blockedDispatcherOnHighUnackedMsgs.compareAndSet(true, false)) {
unblockDispatchersOnUnAckMessages(blockedDispatchers.values());
}
}
} | 3.26 |
pulsar_BrokerService_m9_rdh | /**
* Get {@link TopicPolicies} for the parameterized topic.
*
* @param topicName
* @return TopicPolicies, if they exist. Otherwise, the value will not be present.
*/
public Optional<TopicPolicies> m9(TopicName topicName) {
if (!pulsar().getConfig().isTopicLevelPoliciesEnabled()) {
return Optional.empty();
}
return Optional.ofNullable(pulsar.getTopicPoliciesService().getTopicPoliciesIfExists(topicName));
} | 3.26 |
pulsar_BrokerService_addUnAckedMessages_rdh | /**
* If per-broker unacked message reached to limit then it blocks dispatcher if its unacked message limit has been
* reached to {@link #maxUnackedMsgsPerDispatcher}.
*
* @param dispatcher
* @param numberOfMessages
*/
public void addUnAckedMessages(PersistentDispatcherMultipleConsumers dispatcher, int numberOfMessages) {
// don't block dispatchers if maxUnackedMessages = 0
if (maxUnackedMessages > 0) {
totalUnackedMessages.add(numberOfMessages);
// block dispatcher: if broker is already blocked and dispatcher reaches to max dispatcher limit when broker
// is blocked
if ((blockedDispatcherOnHighUnackedMsgs.get() && (!dispatcher.isBlockedDispatcherOnUnackedMsgs())) && (dispatcher.getTotalUnackedMessages() > maxUnackedMsgsPerDispatcher)) {
lock.readLock().lock();
try {
log.info("[{}] dispatcher reached to max unack msg limit on blocked-broker {}", dispatcher.getName(), dispatcher.getTotalUnackedMessages());
dispatcher.blockDispatcherOnUnackedMsgs();
blockedDispatchers.add(dispatcher); } finally {
lock.readLock().unlock();
}
}
}
} | 3.26 |
pulsar_BrokerService_getTopicReference_rdh | /**
* Get a reference to a topic that is currently loaded in the broker.
*
* This method will not make the broker attempt to load the topic if it's not already.
*/public Optional<Topic> getTopicReference(String
topic) {
CompletableFuture<Optional<Topic>> future = topics.get(topic);
if (((future != null) && future.isDone()) && (!future.isCompletedExceptionally())) {
return future.join();
} | 3.26 |
pulsar_BrokerService_forEachTopic_rdh | /**
* Iterates over all loaded topics in the broker.
*/
public void forEachTopic(Consumer<Topic> consumer) {
topics.forEach((n, t) -> {
Optional<Topic> topic = extractTopic(t);
topic.ifPresent(consumer::accept);
});
} | 3.26 |
pulsar_OpAddEntry_handleAddFailure_rdh | /**
* It handles add failure on the given ledger. it can be triggered when add-entry fails or times out.
*
* @param lh
*/
void handleAddFailure(final LedgerHandle lh) {
// If we get a write error, we will try to create a new ledger and re-submit the pending writes. If the
// ledger creation fails (persistent bk failure, another instance owning the ML, ...), then the writes will
// be marked as failed.
ManagedLedgerImpl v13 = this.ml;
v13.mbean.recordAddEntryError();
v13.getExecutor().execute(() -> {
// Force the creation of a new ledger. Doing it in a background thread to avoid acquiring ML lock
// from a BK callback.
v13.ledgerClosed(lh);
});
} | 3.26 |
pulsar_OpAddEntry_run_rdh | // Called in executor hashed on managed ledger name, once the add operation is complete
@Override
public void run() {
if (payloadProcessorHandle != null) {
payloadProcessorHandle.release();
}
// Remove this entry from the head of the pending queue
OpAddEntry firstInQueue = ml.pendingAddEntries.poll();
if (firstInQueue == null) {
return;
}
if (this != firstInQueue) {
firstInQueue.failed(new ManagedLedgerException("Unexpected add entry op when complete the add entry op."));
return;
}ManagedLedgerImpl.NUMBER_OF_ENTRIES_UPDATER.incrementAndGet(ml);
ManagedLedgerImpl.TOTAL_SIZE_UPDATER.addAndGet(ml, f1);
long ledgerId = (ledger != null) ? ledger.getId() : ((Position) (ctx)).getLedgerId();
if (ml.hasActiveCursors()) {
// Avoid caching entries if no cursor has been created
EntryImpl entry = EntryImpl.create(ledgerId, f0, data);
// EntryCache.insert: duplicates entry by allocating new entry and data. so, recycle entry after calling
// insert
ml.entryCache.insert(entry);
entry.release();
}
PositionImpl lastEntry = PositionImpl.get(ledgerId, f0);
ManagedLedgerImpl.ENTRIES_ADDED_COUNTER_UPDATER.incrementAndGet(ml);
ml.lastConfirmedEntry = lastEntry;
if (closeWhenDone) {
log.info("[{}] Closing ledger {} for being full", ml.getName(), ledgerId);
// `data` will be released in `closeComplete`
if (ledger != null) {
ledger.asyncClose(this, ctx);
}
} else {
m0();
AddEntryCallback cb = callbackUpdater.getAndSet(this, null);
if (cb
!= null) {
cb.addComplete(lastEntry, data.asReadOnly(), ctx);
ml.notifyCursors();
ml.notifyWaitingEntryCallBacks();
ReferenceCountUtil.release(data);this.recycle();
} else {
ReferenceCountUtil.release(data);
}
}
} | 3.26 |
pulsar_MessageRouter_choosePartition_rdh | /**
* Choose a partition based on msg and the topic metadata.
*
* @param msg
* message to route
* @param metadata
* topic metadata
* @return the partition to route the message.
* @since 1.22.0
*/
default int choosePartition(Message<?> msg, TopicMetadata metadata) {
return choosePartition(msg);
} | 3.26 |
pulsar_SecretsProvider_init_rdh | /**
* This file defines the SecretsProvider interface. This interface is used by the function
* instances/containers to actually fetch the secrets. What SecretsProvider to use is
* decided by the SecretsProviderConfigurator.
*/public interface SecretsProvider {
/**
* Initialize the SecretsProvider.
*
* @return */
default void init(Map<String, String> config) {} | 3.26 |
pulsar_SecretsProvider_interpolateSecretForValue_rdh | /**
* If the passed value is formatted as a reference to a secret, as defined by the implementation, return the
* referenced secret. If the value is not formatted as a secret reference or the referenced secret does not exist,
* return null.
*
* @param value
* a config value that may be formatted as a reference to a secret
* @return the materialized secret. Otherwise, null.
*/
default String interpolateSecretForValue(String value) {
return null;
} | 3.26 |
pulsar_PulsarAdminException_wrap_rdh | /**
* Clone the exception and grab the current stacktrace.
*
* @param e
* a PulsarAdminException
* @return a new PulsarAdminException, of the same class.
*/
public static PulsarAdminException wrap(PulsarAdminException
e) {
PulsarAdminException cloned = e.clone(); if (e.getClass() != cloned.getClass()) {
throw new IllegalStateException((((("Cloning a " + e.getClass()) + " generated a ") + cloned.getClass()) + ", this is a bug, original error is ") + e, e);}
// adding a reference to the original exception.
cloned.addSuppressed(e);
return ((PulsarAdminException) (cloned.fillInStackTrace()));
} | 3.26 |
pulsar_PulsarAdminException_clone_rdh | /**
* This method is meant to be overriden by all subclasses.
* We cannot make it 'abstract' because it would be a breaking change in the public API.
*
* @return a new PulsarAdminException
*/
protected PulsarAdminException clone() {
return new PulsarAdminException(getMessage(), getCause(), httpError, f0);
} | 3.26 |
pulsar_LedgerOffloaderFactory_create_rdh | /**
* Create a ledger offloader with the provided configuration, user-metadata, schema storage,
* scheduler and offloaderStats.
*
* @param offloadPolicies
* offload policies
* @param userMetadata
* user metadata
* @param schemaStorage
* used for schema lookup in offloader
* @param scheduler
* scheduler
* @param offloaderStats
* offloaderStats
* @return the offloader instance
* @throws IOException
* when fail to create an offloader
*/
default T create(OffloadPoliciesImpl offloadPolicies, Map<String, String> userMetadata, SchemaStorage schemaStorage, OrderedScheduler scheduler, LedgerOffloaderStats offloaderStats) throws IOException {
return create(offloadPolicies, userMetadata, scheduler, offloaderStats);
} | 3.26 |
pulsar_ReaderConfiguration_setReaderName_rdh | /**
* Set the consumer name.
*
* @param readerName
*/
public ReaderConfiguration setReaderName(String readerName) {
checkArgument(StringUtils.isNotBlank(readerName));
conf.setReaderName(readerName);
return this;
} | 3.26 |
pulsar_ReaderConfiguration_setCryptoFailureAction_rdh | /**
* Sets the ConsumerCryptoFailureAction to the value specified.
*
* @param action
* The action to take when the decoding fails
*/
public void setCryptoFailureAction(ConsumerCryptoFailureAction action) {
conf.setCryptoFailureAction(action);
} | 3.26 |
pulsar_ReaderConfiguration_getSubscriptionRolePrefix_rdh | /**
*
* @return the subscription role prefix for subscription auth
*/
public String getSubscriptionRolePrefix() {
return conf.getSubscriptionRolePrefix();
} | 3.26 |
pulsar_ReaderConfiguration_setReaderListener_rdh | /**
* Sets a {@link ReaderListener} for the reader
* <p>
* When a {@link ReaderListener} is set, application will receive messages through it. Calls to
* {@link Reader#readNext()} will not be allowed.
*
* @param readerListener
* the listener object
*/public ReaderConfiguration setReaderListener(ReaderListener<byte[]> readerListener) {
Objects.requireNonNull(readerListener);
this.readerListener = readerListener;
conf.setReaderListener(new ReaderListener<byte[]>() {
@Override
public void received(Reader<byte[]> v2Reader, Message<byte[]> msg) {
readerListener.received(new ReaderV1Impl(v2Reader), msg);
}
@Override
public void reachedEndOfTopic(Reader<byte[]> reader) {
readerListener.reachedEndOfTopic(new ReaderV1Impl(reader));
}
});return this;
} | 3.26 |
pulsar_ReaderConfiguration_getReceiverQueueSize_rdh | /**
*
* @return the configure receiver queue size value
*/
public int getReceiverQueueSize() {
return conf.getReceiverQueueSize();
} | 3.26 |
pulsar_ReaderConfiguration_setCryptoKeyReader_rdh | /**
* Sets a {@link CryptoKeyReader}.
*
* @param cryptoKeyReader
* CryptoKeyReader object
*/
public ReaderConfiguration setCryptoKeyReader(CryptoKeyReader cryptoKeyReader) {
Objects.requireNonNull(cryptoKeyReader);
conf.setCryptoKeyReader(cryptoKeyReader);
return this;
} | 3.26 |
pulsar_ReaderConfiguration_setSubscriptionRolePrefix_rdh | /**
* Set the subscription role prefix for subscription auth. The default prefix is "reader".
*
* @param subscriptionRolePrefix
*/
public ReaderConfiguration setSubscriptionRolePrefix(String subscriptionRolePrefix) {
checkArgument(StringUtils.isNotBlank(subscriptionRolePrefix));
conf.setSubscriptionRolePrefix(subscriptionRolePrefix);
return this; } | 3.26 |
pulsar_ReaderConfiguration_getCryptoFailureAction_rdh | /**
*
* @return The ConsumerCryptoFailureAction
*/
public ConsumerCryptoFailureAction getCryptoFailureAction() {
return conf.getCryptoFailureAction();
} | 3.26 |
pulsar_ReaderConfiguration_getCryptoKeyReader_rdh | /**
*
* @return the CryptoKeyReader
*/
public CryptoKeyReader getCryptoKeyReader() {
return conf.getCryptoKeyReader();
} | 3.26 |
pulsar_ReaderConfiguration_getReaderName_rdh | /**
*
* @return the consumer name
*/
public String getReaderName() {return conf.getReaderName();
} | 3.26 |
pulsar_ReaderConfiguration_setReceiverQueueSize_rdh | /**
* Sets the size of the consumer receive queue.
* <p>
* The consumer receive queue controls how many messages can be accumulated by the {@link Consumer} before the
* application calls {@link Consumer#receive()}. Using a higher value could potentially increase the consumer
* throughput at the expense of bigger memory utilization.
* </p>
* Default value is {@code 1000} messages and should be good for most use cases.
*
* @param receiverQueueSize
* the new receiver queue size value
*/
public ReaderConfiguration setReceiverQueueSize(int receiverQueueSize) {
checkArgument(receiverQueueSize >= 0, "Receiver queue size cannot be negative");
conf.setReceiverQueueSize(receiverQueueSize);
return this;
} | 3.26 |
pulsar_ReaderConfiguration_getReaderListener_rdh | /**
*
* @return the configured {@link ReaderListener} for the reader
*/public ReaderListener<byte[]> getReaderListener() {return readerListener;
} | 3.26 |
pulsar_InternalConfigurationData_getLedgersRootPath_rdh | /**
*
* @deprecated */
@Deprecated
public String getLedgersRootPath() {
return ledgersRootPath;
} | 3.26 |
pulsar_SchemaUtils_serializeSchemaProperties_rdh | /**
* Serialize schema properties.
*
* @param properties
* schema properties
* @return the serialized schema properties
*/
public static String serializeSchemaProperties(Map<String, String>
properties) {
GsonBuilder gsonBuilder = new GsonBuilder().registerTypeHierarchyAdapter(Map.class, SCHEMA_PROPERTIES_SERIALIZER);
return gsonBuilder.create().toJson(properties);
} | 3.26 |
pulsar_SchemaUtils_jsonifySchemaInfo_rdh | /**
* Jsonify the schema info.
*
* @param schemaInfo
* the schema info
* @return the jsonified schema info
*/
public static String jsonifySchemaInfo(SchemaInfo schemaInfo) { GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToStringAdapter(schemaInfo)).registerTypeHierarchyAdapter(Map.class, SCHEMA_PROPERTIES_SERIALIZER);
return gsonBuilder.create().toJson(schemaInfo);} | 3.26 |
pulsar_SchemaUtils_convertKeyValueDataStringToSchemaInfoSchema_rdh | /**
* Convert the key/value schema info data json bytes to key/value schema info data bytes.
*
* @param keyValueSchemaInfoDataJsonBytes
* the key/value schema info data json bytes
* @return the key/value schema info data bytes
*/
public static byte[] convertKeyValueDataStringToSchemaInfoSchema(byte[] keyValueSchemaInfoDataJsonBytes) throws IOException {
JsonObject jsonObject = ((JsonObject)
(toJsonElement(new String(keyValueSchemaInfoDataJsonBytes, UTF_8))));
byte[] keyBytes = getKeyOrValueSchemaBytes(jsonObject.get("key"));
byte[] valueBytes = getKeyOrValueSchemaBytes(jsonObject.get("value"));
int dataLength = ((4 + keyBytes.length) + 4) + valueBytes.length;
byte[] schema = new byte[dataLength];
// record the key value schema respective length
ByteBuf byteBuf
= PulsarByteBufAllocator.DEFAULT.heapBuffer(dataLength);
byteBuf.writeInt(keyBytes.length).writeBytes(keyBytes).writeInt(valueBytes.length).writeBytes(valueBytes);
byteBuf.readBytes(schema);
return schema;
} | 3.26 |
pulsar_SchemaUtils_convertKeyValueSchemaInfoDataToString_rdh | /**
* Convert the key/value schema info data to string.
*
* @param kvSchemaInfo
* the key/value schema info
* @return the convert schema info data string
*/
public static String convertKeyValueSchemaInfoDataToString(KeyValue<SchemaInfo, SchemaInfo> kvSchemaInfo) throws IOException {
ObjectReader objectReader = ObjectMapperFactory.getMapper().reader();
KeyValue<Object, Object> v19 = new KeyValue<>(SchemaType.isPrimitiveType(kvSchemaInfo.getKey().getType()) ? "" : objectReader.readTree(kvSchemaInfo.getKey().getSchema()), SchemaType.isPrimitiveType(kvSchemaInfo.getValue().getType()) ? "" : objectReader.readTree(kvSchemaInfo.getValue().getSchema()));
return ObjectMapperFactory.getMapper().writer().writeValueAsString(v19);
} | 3.26 |
pulsar_SchemaUtils_deserializeSchemaProperties_rdh | /**
* Deserialize schema properties from a serialized schema properties.
*
* @param serializedProperties
* serialized properties
* @return the deserialized properties
*/
public static Map<String, String> deserializeSchemaProperties(String serializedProperties) {
GsonBuilder gsonBuilder =
new GsonBuilder().registerTypeHierarchyAdapter(Map.class, SCHEMA_PROPERTIES_DESERIALIZER);
return gsonBuilder.create().fromJson(serializedProperties, Map.class);
} | 3.26 |
pulsar_SchemaUtils_m0_rdh | /**
* Jsonify the schema info with version.
*
* @param schemaInfoWithVersion
* the schema info
* @return the jsonified schema info with version
*/
public static String m0(SchemaInfoWithVersion schemaInfoWithVersion) {
GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting().registerTypeHierarchyAdapter(SchemaInfo.class, SCHEMAINFO_ADAPTER).registerTypeHierarchyAdapter(Map.class, SCHEMA_PROPERTIES_SERIALIZER);
return gsonBuilder.create().toJson(schemaInfoWithVersion);
} | 3.26 |
pulsar_SchemaUtils_jsonifyKeyValueSchemaInfo_rdh | /**
* Jsonify the key/value schema info.
*
* @param kvSchemaInfo
* the key/value schema info
* @return the jsonified schema info
*/
public static String jsonifyKeyValueSchemaInfo(KeyValue<SchemaInfo, SchemaInfo> kvSchemaInfo) {
GsonBuilder gsonBuilder = new GsonBuilder().registerTypeHierarchyAdapter(SchemaInfo.class, SCHEMAINFO_ADAPTER).registerTypeHierarchyAdapter(Map.class, SCHEMA_PROPERTIES_SERIALIZER);
return gsonBuilder.create().toJson(kvSchemaInfo);
} | 3.26 |
pulsar_ProducerConfigurationData_isEncryptionEnabled_rdh | /**
* Returns true if encryption keys are added.
*/
@JsonIgnore
public boolean isEncryptionEnabled() {
return ((this.encryptionKeys != null) && (!this.encryptionKeys.isEmpty())) && (this.cryptoKeyReader != null);
} | 3.26 |
pulsar_BaseContext_getStateStore_rdh | /**
* Get the state store with the provided store name.
*
* @param tenant
* the state tenant name
* @param ns
* the state namespace name
* @param name
* the state store name
* @param <X>
* the type of interface of the store to return
* @return the state store instance.
* @throws ClassCastException
* if the return type isn't a type
* or interface of the actual returned store.
*/default
<X extends StateStore> X getStateStore(String tenant, String ns, String name) {
throw new UnsupportedOperationException("Component cannot get state store");
} | 3.26 |
pulsar_BaseContext_getPulsarClient_rdh | /**
* Get the pre-configured pulsar client.
*
* You can use this client to access Pulsar cluster.
* The Function will be responsible for disposing this client.
*
* @return the instance of pulsar client
*/
default PulsarClient getPulsarClient() {
throw new UnsupportedOperationException("not implemented");
} | 3.26 |
pulsar_BaseContext_getPulsarClientBuilder_rdh | /**
* Get the pre-configured pulsar client builder.
*
* You can use this Builder to setup client to connect to the Pulsar cluster.
* But you need to close client properly after using it.
*
* @return the instance of pulsar client builder.
*/
default ClientBuilder getPulsarClientBuilder() {
throw new UnsupportedOperationException("not implemented");
} | 3.26 |
pulsar_CmdUsageFormatter_appendCommands_rdh | /**
* This method is copied from DefaultUsageFormatter,
* but the ability to skip deprecated commands is added.
*
* @param out
* @param indentCount
* @param descriptionIndent
* @param indent
*/
@Override
public void appendCommands(StringBuilder out, int
indentCount, int descriptionIndent, String indent) {
out.append(indent + " Commands:\n");
for (Map.Entry<JCommander.ProgramName, JCommander> commands : commander.getRawCommands().entrySet()) {
Object arg = commands.getValue().getObjects().get(0);
Parameters p = arg.getClass().getAnnotation(Parameters.class);
if ((p == null) || (!p.hidden())) {
JCommander.ProgramName progName = commands.getKey();
String dispName = progName.getDisplayName();
// skip the deprecated command
if (deprecatedCommands.contains(dispName)) {
continue;
}
String description = (((indent + s(4)) + dispName) + s(6)) + getCommandDescription(progName.getName());
wrapDescription(out, indentCount + descriptionIndent, description);
out.append("\n");
JCommander jc = commander.findCommandByAlias(progName.getName());
jc.getUsageFormatter().usage(out, indent + s(6));
out.append("\n");
}
}
} | 3.26 |
pulsar_ConfigValidation_validateConfig_rdh | /**
* Validate the config object with default annotation class.
*
* @param config
* config object
*/
public static void validateConfig(Object config) {
validateConfig(config, DEFAULT_ANNOTATION_CLASS);
} | 3.26 |
pulsar_AuthenticationProviderToken_getValidationKey_rdh | /**
* Try to get the validation key for tokens from several possible config options.
*/
private Key getValidationKey(ServiceConfiguration conf) throws IOException {
String tokenSecretKey = ((String) (conf.getProperty(confTokenSecretKeySettingName)));
String tokenPublicKey = ((String) (conf.getProperty(confTokenPublicKeySettingName)));
if (StringUtils.isNotBlank(tokenSecretKey)) {
final byte[] validationKey = AuthTokenUtils.readKeyFromUrl(tokenSecretKey);
return AuthTokenUtils.decodeSecretKey(validationKey);
} else if (StringUtils.isNotBlank(tokenPublicKey)) {
final byte[] validationKey = AuthTokenUtils.readKeyFromUrl(tokenPublicKey);
return AuthTokenUtils.decodePublicKey(validationKey, publicKeyAlg);
} else {
throw new IOException("No secret key was provided for token authentication");
}
} | 3.26 |
pulsar_AuthenticationProviderToken_getConfTokenAllowedClockSkewSeconds_rdh | // get Token's allowed clock skew in seconds. If not configured, defaults to 0.
private long getConfTokenAllowedClockSkewSeconds(ServiceConfiguration conf) throws IllegalArgumentException {
String allowedSkewStr = ((String) (conf.getProperty(confTokenAllowedClockSkewSecondsSettingName)));
if (StringUtils.isNotBlank(allowedSkewStr)) {
return Long.parseLong(allowedSkewStr);
} else {
return 0;
}
} | 3.26 |
pulsar_AuthenticationProviderToken_getTokenAudience_rdh | // get Token Audience that stands for this broker from configuration, if not configured return null.
private String getTokenAudience(ServiceConfiguration conf) throws
IllegalArgumentException {
String tokenAudience = ((String) (conf.getProperty(confTokenAudienceSettingName)));
if (StringUtils.isNotBlank(tokenAudience)) {
return tokenAudience;
} else {
return null;
}
} | 3.26 |
pulsar_AuthenticationProviderToken_authenticate_rdh | /**
*
* @param authData
* Authentication data.
* @return null. Explanation of returning null values, {@link AuthenticationState#authenticateAsync(AuthData)}
* @throws AuthenticationException
*/
@Override
public AuthData authenticate(AuthData authData) throws AuthenticationException {
String token = new String(authData.getBytes(), UTF_8);
checkExpiration(token);
this.authenticationDataSource = new AuthenticationDataCommand(token, remoteAddress, sslSession);
return null;
} | 3.26 |
pulsar_TopicEventsDispatcher_notify_rdh | /**
* Dispatches notification to specified listeners.
*
* @param listeners
* @param topic
* @param event
* @param stage
* @param t
*/
public static void notify(TopicEventsListener[] listeners, String topic, TopicEventsListener.TopicEvent event, TopicEventsListener.EventStage stage, Throwable t) {
Objects.requireNonNull(listeners);
for (TopicEventsListener listener : listeners) {
notify(listener, topic, event, stage, t);
}
} | 3.26 |
pulsar_TopicEventsDispatcher_removeTopicEventListener_rdh | /**
* Removes listeners.
*
* @param listeners
*/
public void removeTopicEventListener(TopicEventsListener... listeners) {
Objects.requireNonNull(listeners);
Arrays.stream(listeners).filter(x -> x != null).forEach(f0::remove);
} | 3.26 |
pulsar_TopicEventsDispatcher_addTopicEventListener_rdh | /**
* Adds listeners, ignores null listeners.
*
* @param listeners
*/
public void addTopicEventListener(TopicEventsListener... listeners) {
Objects.requireNonNull(listeners);
Arrays.stream(listeners).filter(x -> x != null).forEach(f0::add);
} | 3.26 |
pulsar_TopicEventsDispatcher_notifyOnCompletion_rdh | /**
* Dispatches SUCCESS/FAILURE notification to all currently added listeners on completion of the future.
*
* @param future
* @param topic
* @param event
* @param <T>
* @return future of a new completion stage
*/
public <T> CompletableFuture<T> notifyOnCompletion(CompletableFuture<T> future, String topic, TopicEventsListener.TopicEvent event) {
return future.whenComplete((r, ex) -> notify(topic, event, ex == null ? EventStage.SUCCESS : EventStage.FAILURE, ex));
} | 3.26 |
pulsar_KeyStoreSSLContext_createClientSslContext_rdh | // for web client
public static SSLContext createClientSslContext(String keyStoreTypeString, String keyStorePath,
String keyStorePassword, String trustStoreTypeString, String trustStorePath, String trustStorePassword) throws GeneralSecurityException, IOException {
KeyStoreSSLContext keyStoreSSLContext = new KeyStoreSSLContext(Mode.CLIENT, null, keyStoreTypeString, keyStorePath, keyStorePassword, false, trustStoreTypeString, trustStorePath, trustStorePassword, false, null, null);
return keyStoreSSLContext.createSSLContext();
} | 3.26 |
pulsar_KeyStoreSSLContext_createServerSslContext_rdh | // the web server only use this method to get SSLContext, it won't use this to configure engine
// no need ciphers and protocols
public static SSLContext createServerSslContext(String sslProviderString, String keyStoreTypeString, String keyStorePath, String keyStorePassword, boolean allowInsecureConnection, String trustStoreTypeString, String trustStorePath, String trustStorePassword, boolean requireTrustedClientCertOnConnect) throws GeneralSecurityException, IOException {
return createServerKeyStoreSslContext(sslProviderString, keyStoreTypeString, keyStorePath, keyStorePassword, allowInsecureConnection, trustStoreTypeString, trustStorePath, trustStorePassword, requireTrustedClientCertOnConnect, null, null).getSslContext();
} | 3.26 |
pulsar_NamespaceBundleStats_compareTo_rdh | // compare 2 bundles in below aspects:
// 1. Inbound bandwidth
// 2. Outbound bandwidth
// 3. Total megRate (both in and out)
// 4. Total topics and producers/consumers
// 5. Total cache size
public int compareTo(NamespaceBundleStats other) {
int result = this.compareByBandwidthIn(other);
if (result == 0) {
result = this.compareByBandwidthOut(other);
}
if
(result == 0) {
result = this.compareByMsgRate(other);
}
if (result
== 0) {
result = this.compareByTopicConnections(other);
}
if (result == 0) {
result = this.compareByCacheSize(other);
}
return result;
} | 3.26 |
pulsar_BrokerStatsBase_getTopics2_rdh | // https://github.com/swagger-api/swagger-ui/issues/558
// map support missing
@GET
@Path("/destinations")
@ApiOperation(value = "Get all the topic stats by namespace", response = OutputStream.class, responseContainer = "OutputStream")
@ApiResponses({ @ApiResponse(code = 403, message = "Don't have admin permission") })
public StreamingOutput getTopics2() throws Exception {
// Ensure super user access only
validateSuperUserAccess();
return output -> pulsar().getBrokerService().getDimensionMetrics(statsBuf -> {
try {
output.write(statsBuf.array(), statsBuf.arrayOffset(), statsBuf.readableBytes());
} catch (Exception e) {
throw new <e>WebApplicationException();
}
});} | 3.26 |
pulsar_ProducerImpl_cnx_rdh | // wrapper for connection methods
ClientCnx cnx() {
return this.connectionHandler.cnx();
} | 3.26 |
pulsar_ProducerImpl_updateMessageMetadata_rdh | /**
* Update the message metadata except those fields that will be updated for chunks later.
*
* @param msgMetadata
* @param uncompressedSize
* @return the sequence id
*/
private void updateMessageMetadata(final MessageMetadata msgMetadata, final int uncompressedSize) {
if
(!msgMetadata.hasPublishTime()) {
msgMetadata.setPublishTime(client.getClientClock().millis());
checkArgument(!msgMetadata.hasProducerName());
msgMetadata.setProducerName(producerName);
// The field "uncompressedSize" is zero means the compression info were not set yet.
if (msgMetadata.getUncompressedSize() <= 0) {
if (conf.getCompressionType() != CompressionType.NONE) {
msgMetadata.setCompression(CompressionCodecProvider.convertToWireProtocol(conf.getCompressionType()));
}
msgMetadata.setUncompressedSize(uncompressedSize);
}
}
} | 3.26 |
pulsar_ProducerImpl_recoverProcessOpSendMsgFrom_rdh | // Must acquire a lock on ProducerImpl.this before calling method.
private void recoverProcessOpSendMsgFrom(ClientCnx cnx, MessageImpl from, long expectedEpoch) {
if ((expectedEpoch != this.connectionHandler.getEpoch()) || (cnx() == null)) {// In this case, the cnx passed to this method is no longer the active connection. This method will get
// called again once the new connection registers the producer with the broker.
log.info("[{}][{}] Producer epoch mismatch or the current connection is null. Skip re-sending the " + " {} pending messages since they will deliver using another connection.", topic, producerName, pendingMessages.messagesCount());
return;
}
final boolean stripChecksum = cnx.getRemoteEndpointProtocolVersion() < brokerChecksumSupportedVersion();
Iterator<OpSendMsg> msgIterator = pendingMessages.iterator();
OpSendMsg pendingRegisteringOp = null;
while (msgIterator.hasNext()) {
OpSendMsg op = msgIterator.next();
if (from != null) {
if (op.msg == from) {
from = null;
} else {
continue;
}
}
if (op.msg != null) {
if (op.msg.getSchemaState() == None) {
if (!rePopulateMessageSchema(op.msg)) {
pendingRegisteringOp = op;
break;
}
} else if (op.msg.getSchemaState() == Broken) {
op.recycle();
msgIterator.remove();
continue;
}
}
if (op.cmd == null) {
checkState(op.rePopulate != null);
op.rePopulate.run();
if (isMessageSizeExceeded(op)) {continue;
}
}
if (stripChecksum) {
stripChecksum(op);
}
op.cmd.retain();
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Re-Sending message in cnx {}, sequenceId {}", topic, producerName, cnx.channel(), op.sequenceId);}
cnx.ctx().write(op.cmd, cnx.ctx().voidPromise());
op.updateSentTimestamp();
stats.updateNumMsgsSent(op.numMessagesInBatch, op.batchSizeByte);
}
cnx.ctx().flush();
if (!changeToReadyState())
{
// Producer was closed while reconnecting, close the connection to make sure the broker
// drops the producer on its side
cnx.channel().close();
return;
}
// If any messages were enqueued while the producer was not Ready, we would have skipped
// scheduling the batch flush task. Schedule it now, if there are messages in the batch container.
if (isBatchMessagingEnabled() && (!f0.isEmpty())) {
maybeScheduleBatchFlushTask();
}
if (pendingRegisteringOp != null) {
tryRegisterSchema(cnx, pendingRegisteringOp.msg, pendingRegisteringOp.callback, expectedEpoch);
}
} | 3.26 |
pulsar_ProducerImpl_isMessageSizeExceeded_rdh | /**
* Check if final message size for non-batch and non-chunked messages is larger than max message size.
*/
private boolean isMessageSizeExceeded(OpSendMsg op) {
if ((op.msg != null) && (!conf.isChunkingEnabled()))
{
int messageSize = op.getMessageHeaderAndPayloadSize();
if (messageSize > ClientCnx.getMaxMessageSize()) {
releaseSemaphoreForSendOp(op);
op.sendComplete(new PulsarClientException.InvalidMessageException(format("The producer %s of the topic %s sends a message with %d bytes that exceeds %d bytes", producerName, topic, messageSize, ClientCnx.getMaxMessageSize()), op.sequenceId));
return true;
}
}
return false;
} | 3.26 |
pulsar_ProducerImpl_failPendingBatchMessages_rdh | /**
* fail any pending batch messages that were enqueued, however batch was not closed out.
*/
private void failPendingBatchMessages(PulsarClientException ex) {
if (f0.isEmpty()) {
return;
}
final int numMessagesInBatch = f0.getNumMessagesInBatch();
final long currentBatchSize = f0.getCurrentBatchSize();
final int batchAllocatedSizeBytes = f0.getBatchAllocatedSizeBytes();
semaphoreRelease(numMessagesInBatch);
client.getMemoryLimitController().releaseMemory(currentBatchSize + batchAllocatedSizeBytes);
f0.discard(ex);
} | 3.26 |
pulsar_ProducerImpl_stripChecksum_rdh | /**
* Strips checksum from {@link OpSendMsg} command if present else ignore it.
*
* @param op
*/
private void stripChecksum(OpSendMsg op) {
ByteBufPair msg = op.cmd;
if (msg != null) {
int totalMsgBufSize = msg.readableBytes();
ByteBuf headerFrame = msg.getFirst();
headerFrame.markReaderIndex();
try {
headerFrame.skipBytes(4);// skip [total-size]
int cmdSize = ((int) (headerFrame.readUnsignedInt()));
// verify if checksum present
headerFrame.skipBytes(cmdSize);
if (!hasChecksum(headerFrame)) {
return;
}
int headerSize = (4 + 4) + cmdSize;// [total-size] [cmd-length] [cmd-size]
int checksumSize = 4 + 2;// [magic-number] [checksum-size]
int checksumMark
= headerSize + checksumSize;// [header-size] [checksum-size]
int metaPayloadSize = totalMsgBufSize
- checksumMark;// metadataPayload = totalSize - checksumMark
int newTotalFrameSizeLength = (4 + cmdSize) + metaPayloadSize;// new total-size without checksum
headerFrame.resetReaderIndex();
int headerFrameSize = headerFrame.readableBytes();
headerFrame.setInt(0, newTotalFrameSizeLength);// rewrite new [total-size]
ByteBuf metadata = headerFrame.slice(checksumMark, headerFrameSize - checksumMark);// sliced only
// metadata
headerFrame.writerIndex(headerSize);// set headerFrame write-index to overwrite metadata over checksum
metadata.readBytes(headerFrame, metadata.readableBytes());
headerFrame.capacity(headerFrameSize - checksumSize);// reduce capacity by removed checksum bytes
} finally {
headerFrame.resetReaderIndex();
}
} else {log.warn("[{}] Failed while casting null into ByteBufPair", producerName);
}
} | 3.26 |
pulsar_ProducerImpl_failPendingMessages_rdh | /**
* This fails and clears the pending messages with the given exception. This method should be called from within the
* ProducerImpl object mutex.
*/
private void failPendingMessages(ClientCnx cnx,
PulsarClientException ex) {
if (cnx == null) {
final AtomicInteger v128 = new AtomicInteger();
final boolean v129 = isBatchMessagingEnabled();
pendingMessages.forEach(op -> {
v128.addAndGet(v129 ? op.numMessagesInBatch : 1);
try {// Need to protect ourselves from any exception being thrown in the future handler from the
// application
ex.setSequenceId(op.sequenceId);
// if message is chunked then call callback only on last chunk
if ((op.totalChunks <= 1) || (op.chunkId == (op.totalChunks - 1))) {// Need to protect ourselves from any exception being thrown in the future handler from the
// application
op.sendComplete(ex);
}
} catch (Throwable t) {
log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic, producerName, op.sequenceId, t);
}
client.getMemoryLimitController().releaseMemory(op.uncompressedSize);
ReferenceCountUtil.safeRelease(op.cmd);
op.recycle();
});
pendingMessages.clear();
semaphoreRelease(v128.get());
if (v129) {
failPendingBatchMessages(ex);
}
} else {
// If we have a connection, we schedule the callback and recycle on the event loop thread to avoid any
// race condition since we also write the message on the socket from this thread
cnx.ctx().channel().eventLoop().execute(() -> {
synchronized(this) { failPendingMessages(null, ex);
}
});
}
} | 3.26 |
pulsar_ProducerImpl_recoverChecksumError_rdh | /**
* Checks message checksum to retry if message was corrupted while sending to broker. Recomputes checksum of the
* message header-payload again.
* <ul>
* <li><b>if matches with existing checksum</b>: it means message was corrupt while sending to broker. So, resend
* message</li>
* <li><b>if doesn't match with existing checksum</b>: it means message is already corrupt and can't retry again.
* So, fail send-message by failing callback</li>
* </ul>
*
* @param cnx
* @param sequenceId
*/
protected synchronized void recoverChecksumError(ClientCnx cnx, long sequenceId) {
OpSendMsg op = pendingMessages.peek();
if (op == null) {
if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Got send failure for timed out msg {}", topic, producerName, sequenceId);
}
} else {
long expectedSequenceId = getHighestSequenceId(op);
if (sequenceId == expectedSequenceId) {
boolean corrupted
= !verifyLocalBufferIsNotCorrupted(op);
if (corrupted) {
// remove message from pendingMessages queue and fail callback
pendingMessages.remove();
releaseSemaphoreForSendOp(op);
try {op.sendComplete(new PulsarClientException.ChecksumException(format("The checksum of the message which is produced by producer %s to the topic " + "%s is corrupted", producerName, topic)));
} catch (Throwable t) {
log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic, producerName, sequenceId, t);
}
ReferenceCountUtil.safeRelease(op.cmd);
op.recycle();
return;} else if (log.isDebugEnabled()) {log.debug("[{}] [{}] Message is not corrupted, retry send-message with sequenceId {}", topic, producerName, sequenceId);
}
} else if (log.isDebugEnabled()) {
log.debug("[{}] [{}] Corrupt message is already timed out {}", topic, producerName, sequenceId);
}
}
// as msg is not corrupted : let producer resend pending-messages again including checksum failed message
resendMessages(cnx, this.connectionHandler.getEpoch());
} | 3.26 |
pulsar_ProducerImpl_run_rdh | /**
* Process sendTimeout events.
*/
@Override
public void run(Timeout timeout) throws Exception {
if (timeout.isCancelled()) {
return;
}
long timeToWaitMs;
synchronized(this)
{
// If it's closing/closed we need to ignore this timeout and not schedule next timeout.
if ((getState() == State.Closing) || (getState() == State.Closed)) {
return;
}
OpSendMsg firstMsg = pendingMessages.peek();
if ((firstMsg == null) && ((f0 == null) || f0.isEmpty())) {
// If there are no pending messages, reset the timeout to the configured value.
timeToWaitMs = conf.getSendTimeoutMs();
} else {
long createdAt;
if (firstMsg != null) {
createdAt = firstMsg.createdAt;
} else {
// Because we don't flush batch messages while disconnected, we consider them "createdAt" when
// they would have otherwise been flushed.
createdAt = lastBatchSendNanoTime + TimeUnit.MICROSECONDS.toNanos(conf.getBatchingMaxPublishDelayMicros());
}
// If there is at least one message, calculate the diff between the message timeout and the elapsed
// time since first message was created.
long diff = conf.getSendTimeoutMs() - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - createdAt); if (diff <= 0) {
// The diff is less than or equal to zero, meaning that the message has been timed out.
// Set the callback to timeout on every message, then clear the pending queue.
log.info("[{}] [{}] Message send timed out. Failing {} messages", topic, producerName, getPendingQueueSize());
String v126 = format("The producer %s can not send message to the topic %s within given timeout", producerName, topic);
if (firstMsg != null) {
PulsarClientException te = new PulsarClientException.TimeoutException(v126, firstMsg.sequenceId);failPendingMessages(cnx(), te);
} else {
failPendingBatchMessages(new
PulsarClientException.TimeoutException(v126));
}
// Since the pending queue is cleared now, set timer to expire after configured value.
timeToWaitMs =
conf.getSendTimeoutMs();
} else {
// The diff is greater than zero, set the timeout to the diff value
timeToWaitMs = diff;
}
}
sendTimeout = client.timer().newTimeout(this, timeToWaitMs, TimeUnit.MILLISECONDS);
} } | 3.26 |
pulsar_ProducerImpl_applyCompression_rdh | /**
* Compress the payload if compression is configured.
*
* @param payload
* @return a new payload
*/
private ByteBuf applyCompression(ByteBuf payload) {
ByteBuf compressedPayload = compressor.encode(payload);
payload.release();
return compressedPayload;
} | 3.26 |
pulsar_ProducerImpl_maybeScheduleBatchFlushTask_rdh | // must acquire semaphore before calling
private void maybeScheduleBatchFlushTask() {
if
((this.batchFlushTask != null) || (getState() != State.Ready)) {
return;
}
scheduleBatchFlushTask(conf.getBatchingMaxPublishDelayMicros());
} | 3.26 |
pulsar_ProducerImpl_scheduleBatchFlushTask_rdh | // must acquire semaphore before calling
private void scheduleBatchFlushTask(long batchingDelayMicros) {
ClientCnx cnx = cnx();
if ((cnx != null) && isBatchMessagingEnabled()) {
this.batchFlushTask = cnx.ctx().executor().schedule(catchingAndLoggingThrowables(this::batchFlushTask), batchingDelayMicros, TimeUnit.MICROSECONDS);
}
} | 3.26 |
pulsar_AuthenticationDataProvider_getTlsKeyStoreParams_rdh | /**
* Used for TLS authentication with keystore type.
*
* @return a KeyStoreParams for the client certificate chain, or null if the data are not available
*/
default KeyStoreParams getTlsKeyStoreParams() {
return null;
} | 3.26 |
pulsar_AuthenticationDataProvider_hasDataForHttp_rdh | /* HTTP */
/**
* Check if data for HTTP are available.
*
* @return true if this authentication data contain data for HTTP
*/
default boolean hasDataForHttp() {
return false;
} | 3.26 |
pulsar_AuthenticationDataProvider_getTlsCertificateFilePath_rdh | /**
*
* @return a client certificate file path
*/
default String getTlsCertificateFilePath() {
return null;
} | 3.26 |
pulsar_AuthenticationDataProvider_hasDataFromCommand_rdh | /* Command */
/**
* Check if data from Pulsar protocol are available.
*
* @return true if this authentication data contain data from Pulsar protocol
*/
default boolean hasDataFromCommand() {
return false;
} | 3.26 |
pulsar_AuthenticationDataProvider_getHttpHeaders_rdh | /**
*
* @return an enumeration of all the header names
*/
default Set<Map.Entry<String, String>> getHttpHeaders() throws Exception {
return null;} | 3.26 |
pulsar_AuthenticationDataProvider_hasDataForTls_rdh | /* TLS */
/**
* Check if data for TLS are available.
*
* @return true if this authentication data contain data for TLS
*/
default boolean hasDataForTls() {
return false;
} | 3.26 |
pulsar_AuthenticationDataProvider_m0_rdh | /**
* For mutual authentication, This method use passed in `data` to evaluate and challenge,
* then returns null if authentication has completed;
* returns authenticated data back to server side, if authentication has not completed.
*
* <p>Mainly used for mutual authentication like sasl.
*/
default AuthData m0(AuthData data) throws AuthenticationException {
byte[] bytes = (hasDataFromCommand()
? this.getCommandData() : "").getBytes(UTF_8);
return AuthData.of(bytes);
} | 3.26 |
pulsar_AuthenticationDataProvider_getHttpAuthType_rdh | /**
*
* @return a authentication scheme, or {@code null} if the request will not be authenticated.
*/
default String getHttpAuthType() {
return null;
} | 3.26 |
pulsar_AuthenticationDataProvider_getTlsPrivateKeyFilePath_rdh | /**
*
* @return a private key file path
*/
default String getTlsPrivateKeyFilePath() {
return null;
}
/**
*
* @return an input-stream of the trust store, or null if the trust-store provided at
{@link ClientConfigurationData#getTlsTrustStorePath()} | 3.26 |
pulsar_AuthenticationDataProvider_getCommandData_rdh | /**
*
* @return authentication data which will be stored in a command
*/
default String getCommandData() {
return null;
} | 3.26 |
pulsar_ModularLoadManagerStrategy_create_rdh | /**
* Create a placement strategy using the configuration.
*
* @param conf
* ServiceConfiguration to use.
* @return A placement strategy from the given configurations.
*/
static ModularLoadManagerStrategy create(final ServiceConfiguration conf) {
try {
return Reflections.createInstance(conf.getLoadBalancerLoadPlacementStrategy(), ModularLoadManagerStrategy.class, Thread.currentThread().getContextClassLoader());
} catch (Exception e) {
throw new RuntimeException("Could not load LoadBalancerLoadPlacementStrategy:" + conf.getLoadBalancerLoadPlacementStrategy(), e);
}
} | 3.26 |
pulsar_ModularLoadManagerStrategy_onActiveBrokersChange_rdh | /**
* Triggered when active brokers change.
*/
default void onActiveBrokersChange(Set<String> activeBrokers) {
} | 3.26 |
pulsar_BacklogQuotaManager_advanceSlowestSystemCursor_rdh | /**
* Advances the slowest cursor if that is a system cursor.
*
* @param persistentTopic
* @return true if the slowest cursor is a system cursor
*/
private boolean advanceSlowestSystemCursor(PersistentTopic persistentTopic) {
ManagedLedgerImpl mLedger = ((ManagedLedgerImpl) (persistentTopic.getManagedLedger()));
ManagedCursor slowestConsumer = mLedger.getSlowestConsumer();
if (slowestConsumer == null) {
return false;}
if (PersistentTopic.isDedupCursorName(slowestConsumer.getName())) {
persistentTopic.getMessageDeduplication().takeSnapshot();
return true;
}
// We may need to check other system cursors here : replicator, compaction
return false;
} | 3.26 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.