name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
pulsar_ConsumerConfiguration_setCryptoKeyReader_rdh
/** * Sets a {@link CryptoKeyReader}. * * @param cryptoKeyReader * CryptoKeyReader object */ public ConsumerConfiguration setCryptoKeyReader(CryptoKeyReader cryptoKeyReader) { Objects.requireNonNull(cryptoKeyReader); conf.setCryptoKeyReader(cryptoKeyReader); return this; }
3.26
pulsar_ConsumerConfiguration_setConsumerEventListener_rdh
/** * Sets a {@link ConsumerEventListener} for the consumer. * * <p> * The consumer group listener is used for receiving consumer state change in a consumer group for failover * subscription. Application can then react to the consumer state changes. * * <p> * This change is experimental. It is subject to changes coming in release 2.0. * * @param listener * the consumer group listener object * @return consumer configuration * @since 2.0 */ public ConsumerConfiguration setConsumerEventListener(ConsumerEventListener listener) { Objects.requireNonNull(listener); conf.setConsumerEventListener(listener); return this; }
3.26
pulsar_ConsumerConfiguration_getMaxTotalReceiverQueueSizeAcrossPartitions_rdh
/** * * @return the configured max total receiver queue size across partitions */ public int getMaxTotalReceiverQueueSizeAcrossPartitions() { return conf.getMaxTotalReceiverQueueSizeAcrossPartitions(); }
3.26
pulsar_ConsumerConfiguration_getCryptoKeyReader_rdh
/** * * @return the CryptoKeyReader */ public CryptoKeyReader getCryptoKeyReader() { return conf.getCryptoKeyReader(); }
3.26
pulsar_ConsumerConfiguration_getMessageListener_rdh
/** * * @return the configured {@link MessageListener} for the consumer */public MessageListener<byte[]> getMessageListener() { return messageListener; }
3.26
pulsar_ConsumerConfiguration_setProperty_rdh
/** * Set a name/value property with this consumer. * * @param key * @param value * @return */ public ConsumerConfiguration setProperty(String key, String value) { checkArgument(key != null); checkArgument(value != null); conf.getProperties().put(key, value); return this; }
3.26
pulsar_ConsumerConfiguration_getReceiverQueueSize_rdh
/** * * @return the configure receiver queue size value */ public int getReceiverQueueSize() { return conf.getReceiverQueueSize(); }
3.26
pulsar_ConsumerConfiguration_getAckTimeoutRedeliveryBackoff_rdh
/** * * @return the configured {@link RedeliveryBackoff} for the consumer */ public RedeliveryBackoff getAckTimeoutRedeliveryBackoff() { return conf.getAckTimeoutRedeliveryBackoff(); }
3.26
pulsar_ConsumerConfiguration_getSubscriptionInitialPosition_rdh
/** * * @return the configured {@link subscriptionInitialPosition} for the consumer */ public SubscriptionInitialPosition getSubscriptionInitialPosition() {return conf.getSubscriptionInitialPosition(); }
3.26
pulsar_ConsumerConfiguration_m0_rdh
/** * * @return this configured {@link ConsumerEventListener} for the consumer. * @see #setConsumerEventListener(ConsumerEventListener) * @since 2.0 */ public ConsumerEventListener m0() { return conf.getConsumerEventListener(); }
3.26
pulsar_ConsumerConfiguration_m1_rdh
/** * If enabled, the consumer will read messages from the compacted topic rather than reading the full message backlog * of the topic. This means that, if the topic has been compacted, the consumer will only see the latest value for * each key in the topic, up until the point in the topic message backlog that has been compacted. Beyond that * point, the messages will be sent as normal. * * readCompacted can only be enabled subscriptions to persistent topics, which have a single active consumer (i.e. * failure or exclusive subscriptions). Attempting to enable it on subscriptions to a non-persistent topics or on a * shared subscription, will lead to the subscription call throwing a PulsarClientException. * * @param readCompacted * whether to read from the compacted topic */ public ConsumerConfiguration m1(boolean readCompacted) { conf.setReadCompacted(readCompacted); return this; }
3.26
pulsar_ConsumerConfiguration_getCryptoFailureAction_rdh
/** * * @return The ConsumerCryptoFailureAction */ public ConsumerCryptoFailureAction getCryptoFailureAction() { return conf.getCryptoFailureAction(); }
3.26
pulsar_ConsumerConfiguration_setConsumerName_rdh
/** * Set the consumer name. * * @param consumerName */ public ConsumerConfiguration setConsumerName(String consumerName) { checkArgument((consumerName != null) && (!consumerName.equals(""))); conf.setConsumerName(consumerName); return this; }
3.26
pulsar_ConsumerConfiguration_setNegativeAckRedeliveryBackoff_rdh
/** * * @param negativeAckRedeliveryBackoff * the negative ack redelivery backoff policy. * Default value is: MultiplierRedeliveryBackoff * @return the {@link ConsumerConfiguration} */ public ConsumerConfiguration setNegativeAckRedeliveryBackoff(RedeliveryBackoff negativeAckRedeliveryBackoff) { conf.setNegativeAckRedeliveryBackoff(negativeAckRedeliveryBackoff);return this; }
3.26
pulsar_ConsumerConfiguration_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> * <p> * <b>Setting the consumer queue size as zero</b> * <ul> * <li>Decreases the throughput of the consumer, by disabling pre-fetching of messages. This approach improves the * message distribution on shared subscription, by pushing messages only to the consumers that are ready to process * them. Neither {@link Consumer#receive(int, TimeUnit)} nor Partitioned Topics can be used if the consumer queue * size is zero. {@link Consumer#receive()} function call should not be interrupted when the consumer queue size is * zero.</li> * <li>Doesn't support Batch-Message: if consumer receives any batch-message then it closes consumer connection with * broker and {@link Consumer#receive()} call will remain blocked while {@link Consumer#receiveAsync()} receives * exception in callback. <b> consumer will not be able receive any further message unless batch-message in pipeline * is removed</b></li> * </ul> * </p> * Default value is {@code 1000} messages and should be good for most use cases. * * @param receiverQueueSize * the new receiver queue size value */ public ConsumerConfiguration setReceiverQueueSize(int receiverQueueSize) { checkArgument(receiverQueueSize >= 0, "Receiver queue size cannot be negative"); conf.setReceiverQueueSize(receiverQueueSize); return this; }
3.26
pulsar_ConsumerConfiguration_setSubscriptionInitialPosition_rdh
/** * * @param subscriptionInitialPosition * the initial position at which to set * set cursor when subscribing to the topic first time * Default is {@value InitialPosition.Latest} */ public ConsumerConfiguration setSubscriptionInitialPosition(SubscriptionInitialPosition subscriptionInitialPosition) { conf.setSubscriptionInitialPosition(subscriptionInitialPosition);return this; }
3.26
pulsar_ConsumerConfiguration_setAckTimeoutRedeliveryBackoff_rdh
/** * * @param ackTimeoutRedeliveryBackoff * redelivery backoff policy for ack timeout. * Default value is: MultiplierRedeliveryBackoff * @return the {@link ConsumerConfiguration} */ public ConsumerConfiguration setAckTimeoutRedeliveryBackoff(RedeliveryBackoff ackTimeoutRedeliveryBackoff) { conf.setAckTimeoutRedeliveryBackoff(ackTimeoutRedeliveryBackoff); return this; }
3.26
pulsar_ConsumerConfiguration_getConsumerName_rdh
/** * * @return the consumer name */ public String getConsumerName() { return conf.getConsumerName(); }
3.26
pulsar_MessageAcknowledger_acknowledgeAsync_rdh
/** * The asynchronous version of {@link #acknowledge(MessageId)}. */default CompletableFuture<Void> acknowledgeAsync(MessageId messageId) { return acknowledgeAsync(messageId, null); }
3.26
pulsar_TransactionMetadataStoreProvider_newProvider_rdh
/** * Construct a provider from the provided class. * * @param providerClassName * the provider class name. * @return an instance of transaction metadata store provider. */ static TransactionMetadataStoreProvider newProvider(String providerClassName) throws IOException { Class<?> providerClass; try { providerClass = Class.forName(providerClassName); Object obj = providerClass.getDeclaredConstructor().newInstance(); checkArgument(obj instanceof TransactionMetadataStoreProvider, "The factory has to be an instance of " + TransactionMetadataStoreProvider.class.getName()); return ((TransactionMetadataStoreProvider) (obj)); } catch (Exception e) { throw new IOException(e); } } /** * Open the transaction metadata store for transaction coordinator * identified by <tt>transactionCoordinatorId</tt>. * * @param transactionCoordinatorId * {@link TransactionCoordinatorID} the coordinator id. * @param managedLedgerFactory * {@link ManagedLedgerFactory} the managedLedgerFactory to create managedLedger. * @param managedLedgerConfig * {@link ManagedLedgerConfig} the managedLedgerConfig to create managedLedger. * @param timeoutTracker * {@link TransactionTimeoutTracker} the timeoutTracker to handle transaction time out. * @param recoverTracker * {@link TransactionRecoverTracker} the recoverTracker to handle transaction recover. * @return a future represents the result of the operation. an instance of {@link TransactionMetadataStore}
3.26
pulsar_AuthenticationFactory_TLS_rdh
// CHECKSTYLE.OFF: MethodName /** * Create an authentication provider for TLS based authentication. * * @param certFilePath * the path to the TLS client public key * @param keyFilePath * the path to the TLS client private key * @return the Authentication object initialized with the TLS credentials */ public static Authentication TLS(String certFilePath, String keyFilePath) { return DefaultImplementation.getDefaultImplementation().newAuthenticationTLS(certFilePath, keyFilePath); }
3.26
pulsar_AuthenticationFactory_create_rdh
/** * Create an instance of the Authentication-Plugin. * * @param authPluginClassName * name of the Authentication-Plugin you want to use * @param authParams * map which represents parameters for the Authentication-Plugin * @return instance of the Authentication-Plugin * @throws UnsupportedAuthenticationException */ public static Authentication create(String authPluginClassName, Map<String, String> authParams) throws UnsupportedAuthenticationException { try { return DefaultImplementation.getDefaultImplementation().createAuthentication(authPluginClassName, authParams); } catch (Throwable t) { throw new UnsupportedAuthenticationException(t); } }
3.26
pulsar_AuthenticationFactory_token_rdh
/** * Create an authentication provider for token based authentication. * * @param tokenSupplier * a supplier of the client auth token * @return the Authentication object initialized with the token credentials */ public static Authentication token(Supplier<String> tokenSupplier) { return DefaultImplementation.getDefaultImplementation().newAuthenticationToken(tokenSupplier); }
3.26
pulsar_ProxyService_shutdownEventLoop_rdh
// Shutdown the event loop. // If graceful is true, will wait for the current requests to be completed, up to 15 seconds. // Graceful shutdown can be disabled by setting the gracefulShutdown flag to false. This is used in tests // to speed up the shutdown process. private Future<?> shutdownEventLoop(EventLoopGroup eventLoop) { if (gracefulShutdown) { return eventLoop.shutdownGracefully(); } else { return eventLoop.shutdownGracefully(0, 0, TimeUnit.SECONDS); } }
3.26
pulsar_KubernetesSecretsProviderConfigurator_configureKubernetesRuntimeSecretsProvider_rdh
// Kubernetes secrets can be exposed as volume mounts or as // environment variables in the pods. We are currently using the // environment variables way. Essentially the secretName/secretPath // is attached as secretRef to the environment variables // of a pod and kubernetes magically makes the secret pointed to by this combination available as a env variable. @Override public void configureKubernetesRuntimeSecretsProvider(V1PodSpec podSpec, String functionsContainerName, Function.FunctionDetails functionDetails) { V1Container container = null; for (V1Container v1Container : podSpec.getContainers()) { if (v1Container.getName().equals(functionsContainerName)) { container = v1Container; break; } } if (container == null) { throw new RuntimeException("No FunctionContainer found"); } if (!StringUtils.isEmpty(functionDetails.getSecretsMap())) { Type v2 = new TypeToken<Map<String, Object>>() {}.getType(); Map<String, Object> secretsMap = new Gson().fromJson(functionDetails.getSecretsMap(), v2); for (Map.Entry<String, Object> entry : secretsMap.entrySet()) { final V1EnvVar secretEnv = new V1EnvVar(); Map<String, String> kv = ((Map<String, String>) (entry.getValue())); secretEnv.name(entry.getKey()).valueFrom(new V1EnvVarSource().secretKeyRef(new V1SecretKeySelector().name(kv.get(idKey)).key(kv.get(keyKey)))); container.addEnvItem(secretEnv); } } }
3.26
pulsar_KubernetesSecretsProviderConfigurator_doAdmissionChecks_rdh
// The secret object should be of type Map<String, String> and it should contain "id" and "key" @Override public void doAdmissionChecks(AppsV1Api appsV1Api, CoreV1Api coreV1Api, String jobNamespace, String jobName, Function.FunctionDetails functionDetails) { if (!StringUtils.isEmpty(functionDetails.getSecretsMap())) { Type type = new TypeToken<Map<String, Object>>() {}.getType(); Map<String, Object> secretsMap = new Gson().fromJson(functionDetails.getSecretsMap(), type); for (Object object : secretsMap.values()) { if (object instanceof Map) {Map<String, String> kubernetesSecret = ((Map<String, String>) (object)); if (kubernetesSecret.size() < 2) { throw new IllegalArgumentException("Kubernetes Secret should contain id and key"); } if (!kubernetesSecret.containsKey(idKey)) { throw new IllegalArgumentException("Kubernetes Secret should contain id information"); } if (!kubernetesSecret.containsKey(keyKey)) { throw new IllegalArgumentException("Kubernetes Secret should contain key information"); } } else { throw new IllegalArgumentException("Kubernetes Secret should be a Map containing id/key pairs"); } } } }
3.26
pulsar_BrokerLoadData_updateSystemResourceUsage_rdh
// Update resource usage given each individual usage. private void updateSystemResourceUsage(final ResourceUsage cpu, final ResourceUsage memory, final ResourceUsage directMemory, final ResourceUsage bandwidthIn, final ResourceUsage bandwidthOut) {this.cpu = cpu; this.memory = memory; this.directMemory = directMemory; this.bandwidthIn = bandwidthIn; this.f0 = bandwidthOut; }
3.26
pulsar_BrokerLoadData_update_rdh
/** * Using another BrokerLoadData, update this. * * @param other * BrokerLoadData to update from. */ public void update(final BrokerLoadData other) { updateSystemResourceUsage(other.cpu, other.memory, other.directMemory, other.bandwidthIn, other.f0); msgThroughputIn = other.msgThroughputIn; msgThroughputOut = other.msgThroughputOut; msgRateIn = other.msgRateIn; msgRateOut = other.msgRateOut; bundleCount = other.bundleCount; topics = other.topics; weightedMaxEMA = other.weightedMaxEMA; msgThroughputEMA = other.msgThroughputEMA; maxResourceUsage = other.maxResourceUsage; updatedAt = other.updatedAt; reportedAt = other.reportedAt; }
3.26
pulsar_TopKBundles_update_rdh
/** * Update the topK bundles from the input bundleStats. * * @param bundleStats * bundle stats. * @param topk * top k bundle stats to select. */ public void update(Map<String, NamespaceBundleStats> bundleStats, int topk) { arr.clear(); try { var isLoadBalancerSheddingBundlesWithPoliciesEnabled = pulsar.getConfiguration().isLoadBalancerSheddingBundlesWithPoliciesEnabled(); for (var etr : bundleStats.entrySet()) { String v2 = etr.getKey(); // TODO: do not filter system topic while shedding if (NamespaceService.isSystemServiceNamespace(NamespaceBundle.getBundleNamespace(v2))) { continue; } if ((!isLoadBalancerSheddingBundlesWithPoliciesEnabled) && hasPolicies(v2)) { continue;} arr.add(etr); } var v3 = loadData.getTopBundlesLoadData(); v3.clear(); if (arr.isEmpty()) { return; } topk = Math.min(topk, arr.size()); partitionSort(arr, topk); for (int i = topk - 1; i >= 0; i--) { var etr = arr.get(i); v3.add(new TopBundlesLoadData.BundleLoadData(etr.getKey(), ((NamespaceBundleStats) (etr.getValue())))); } } finally { arr.clear(); } }
3.26
pulsar_TxnMetaImpl_addProducedPartitions_rdh
/** * Add the list partitions that the transaction produces to. * * @param partitions * the list of partitions that the txn produces to * @return the transaction itself. * @throws InvalidTxnStatusException */ @Override public synchronized TxnMetaImpl addProducedPartitions(List<String> partitions) throws InvalidTxnStatusException { checkTxnStatus(TxnStatus.OPEN); this.producedPartitions.addAll(partitions); return this; }
3.26
pulsar_TxnMetaImpl_addAckedPartitions_rdh
/** * Remove the list partitions that the transaction acknowledges to. * * @param partitions * the list of partitions that the txn acknowledges to * @return the transaction itself. * @throws InvalidTxnStatusException */ @Override public synchronized TxnMetaImpl addAckedPartitions(List<TransactionSubscription> partitions) throws InvalidTxnStatusException { checkTxnStatus(TxnStatus.OPEN);this.ackedPartitions.addAll(partitions);return this; }
3.26
pulsar_TxnMetaImpl_checkTxnStatus_rdh
/** * Check if the transaction is in an expected status. * * @param expectedStatus */ private synchronized void checkTxnStatus(TxnStatus expectedStatus) throws InvalidTxnStatusException { if (this.txnStatus != expectedStatus) { throw new InvalidTxnStatusException(txnID, expectedStatus, txnStatus); } }
3.26
pulsar_TxnMetaImpl_updateTxnStatus_rdh
/** * Update the transaction stats from the <tt>newStatus</tt> only when * the current status is the expected <tt>expectedStatus</tt>. * * @param newStatus * the new transaction status * @param expectedStatus * the expected transaction status * @return the transaction itself. * @throws InvalidTxnStatusException */ @Override public synchronized TxnMetaImpl updateTxnStatus(TxnStatus newStatus, TxnStatus expectedStatus) throws InvalidTxnStatusException { checkTxnStatus(expectedStatus); if (!TransactionUtil.canTransitionTo(txnStatus, newStatus)) {throw new InvalidTxnStatusException((((("Transaction `" + txnID) + "` CANNOT transaction from status ") + txnStatus) + " to ") + newStatus); } this.txnStatus = newStatus; return this; }
3.26
pulsar_TxnMetaImpl_status_rdh
/** * Return the current status of the transaction. * * @return current status of the transaction. */ @Override public synchronized TxnStatus status() { return txnStatus; }
3.26
pulsar_AuthenticationDataCommand_hasDataFromCommand_rdh
/* Command */ @Override public boolean hasDataFromCommand() { return authData != null; }
3.26
pulsar_AuthenticationDataCommand_hasDataFromTls_rdh
/* TLS */ @Override public boolean hasDataFromTls() { return sslSession != null; }
3.26
pulsar_AuthenticationDataCommand_hasDataFromPeer_rdh
/* Peer */ @Override public boolean hasDataFromPeer() { return remoteAddress != null; }
3.26
pulsar_DLInputStream_read_rdh
/** * When reading the end of a stream, it will throw an EndOfStream exception. So we can use this to * check if we read to the end. * * @param outputStream * the data write to * @param readFuture * a future that wait to read complete * @param num * how many entries read in one time */ private void read(OutputStream outputStream, CompletableFuture<Void> readFuture, int num) { reader.readBulk(num).whenComplete((logRecordWithDLSNS, throwable) -> { if (null != throwable) { if (throwable instanceof EndOfStreamException) { readFuture.complete(null); } else { readFuture.completeExceptionally(throwable); } return; } CompletableFuture.runAsync(() -> logRecordWithDLSNS.forEach(logRecord -> {try { outputStream.write(logRecord.getPayload()); } catch (IOException e) { readFuture.completeExceptionally(e); } })).thenRun(() -> read(outputStream, readFuture, num)); }); }
3.26
pulsar_DLInputStream_readAsync_rdh
/** * Read data to output stream. * * @param outputStream * the data write to * @return */ CompletableFuture<DLInputStream> readAsync(OutputStream outputStream) { CompletableFuture<Void> outputFuture = new CompletableFuture<>(); read(outputStream, outputFuture, 10); return outputFuture.thenApply(ignore -> this); }
3.26
pulsar_RecordSchemaBuilderImpl_splitName_rdh
/** * Split a full dotted-syntax name into a namespace and a single-component name. */ private static String[] splitName(String fullName) { String[] result = new String[2]; int indexLastDot = fullName.lastIndexOf('.'); if (indexLastDot >= 0) { result[0] = fullName.substring(0, indexLastDot); result[1] = fullName.substring(indexLastDot + 1); } else { result[0] = null; result[1] = fullName; } return result; }
3.26
pulsar_ClusterDataImpl_checkPropertiesIfPresent_rdh
/** * Check cluster data properties by rule, if some property is illegal, it will throw * {@link IllegalArgumentException}. * * @throws IllegalArgumentException * exist illegal property. */ public void checkPropertiesIfPresent() throws IllegalArgumentException { URIPreconditions.checkURIIfPresent(getServiceUrl(), uri -> Objects.equals(uri.getScheme(), "http"), "Illegal service url, example: http://pulsar.example.com:8080"); URIPreconditions.checkURIIfPresent(getServiceUrlTls(), uri -> Objects.equals(uri.getScheme(), "https"), "Illegal service tls url, example: https://pulsar.example.com:8443");URIPreconditions.checkURIIfPresent(getBrokerServiceUrl(), uri -> Objects.equals(uri.getScheme(), "pulsar"), "Illegal broker service url, example: pulsar://pulsar.example.com:6650"); URIPreconditions.checkURIIfPresent(getBrokerServiceUrlTls(), uri -> Objects.equals(uri.getScheme(), "pulsar+ssl"), "Illegal broker service tls url, example: pulsar+ssl://pulsar.example.com:6651"); URIPreconditions.checkURIIfPresent(getProxyServiceUrl(), uri -> Objects.equals(uri.getScheme(), "pulsar") || Objects.equals(uri.getScheme(), "pulsar+ssl"), "Illegal proxy service url, example: pulsar+ssl://ats-proxy.example.com:4443 " + "or pulsar://ats-proxy.example.com:4080"); m2(); }
3.26
pulsar_Commands_peekAndCopyMessageMetadata_rdh
/** * Peek the message metadata from the buffer and return a deep copy of the metadata. * * If you want to hold multiple {@link MessageMetadata} instances from multiple buffers, you must call this method * rather than {@link Commands#peekMessageMetadata(ByteBuf, String, long)}, which returns a thread local reference, * see {@link Commands#LOCAL_MESSAGE_METADATA}. */ public static MessageMetadata peekAndCopyMessageMetadata(ByteBuf metadataAndPayload, String subscription, long consumerId) { final MessageMetadata localMetadata = peekMessageMetadata(metadataAndPayload, subscription, consumerId); if (localMetadata == null) { return null; } final MessageMetadata metadata = new MessageMetadata(); metadata.copyFrom(localMetadata); return metadata; }
3.26
pulsar_Commands_readChecksum_rdh
/** * Read the checksum and advance the reader index in the buffer. * * <p>Note: This method assume the checksum presence was already verified before. */ public static int readChecksum(ByteBuf buffer) { buffer.skipBytes(2);// skip magic bytes return buffer.readInt(); }
3.26
pulsar_Commands_newTxn_rdh
// ---- transaction related ---- public static ByteBuf newTxn(long tcId, long requestId, long ttlSeconds) { BaseCommand cmd = localCmd(Type.NEW_TXN); cmd.setNewTxn().setTcId(tcId).setRequestId(requestId).setTxnTtlSeconds(ttlSeconds); return m5(cmd); }
3.26
pulsar_BaseResource_requestAsync_rdh
// do the authentication stage, and once authentication completed return a Builder public CompletableFuture<Builder> requestAsync(final WebTarget target) { CompletableFuture<Builder> builderFuture = new CompletableFuture<>(); CompletableFuture<Map<String, String>> authFuture = new CompletableFuture<>(); try { AuthenticationDataProvider authData = auth.getAuthData(target.getUri().getHost()); if (authData.hasDataForHttp()) { auth.authenticationStage(target.getUri().toString(), authData, null, authFuture); } else { authFuture.complete(null); } // auth complete, return a new Builder authFuture.whenComplete((respHeaders, ex) -> { if (ex != null) { log.warn("[{}] Failed to perform http request at auth stage: {}", target.getUri(), ex.getMessage()); builderFuture.completeExceptionally(new PulsarClientException(ex)); return; } try { Builder builder = target.request(MediaType.APPLICATION_JSON);if (authData.hasDataForHttp()) { Set<Entry<String, String>> headers = auth.newRequestHeader(target.getUri().toString(), authData, respHeaders); if (headers != null) { headers.forEach(entry -> builder.header(entry.getKey(), entry.getValue())); } } builderFuture.complete(builder); } catch (Throwable t) { builderFuture.completeExceptionally(new GettingAuthenticationDataException(t)); } }); } catch (Throwable t) { builderFuture.completeExceptionally(new GettingAuthenticationDataException(t)); } return builderFuture; }
3.26
pulsar_AdminResource_checkTopicExistsAsync_rdh
/** * Check the exists topics contains the given topic. * Since there are topic partitions and non-partitioned topics in Pulsar, must ensure both partitions * and non-partitioned topics are not duplicated. So, if compare with a partition name, we should compare * to the partitioned name of this partition. * * @param topicName * given topic name */ protected CompletableFuture<Boolean> checkTopicExistsAsync(TopicName topicName) { return pulsar().getNamespaceService().getListOfTopics(topicName.getNamespaceObject(), Mode.ALL).thenCompose(topics -> { boolean exists = false; for (String topic : topics) { if (topicName.getPartitionedTopicName().equals(TopicName.get(topic).getPartitionedTopicName())) { exists = true; break; } } return CompletableFuture.completedFuture(exists); }); }
3.26
pulsar_AdminResource_validateAdminAccessForTenant_rdh
// This is a stub method for Mockito @Override protected void validateAdminAccessForTenant(String property) { super.validateAdminAccessForTenant(property); }
3.26
pulsar_AdminResource_validatePoliciesReadOnlyAccess_rdh
/** * Checks whether the broker is allowed to do read-write operations based on the existence of a node in * configuration metadata-store. * * @throws WebApplicationException * if broker has a read only access if broker is not connected to the configuration metadata-store */ public void validatePoliciesReadOnlyAccess() { try { validatePoliciesReadOnlyAccessAsync().join(); } catch (CompletionException ce) { throw new RestException(ce.getCause()); } }
3.26
pulsar_AdminResource_domain_rdh
/** * Get the domain of the topic (whether it's persistent or non-persistent). */ protected String domain() { if (uri.getPath().startsWith("persistent/")) { return "persistent"; } else if (uri.getPath().startsWith("non-persistent/")) { return "non-persistent"; } else { throw new RestException(Status.INTERNAL_SERVER_ERROR, "domain() invoked from wrong resource"); } }
3.26
pulsar_AdminResource_isRedirectException_rdh
/** * Check current exception whether is redirect exception. * * @param ex * The throwable. * @return Whether is redirect exception */ protected static boolean isRedirectException(Throwable ex) { Throwable realCause = FutureUtil.unwrapCompletionException(ex); return (realCause instanceof WebApplicationException) && (((WebApplicationException) (realCause)).getResponse().getStatus() == Status.TEMPORARY_REDIRECT.getStatusCode()); }
3.26
pulsar_AdminResource_validateBundleOwnership_rdh
// This is a stub method for Mockito @Overrideprotected void validateBundleOwnership(String property, String cluster, String namespace, boolean authoritative, boolean readOnly, NamespaceBundle bundle) { super.validateBundleOwnership(property, cluster, namespace, authoritative, readOnly, bundle); }
3.26
pulsar_AwsCredentialProviderPlugin_getV2CredentialsProvider_rdh
/** * Returns a V2 credential provider for use with the v2 SDK. * * Defaults to an implementation that pulls credentials from a v1 provider */ default AwsCredentialsProvider getV2CredentialsProvider() { // make a small wrapper to forward requests to v1, this allows // for this interface to not "break" for implementers AWSCredentialsProvider v1Provider = getCredentialProvider(); return () -> { AWSCredentials creds = v1Provider.getCredentials(); if (creds instanceof AWSSessionCredentials) { return software.amazon.awssdk.auth.credentials.AwsSessionCredentials.create(creds.getAWSAccessKeyId(), creds.getAWSSecretKey(), ((AWSSessionCredentials) (creds)).getSessionToken()); } else { return software.amazon.awssdk.auth.credentials.AwsBasicCredentials.create(creds.getAWSAccessKeyId(), creds.getAWSSecretKey()); } }; }
3.26
pulsar_BrokerInterceptorUtils_getBrokerInterceptorDefinition_rdh
/** * Retrieve the broker interceptor definition from the provided handler nar package. * * @param narPath * the path to the broker interceptor NAR package * @return the broker interceptor definition * @throws IOException * when fail to load the broker interceptor or get the definition */ public BrokerInterceptorDefinition getBrokerInterceptorDefinition(String narPath, String narExtractionDirectory) throws IOException { try (NarClassLoader ncl = NarClassLoaderBuilder.builder().narFile(new File(narPath)).extractionDirectory(narExtractionDirectory).build()) { return getBrokerInterceptorDefinition(ncl); } }
3.26
pulsar_BrokerInterceptorUtils_searchForInterceptors_rdh
/** * Search and load the available broker interceptors. * * @param interceptorsDirectory * the directory where all the broker interceptors are stored * @return a collection of broker interceptors * @throws IOException * when fail to load the available broker interceptors from the provided directory. */ public BrokerInterceptorDefinitions searchForInterceptors(String interceptorsDirectory, String narExtractionDirectory) throws IOException { Path path = Paths.get(interceptorsDirectory).toAbsolutePath();log.info("Searching for broker interceptors in {}", path); BrokerInterceptorDefinitions interceptors = new BrokerInterceptorDefinitions(); if (!path.toFile().exists()) { log.warn("Pulsar broker interceptors directory not found"); return interceptors; } try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, "*.nar")) { for (Path archive : stream) { try { BrokerInterceptorDefinition def = BrokerInterceptorUtils.getBrokerInterceptorDefinition(archive.toString(), narExtractionDirectory); log.info("Found broker interceptors from {} : {}", archive, def); checkArgument(StringUtils.isNotBlank(def.getName())); checkArgument(StringUtils.isNotBlank(def.getInterceptorClass())); BrokerInterceptorMetadata metadata = new BrokerInterceptorMetadata(); metadata.setDefinition(def); metadata.setArchivePath(archive); interceptors.interceptors().put(def.getName(), metadata); } catch (Throwable t) { log.warn((("Failed to load broker interceptor from {}." + " It is OK however if you want to use this broker interceptor,") + " please make sure you put the correct broker interceptor NAR") + " package in the broker interceptors directory.", archive, t); } }} return interceptors; }
3.26
pulsar_BrokerInterceptorUtils_load_rdh
/** * Load the broker interceptors according to the interceptor definition. * * @param metadata * the broker interceptors definition. */ BrokerInterceptorWithClassLoader load(BrokerInterceptorMetadata metadata, String narExtractionDirectory) throws IOException { final File narFile = metadata.getArchivePath().toAbsolutePath().toFile(); NarClassLoader ncl = NarClassLoaderBuilder.builder().narFile(narFile).parentClassLoader(BrokerInterceptorUtils.class.getClassLoader()).extractionDirectory(narExtractionDirectory).build(); BrokerInterceptorDefinition v10 = getBrokerInterceptorDefinition(ncl); if (StringUtils.isBlank(v10.getInterceptorClass())) { throw new IOException((("Broker interceptors `" + v10.getName()) + "` does NOT provide a broker") + " interceptors implementation"); } try { Class interceptorClass = ncl.loadClass(v10.getInterceptorClass()); Object interceptor = interceptorClass.getDeclaredConstructor().newInstance(); if (!(interceptor instanceof BrokerInterceptor)) { throw new IOException(("Class " + v10.getInterceptorClass()) + " does not implement broker interceptor interface"); } BrokerInterceptor pi = ((BrokerInterceptor) (interceptor)); return new BrokerInterceptorWithClassLoader(pi, ncl); } catch (Throwable t) { rethrowIOException(t); return null; } }
3.26
pulsar_BlockAwareSegmentInputStreamImpl_calculateBlockSize_rdh
// Calculate the block size after uploaded `entryBytesAlreadyWritten` bytes public static int calculateBlockSize(int maxBlockSize, ReadHandle readHandle, long firstEntryToWrite, long entryBytesAlreadyWritten) { return ((int) (Math.min(maxBlockSize, ((((readHandle.getLastAddConfirmed() - firstEntryToWrite) + 1) * f0) + (readHandle.getLength() - entryBytesAlreadyWritten)) + DataBlockHeaderImpl.getDataStartOffset()))); }
3.26
pulsar_BlockAwareSegmentInputStreamImpl_readEntries_rdh
// read ledger entries. private int readEntries() throws IOException { checkState(bytesReadOffset >= DataBlockHeaderImpl.getDataStartOffset()); checkState(bytesReadOffset < blockSize); // once reach the end of entry buffer, read more, if there is more if (((bytesReadOffset < dataBlockFullOffset) && entriesByteBuf.isEmpty()) && ((startEntryId + blockEntryCount) <= ledger.getLastAddConfirmed())) { entriesByteBuf = readNextEntriesFromLedger(startEntryId + blockEntryCount, ENTRIES_PER_READ); } if ((!entriesByteBuf.isEmpty()) && ((bytesReadOffset + entriesByteBuf.get(0).readableBytes()) <= blockSize)) { // always read from the first ByteBuf in the list, once read all of its content remove it. ByteBuf entryByteBuf = entriesByteBuf.get(0); int ret = entryByteBuf.readUnsignedByte(); bytesReadOffset++; if (entryByteBuf.readableBytes() == 0) { entryByteBuf.release(); entriesByteBuf.remove(0); blockEntryCount++; } return ret; } else { // no space for a new entry or there are no more entries // set data block full, return end padding if (dataBlockFullOffset == blockSize) { dataBlockFullOffset = bytesReadOffset; } return BLOCK_END_PADDING[((bytesReadOffset++) - dataBlockFullOffset) % BLOCK_END_PADDING.length]; } }
3.26
pulsar_PulsarFieldValueProviders_timeValueProvider_rdh
/** * FieldValueProvider for Time (Data, Timestamp etc.) with indicate Null instead of longValueProvider. */ public static FieldValueProvider timeValueProvider(long millis, boolean isNull) { return new FieldValueProvider() { @Override public long getLong() { return millis * Timestamps.MICROSECONDS_PER_MILLISECOND; } @Override public boolean isNull() { return isNull; } }; }
3.26
pulsar_TopicsImpl_validateTopic_rdh
/* returns topic name with encoded Local Name */ private TopicName validateTopic(String topic) { // Parsing will throw exception if name is not valid return TopicName.get(topic); }
3.26
pulsar_ProducerStats_getPartitionStats_rdh
/** * * @return stats for each partition if topic is partitioned topic */ default Map<String, ProducerStats> getPartitionStats() { return Collections.emptyMap(); }
3.26
pulsar_TxnBatchedPositionImpl_compareTo_rdh
/** * It's exactly the same as {@link PositionImpl},to make sure that when compare to the "markDeletePosition", it * looks like {@link PositionImpl}. {@link #batchSize} and {@link #batchIndex} should not be involved in calculate, * just like {@link PositionImpl#ackSet} is not involved in calculate. * Note: In {@link java.util.concurrent.ConcurrentSkipListMap}, it use the {@link Comparable#compareTo(Object)} to * determine whether the keys are the same. In {@link java.util.HashMap}, it use the * {@link Object#hashCode()} & {@link Object#equals(Object)} to determine whether the keys are the same. */ public int compareTo(PositionImpl that) { return super.compareTo(that); }
3.26
pulsar_TxnBatchedPositionImpl_setAckSetByIndex_rdh
/** * Build the attribute ackSet to that {@link #batchIndex} is false and others is true. */ public void setAckSetByIndex() { if (batchSize == 1) { return; } BitSetRecyclable bitSetRecyclable = BitSetRecyclable.create(); bitSetRecyclable.set(0, batchSize, true); bitSetRecyclable.clear(batchIndex); long[] ackSet = bitSetRecyclable.toLongArray();bitSetRecyclable.recycle(); setAckSet(ackSet); }
3.26
pulsar_TxnBatchedPositionImpl_hashCode_rdh
/** * It's exactly the same as {@link PositionImpl},make sure that when {@link TxnBatchedPositionImpl} used as the key * of map same as {@link PositionImpl}. {@link #batchSize} and {@link #batchIndex} should not be involved in * calculate, just like {@link PositionImpl#ackSet} is not involved in calculate. * Note: In {@link java.util.concurrent.ConcurrentSkipListMap}, it use the {@link Comparable#compareTo(Object)} to * determine whether the keys are the same. In {@link java.util.HashMap}, it use the * {@link Object#hashCode()} & {@link Object#equals(Object)} to determine whether the keys are the same. */ @Override public int hashCode() { return super.hashCode();}
3.26
pulsar_TxnBatchedPositionImpl_equals_rdh
/** * It's exactly the same as {@link PositionImpl},make sure that when {@link TxnBatchedPositionImpl} used as the key * of map same as {@link PositionImpl}. {@link #batchSize} and {@link #batchIndex} should not be involved in * calculate, just like {@link PositionImpl#ackSet} is not involved in calculate. * Note: In {@link java.util.concurrent.ConcurrentSkipListMap}, it use the {@link Comparable#compareTo(Object)} to * determine whether the keys are the same. In {@link java.util.HashMap}, it use the * {@link Object#hashCode()} & {@link Object#equals(Object)} to determine whether the keys are the same. */ @Override public boolean equals(Object o) { return super.equals(o); }
3.26
pulsar_ConcurrentOpenHashSet_forEach_rdh
/** * Iterate over all the elements in the set and apply the provided function. * <p> * <b>Warning: Do Not Guarantee Thread-Safety.</b> * * @param processor * the function to apply to each element */ public void forEach(Consumer<? super V> processor) { for (int i = 0; i < sections.length; i++) { sections[i].forEach(processor); } }
3.26
pulsar_ConcurrentOpenHashSet_values_rdh
/** * * @return a new list of all values (makes a copy) */ public List<V> values() { List<V> values = new ArrayList<>(); forEach(value -> values.add(value)); return values; }
3.26
pulsar_ProducerResponse_getSchemaVersion_rdh
// Shadow the default getter generated by lombok. In broker, if the schema version is an empty byte array, it means // the topic doesn't have schema. public byte[] getSchemaVersion() { if ((schemaVersion != null) && (schemaVersion.length != 0)) { return schemaVersion; } else { return null; } }
3.26
pulsar_BlobStoreBackedInputStreamImpl_refillBufferIfNeeded_rdh
/** * Refill the buffered input if it is empty. * * @return true if there are bytes to read, false otherwise */ private boolean refillBufferIfNeeded() throws IOException { if (buffer.readableBytes() == 0) {if (cursor >= objectLen) { return false; } long startRange = cursor; long endRange = Math.min((cursor + bufferSize) - 1, objectLen - 1); if (log.isDebugEnabled()) { log.info("refillBufferIfNeeded {} - {} ({} bytes to fill)", startRange, endRange, endRange - startRange); } try { long startReadTime = System.nanoTime(); Blob blob = blobStore.getBlob(bucket, key, new GetOptions().range(startRange, endRange));versionCheck.check(key, blob); try (InputStream stream = blob.getPayload().openStream()) { buffer.clear(); bufferOffsetStart = startRange; bufferOffsetEnd = endRange; long bytesRead = (endRange - startRange) + 1; int bytesToCopy = ((int) (bytesRead)); while (bytesToCopy > 0) {bytesToCopy -= buffer.writeBytes(stream, bytesToCopy); } cursor += buffer.readableBytes(); } // here we can get the metrics // because JClouds streams the content // and actually the HTTP call finishes when the stream is fully read if (this.offloaderStats != null) { this.offloaderStats.recordReadOffloadDataLatency(topicName, System.nanoTime() - startReadTime, TimeUnit.NANOSECONDS); this.offloaderStats.recordReadOffloadBytes(topicName, (endRange - startRange) + 1); } } catch (Throwable e) { if (null != this.offloaderStats) { this.offloaderStats.recordReadOffloadError(this.topicName); } throw new IOException("Error reading from BlobStore", e); } } return true; }
3.26
pulsar_AvroRecordBuilderImpl_set_rdh
/** * Sets the value of a field. * * @param index * the field to set. * @param value * the value to set. * @return a reference to the RecordBuilder. */ protected GenericRecordBuilder set(int index, Object value) { if (value instanceof GenericRecord) { if (value instanceof GenericAvroRecord) { avroRecordBuilder.set(genericSchema.getAvroSchema().getFields().get(index), ((GenericAvroRecord) (value)).getAvroRecord()); } else { throw new IllegalArgumentException("Avro Record Builder doesn't support non-avro record as a field"); } } else { avroRecordBuilder.set(genericSchema.getAvroSchema().getFields().get(index), value); } return this;}
3.26
pulsar_AvroRecordBuilderImpl_clear_rdh
/** * Clears the value of the given field. * * @param index * the index of the field to clear. * @return a reference to the RecordBuilder. */ protected GenericRecordBuilder clear(int index) { avroRecordBuilder.clear(genericSchema.getAvroSchema().getFields().get(index)); return this; }
3.26
pulsar_Context_getCurrentRecord_rdh
/** * Access the record associated with the current input value. * * @return the current record */ Record<?> getCurrentRecord() { }
3.26
pulsar_Context_newOutputRecordBuilder_rdh
/** * Creates a FunctionRecordBuilder initialized with values from this Context. * It can be used in Functions to prepare a Record to return with default values taken from the Context and the * input Record. * * @param schema * provide a way to convert between serialized data and domain objects * @param <X> * the message type of record builder * @return the record builder instance */ <X> FunctionRecord.FunctionRecordBuilder<X> newOutputRecordBuilder(Schema<X> schema) { }
3.26
pulsar_EnumValuesDataProvider_toDataProviderArray_rdh
/* Converts all values of an Enum class to a TestNG DataProvider object array */ public static Object[][] toDataProviderArray(Class<? extends Enum<?>> enumClass) { Enum<?>[] enumValues = enumClass.getEnumConstants(); return Stream.of(enumValues).map(enumValue -> new Object[]{ enumValue }).collect(Collectors.toList()).toArray(new Object[0][]); }
3.26
pulsar_LoadSimulationController_handleCopy_rdh
// Handle the command line arguments associated with the copy command. private void handleCopy(final ShellArguments arguments) throws Exception { final List<String> commandArguments = arguments.commandArguments; // Copy accepts 3 application arguments: Tenant name, source ZooKeeper and target ZooKeeper connect strings. if (checkAppArgs(commandArguments.size() - 1, 3)) { final String tenantName = commandArguments.get(1); final String sourceZKConnectString = commandArguments.get(2); final String targetZKConnectString = commandArguments.get(3); final ZooKeeper sourceZKClient = new ZooKeeper(sourceZKConnectString, 5000, null); final ZooKeeper targetZKClient = new ZooKeeper(targetZKConnectString, 5000, null); // Make a map for each thread to speed up the ZooKeeper writing process. final Map<String, ResourceQuota>[] threadLocalMaps = new Map[clients.length]; for (int i = 0; i < clients.length; ++i) { threadLocalMaps[i] = new HashMap<>();} getResourceQuotas(QUOTA_ROOT, sourceZKClient, threadLocalMaps); final List<Future> futures = new ArrayList<>(clients.length); int i = 0; log.info("Copying..."); for (final Map<String, ResourceQuota> bundleToQuota : threadLocalMaps) { final int j = i; futures.add(threadPool.submit(() -> { for (final Map.Entry<String, ResourceQuota> entry : bundleToQuota.entrySet()) { final String bundle = entry.getKey(); final ResourceQuota quota = entry.getValue(); // Simulation will send messages in and out at about the same rate, so just make the rate the // average of in and out. final int tenantStart = QUOTA_ROOT.length() + 1; final int clusterStart = bundle.indexOf('/', tenantStart) + 1; final String sourceTenant = bundle.substring(tenantStart, clusterStart - 1); final int namespaceStart = bundle.indexOf('/', clusterStart) + 1; final String sourceCluster = bundle.substring(clusterStart, namespaceStart - 1); final String namespace = bundle.substring(namespaceStart, bundle.lastIndexOf('/')); final String keyRangeString = bundle.substring(bundle.lastIndexOf('/') + 1); // To prevent duplicate node issues for same namespace names in different clusters/tenants. final String manglePrefix = String.format("%s-%s-%s", sourceCluster, sourceTenant, keyRangeString); final String mangledNamespace = String.format("%s-%s", manglePrefix, namespace); final BundleData bundleData = initializeBundleData(quota, arguments); final String oldAPITargetPath = String.format("/loadbalance/resource-quota/namespace/%s/%s/%s/0x00000000_0xffffffff", tenantName, cluster, mangledNamespace); final String newAPITargetPath = String.format("%s/%s/%s/%s/0x00000000_0xffffffff", BUNDLE_DATA_BASE_PATH, tenantName, cluster, mangledNamespace); try { ZkUtils.createFullPathOptimistic(targetZKClient, oldAPITargetPath, ObjectMapperFactory.getMapper().writer().writeValueAsBytes(quota), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException e) { // Ignore already created nodes. } catch (Exception e) { throw new RuntimeException(e); } // Put the bundle data in the new ZooKeeper. try {ZkUtils.createFullPathOptimistic(targetZKClient, newAPITargetPath, ObjectMapperFactory.getMapper().writer().writeValueAsBytes(bundleData), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException e) {// Ignore already created nodes. } catch (Exception e) { throw new RuntimeException(e); } try { trade(arguments, makeTopic(tenantName, mangledNamespace, "t"), j); } catch (Exception e) { throw new RuntimeException(e); } } })); ++i; } for (final Future future : futures) { future.get(); } sourceZKClient.close(); targetZKClient.close(); } }
3.26
pulsar_LoadSimulationController_writeProducerOptions_rdh
// Write options that are common to modifying and creating topics. private void writeProducerOptions(final DataOutputStream outputStream, final ShellArguments arguments, final String topic) throws Exception { if (!arguments.rangeString.isEmpty()) { // If --rand-rate was specified, extract the bounds by splitting on // the comma and parsing the resulting // doubles. final String[] splits = arguments.rangeString.split(","); if (splits.length != 2) { log.error("Argument to --rand-rate should be two comma-separated values"); return; } final double first = Double.parseDouble(splits[0]); final double second = Double.parseDouble(splits[1]);final double min = Math.min(first, second); final double max = Math.max(first, second); arguments.rate = (random.nextDouble() * (max - min)) + min; } outputStream.writeUTF(topic); outputStream.writeInt(arguments.size); outputStream.writeDouble(arguments.rate); }
3.26
pulsar_LoadSimulationController_handleChange_rdh
// Handle the command line arguments associated with the change command. private void handleChange(final ShellArguments arguments) throws Exception { final List<String> v30 = arguments.commandArguments; // Change expects three application arguments: tenant name, namespace name, and topic name. if (checkAppArgs(v30.size() - 1, 3)) { final String topic = makeTopic(v30.get(1), v30.get(2), v30.get(3)); if (changeIfExists(arguments, topic) == (-1)) { log.info("Topic {} not found", topic); } } }
3.26
pulsar_LoadSimulationController_initializeBundleData_rdh
// Initialize a BundleData from a resource quota and configurations and modify the quota accordingly. private BundleData initializeBundleData(final ResourceQuota quota, final ShellArguments arguments) { final double messageRate = (quota.getMsgRateIn() + quota.getMsgRateOut()) / 2; final int messageSize = ((int) (Math.ceil((quota.getBandwidthIn() + quota.getBandwidthOut()) / (2 * messageRate)))); arguments.rate = messageRate * arguments.rateMultiplier; arguments.size = messageSize; final NamespaceBundleStats startingStats = new NamespaceBundleStats(); // Modify the original quota so that new rates are set. final double modifiedRate = messageRate * arguments.rateMultiplier; final double modifiedBandwidth = ((quota.getBandwidthIn() + quota.getBandwidthOut()) * arguments.rateMultiplier) / 2; quota.setMsgRateIn(modifiedRate); quota.setMsgRateOut(modifiedRate); quota.setBandwidthIn(modifiedBandwidth); quota.setBandwidthOut(modifiedBandwidth); // Assume modified memory usage is comparable to the rate multiplier times the original usage. quota.setMemory(quota.getMemory() * arguments.rateMultiplier); startingStats.msgRateIn = quota.getMsgRateIn(); startingStats.msgRateOut = quota.getMsgRateOut(); startingStats.msgThroughputIn = quota.getBandwidthIn(); startingStats.msgThroughputOut = quota.getBandwidthOut(); final BundleData bundleData = new BundleData(10, 1000, startingStats); // Assume there is ample history for the bundle. bundleData.getLongTermData().setNumSamples(1000); bundleData.getShortTermData().setNumSamples(10); return bundleData; }
3.26
pulsar_LoadSimulationController_handleStream_rdh
// Handle the command line arguments associated with the stream command. private void handleStream(final ShellArguments arguments) throws Exception { final List<String> commandArguments = arguments.commandArguments; // Stream accepts 1 application argument: ZooKeeper connect string. if (checkAppArgs(commandArguments.size() - 1, 1)) { final String zkConnectString = commandArguments.get(1); final ZooKeeper zkClient = new ZooKeeper(zkConnectString, 5000, null); new BrokerWatcher(zkClient, arguments); // This controller will now stream rate changes from the given ZK. // Users wishing to stop this should Ctrl + C and use another // Controller to send new commands. while (true) { } } }
3.26
pulsar_LoadSimulationController_change_rdh
// Change producer settings for a given topic and JCommander arguments. private void change(final ShellArguments arguments, final String topic, final int client) throws Exception { outputStreams[client].write(LoadSimulationClient.CHANGE_COMMAND);writeProducerOptions(outputStreams[client], arguments, topic); outputStreams[client].flush(); }
3.26
pulsar_LoadSimulationController_changeOrCreate_rdh
// Change an existing topic, or create it if it does not exist. private int changeOrCreate(final ShellArguments arguments, final String topic) throws Exception { final int client = find(topic); if (client == (-1)) { trade(arguments, topic, random.nextInt(clients.length)); } else { change(arguments, topic, client); } return client; }
3.26
pulsar_LoadSimulationController_trade_rdh
// Trade using the arguments parsed via JCommander and the topic name. private synchronized void trade(final ShellArguments arguments, final String topic, final int client) throws Exception { // Decide which client to send to randomly to preserve statelessness of // the controller. outputStreams[client].write(LoadSimulationClient.TRADE_COMMAND); writeProducerOptions(outputStreams[client], arguments, topic); outputStreams[client].flush(); }
3.26
pulsar_LoadSimulationController_read_rdh
/** * Read the user-submitted arguments as commands to send to clients. * * @param args * Arguments split on whitespace from user input. */ private void read(final String[] args) { // Don't attempt to process blank input. if ((args.length > 0) && (!((args.length == 1) && args[0].isEmpty()))) { final ShellArguments arguments = new ShellArguments(); final JCommander jc = new JCommander(arguments); try { jc.parse(args); final String command = arguments.commandArguments.get(0); switch (command) { case "trade" : handleTrade(arguments); break; case "change" : handleChange(arguments); break; case "stop" : m0(arguments); break; case "trade_group" : handleGroupTrade(arguments); break; case "change_group" : handleGroupChange(arguments); break; case "stop_group" : handleGroupStop(arguments); break; case "script" : // Read input from the given script instead of stdin until // the script has executed completely. final List<String> commandArguments = arguments.commandArguments; checkAppArgs(commandArguments.size() - 1, 1); final String scriptName = commandArguments.get(1); final BufferedReader scriptReader = new BufferedReader(new InputStreamReader(new FileInputStream(Paths.get(scriptName).toFile()))); String line = scriptReader.readLine(); while (line != null) { read(line.split("\\s+")); line = scriptReader.readLine(); } scriptReader.close(); break; case "copy" : handleCopy(arguments); break;case "stream" : handleStream(arguments); break; case "simulate" : handleSimulate(arguments); break; case "quit" : case "exit" : PerfClientUtils.exit(0); break; default : log.info("ERROR: Unknown command \"{}\"", command); } } catch (ParameterException ex) { ex.printStackTrace(); jc.usage(); } catch (Exception ex) { ex.printStackTrace(); } } }
3.26
pulsar_LoadSimulationController_run_rdh
/** * Create a shell for the user to send commands to clients. */ public void run() throws Exception { BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while (true) { // Print the very simple prompt. System.out.println(); System.out.print("> "); read(inReader.readLine().split("\\s+"));} }
3.26
pulsar_LoadSimulationController_process_rdh
// Update the message rate information for the bundles in a recently changed load report. public synchronized void process(final WatchedEvent event) { try { // Get the load report and put this back as a watch. final LoadReport loadReport = ObjectMapperFactory.getMapper().getObjectMapper().readValue(zkClient.getData(path, this, null), LoadReport.class); for (final Map.Entry<String, NamespaceBundleStats> entry : loadReport.getBundleStats().entrySet()) { final String bundle = entry.getKey(); final String namespace = bundle.substring(0, bundle.lastIndexOf('/')); final String topic = String.format("%s/%s", namespace, "t"); final NamespaceBundleStats stats = entry.getValue(); // Approximate total message rate via average between in/out. final double messageRate = (arguments.rateMultiplier * (stats.msgRateIn + stats.msgRateOut)) / 2; // size = throughput / rate. final int messageSize = ((int) (Math.ceil((arguments.rateMultiplier * (stats.msgThroughputIn + stats.msgThroughputOut)) / (2 * messageRate)))); arguments.rate = messageRate; arguments.size = messageSize;// Try to modify the topic if it already exists. Otherwise, create it. changeOrCreate(arguments, topic); } } catch (Exception ex) { throw new RuntimeException(ex); } }
3.26
pulsar_LoadSimulationController_checkAppArgs_rdh
// Check that the expected number of application arguments matches the // actual number of application arguments. private boolean checkAppArgs(final int numAppArgs, final int numRequired) { if (numAppArgs != numRequired) { log.info("ERROR: Wrong number of application arguments (found {}, required {})", numAppArgs, numRequired); return false; }return true; }
3.26
pulsar_LoadSimulationController_handleGroupTrade_rdh
// Handle the command line arguments associated with the group trade command. private void handleGroupTrade(final ShellArguments arguments) throws Exception { final List<String> commandArguments = arguments.commandArguments;// Group trade expects 3 application arguments: tenant name, group name, // and number of namespaces. if (checkAppArgs(commandArguments.size() - 1, 3)) { final String tenant = commandArguments.get(1); final String group = commandArguments.get(2); final int numNamespaces = Integer.parseInt(commandArguments.get(3)); for (int i = 0; i < numNamespaces; ++i) { for (int j = 0; j < arguments.topicsPerNamespace; ++j) { // For each namespace and topic pair, create the namespace // by using the group name and the // namespace index, and then create the topic by using the // topic index. Then just call trade. final String topic = makeTopic(tenant, String.format("%s-%d", group, i), Integer.toString(j)); trade(arguments, topic, random.nextInt(clients.length)); Thread.sleep(arguments.separation);} } } }
3.26
pulsar_LoadSimulationController_main_rdh
/** * Start a controller with command line arguments. * * @param args * Arguments to pass in. */ public static void main(String[] args) throws Exception { final MainArguments v107 = new MainArguments(); final JCommander jc = new JCommander(v107); jc.setProgramName("pulsar-perf simulation-controller"); try { jc.parse(args); } catch (Exception ex) { System.out.println(ex.getMessage()); jc.usage(); PerfClientUtils.exit(1); } new LoadSimulationController(v107).run(); }
3.26
pulsar_LoadSimulationController_handleGroupStop_rdh
// Handle the command line arguments associated with the group stop command. private void handleGroupStop(final ShellArguments arguments) throws Exception { final List<String> v88 = arguments.commandArguments; // Group stop requires two application arguments: tenant name and group // name. if (checkAppArgs(v88.size() - 1, 2)) { final String tenant = v88.get(1); final String group = v88.get(2); for (DataOutputStream outputStream : outputStreams) { outputStream.write(LoadSimulationClient.STOP_GROUP_COMMAND); outputStream.writeUTF(tenant); outputStream.writeUTF(group); outputStream.flush(); } } }
3.26
pulsar_LoadSimulationController_getResourceQuotas_rdh
// on the children if there are any, or getting the data from this ZNode otherwise. private void getResourceQuotas(final String path, final ZooKeeper zkClient, final Map<String, ResourceQuota>[] threadLocalMaps) throws Exception { final List<String> children = zkClient.getChildren(path, false); if (children.isEmpty()) { threadLocalMaps[random.nextInt(clients.length)].put(path, ObjectMapperFactory.getMapper().getObjectMapper().readValue(zkClient.getData(path, false, null), ResourceQuota.class));} else { for (final String child : children) { getResourceQuotas(String.format("%s/%s", path, child), zkClient, threadLocalMaps); } } }
3.26
pulsar_LoadSimulationController_handleTrade_rdh
// Handle the command line arguments associated with the trade command. private void handleTrade(final ShellArguments arguments) throws Exception { final List<String> commandArguments = arguments.commandArguments; // Trade expects three application arguments: tenant, namespace, and // topic. if (checkAppArgs(commandArguments.size() - 1, 3)) {final String topic = makeTopic(commandArguments.get(1), commandArguments.get(2), commandArguments.get(3)); trade(arguments, topic, random.nextInt(clients.length)); } }
3.26
pulsar_LoadSimulationController_changeIfExists_rdh
// Find a topic and change it if it exists. private int changeIfExists(final ShellArguments arguments, final String topic) throws Exception { final int client = find(topic); if (client != (-1)) { change(arguments, topic, client); }return client; }
3.26
pulsar_LoadSimulationController_m0_rdh
// Handle the command line arguments associated with the stop command. private void m0(final ShellArguments arguments) throws Exception { final List<String> commandArguments = arguments.commandArguments; // Stop expects three application arguments: tenant name, namespace // name, and topic name. if (checkAppArgs(commandArguments.size() - 1, 3)) { final String topic = makeTopic(commandArguments.get(1), commandArguments.get(2), commandArguments.get(3)); for (DataOutputStream outputStream : outputStreams) { outputStream.write(LoadSimulationClient.STOP_COMMAND); outputStream.writeUTF(topic); outputStream.flush(); } } }
3.26
pulsar_LoadSimulationController_find_rdh
// Attempt to find a topic on the clients. private int find(final String topic) throws Exception { int clientWithTopic = -1;for (int i = 0; i < clients.length; ++i) { outputStreams[i].write(LoadSimulationClient.FIND_COMMAND); outputStreams[i].writeUTF(topic); } for (int i = 0; i < clients.length; ++i) { if (inputStreams[i].readBoolean()) { clientWithTopic = i; } } return clientWithTopic; }
3.26
pulsar_SessionEvent_isConnected_rdh
/** * Check whether the state represents a connected or not-connected state. */ public boolean isConnected() { switch (this) { case Reconnected : case SessionReestablished : return true; case ConnectionLost : case SessionLost : default : return false; } }
3.26
pulsar_Dispatcher_trackDelayedDelivery_rdh
/** * Check with dispatcher if the message should be added to the delayed delivery tracker. * Return true if the message should be delayed and ignored at this point. */ default boolean trackDelayedDelivery(long ledgerId, long entryId, MessageMetadata msgMetadata) { return false; }
3.26
pulsar_NonPersistentTopic_close_rdh
/** * Close this topic - close all producers and subscriptions associated with this topic. * * @param disconnectClients * disconnect clients * @param closeWithoutWaitingClientDisconnect * don't wait for client disconnect and forcefully close managed-ledger * @return Completable future indicating completion of close operation */ @Override public CompletableFuture<Void> close(boolean disconnectClients, boolean closeWithoutWaitingClientDisconnect) { CompletableFuture<Void> closeFuture = new CompletableFuture<>(); lock.writeLock().lock(); try { if ((!isFenced) || closeWithoutWaitingClientDisconnect) { isFenced = true; } else { log.warn("[{}] Topic is already being closed or deleted", topic); closeFuture.completeExceptionally(new TopicFencedException("Topic is already fenced")); return closeFuture; } } finally { lock.writeLock().unlock(); } List<CompletableFuture<Void>> futures = new ArrayList<>(); replicators.forEach((cluster, replicator) -> futures.add(replicator.disconnect()));if (disconnectClients) { futures.add(ExtensibleLoadManagerImpl.getAssignedBrokerLookupData(brokerService.getPulsar(), topic).thenAccept(lookupData -> producers.values().forEach(producer -> futures.add(producer.disconnect(lookupData))))); } if (topicPublishRateLimiter != null) { topicPublishRateLimiter.close(); } subscriptions.forEach((s, sub) -> futures.add(sub.disconnect())); if (this.resourceGroupPublishLimiter != null) { this.resourceGroupPublishLimiter.unregisterRateLimitFunction(this.getName()); } if (entryFilters != null) { entryFilters.getRight().forEach(filter -> { try { filter.close(); } catch (Throwable e) { log.warn("Error shutting down entry filter {}", filter, e); } }); } CompletableFuture<Void> clientCloseFuture = (closeWithoutWaitingClientDisconnect) ? CompletableFuture.completedFuture(null) : FutureUtil.waitForAll(futures); clientCloseFuture.thenRun(() -> { log.info("[{}] Topic closed", topic); // unload topic iterates over topics map and removing from the map with the same thread creates deadlock. // so, execute it in different thread brokerService.executor().execute(() -> { if (disconnectClients) { brokerService.removeTopicFromCache(this);unregisterTopicPolicyListener(); } closeFuture.complete(null); }); }).exceptionally(exception -> { log.error("[{}] Error closing topic", topic, exception); isFenced = false; closeFuture.completeExceptionally(exception); return null; }); return closeFuture; }
3.26
pulsar_NonPersistentTopic_checkBacklogQuotaExceeded_rdh
/** * * @return quota exceeded status for blocking producer creation */@Override public CompletableFuture<Void> checkBacklogQuotaExceeded(String producerName, BacklogQuotaType backlogQuotaType) {// No-op return CompletableFuture.completedFuture(null); }
3.26
pulsar_NonPersistentTopic_deleteForcefully_rdh
/** * Forcefully close all producers/consumers/replicators and deletes the topic. * * @return */ @Override public CompletableFuture<Void> deleteForcefully() { return delete(false, true); }
3.26
pulsar_ResourceQuotaCalculatorImpl_needToReportLocalUsage_rdh
// Return true if a report needs to be sent for the current round; false if it can be suppressed for this round. @Override public boolean needToReportLocalUsage(long currentBytesUsed, long lastReportedBytes, long currentMessagesUsed, long lastReportedMessages, long lastReportTimeMSecsSinceEpoch) { // If we are about to go more than maxUsageReportSuppressRounds without reporting, send a report. long currentTimeMSecs = System.currentTimeMillis(); long mSecsSinceLastReport = currentTimeMSecs - lastReportTimeMSecsSinceEpoch; if (mSecsSinceLastReport >= ResourceGroupService.maxIntervalForSuppressingReportsMSecs) {return true; } // If the percentage change (increase or decrease) in usage is more than a threshold for // either bytes or messages, send a report. final float toleratedDriftPercentage = ResourceGroupService.UsageReportSuppressionTolerancePercentage; if (currentBytesUsed > 0) { long diff = abs(currentBytesUsed - lastReportedBytes); float diffPercentage = (((float) (diff)) * 100) / lastReportedBytes; if (diffPercentage > toleratedDriftPercentage) { return true; } } if (currentMessagesUsed > 0) { long diff = abs(currentMessagesUsed - lastReportedMessages); float diffPercentage = (((float) (diff)) * 100) / lastReportedMessages; if (diffPercentage > toleratedDriftPercentage) { return true; } } return false; }
3.26
pulsar_ManagedCursorImpl_skipNonRecoverableLedger_rdh
/** * Manually acknowledge all entries in the lost ledger. * - Since this is an uncommon event, we focus on maintainability. So we do not modify * {@link #individualDeletedMessages} and {@link #batchDeletedIndexes}, but call * {@link #asyncDelete(Position, AsyncCallbacks.DeleteCallback, Object)}. * - This method is valid regardless of the consumer ACK type. * - If there is a consumer ack request after this event, it will also work. */ @Override public void skipNonRecoverableLedger(final long ledgerId) { LedgerInfo ledgerInfo = ledger.getLedgersInfo().get(ledgerId);if (ledgerInfo == null) { return; } f2.writeLock().lock(); log.warn("[{}] [{}] Since the ledger [{}] is lost and the autoSkipNonRecoverableData is true, this ledger will" + " be auto acknowledge in subscription", ledger.getName(), name, ledgerId); try { for (int i = 0; i < ledgerInfo.getEntries(); i++) { if (!individualDeletedMessages.contains(ledgerId, i)) { asyncDelete(PositionImpl.get(ledgerId, i), new AsyncCallbacks.DeleteCallback() { @Override public void deleteComplete(Object ctx) { // ignore. } @Override public void deleteFailed(ManagedLedgerException ex, Object ctx) { // The method internalMarkDelete already handled the failure operation. We only need to // make sure the memory state is updated. // If the broker crashed, the non-recoverable ledger will be detected again. } }, null); } } } finally { f2.writeLock().unlock(); } }
3.26