name
stringlengths
12
178
code_snippet
stringlengths
8
36.5k
score
float64
3.26
3.68
pulsar_PulsarRecordCursor_haveAvailableCacheSize_rdh
/** * Check the queue has available cache size quota or not. * 1. If the CacheSizeAllocator is NullCacheSizeAllocator, return true. * 2. If the available cache size > 0, return true. * 3. If the available cache size is invalid and the queue size == 0, return true, ensure not block the query. */ private boolean haveAvailableCacheSize(CacheSizeAllocator cacheSizeAllocator, SpscArrayQueue queue) { if (cacheSizeAllocator instanceof NullCacheSizeAllocator) { return true; } return (cacheSizeAllocator.getAvailableCacheSize() > 0) || (queue.size() == 0); }
3.26
pulsar_PulsarRecordCursor_getSchemaInfo_rdh
/** * Get the schemaInfo of the message. * * 1. If the schema type of pulsarSplit is NONE or BYTES, use the BYTES schema. * 2. If the schema type of pulsarSplit is BYTEBUFFER, use the BYTEBUFFER schema. * 3. If the schema version of the message is null, use the schema info of pulsarSplit. * 4. If the schema version of the message is not null, get the specific version schema by PulsarAdmin. * 5. If the final schema is null throw a runtime exception. */ private SchemaInfo getSchemaInfo(PulsarSplit pulsarSplit) { SchemaInfo schemaInfo = getBytesSchemaInfo(pulsarSplit.getSchemaType(), pulsarSplit.getSchemaName()); if (schemaInfo != null) { return schemaInfo; } try { if ((this.f1.getSchemaVersion() == null) || (this.f1.getSchemaVersion().length == 0)) { schemaInfo = pulsarSplit.getSchemaInfo(); } else { schemaInfo = schemaInfoProvider.getSchemaByVersion(this.f1.getSchemaVersion()).get(); } } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } if (schemaInfo == null) { String schemaVersion = (this.f1.getSchemaVersion() == null) ? "null" : BytesSchemaVersion.of(this.f1.getSchemaVersion()).toString(); throw new RuntimeException(((("The specific version (" + schemaVersion) + ") schema of the table ") + pulsarSplit.getTableName()) + " is null"); } return schemaInfo; }
3.26
pulsar_PulsarStandalone_builder_rdh
/** * This method gets a builder to build an embedded pulsar instance * i.e. * <pre> * <code> * PulsarStandalone pulsarStandalone = PulsarStandalone.builder().build(); * pulsarStandalone.start(); * pulsarStandalone.stop(); * </code> * </pre> * * @return PulsarStandaloneBuilder instance */ public static PulsarStandaloneBuilder builder() { return PulsarStandaloneBuilder.instance(); }
3.26
pulsar_ConcurrentOpenHashMap_keys_rdh
/** * * @return a new list of all keys (makes a copy) */ public List<K> keys() { List<K> keys = new ArrayList<>(((int) (size()))); forEach((key, value) -> keys.add(key)); return keys; }
3.26
pulsar_ConcurrentOpenHashMap_equals_rdh
/** * This object is used to delete empty value in this map. * EmptyValue.equals(null) = true. */private static final Object EmptyValue = new Object() { @SuppressFBWarnings @Override public boolean equals(Object obj) { return obj == null; }
3.26
pulsar_ConcurrentOpenHashMap_forEach_rdh
/** * Iterate over all the entries in the map and apply the processor function to each of them. * <p> * <b>Warning: Do Not Guarantee Thread-Safety.</b> * * @param processor * the function to apply to each entry */ public void forEach(BiConsumer<? super K, ? super V> processor) { for (int i = 0; i < sections.length; i++) { sections[i].forEach(processor); } }
3.26
pulsar_PulsarMockBookKeeper_returnEmptyLedgerAfter_rdh
/** * After N times, make a ledger to appear to be empty. */ public synchronized void returnEmptyLedgerAfter(int steps) { emptyLedgerAfter = steps; }
3.26
pulsar_MultiMessageIdImpl_toByteArray_rdh
// TODO: Add support for Serialization and Deserialization // https://github.com/apache/pulsar/issues/4940 @Override public byte[] toByteArray() { throw new UnsupportedOperationException(); }
3.26
pulsar_MultiMessageIdImpl_compareTo_rdh
// If all messageId in map are same size, and all bigger/smaller than the other, return valid value. @Override public int compareTo(MessageId o) { if (!(o instanceof MultiMessageIdImpl)) { throw new IllegalArgumentException("expected MultiMessageIdImpl object. Got instance of " + o.getClass().getName()); } MultiMessageIdImpl other = ((MultiMessageIdImpl) (o)); Map<String, MessageId> otherMap = other.getMap(); if (((map == null) || map.isEmpty()) && ((otherMap == null) || otherMap.isEmpty())) { return 0; } if (((otherMap == null) || (map == null)) || (otherMap.size() != map.size())) { throw new IllegalArgumentException("Current size and other size not equals"); } int result = 0; for (Entry<String, MessageId> entry : map.entrySet()) { MessageId otherMessage = otherMap.get(entry.getKey()); if (otherMessage == null) { throw new IllegalArgumentException("Other MessageId not have topic " + entry.getKey()); } int currentResult = entry.getValue().compareTo(otherMessage); if (result == 0) { result = currentResult; } else if (currentResult == 0) { continue; } else if (result != currentResult) { throw new IllegalArgumentException("Different MessageId in Map get different compare result"); } else { continue; } } return result; }
3.26
pulsar_FunctionCommon_getStateNamespace_rdh
/** * Convert pulsar tenant and namespace to state storage namespace. * * @param tenant * pulsar tenant * @param namespace * pulsar namespace * @return state storage namespace */ public static String getStateNamespace(String tenant, String namespace) { return String.format("%s_%s", tenant, namespace).replace("-", "_"); }
3.26
pulsar_KeyValueSchemaImpl_getKeySchema_rdh
/** * Get the Schema of the Key. * * @return the Schema of the Key */ @Override public Schema<K> getKeySchema() { return keySchema; }
3.26
pulsar_KeyValueSchemaImpl_encode_rdh
// encode as bytes: [key.length][key.bytes][value.length][value.bytes] or [value.bytes] public byte[] encode(KeyValue<K, V> message) { if ((keyValueEncodingType != null) && (keyValueEncodingType == KeyValueEncodingType.INLINE)) { return KeyValue.encode(message.getKey(), keySchema, message.getValue(), valueSchema); } else { if (message.getValue() == null) { return null; } return valueSchema.encode(message.getValue()); } }
3.26
pulsar_KeyValueSchemaImpl_fetchSchemaIfNeeded_rdh
/** * It may happen that the schema is not loaded but we need it, for instance in order to call getSchemaInfo() * We cannot call this method in getSchemaInfo. * * @see AutoConsumeSchema#fetchSchemaIfNeeded(SchemaVersion) */ public void fetchSchemaIfNeeded(String topicName, SchemaVersion schemaVersion) throws SchemaSerializationException { if (f0 != null) { if (keySchema instanceof AutoConsumeSchema) { ((AutoConsumeSchema) (keySchema)).fetchSchemaIfNeeded(schemaVersion); } if (valueSchema instanceof AutoConsumeSchema) { ((AutoConsumeSchema) (valueSchema)).fetchSchemaIfNeeded(schemaVersion); } return; } setSchemaInfoProviderOnSubschemas(); if (schemaVersion == null) { schemaVersion = BytesSchemaVersion.of(new byte[0]); } if (schemaInfoProvider == null) { throw new SchemaSerializationException((("Can't get accurate schema information for " + topicName) + " ") + "using KeyValueSchemaImpl because SchemaInfoProvider is not set yet"); } else { SchemaInfo schemaInfo; try { schemaInfo = schemaInfoProvider.getSchemaByVersion(schemaVersion.bytes()).get(); if (schemaInfo == null) { // schemaless topic schemaInfo = BytesSchema.of().getSchemaInfo(); } configureSchemaInfo(topicName, "topic", schemaInfo); } catch (InterruptedException | ExecutionException e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } log.error("Can't get last schema for topic {} using KeyValueSchemaImpl", topicName); throw new SchemaSerializationException(e.getCause()); } log.info("Configure schema {} for topic {} : {}", schemaVersion, topicName, schemaInfo.getSchemaDefinition()); } }
3.26
pulsar_KeyValueSchemaImpl_of_rdh
/** * Key Value Schema using passed in schema type, support JSON and AVRO currently. */ public static <K, V> Schema<KeyValue<K, V>> of(Class<K> key, Class<V> value, SchemaType type) { checkArgument((SchemaType.JSON == type) || (SchemaType.AVRO == type)); if (SchemaType.JSON == type) { return new KeyValueSchemaImpl<>(JSONSchema.of(key), JSONSchema.of(value), KeyValueEncodingType.INLINE); } else {// AVRO return new KeyValueSchemaImpl<>(AvroSchema.of(key), AvroSchema.of(value), KeyValueEncodingType.INLINE); } }
3.26
pulsar_AuthenticationService_authenticateHttpRequest_rdh
/** * * @deprecated use {@link #authenticateHttpRequest(HttpServletRequest, HttpServletResponse)} */ @Deprecated(since = "3.0.0") public String authenticateHttpRequest(HttpServletRequest request, AuthenticationDataSource authData) throws AuthenticationException { String authMethodName = getAuthMethodName(request); if (authMethodName != null) { AuthenticationProvider providerToUse = getAuthProvider(authMethodName); try { if (authData == null) { AuthenticationState authenticationState = providerToUse.newHttpAuthState(request); authData = authenticationState.getAuthDataSource(); } // Backward compatible, the authData value was null in the previous implementation return providerToUse.authenticateAsync(authData).get(); } catch (AuthenticationException e) { if (LOG.isDebugEnabled()) { LOG.debug((("Authentication failed for provider " + providerToUse.getAuthMethodName()) + " : ") + e.getMessage(), e); } throw e; } catch (ExecutionException | InterruptedException e) { if (LOG.isDebugEnabled()) { LOG.debug((("Authentication failed for provider " + providerToUse.getAuthMethodName()) + " : ") + e.getMessage(), e);} throw new RuntimeException(e); } } else { for (AuthenticationProvider provider : providers.values()) { try { AuthenticationState authenticationState = provider.newHttpAuthState(request); return provider.authenticateAsync(authenticationState.getAuthDataSource()).get(); } catch (ExecutionException | InterruptedException | AuthenticationException e) { if (LOG.isDebugEnabled()) { LOG.debug((("Authentication failed for provider " + provider.getAuthMethodName()) + ": ") + e.getMessage(), e); } // Ignore the exception because we don't know which authentication method is expected here. } } } // No authentication provided if (!providers.isEmpty()) { if (StringUtils.isNotBlank(anonymousUserRole)) { return anonymousUserRole; } // If at least a provider was configured, then the authentication needs to be provider throw new AuthenticationException("Authentication required"); } else { // No authentication required return "<none>"; }} /** * Mark this function as deprecated, it is recommended to use a method with the AuthenticationDataSource * signature to implement it. * * @deprecated use {@link #authenticateHttpRequest(HttpServletRequest, HttpServletResponse)}
3.26
pulsar_OwnershipCache_updateBundleState_rdh
/** * Update bundle state in a local cache. * * @param bundle * @throws Exception */ public CompletableFuture<Void> updateBundleState(NamespaceBundle bundle, boolean isActive) { // Disable owned instance in local cache CompletableFuture<OwnedBundle> f = ownedBundlesCache.getIfPresent(bundle); if (((f != null) && f.isDone()) && (!f.isCompletedExceptionally())) { return f.thenAccept(ob -> ob.setActive(isActive)); } else { return CompletableFuture.completedFuture(null); } }
3.26
pulsar_OwnershipCache_isNamespaceBundleOwned_rdh
/** * Checked whether a particular bundle is currently owned by this broker. * * @param bundle * @return */ public boolean isNamespaceBundleOwned(NamespaceBundle bundle) { OwnedBundle ownedBundle = m0(bundle); return (ownedBundle != null) && ownedBundle.isActive(); }
3.26
pulsar_OwnershipCache_m0_rdh
/** * Return the {@link OwnedBundle} instance from the local cache. Does not block. * * @param bundle * @return */ public OwnedBundle m0(NamespaceBundle bundle) { CompletableFuture<OwnedBundle> future = ownedBundlesCache.getIfPresent(bundle); if (((future != null) && future.isDone()) && (!future.isCompletedExceptionally())) { try { return future.get(pulsar.getConfiguration().getMetadataStoreOperationTimeoutSeconds(), TimeUnit.SECONDS); } catch (InterruptedException | TimeoutException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } } else { return null; } }
3.26
pulsar_OwnershipCache_checkOwnershipAsync_rdh
/** * Check whether this broker owns given namespace bundle. * * @param bundle * namespace bundle * @return future that will complete with check result */ public CompletableFuture<Boolean> checkOwnershipAsync(NamespaceBundle bundle) { Optional<CompletableFuture<OwnedBundle>> ownedBundleFuture = getOwnedBundleAsync(bundle); if (!ownedBundleFuture.isPresent()) { return CompletableFuture.completedFuture(false); } return ownedBundleFuture.get().thenApply(bd -> (bd != null) && bd.isActive()); }
3.26
pulsar_OwnershipCache_tryAcquiringOwnership_rdh
/** * Method to get the current owner of the <code>NamespaceBundle</code> * or set the local broker as the owner if absent. * * @param bundle * the <code>NamespaceBundle</code> * @return The ephemeral node data showing the current ownership info in <code>ZooKeeper</code> * @throws Exception */ public CompletableFuture<NamespaceEphemeralData> tryAcquiringOwnership(NamespaceBundle bundle) throws Exception { if (!refreshSelfOwnerInfo()) { return FutureUtil.failedFuture(new RuntimeException("Namespace service is not ready for acquiring ownership")); } LOG.info("Trying to acquire ownership of {}", bundle); // Doing a get() on the ownedBundlesCache will trigger an async metadata write to acquire the lock over the // service unit return ownedBundlesCache.get(bundle).thenApply(namespaceBundle -> { LOG.info("Successfully acquired ownership of {}", namespaceBundle); namespaceService.onNamespaceBundleOwned(bundle); return selfOwnerInfo; }); }
3.26
pulsar_OwnershipCache_removeOwnership_rdh
/** * Method to remove the ownership of local broker on the <code>NamespaceBundle</code>, if owned. */ public CompletableFuture<Void> removeOwnership(NamespaceBundle bundle) { ResourceLock<NamespaceEphemeralData> lock = locallyAcquiredLocks.remove(bundle); if (lock == null) { // We don't own the specified bundle anymore return CompletableFuture.completedFuture(null); } return lock.release(); }
3.26
pulsar_FunctionsApiV2Resource_getConnectorsList_rdh
/** * Deprecated in favor of moving endpoint to {@link org.apache.pulsar.broker.admin.v2.Worker} */ @GET @ApiOperation(value = "Fetches a list of supported Pulsar IO connectors currently running in cluster mode", response = List.class) @ApiResponses({ @ApiResponse(code = 403, message = "The requester doesn't have admin permissions"), @ApiResponse(code = 400, message = "Invalid request"), @ApiResponse(code = 408, message = "Request timeout") }) @Path("/connectors") @Deprecated public List<ConnectorDefinition> getConnectorsList() throws IOException { return functions().getListOfConnectors(); }
3.26
pulsar_GenericSchemaImpl_of_rdh
/** * warning : * we suggest migrate GenericSchemaImpl.of() to <GenericSchema Implementor>.of() method * (e.g. GenericJsonSchema 、GenericAvroSchema ) * * @param schemaInfo * {@link SchemaInfo} * @param useProvidedSchemaAsReaderSchema * {@link Boolean} * @return generic schema implementation */ public static GenericSchemaImpl of(SchemaInfo schemaInfo, boolean useProvidedSchemaAsReaderSchema) { switch (schemaInfo.getType()) { case AVRO : return new GenericAvroSchema(schemaInfo, useProvidedSchemaAsReaderSchema); case JSON :return new GenericJsonSchema(schemaInfo, useProvidedSchemaAsReaderSchema); default : throw new UnsupportedOperationException(("Generic schema is not supported on schema type " + schemaInfo.getType()) + "'"); } }
3.26
pulsar_PulsarClientException_getPreviousExceptions_rdh
/** * Get the collection of previous exceptions which have caused retries * for this operation. * * @return a collection of exception, ordered as they occurred */ public Collection<Throwable> getPreviousExceptions() { return this.previous; }
3.26
pulsar_PulsarClientException_wrap_rdh
// wrap an exception to enriching more info messages. public static Throwable wrap(Throwable t, String msg) { msg += "\n" + t.getMessage(); // wrap an exception with new message info if (t instanceof TimeoutException) { return new TimeoutException(msg); } else if (t instanceof InvalidConfigurationException) { return new InvalidConfigurationException(msg); } else if (t instanceof AuthenticationException) { return new AuthenticationException(msg); } else if (t instanceof IncompatibleSchemaException) { return new IncompatibleSchemaException(msg); } else if (t instanceof TooManyRequestsException) { return new TooManyRequestsException(msg); } else if (t instanceof LookupException) { return new LookupException(msg); } else if (t instanceof ConnectException) { return new ConnectException(msg); } else if (t instanceof AlreadyClosedException) { return new AlreadyClosedException(msg); } else if (t instanceof TopicTerminatedException) { return new TopicTerminatedException(msg); } else if (t instanceof AuthorizationException) { return new AuthorizationException(msg); } else if (t instanceof GettingAuthenticationDataException) { return new GettingAuthenticationDataException(msg); } else if (t instanceof UnsupportedAuthenticationException) { return new UnsupportedAuthenticationException(msg); } else if (t instanceof BrokerPersistenceException) { return new BrokerPersistenceException(msg); } else if (t instanceof BrokerMetadataException) { return new BrokerMetadataException(msg); } else if (t instanceof ProducerBusyException) { return new ProducerBusyException(msg); } else if (t instanceof ConsumerBusyException) { return new ConsumerBusyException(msg); } else if (t instanceof NotConnectedException) { return new NotConnectedException(); } else if (t instanceof InvalidMessageException) { return new InvalidMessageException(msg); } else if (t instanceof InvalidTopicNameException) { return new InvalidTopicNameException(msg); } else if (t instanceof NotSupportedException) { return new NotSupportedException(msg); } else if (t instanceof NotAllowedException) { return new NotAllowedException(msg); } else if (t instanceof ProducerQueueIsFullError) { return new ProducerQueueIsFullError(msg); } else if (t instanceof ProducerBlockedQuotaExceededError) { return new ProducerBlockedQuotaExceededError(msg); } else if (t instanceof ProducerBlockedQuotaExceededException) { return new ProducerBlockedQuotaExceededException(msg); } else if (t instanceof ChecksumException) { return new ChecksumException(msg); } else if (t instanceof CryptoException) {return new CryptoException(msg); } else if (t instanceof ConsumerAssignException) { return new ConsumerAssignException(msg); } else if (t instanceof MessageAcknowledgeException) { return new MessageAcknowledgeException(msg);} else if (t instanceof TransactionConflictException) { return new TransactionConflictException(msg); } else if (t instanceof TransactionHasOperationFailedException) { return new TransactionHasOperationFailedException(msg); } else if (t instanceof PulsarClientException) { return new PulsarClientException(msg); } else if (t instanceof CompletionException) { return t; } else if (t instanceof RuntimeException) { return new RuntimeException(msg, t.getCause()); } else if (t instanceof InterruptedException) { return t; } else if (t instanceof ExecutionException) {return t; } return t; }
3.26
pulsar_PulsarClientException_setPreviousExceptions_rdh
/** * Add a list of previous exception which occurred for the same operation * and have been retried. * * @param previous * A collection of throwables that triggered retries */public void setPreviousExceptions(Collection<Throwable> previous) { this.previous = previous;}
3.26
pulsar_MessageParser_parseMessage_rdh
/** * Parse a raw Pulsar entry payload and extract all the individual message that may be included in the batch. The * provided {@link MessageProcessor} will be invoked for each individual message. */ public static void parseMessage(TopicName topicName, long ledgerId, long entryId, ByteBuf headersAndPayload, MessageProcessor processor, int maxMessageSize) throws IOException { ByteBuf payload = headersAndPayload; ByteBuf uncompressedPayload = null; ReferenceCountedMessageMetadata refCntMsgMetadata = null; try { if (!verifyChecksum(topicName, headersAndPayload, ledgerId, entryId)) { // discard message with checksum error return; } refCntMsgMetadata = ReferenceCountedMessageMetadata.get(headersAndPayload); MessageMetadata msgMetadata = refCntMsgMetadata.getMetadata(); try { Commands.parseMessageMetadata(payload, msgMetadata); } catch (Throwable t) { log.warn("[{}] Failed to deserialize metadata for message {}:{} - Ignoring", topicName, ledgerId, entryId); return; } if (msgMetadata.hasMarkerType()) { // Ignore marker messages as they don't contain user data return;}if (msgMetadata.getEncryptionKeysCount() > 0) { throw new IOException((("Cannot parse encrypted message " + msgMetadata) + " on topic ") + topicName); } uncompressedPayload = uncompressPayloadIfNeeded(topicName, msgMetadata, headersAndPayload, ledgerId, entryId, maxMessageSize); if (uncompressedPayload == null) { // Message was discarded on decompression error return; } final int numMessages = msgMetadata.getNumMessagesInBatch(); if ((numMessages == 1) && (!msgMetadata.hasNumMessagesInBatch())) { processor.process(RawMessageImpl.get(refCntMsgMetadata, null, uncompressedPayload.retain(), ledgerId, entryId, 0)); } else { // handle batch message enqueuing; uncompressed payload has all messages in batch receiveIndividualMessagesFromBatch(refCntMsgMetadata, uncompressedPayload, ledgerId, entryId, processor); } } finally { ReferenceCountUtil.safeRelease(uncompressedPayload); ReferenceCountUtil.safeRelease(refCntMsgMetadata); } }
3.26
pulsar_SchemaDataValidator_validateSchemaData_rdh
/** * Validate if the schema data is well formed. * * @param schemaData * schema data to validate * @throws InvalidSchemaDataException * if the schema data is not in a valid form. */ static void validateSchemaData(SchemaData schemaData) throws InvalidSchemaDataException {switch (schemaData.getType()) { case AVRO : case JSON : case PROTOBUF : StructSchemaDataValidator.of().validate(schemaData); break; case PROTOBUF_NATIVE : ProtobufNativeSchemaDataValidator.of().validate(schemaData); break; case STRING : StringSchemaDataValidator.of().validate(schemaData); break; case BOOLEAN : case INT8 : case INT16 : case INT32 : case INT64 : case FLOAT : case DOUBLE : case DATE : case TIME : case TIMESTAMP : case INSTANT : case LOCAL_DATE : case LOCAL_TIME : case LOCAL_DATE_TIME : PrimitiveSchemaDataValidator.of().validate(schemaData); break; case NONE : case BYTES : // `NONE` and `BYTES` schema is not stored break;case AUTO : case AUTO_CONSUME :case AUTO_PUBLISH : throw new InvalidSchemaDataException(("Schema " + schemaData.getType()) + " is a client-side schema type");case KEY_VALUE : KeyValue<SchemaData, SchemaData> v0 = KeyValueSchemaCompatibilityCheck.decodeKeyValueSchemaData(schemaData); validateSchemaData(v0.getKey()); validateSchemaData(v0.getValue()); break; default : throw new InvalidSchemaDataException("Unknown schema type : " + schemaData.getType()); } }
3.26
pulsar_ReplicatedSubscriptionsController_completed_rdh
/** * From Topic.PublishContext. */@Override public void completed(Exception e, long ledgerId, long entryId) { // Nothing to do in case of publish errors since the retry logic is applied upstream after a snapshot is not // closed if (log.isDebugEnabled()) { log.debug("[{}] Published marker at {}:{}. Exception: {}", topic.getName(), ledgerId, entryId, e); } this.positionOfLastLocalMarker = new PositionImpl(ledgerId, entryId); }
3.26
pulsar_TenantsImpl_m0_rdh
// Compat method names @Override public void m0(String tenant, TenantInfo config) throws PulsarAdminException { createTenant(tenant, config); }
3.26
pulsar_AbstractDispatcherMultipleConsumers_getConsumerFromHigherPriority_rdh
/** * Finds index of first available consumer which has higher priority then given targetPriority. * * @param targetPriority * @return -1 if couldn't find any available consumer */ private int getConsumerFromHigherPriority(int targetPriority) { for (int i = 0; i < currentConsumerRoundRobinIndex; i++) { Consumer consumer = consumerList.get(i); if (consumer.getPriorityLevel() < targetPriority) { if (m0(consumerList.get(i))) { return i; } } else { break;} } return -1; }
3.26
pulsar_AbstractDispatcherMultipleConsumers_getNextConsumerFromSameOrLowerLevel_rdh
/** * Finds index of round-robin available consumer that present on same level as consumer on * currentRoundRobinIndex if doesn't find consumer on same level then it finds first available consumer on lower * priority level else returns * index=-1 if couldn't find any available consumer in the list. * * @param currentRoundRobinIndex * @return */ private int getNextConsumerFromSameOrLowerLevel(int currentRoundRobinIndex) { Consumer currentRRConsumer = consumerList.get(currentRoundRobinIndex); if (m0(currentRRConsumer)) { return currentRoundRobinIndex; } // scan the consumerList, if consumer in currentRoundRobinIndex is unavailable int targetPriority = currentRRConsumer.getPriorityLevel(); int scanIndex = currentRoundRobinIndex + 1; int endPriorityLevelIndex = currentRoundRobinIndex; do { /* reached to last consumer of list */ Consumer scanConsumer = (scanIndex < consumerList.size()) ? consumerList.get(scanIndex) : null; // if reached to last consumer of list then check from beginning to currentRRIndex of the list if ((scanConsumer == null) || (scanConsumer.getPriorityLevel() != targetPriority)) { endPriorityLevelIndex = scanIndex;// last consumer on this level scanIndex = getFirstConsumerIndexOfPriority(targetPriority); } else { if (m0(scanConsumer)) { return scanIndex; } scanIndex++; } } while (scanIndex != currentRoundRobinIndex ); // it means: didn't find consumer in the same priority-level so, check available consumer lower than this level for (int i = endPriorityLevelIndex; i < consumerList.size(); i++) { if (m0(consumerList.get(i))) { return i; } } return -1; }
3.26
pulsar_AbstractDispatcherMultipleConsumers_getRandomConsumer_rdh
/** * Get random consumer from consumerList. * * @return null if no consumer available, else return random consumer from consumerList */ public Consumer getRandomConsumer() { if (consumerList.isEmpty() || (IS_CLOSED_UPDATER.get(this) == TRUE)) { // abort read if no consumers are connected of if disconnect is initiated return null; } return consumerList.get(ThreadLocalRandom.current().nextInt(consumerList.size())); }
3.26
pulsar_AbstractDispatcherMultipleConsumers_getNextConsumer_rdh
/** * <pre> * Broker gives more priority while dispatching messages. Here, broker follows descending priorities. (eg: * 0=max-priority, 1, 2,..) * <p> * Broker will first dispatch messages to max priority-level consumers if they * have permits, else broker will consider next priority level consumers. * Also on the same priority-level, it selects consumer in round-robin manner. * <p> * If subscription has consumer-A with priorityLevel 1 and Consumer-B with priorityLevel 2 * then broker will dispatch * messages to only consumer-A until it runs out permit and then broker starts dispatching messages to Consumer-B. * <p> * Consumer PriorityLevel Permits * C1 0 2 * C2 0 1 * C3 0 1 * C4 1 2 * C5 1 1 * Result of getNextConsumer(): C1, C2, C3, C1, C4, C5, C4 * </pre> * * <pre> * <b>Algorithm:</b> * 1. consumerList: it stores consumers in sorted-list: max-priority stored first * 2. currentConsumerRoundRobinIndex: it always stores last served consumer-index * * Each time getNextConsumer() is called:<p> * 1. It always starts to traverse from the max-priority consumer (first element) from sorted-list * 2. Consumers on same priority-level will be treated equally and it tries to pick one of them in * round-robin manner * 3. If consumer is not available on given priority-level then only it will go to the next lower priority-level * consumers * 4. Returns null in case it doesn't find any available consumer * </pre> * * @return nextAvailableConsumer */ public Consumer getNextConsumer() { if (consumerList.isEmpty() || (IS_CLOSED_UPDATER.get(this) == TRUE)) { // abort read if no consumers are connected or if disconnect is initiated return null; } if (currentConsumerRoundRobinIndex >= consumerList.size()) { currentConsumerRoundRobinIndex = 0; } int currentRoundRobinConsumerPriority = consumerList.get(currentConsumerRoundRobinIndex).getPriorityLevel(); // first find available-consumer on higher level unless currentIndex is not on highest level which is 0 if (currentRoundRobinConsumerPriority != 0) { int higherPriorityConsumerIndex = getConsumerFromHigherPriority(currentRoundRobinConsumerPriority); if (higherPriorityConsumerIndex != (-1)) { currentConsumerRoundRobinIndex = higherPriorityConsumerIndex + 1; return consumerList.get(higherPriorityConsumerIndex); } } // currentIndex is already on highest level or couldn't find consumer on higher level so, find consumer on same // or lower level int availableConsumerIndex = getNextConsumerFromSameOrLowerLevel(currentConsumerRoundRobinIndex); if (availableConsumerIndex != (-1)) { currentConsumerRoundRobinIndex = availableConsumerIndex + 1; return consumerList.get(availableConsumerIndex); } // couldn't find available consumer return null; }
3.26
pulsar_AbstractDispatcherMultipleConsumers_getFirstConsumerIndexOfPriority_rdh
/** * Finds index of first consumer in list which has same priority as given targetPriority. * * @param targetPriority * @return */ private int getFirstConsumerIndexOfPriority(int targetPriority) { for (int i = 0; i < consumerList.size(); i++) { if (consumerList.get(i).getPriorityLevel() == targetPriority) { return i; } } return -1;}
3.26
pulsar_ConsumerHandler_handleEndOfTopic_rdh
// Check and notify consumer if reached end of topic. private void handleEndOfTopic() { if (log.isDebugEnabled()) { log.debug("[{}/{}] Received check reach the end of topic request from {} ", consumer.getTopic(), subscription, getRemote().getInetSocketAddress().toString()); } try { String msg = objectWriter().writeValueAsString(new EndOfTopicResponse(consumer.hasReachedEndOfTopic())); getSession().getRemote().sendString(msg, new WriteCallback() { @Override public void writeFailed(Throwable th) { log.warn("[{}/{}] Failed to send end of topic msg to {} due to {}", consumer.getTopic(), subscription, getRemote().getInetSocketAddress().toString(), th.getMessage()); } @Override public void writeSuccess() { if (log.isDebugEnabled()) { log.debug("[{}/{}] End of topic message is delivered successfully to {} ", consumer.getTopic(), subscription, getRemote().getInetSocketAddress().toString()); } } }); } catch (JsonProcessingException e) { log.warn("[{}] Failed to generate end of topic response: {}", consumer.getTopic(), e.getMessage()); } catch (Exception e) { log.warn("[{}] Failed to send end of topic response: {}", consumer.getTopic(), e.getMessage()); } }
3.26
pulsar_Reflections_classInJarImplementsIface_rdh
/** * check if a class implements an interface. * * @param fqcn * fully qualified class name to search for in jar * @param xface * interface to check if implement * @return true if class from jar implements interface xface and false if otherwise */ public static boolean classInJarImplementsIface(File jar, String fqcn, Class xface) { boolean ret = false; URLClassLoader loader = null; try {loader = ((URLClassLoader) (ClassLoaderUtils.loadJar(jar))); if (xface.isAssignableFrom(Class.forName(fqcn, false, loader))) { ret = true; } } catch (ClassNotFoundException | NoClassDefFoundError | IOException e) { throw new RuntimeException(e); } finally { if (loader != null) { try { loader.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } } return ret; }
3.26
pulsar_Reflections_classExistsInJar_rdh
/** * Check if a class is in a jar. * * @param jar * location of the jar * @param fqcn * fully qualified class name to search for in jar * @return true if class can be loaded from jar and false if otherwise */ public static boolean classExistsInJar(File jar, String fqcn) { URLClassLoader loader = null; try { loader = ((URLClassLoader) (ClassLoaderUtils.loadJar(jar))); Class.forName(fqcn, false, loader); return true; } catch (ClassNotFoundException | NoClassDefFoundError | IOException e) { return false; } finally { if (loader != null) { try { loader.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } } }
3.26
pulsar_Reflections_loadClass_rdh
/** * Load class to resolve array types. * * @param className * class name * @param classLoader * class loader * @return loaded class * @throws ClassNotFoundException */ public static Class loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { if (className.length() == 1) { char type = className.charAt(0); if (type == 'B') { return Byte.TYPE; } else if (type == 'C') { return Character.TYPE; } else if (type == 'D') { return Double.TYPE; } else if (type == 'F') { return Float.TYPE; } else if (type == 'I') { return Integer.TYPE; } else if (type == 'J') { return Long.TYPE; } else if (type == 'S') { return Short.TYPE; } else if (type == 'Z') { return Boolean.TYPE; } else if (type == 'V') { return Void.TYPE; } else { throw new ClassNotFoundException(className); } } else if (isPrimitive(className)) { return ((Class) (PRIMITIVE_NAME_TYPE_MAP.get(className))); } else if ((className.charAt(0) == 'L') && (className.charAt(className.length() - 1) == ';')) { return classLoader.loadClass(className.substring(1, className.length() - 1)); } else { try { return classLoader.loadClass(className); } catch (ClassNotFoundException | NoClassDefFoundError var4) { if (className.charAt(0) != '[') { throw var4; } else { // CHECKSTYLE.OFF: EmptyStatement int arrayDimension; for (arrayDimension = 0; className.charAt(arrayDimension) == '['; ++arrayDimension) { } // CHECKSTYLE.ON: EmptyStatement Class componentType = loadClass(className.substring(arrayDimension), classLoader); return Array.newInstance(componentType, new int[arrayDimension]).getClass(); } } } }
3.26
pulsar_Reflections_createInstance_rdh
/** * Create an instance of <code>userClassName</code> using provided <code>classLoader</code>. * * @param userClassName * user class name * @param classLoader * class loader to load the class. * @return the instance */ public static Object createInstance(String userClassName, ClassLoader classLoader) { Class<?> theCls; try { theCls = Class.forName(userClassName, true, classLoader); } catch (ClassNotFoundException | NoClassDefFoundError cnfe) { throw new RuntimeException("User class must be in class path", cnfe); } Object result; try { Constructor<?> v6 = constructorCache.get(theCls); if (null == v6) { v6 = theCls.getDeclaredConstructor(); v6.setAccessible(true); constructorCache.put(theCls, v6); } result = v6.newInstance(); } catch (InstantiationException ie) { throw new RuntimeException("User class must be concrete", ie); } catch (NoSuchMethodException e) {throw new RuntimeException("User class doesn't have such method", e); } catch (IllegalAccessException e) { throw new RuntimeException("User class must have a no-arg constructor", e); } catch (InvocationTargetException e) { throw new RuntimeException("User class constructor throws exception", e); } return result; }
3.26
pulsar_Reflections_classImplementsIface_rdh
/** * check if class implements interface. * * @param fqcn * fully qualified class name * @param xface * the interface the fqcn should implement * @return true if class implements interface xface and false if otherwise */ public static boolean classImplementsIface(String fqcn, Class xface) { boolean ret = false; try { if (xface.isAssignableFrom(Class.forName(fqcn))) { ret = true; } } catch (ClassNotFoundException | NoClassDefFoundError e) { throw new RuntimeException(e); } return ret; }
3.26
pulsar_Reflections_classExists_rdh
/** * Check if class exists. * * @param fqcn * fully qualified class name to search for * @return true if class can be loaded from jar and false if otherwise */ public static boolean classExists(String fqcn) { try { Class.forName(fqcn); return true; } catch (ClassNotFoundException e) { return false; } }
3.26
pulsar_AuthenticationDataHttp_hasSubscription_rdh
/* Subscription */ @Override public boolean hasSubscription() { return this.subscription != null; }
3.26
pulsar_AuthenticationDataHttp_hasDataFromHttp_rdh
/* HTTP */ @Override public boolean hasDataFromHttp() { return true; }
3.26
pulsar_NonPersistentTopicsImpl_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_ClearTextSecretsProvider_provideSecret_rdh
/** * Fetches a secret. * * @return The actual secret */ @Override public String provideSecret(String secretName, Object pathToSecret) { if (pathToSecret != null) { return pathToSecret.toString(); } else { return null;} }
3.26
pulsar_NonPersistentReplicator_getProducerName_rdh
/** * * @return Producer name format : replicatorPrefix.localCluster-->remoteCluster */ @Override protected String getProducerName() { return (getReplicatorName(replicatorPrefix, localCluster) + REPL_PRODUCER_NAME_DELIMITER) + remoteCluster; }
3.26
pulsar_ConcurrentLongHashMap_forEach_rdh
/** * Iterate over all the entries in the map and apply the processor function to each of them. * <p> * <b>Warning: Do Not Guarantee Thread-Safety.</b> * * @param processor * the processor to apply to each entry */ public void forEach(EntryProcessor<V> processor) { for (int v19 = 0; v19 < sections.length; v19++) { sections[v19].forEach(processor); } }
3.26
pulsar_ConcurrentLongHashMap_keys_rdh
/** * * @return a new list of all keys (makes a copy) */ public List<Long> keys() { List<Long> v20 = Lists.newArrayListWithExpectedSize(((int) (size()))); forEach((key, value) -> v20.add(key)); return v20; }
3.26
pulsar_TokenClient_buildClientCredentialsBody_rdh
/** * Constructing http request parameters. * * @param req * object with relevant request parameters * @return Generate the final request body from a map. */ String buildClientCredentialsBody(ClientCredentialsExchangeRequest req) { Map<String, String> bodyMap = new TreeMap<>(); bodyMap.put("grant_type", "client_credentials"); bodyMap.put("client_id", req.getClientId()); bodyMap.put("client_secret", req.getClientSecret()); // Only set audience and scope if they are non-empty. if (!StringUtils.isBlank(req.getAudience())) { bodyMap.put("audience", req.getAudience()); } if (!StringUtils.isBlank(req.getScope())) { bodyMap.put("scope", req.getScope()); } return bodyMap.entrySet().stream().map(e -> { try { return (URLEncoder.encode(e.getKey(), "UTF-8") + '=') + URLEncoder.encode(e.getValue(), "UTF-8"); } catch (UnsupportedEncodingException e1) { throw new RuntimeException(e1);} }).collect(Collectors.joining("&")); }
3.26
pulsar_TokenClient_exchangeClientCredentials_rdh
/** * Performs a token exchange using client credentials. * * @param req * the client credentials request details. * @return a token result * @throws TokenExchangeException */ public TokenResult exchangeClientCredentials(ClientCredentialsExchangeRequest req) throws TokenExchangeException, IOException { String body = buildClientCredentialsBody(req); try { Response res = httpClient.preparePost(tokenUrl.toString()).setHeader("Accept", "application/json").setHeader("Content-Type", "application/x-www-form-urlencoded").setBody(body).execute().get(); switch (res.getStatusCode()) {case 200 : return ObjectMapperFactory.getMapper().reader().readValue(res.getResponseBodyAsBytes(), TokenResult.class); case 400 : // Bad request case 401 : // Unauthorized throw new TokenExchangeException(ObjectMapperFactory.getMapper().reader().readValue(res.getResponseBodyAsBytes(), TokenError.class)); default : throw new IOException((("Failed to perform HTTP request. res: " + res.getStatusCode()) + " ") + res.getStatusText()); } } catch (InterruptedException | ExecutionException e1) { throw new IOException(e1); } }
3.26
pulsar_TimeAverageMessageData_getUpdatedValue_rdh
// Update the average of a sample using the number of samples, the previous // average, and a new sample. private double getUpdatedValue(final double oldAverage, final double newSample) { // Note that for numSamples == 1, this returns newSample. // This ensures that default stats get overwritten after the first // update. return (((numSamples - 1) * oldAverage) + newSample) / numSamples; }
3.26
pulsar_TimeAverageMessageData_totalMsgThroughput_rdh
/** * Get the total message throughput. * * @return Message throughput in + message throughput out. */ public double totalMsgThroughput() {return msgThroughputIn + msgThroughputOut; }
3.26
pulsar_TimeAverageMessageData_update_rdh
/** * Update using new samples for the message data. * * @param newMsgThroughputIn * Most recently observed throughput in. * @param newMsgThroughputOut * Most recently observed throughput out. * @param newMsgRateIn * Most recently observed message rate in. * @param newMsgRateOut * Most recently observed message rate out. */ public void update(final double newMsgThroughputIn, final double newMsgThroughputOut, final double newMsgRateIn, final double newMsgRateOut) { // If max samples has been reached, don't increase numSamples. numSamples = Math.min(numSamples + 1, maxSamples); msgThroughputIn = getUpdatedValue(msgThroughputIn, newMsgThroughputIn); msgThroughputOut = getUpdatedValue(msgThroughputOut, newMsgThroughputOut); msgRateIn = getUpdatedValue(msgRateIn, newMsgRateIn); msgRateOut = getUpdatedValue(msgRateOut, newMsgRateOut); }
3.26
pulsar_PersistentSubscription_delete_rdh
/** * Delete the subscription by closing and deleting its managed cursor. Handle unsubscribe call from admin layer. * * @param closeIfConsumersConnected * Flag indicate whether explicitly close connected consumers before trying to * delete subscription. If * any consumer is connected to it and if this flag is disable then this operation * fails. * @return CompletableFuture indicating the completion of delete operation */ private CompletableFuture<Void> delete(boolean closeIfConsumersConnected) { CompletableFuture<Void> deleteFuture = new CompletableFuture<>(); log.info("[{}][{}] Unsubscribing", topicName, subName); CompletableFuture<Void> closeSubscriptionFuture = new CompletableFuture<>();if (closeIfConsumersConnected) { this.disconnect().thenRun(() -> { closeSubscriptionFuture.complete(null); }).exceptionally(ex -> { log.error("[{}][{}] Error disconnecting and closing subscription", topicName, subName, ex); closeSubscriptionFuture.completeExceptionally(ex);return null; }); } else { this.close().thenRun(() -> { closeSubscriptionFuture.complete(null); }).exceptionally(exception -> {log.error("[{}][{}] Error closing subscription", topicName, subName, exception); closeSubscriptionFuture.completeExceptionally(exception); return null;}); } // cursor close handles pending delete (ack) operations closeSubscriptionFuture.thenCompose(v -> topic.unsubscribe(subName)).thenAccept(v -> { synchronized(this) { (dispatcher != null ? dispatcher.close() : CompletableFuture.completedFuture(null)).thenRun(() -> { log.info("[{}][{}] Successfully deleted subscription", topicName, subName); deleteFuture.complete(null); }).exceptionally(ex -> { IS_FENCED_UPDATER.set(this, FALSE); if (dispatcher != null) { dispatcher.reset(); } log.error("[{}][{}] Error deleting subscription", topicName, subName, ex); deleteFuture.completeExceptionally(ex); return null; }); } }).exceptionally(exception -> { IS_FENCED_UPDATER.set(this, FALSE); log.error("[{}][{}] Error deleting subscription", topicName, subName, exception); deleteFuture.completeExceptionally(exception); return null; }); return deleteFuture; }
3.26
pulsar_PersistentSubscription_doUnsubscribe_rdh
/** * Handle unsubscribe command from the client API Check with the dispatcher is this consumer can proceed with * unsubscribe. * * @param consumer * consumer object that is initiating the unsubscribe operation * @return CompletableFuture indicating the completion of unsubscribe operation */ @Override public CompletableFuture<Void> doUnsubscribe(Consumer consumer) { CompletableFuture<Void> future = new CompletableFuture<>(); try { if (dispatcher.canUnsubscribe(consumer)) { consumer.close();return delete(); } future.completeExceptionally(new ServerMetadataException("Unconnected or shared consumer attempting to unsubscribe")); } catch (BrokerServiceException e) { log.warn("Error removing consumer {}", consumer); future.completeExceptionally(e); } return future; }
3.26
pulsar_PersistentSubscription_mergeCursorProperties_rdh
/** * Return a merged map that contains the cursor properties specified by used * (eg. when using compaction subscription) and the subscription properties. */ protected Map<String, Long> mergeCursorProperties(Map<String, Long> userProperties) { Map<String, Long> baseProperties = getBaseCursorProperties(isReplicated()); if (userProperties.isEmpty()) { // Use only the static instance in the common case return baseProperties; } else { Map<String, Long> merged = new TreeMap<>(); merged.putAll(userProperties);merged.putAll(baseProperties); return merged; } }
3.26
pulsar_PersistentSubscription_resumeAfterFence_rdh
/** * Resume subscription after topic deletion or close failure. */ public synchronized void resumeAfterFence() { // If "fenceFuture" is null, it means that "disconnect" has never been called. if (fenceFuture != null) { fenceFuture.whenComplete((ignore, ignoreEx) -> { synchronized(this) { try { if (IS_FENCED_UPDATER.compareAndSet(this, f0, FALSE)) { if (dispatcher != null) { dispatcher.reset(); } } fenceFuture = null; } catch (Exception ex) { log.error("[{}] Resume subscription [{}] failure", topicName, subName, ex); } } }); } }
3.26
pulsar_PersistentSubscription_deleteForcefully_rdh
/** * Forcefully close all consumers and deletes the subscription. * * @return */ @Overridepublic CompletableFuture<Void> deleteForcefully() { return delete(true); }
3.26
pulsar_PersistentSubscription_close_rdh
/** * Close the cursor ledger for this subscription. Requires that there are no active consumers on the dispatcher * * @return CompletableFuture indicating the completion of delete operation */ @Override public CompletableFuture<Void> close() { synchronized(this) { if ((dispatcher != null) && dispatcher.isConsumerConnected()) { return FutureUtil.failedFuture(new SubscriptionBusyException("Subscription has active consumers")); } return this.pendingAckHandle.closeAsync().thenAccept(v -> { IS_FENCED_UPDATER.set(this, f0); log.info("[{}][{}] Successfully closed subscription [{}]", topicName, subName, cursor); }); } }
3.26
pulsar_ManagedLedgerPayloadProcessor_inputProcessor_rdh
/** * Used by ManagedLedger for pre-processing payload before storing in bookkeeper ledger. * * @return Handle to Processor instance */ default Processor inputProcessor() { return null; }
3.26
pulsar_ManagedLedgerPayloadProcessor_outputProcessor_rdh
/** * Used by ManagedLedger for processing payload after reading from bookkeeper ledger. * * @return Handle to Processor instance */ default Processor outputProcessor() { return null; }
3.26
pulsar_ZipFiles_isZip_rdh
/** * Returns true if the given file is a gzip file. */ public static boolean isZip(File f) { try (DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(f)))) { int test = in.readInt(); return test == 0x504b0304; } catch (final Exception e) { return false; } }
3.26
pulsar_ZipFiles_lines_rdh
/** * Get a lazily loaded stream of lines from a gzipped file, similar to * {@link Files#lines(java.nio.file.Path)}. * * @param path * The path to the zipped file. * @return stream with lines. */ public static Stream<String> lines(Path path) { ZipInputStream zipStream = null; try { zipStream = new ZipInputStream(Files.newInputStream(path)); } catch (IOException e) { closeSafely(zipStream); throw new UncheckedIOException(e); } // Reader decoder = new InputStreamReader(gzipStream, Charset.defaultCharset()); BufferedReader reader = new BufferedReader(new InputStreamReader(zipStream)); return reader.lines().onClose(() -> closeSafely(reader)); }
3.26
pulsar_DataBlockHeaderImpl_fromStream_rdh
// Construct DataBlockHeader from InputStream, which contains `HEADER_MAX_SIZE` bytes readable. public static DataBlockHeader fromStream(InputStream stream) throws IOException { CountingInputStream countingStream = new CountingInputStream(stream); DataInputStream dis = new DataInputStream(countingStream); int magic = dis.readInt(); if (magic != MAGIC_WORD) { throw new IOException((("Data block header magic word not match. read: " + magic) + " expected: ") + MAGIC_WORD); } long headerLen = dis.readLong(); long blockLen = dis.readLong(); long firstEntryId = dis.readLong(); long toSkip = headerLen - countingStream.getCount(); if (dis.skip(toSkip) != toSkip) { throw new EOFException("Header was too small"); } return new DataBlockHeaderImpl(headerLen, blockLen, firstEntryId); }
3.26
pulsar_DataBlockHeaderImpl_toStream_rdh
/** * Get the content of the data block header as InputStream. * Read out in format: * [ magic_word -- int ][ block_len -- int ][ first_entry_id -- long] [padding zeros] */ @Override public InputStream toStream() { ByteBuf out = PulsarByteBufAllocator.DEFAULT.buffer(HEADER_MAX_SIZE, HEADER_MAX_SIZE); out.writeInt(MAGIC_WORD).writeLong(headerLength).writeLong(blockLength).writeLong(firstEntryId).writeBytes(PADDING); // true means the input stream will release the ByteBuf on close return new ByteBufInputStream(out, true); }
3.26
pulsar_AuthenticationDataHttps_hasDataFromTls_rdh
/* TLS */ @Override public boolean hasDataFromTls() { return certificates != null; }
3.26
pulsar_NarClassLoader_getServiceDefinition_rdh
/** * Read a service definition as a String. */public String getServiceDefinition(String serviceName) throws IOException { String serviceDefPath = (narWorkingDirectory + "/META-INF/services/") + serviceName; return new String(Files.readAllBytes(Paths.get(serviceDefPath)), StandardCharsets.UTF_8); }
3.26
pulsar_NarClassLoader_updateClasspath_rdh
/** * Adds URLs for the resources unpacked from this NAR: * <ul> * <li>the root: for classes, <tt>META-INF</tt>, etc.</li> * <li><tt>META-INF/dependencies</tt>: for config files, <tt>.so</tt>s, etc.</li> * <li><tt>META-INF/dependencies/*.jar</tt>: for dependent libraries</li> * </ul> * * @param root * the root directory of the unpacked NAR. * @throws IOException * if the URL list could not be updated. */ private void updateClasspath(File root) throws IOException { addURL(root.toURI().toURL());// for compiled classes, META-INF/, etc. File dependencies = new File(root, "META-INF/bundled-dependencies"); if (!dependencies.isDirectory()) { log.warn("{} does not contain META-INF/bundled-dependencies!", narWorkingDirectory); } addURL(dependencies.toURI().toURL());if (dependencies.isDirectory()) { final File[] jarFiles = dependencies.listFiles(JAR_FILTER); if (jarFiles != null) { Arrays.sort(jarFiles, Comparator.comparing(File::getName)); for (File libJar : jarFiles) { addURL(libJar.toURI().toURL()); } } } }
3.26
pulsar_WatermarkCountTriggerPolicy_handleWaterMarkEvent_rdh
/** * Triggers all the pending windows up to the waterMarkEvent timestamp * based on the sliding interval count. * * @param waterMarkEvent * the watermark event */ private void handleWaterMarkEvent(Event<T> waterMarkEvent) { long watermarkTs = waterMarkEvent.getTimestamp(); List<Long> eventTs = windowManager.getSlidingCountTimestamps(lastProcessedTs, watermarkTs, count); for (long ts : eventTs) { evictionPolicy.setContext(new DefaultEvictionContext(ts, null, ((long) (count)))); handler.onTrigger(); lastProcessedTs = ts; } }
3.26
pulsar_ElasticSearchSink_m0_rdh
/** * Extract ES _id and _source using the Schema if available. * * @param record * @return A pair for _id and _source */ public Pair<String, String> m0(Record<GenericObject> record) throws JsonProcessingException { if (elasticSearchConfig.isSchemaEnable()) { Object key = null; GenericObject value = null; Schema<?> keySchema = null; Schema<?> valueSchema = null; if ((record.getSchema() != null) && (record.getSchema() instanceof KeyValueSchema)) { KeyValueSchema<GenericObject, GenericObject> keyValueSchema = ((KeyValueSchema) (record.getSchema())); keySchema = keyValueSchema.getKeySchema(); valueSchema = keyValueSchema.getValueSchema(); KeyValue<GenericObject, GenericObject> keyValue = ((KeyValue<GenericObject, GenericObject>) (record.getValue().getNativeObject())); key = keyValue.getKey(); value = keyValue.getValue(); } else { key = record.getKey().orElse(null); valueSchema = record.getSchema(); value = getGenericObjectFromRecord(record); } String id = null; if ((!elasticSearchConfig.isKeyIgnore()) && (key != null)) { if (keySchema != null) { id = stringifyKey(keySchema, key); } else { id = key.toString(); } } String doc = null; if (value != null) { if (valueSchema != null) { if (elasticSearchConfig.isCopyKeyFields() && (keySchema.getSchemaInfo().getType().equals(SchemaType.AVRO) || keySchema.getSchemaInfo().getType().equals(SchemaType.JSON))) { JsonNode v9 = extractJsonNode(keySchema, key); JsonNode valueNode = extractJsonNode(valueSchema, value); doc = stringify(JsonConverter.topLevelMerge(v9, valueNode)); } else { doc = stringifyValue(valueSchema, value); } } else if (value.getNativeObject() instanceof byte[]) { // for BWC with the ES-Sink doc = new String(((byte[]) (value.getNativeObject())), StandardCharsets.UTF_8); } else { doc = value.getNativeObject().toString(); } } if ((doc != null) && (primaryFields != null)) { try { // extract the PK from the JSON document JsonNode jsonNode = objectMapper.readTree(doc); id = stringifyKey(jsonNode, primaryFields); } catch (JsonProcessingException e) { log.error("Failed to read JSON", e);throw e; } } final ElasticSearchConfig.IdHashingAlgorithm idHashingAlgorithm = elasticSearchConfig.getIdHashingAlgorithm(); if (((id != null) && (idHashingAlgorithm != null)) && (idHashingAlgorithm != IdHashingAlgorithm.NONE)) { final byte[] idBytes = id.getBytes(StandardCharsets.UTF_8); boolean performHashing = true; if (elasticSearchConfig.isConditionalIdHashing() && (idBytes.length <= 512)) { performHashing = false; } if (performHashing) { Hasher v15; switch (idHashingAlgorithm) { case SHA256 : v15 = Hashing.sha256().newHasher(); break; case SHA512 : v15 = Hashing.sha512().newHasher(); break; default : throw new UnsupportedOperationException("Unsupported IdHashingAlgorithm: " + idHashingAlgorithm); } v15.putBytes(idBytes); id = base64Encoder.encodeToString(v15.hash().asBytes()); } } if (log.isDebugEnabled()) { SchemaType schemaType = null; if ((record.getSchema() != null) && (record.getSchema().getSchemaInfo() != null)) { schemaType = record.getSchema().getSchemaInfo().getType(); } log.debug("recordType={} schemaType={} id={} doc={}", record.getClass().getName(), schemaType, id, doc); } doc = sanitizeValue(doc); return Pair.of(id, doc); } else { Message message = record.getMessage().orElse(null); final String rawData; if (message != null) { rawData = new String(message.getData(), StandardCharsets.UTF_8);} else { GenericObject recordObject = getGenericObjectFromRecord(record); rawData = stringifyValue(record.getSchema(), recordObject); } if ((rawData == null) || (rawData.length() == 0)) { throw new IllegalArgumentException("Record does not carry message information."); } String key = (elasticSearchConfig.isKeyIgnore()) ? null : record.getKey().map(Object::toString).orElse(null); return Pair.of(key, sanitizeValue(rawData)); } }
3.26
pulsar_ElasticSearchSink_stringifyKey_rdh
/** * Convert a JsonNode to an Elasticsearch id. */ public String stringifyKey(JsonNode jsonNode) throws JsonProcessingException { List<String> fields = new ArrayList<>(); jsonNode.fieldNames().forEachRemaining(fields::add); return stringifyKey(jsonNode, fields); }
3.26
pulsar_PrometheusMetricStreams_flushAllToStream_rdh
/** * Flush all the stored metrics to the supplied stream. * * @param stream * the stream to write to. */ void flushAllToStream(SimpleTextOutputStream stream) { metricStreamMap.values().forEach(s -> stream.write(s.getBuffer())); }
3.26
pulsar_PrometheusMetricStreams_writeSample_rdh
/** * Write the given metric and sample value to the stream. Will write #TYPE header if metric not seen before. * * @param metricName * name of the metric. * @param value * value of the sample * @param labelsAndValuesArray * varargs of label and label value */ void writeSample(String metricName, Number value, String... labelsAndValuesArray) { SimpleTextOutputStream stream = initGaugeType(metricName); stream.write(metricName).write('{'); for (int i = 0; i < labelsAndValuesArray.length; i += 2) { String labelValue = labelsAndValuesArray[i + 1]; if (labelValue != null) { labelValue = labelValue.replace("\"", "\\\""); } stream.write(labelsAndValuesArray[i]).write("=\"").write(labelValue).write('\"'); if ((i + 2) != labelsAndValuesArray.length) { stream.write(','); } } stream.write("} ").write(value).write('\n'); }
3.26
pulsar_PrometheusMetricStreams_releaseAll_rdh
/** * Release all the streams to clean up resources. */void releaseAll() { metricStreamMap.values().forEach(s -> s.getBuffer().release()); metricStreamMap.clear(); }
3.26
pulsar_LoadReportDeserializer_deserialize_rdh
/** * Deserializer for a load report. */public class LoadReportDeserializer extends JsonDeserializer<LoadManagerReport> {@Override public LoadManagerReport deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { ObjectReader reader = ObjectMapperFactory.getMapper().reader(); ObjectNode root = reader.readTree(jsonParser); if ((root.has("loadReportType") && root.get("loadReportType").asText().equals(LoadReport.loadReportType)) || root.has("underLoaded")) { return reader.treeToValue(root, LoadReport.class); } else { return reader.treeToValue(root, LocalBrokerData.class); } }
3.26
pulsar_JdbcUtils_getTableId_rdh
/** * Get the {@link TableId} for the given tableName. */ public static TableId getTableId(Connection connection, String tableName) throws Exception { DatabaseMetaData metadata = connection.getMetaData(); try (ResultSet rs = metadata.getTables(null, null, tableName, new String[]{ "TABLE", "PARTITIONED TABLE" })) { if (rs.next()) { String catalogName = rs.getString(1); String schemaName = rs.getString(2); String gotTableName = rs.getString(3); checkState(tableName.equals(gotTableName), (("TableName not match: " + tableName) + " Got: ") + gotTableName); if (log.isDebugEnabled()) { log.debug("Get Table: {}, {}, {}", catalogName, schemaName, tableName); } return TableId.of(catalogName, schemaName, tableName); } else { throw new Exception("Not able to find table: " + tableName); } } }
3.26
pulsar_JdbcUtils_getTableDefinition_rdh
/** * Get the {@link TableDefinition} for the given table. */ public static TableDefinition getTableDefinition(Connection connection, TableId tableId, List<String> keyList, List<String> nonKeyList, boolean excludeNonDeclaredFields) throws Exception { TableDefinition table = TableDefinition.of(tableId, Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList()); keyList = (keyList == null) ? Collections.emptyList() : keyList; nonKeyList = (nonKeyList == null) ? Collections.emptyList() : nonKeyList; try (ResultSet rs = connection.getMetaData().getColumns(tableId.getCatalogName(), tableId.getSchemaName(), tableId.getTableName(), null)) { while (rs.next()) { final String columnName = rs.getString(4); final int sqlDataType = rs.getInt(5); final String typeName = rs.getString(6); final int position = rs.getInt(17); if (log.isDebugEnabled()) { log.debug("Get column. name: {}, data type: {}, position: {}", columnName, typeName, position); }ColumnId columnId = ColumnId.of(tableId, columnName, sqlDataType, typeName, position); if (keyList.contains(columnName)) { table.keyColumns.add(columnId); table.columns.add(columnId); } else if (nonKeyList.contains(columnName)) { table.nonKeyColumns.add(columnId); table.columns.add(columnId); } else if (!excludeNonDeclaredFields) { table.columns.add(columnId); }} return table; } }
3.26
pulsar_FunctionCacheManager_unregisterFunction_rdh
/** * Unregisters a job from the function cache manager. * * @param fid * function id */ default void unregisterFunction(String fid) { unregisterFunctionInstance(fid, null); }
3.26
pulsar_FunctionCacheManager_registerFunction_rdh
/** * Registers a function with its required jar files and classpaths. * * <p>The jar files are identified by their blob keys and downloaded for * use by a {@link ClassLoader}. * * @param fid * function id * @param requiredJarFiles * collection of blob keys identifying the required jar files. * @param requiredClasspaths * collection of classpaths that are added to the function code class loader. */default void registerFunction(String fid, List<String> requiredJarFiles, List<URL> requiredClasspaths) throws IOException { registerFunctionInstance(fid, null, requiredJarFiles, requiredClasspaths); }
3.26
pulsar_TopicPoliciesService_getTopicPoliciesAsyncWithRetry_rdh
/** * When getting TopicPolicies, if the initialization has not been completed, * we will go back off and try again until time out. * * @param topicName * topic name * @param backoff * back off policy * @param isGlobal * is global policies * @return CompletableFuture&lt;Optional&lt;TopicPolicies&gt;&gt; */ default CompletableFuture<Optional<TopicPolicies>> getTopicPoliciesAsyncWithRetry(TopicName topicName, final Backoff backoff, ScheduledExecutorService scheduledExecutorService, boolean isGlobal) { CompletableFuture<Optional<TopicPolicies>> response = new CompletableFuture<>(); Backoff usedBackoff = (backoff == null) ? new BackoffBuilder().setInitialTime(500, TimeUnit.MILLISECONDS).setMandatoryStop(DEFAULT_GET_TOPIC_POLICY_TIMEOUT, TimeUnit.MILLISECONDS).setMax(DEFAULT_GET_TOPIC_POLICY_TIMEOUT, TimeUnit.MILLISECONDS).create() : backoff; try { RetryUtil.retryAsynchronously(() -> { CompletableFuture<Optional<TopicPolicies>> future = new CompletableFuture<>(); try { future.complete(Optional.ofNullable(getTopicPolicies(topicName, isGlobal))); } catch (BrokerServiceException.TopicPoliciesCacheNotInitException exception) { future.completeExceptionally(exception); } return future; }, usedBackoff, scheduledExecutorService, response); } catch (Exception e) { response.completeExceptionally(e); } return response; }
3.26
pulsar_ConcurrentLongLongPairHashMap_keys_rdh
/** * * @return a new list of all keys (makes a copy). */ public List<LongPair> keys() { List<LongPair> keys = Lists.newArrayListWithExpectedSize(((int) (size()))); forEach((key1, key2, value1, value2) -> keys.add(new LongPair(key1, key2))); return keys; }
3.26
pulsar_ConcurrentLongLongPairHashMap_forEach_rdh
/** * Iterate over all the entries in the map and apply the processor function to each of them. * <p> * <b>Warning: Do Not Guarantee Thread-Safety.</b> * * @param processor * the processor to process the elements. */ public void forEach(BiConsumerLongPair processor) { for (Section s : sections) { s.forEach(processor); } }
3.26
pulsar_ConcurrentLongLongPairHashMap_remove_rdh
/** * Remove an existing entry if found. * * @param key1 * @param key2 * @return the value associated with the key or -1 if key was not present. */public boolean remove(long key1, long key2) { checkBiggerEqualZero(key1); long v14 = hash(key1, key2); return getSection(v14).remove(key1, key2, ValueNotFound, ValueNotFound, ((int) (v14))); }
3.26
pulsar_ConcurrentLongLongPairHashMap_get_rdh
/** * * @param key1 * @param key2 * @return the value or -1 if the key was not present. */ public LongPair get(long key1, long key2) { checkBiggerEqualZero(key1); long h = hash(key1, key2); return getSection(h).get(key1, key2, ((int) (h))); }
3.26
pulsar_TopicPoliciesImpl_m7_rdh
/* returns topic name with encoded Local Name */ private TopicName m7(String topic) { // Parsing will throw exception if name is not valid return TopicName.get(topic); }
3.26
pulsar_ReplicatedSubscriptionSnapshotCache_advancedMarkDeletePosition_rdh
/** * Signal that the mark-delete position on the subscription has been advanced. If there is a snapshot that * correspond to this position, it will returned, other it will return null. */ public synchronized ReplicatedSubscriptionsSnapshot advancedMarkDeletePosition(PositionImpl pos) {ReplicatedSubscriptionsSnapshot snapshot = null; while (!snapshots.isEmpty()) { PositionImpl v3 = snapshots.firstKey(); if (v3.compareTo(pos) > 0) { // Snapshot is associated which an higher position, so it cannot be used now break; } else { // This snapshot is potentially good. Continue the search for to see if there is a higher snapshot we // can use snapshot = snapshots.pollFirstEntry().getValue(); } } if (log.isDebugEnabled()) {if (snapshot != null) { log.debug("[{}] Advanced mark-delete position to {} -- found snapshot {} at {}:{}", subscription, pos, snapshot.getSnapshotId(), snapshot.getLocalMessageId().getLedgerId(), snapshot.getLocalMessageId().getEntryId()); } else { log.debug("[{}] Advanced mark-delete position to {} -- snapshot not found", subscription, pos); } } return snapshot; }
3.26
pulsar_ReaderHandler_handleEndOfTopic_rdh
// Check and notify reader if reached end of topic. private void handleEndOfTopic() { try { String msg = objectWriter().writeValueAsString(new EndOfTopicResponse(reader.hasReachedEndOfTopic())); getSession().getRemote().sendString(msg, new WriteCallback() { @Override public void writeFailed(Throwable th) { log.warn("[{}/{}] Failed to send end of topic msg to {} due to {}", reader.getTopic(), subscription, getRemote().getInetSocketAddress().toString(), th.getMessage()); } @Override public void writeSuccess() { if (log.isDebugEnabled()) { log.debug("[{}/{}] End of topic message is delivered successfully to {} ", reader.getTopic(), subscription, getRemote().getInetSocketAddress().toString()); }} }); } catch (JsonProcessingException e) { log.warn("[{}] Failed to generate end of topic response: {}", reader.getTopic(), e.getMessage()); } catch (Exception e) { log.warn("[{}] Failed to send end of topic response: {}", reader.getTopic(), e.getMessage()); } }
3.26
pulsar_PulsarAuthorizationProvider_canLookupAsync_rdh
/** * Check whether the specified role can perform a lookup for the specified topic. * * For that the caller needs to have producer or consumer permission. * * @param topicName * @param role * @return * @throws Exception */ @Override public CompletableFuture<Boolean> canLookupAsync(TopicName topicName, String role, AuthenticationDataSource authenticationData) { return canProduceAsync(topicName, role, authenticationData).thenCompose(canProduce -> { if (canProduce) { return CompletableFuture.completedFuture(true); } return canConsumeAsync(topicName, role, authenticationData, null); }); }
3.26
pulsar_PulsarAuthorizationProvider_canProduceAsync_rdh
/** * Check if the specified role has permission to send messages to the specified fully qualified topic name. * * @param topicName * the fully qualified topic name associated with the topic. * @param role * the app id used to send messages to the topic. */ @Override public CompletableFuture<Boolean> canProduceAsync(TopicName topicName, String role, AuthenticationDataSource authenticationData) { return checkAuthorization(topicName, role, AuthAction.produce); }
3.26
pulsar_PulsarAuthorizationProvider_canConsumeAsync_rdh
/** * Check if the specified role has permission to receive messages from the specified fully qualified topic * name. * * @param topicName * the fully qualified topic name associated with the topic. * @param role * the app id used to receive messages from the topic. * @param subscription * the subscription name defined by the client */ @Override public CompletableFuture<Boolean> canConsumeAsync(TopicName topicName, String role, AuthenticationDataSource authenticationData, String subscription) {return pulsarResources.getNamespaceResources().getPoliciesAsync(topicName.getNamespaceObject()).thenCompose(policies -> { if (!policies.isPresent()) { if (log.isDebugEnabled()) { log.debug("Policies node couldn't be found for topic : {}", topicName); } } else if (isNotBlank(subscription)) { // validate if role is authorized to access subscription. (skip validation if authorization // list is empty) Set<String> roles = policies.get().auth_policies.getSubscriptionAuthentication().get(subscription); if (((roles != null) && (!roles.isEmpty())) && (!roles.contains(role))) { log.warn("[{}] is not authorized to subscribe on {}-{}", role, topicName, subscription); return CompletableFuture.completedFuture(false); } // validate if subscription-auth mode is configured if (policies.get().subscription_auth_mode != null) { switch (policies.get().subscription_auth_mode) { case Prefix : if (!subscription.startsWith(role)) { PulsarServerException ex = new PulsarServerException(String.format("Failed to create consumer - The subscription name needs to be" + " prefixed by the authentication role, like %s-xxxx for topic: %s", role, topicName)); return FutureUtil.failedFuture(ex); } break; default : break; } } } return checkAuthorization(topicName, role, AuthAction.consume); }); }
3.26
pulsar_GZipFiles_isGzip_rdh
/** * Returns true if the given file is a gzip file. */ public static boolean isGzip(File f) { try (InputStream input = new FileInputStream(f)) { PushbackInputStream pb = new PushbackInputStream(input, 2); byte[] signature = new byte[2]; int len = pb.read(signature);// read the signature pb.unread(signature, 0, len);// push back the signature to the stream // check if matches standard gzip magic number return (signature[0] == ((byte) (0x1f))) && (signature[1] == ((byte) (0x8b))); } catch (final Exception e) { return false; } }
3.26
pulsar_GZipFiles_lines_rdh
/** * Get a lazily loaded stream of lines from a gzipped file, similar to * {@link Files#lines(java.nio.file.Path)}. * * @param path * The path to the gzipped file. * @return stream with lines. */ public static Stream<String> lines(Path path) { GZIPInputStream gzipStream = null; try { gzipStream = new GZIPInputStream(Files.newInputStream(path)); } catch (IOException e) { closeSafely(gzipStream); throw new UncheckedIOException(e); } BufferedReader reader = new BufferedReader(new InputStreamReader(gzipStream)); return reader.lines().onClose(() -> closeSafely(reader)); }
3.26
pulsar_SchemaStorage_put_rdh
/** * Put the schema to the schema storage. * * @param key * The schema ID * @param fn * The function to calculate the value and hash that need to put to the schema storage * The input of the function is all the existing schemas that used to do the schemas compatibility check * @return The schema version of the stored schema */default CompletableFuture<SchemaVersion> put(String key, Function<CompletableFuture<List<CompletableFuture<StoredSchema>>>, CompletableFuture<Pair<byte[], byte[]>>> fn) { return fn.apply(getAll(key)).thenCompose(pair -> put(key, pair.getLeft(), pair.getRight())); }
3.26
pulsar_SimpleLoadManagerImpl_doNamespaceBundleSplit_rdh
/** * Detect and split hot namespace bundles. */@Override public void doNamespaceBundleSplit() throws Exception { int maxBundleCount = pulsar.getConfiguration().getLoadBalancerNamespaceMaximumBundles(); long maxBundleTopics = pulsar.getConfiguration().getLoadBalancerNamespaceBundleMaxTopics(); long maxBundleSessions = pulsar.getConfiguration().getLoadBalancerNamespaceBundleMaxSessions();long maxBundleMsgRate = pulsar.getConfiguration().getLoadBalancerNamespaceBundleMaxMsgRate(); long maxBundleBandwidth = pulsar.getConfiguration().getLoadBalancerNamespaceBundleMaxBandwidthMbytes() * MBytes; log.info("Running namespace bundle split with thresholds: topics {}, sessions {}," + " msgRate {}, bandwidth {}, maxBundles {}", maxBundleTopics, maxBundleSessions, maxBundleMsgRate, maxBundleBandwidth, maxBundleCount); if ((this.lastLoadReport == null) || (this.lastLoadReport.getBundleStats() == null)) { return; } Map<String, NamespaceBundleStats> bundleStats = this.lastLoadReport.getBundleStats(); Set<String> bundlesToBeSplit = new HashSet<>(); for (Map.Entry<String, NamespaceBundleStats> v196 : bundleStats.entrySet()) { String bundleName = v196.getKey(); NamespaceBundleStats stats = v196.getValue(); long totalSessions = stats.consumerCount + stats.producerCount; double totalMsgRate = stats.msgRateIn + stats.msgRateOut; double totalBandwidth = stats.msgThroughputIn + stats.msgThroughputOut; boolean needSplit = false; if ((((stats.topics > maxBundleTopics) || ((maxBundleSessions > 0) && (totalSessions > maxBundleSessions))) || (totalMsgRate > maxBundleMsgRate)) || (totalBandwidth > maxBundleBandwidth)) { if (stats.topics <= 1) { log.info("Unable to split hot namespace bundle {} since there is only one topic.", bundleName); } else { NamespaceName namespaceName = NamespaceName.get(LoadManagerShared.getNamespaceNameFromBundleName(bundleName)); int numBundles = pulsar.getNamespaceService().getBundleCount(namespaceName); if (numBundles >= maxBundleCount) { log.info("Unable to split hot namespace bundle {} since the namespace has too many bundles.", bundleName); } else { needSplit = true; } } } if (needSplit) { if (this.getLoadBalancerAutoBundleSplitEnabled()) { log.info("Will split hot namespace bundle {}, topics {}, producers+consumers {}," + " msgRate in+out {}, bandwidth in+out {}", bundleName, stats.topics, totalSessions, totalMsgRate, totalBandwidth); bundlesToBeSplit.add(bundleName); } else { log.info("DRY RUN - split hot namespace bundle {}, topics {}, producers+consumers {}," + " msgRate in+out {}, bandwidth in+out {}", bundleName, stats.topics, totalSessions, totalMsgRate, totalBandwidth); } } } if (bundlesToBeSplit.size() > 0) { for (String bundleName : bundlesToBeSplit) { try { pulsar.getAdminClient().namespaces().splitNamespaceBundle(LoadManagerShared.getNamespaceNameFromBundleName(bundleName), LoadManagerShared.getBundleRangeFromBundleName(bundleName), pulsar.getConfiguration().isLoadBalancerAutoUnloadSplitBundlesEnabled(), null); log.info("Successfully split namespace bundle {}", bundleName); } catch (Exception e) { log.error("Failed to split namespace bundle {}", bundleName, e); } } this.setLoadReportForceUpdateFlag(); } }
3.26
pulsar_SimpleLoadManagerImpl_getTotalAllocatedQuota_rdh
/** * Get the sum of allocated resource for the list of namespace bundles. */ private ResourceQuota getTotalAllocatedQuota(Set<String> bundles) {ResourceQuota totalQuota = new ResourceQuota(); for (String bundle : bundles) { ResourceQuota quota = this.getResourceQuota(bundle); totalQuota.add(quota); } return totalQuota; }
3.26
pulsar_SimpleLoadManagerImpl_m1_rdh
/* temp method, remove it in future, in-place to make this glue code to make load balancing work */ private PulsarResourceDescription m1(LoadReport report) { SystemResourceUsage sru = report.getSystemResourceUsage();PulsarResourceDescription resourceDescription = new PulsarResourceDescription(); if (sru == null) {return resourceDescription; } if (sru.bandwidthIn != null) { resourceDescription.put("bandwidthIn", sru.bandwidthIn); } if (sru.bandwidthOut != null) { resourceDescription.put("bandwidthOut", sru.bandwidthOut); }if (sru.memory != null) { resourceDescription.put("memory", sru.memory); }if (sru.cpu != null) { resourceDescription.put("cpu", sru.cpu); } return resourceDescription; }
3.26
pulsar_SimpleLoadManagerImpl_updateBrokerToNamespaceToBundle_rdh
// Update the brokerToNamespaceToBundleRange map with the current preallocated and assigned bundle data. private synchronized void updateBrokerToNamespaceToBundle() { resourceUnitRankings.forEach((resourceUnit, ranking) -> { final String broker = resourceUnit.getResourceId(); final Set<String> loadedBundles = ranking.getLoadedBundles(); final Set<String> preallocatedBundles = resourceUnitRankings.get(resourceUnit).getPreAllocatedBundles(); final ConcurrentOpenHashMap<String, ConcurrentOpenHashSet<String>> namespaceToBundleRange = brokerToNamespaceToBundleRange.computeIfAbsent(broker.replace("http://", ""), k -> ConcurrentOpenHashMap.<String, ConcurrentOpenHashSet<String>>newBuilder().build()); namespaceToBundleRange.clear(); LoadManagerShared.fillNamespaceToBundlesMap(loadedBundles, namespaceToBundleRange); LoadManagerShared.fillNamespaceToBundlesMap(preallocatedBundles, namespaceToBundleRange); }); }
3.26
pulsar_SimpleLoadManagerImpl_findBrokerForPlacement_rdh
/** * Assign owner for specified ServiceUnit from the given candidates, following the the principles: 1) Optimum * distribution: fill up one broker till its load reaches optimum level (defined by underload threshold) before pull * another idle broker in; 2) Even distribution: once all brokers' load are above optimum level, maintain all * brokers to have even load; 3) Set the underload threshold to small value (like 1) for pure even distribution, and * high value (like 80) for pure optimum distribution; * <p> * Strategy to select broker: 1) The first choice is the least loaded broker which is underload but not idle; 2) The * second choice is idle broker (if there is any); 3) Otherwise simply select the least loaded broker if it is NOT * overloaded; 4) If all brokers are overloaded, select the broker with maximum available capacity (considering * brokers could have different hardware configuration, this usually means to select the broker with more hardware * resource); * <p> * Broker's load level: 1) Load ranking (triggered by LoadReport update) estimate the load level according to the * resource usage and namespace bundles already loaded by each broker; 2) When leader broker decide the owner for a * new namespace bundle, it may take time for the real owner to actually load the bundle and refresh LoadReport, * leader broker will store the bundle in a list called preAllocatedBundles, and the quota of all * preAllocatedBundles in preAllocatedQuotas, and re-estimate the broker's load level by putting the * preAllocatedQuota into calculation; 3) Everything (preAllocatedBundles and preAllocatedQuotas) will get reset in * load ranking. */ private synchronized ResourceUnit findBrokerForPlacement(Multimap<Long, ResourceUnit> candidates, ServiceUnitId serviceUnit) { long underloadThreshold = this.getLoadBalancerBrokerUnderloadedThresholdPercentage(); long overloadThreshold = this.getLoadBalancerBrokerOverloadedThresholdPercentage(); ResourceQuota defaultQuota = pulsar.getBrokerService().getBundlesQuotas().getDefaultResourceQuota().join(); double minLoadPercentage = 101.0; long maxAvailability = -1; ResourceUnit idleRU = null; ResourceUnit maxAvailableRU = null; ResourceUnit randomRU = null; ResourceUnit selectedRU = null; ResourceUnitRanking v89 = null; String serviceUnitId = serviceUnit.toString(); // If the ranking is expected to be in the range [0,100] (which is the case for LOADBALANCER_STRATEGY_LLS), // the ranks are bounded. Otherwise (as is the case in LOADBALANCER_STRATEGY_LEAST_MSG, the ranks are simply // the total message rate which is in the range [0,Infinity) so they are unbounded. The // "boundedness" affects how two ranks are compared to see which one is better boolean unboundedRanks = getLoadBalancerPlacementStrategy().equals(LOADBALANCER_STRATEGY_LEAST_MSG); long randomBrokerIndex = (candidates.size() > 0) ? this.brokerRotationCursor % candidates.size() : 0; // find the least loaded & not-idle broker for (Map.Entry<Long, ResourceUnit> candidateOwner : candidates.entries()) {ResourceUnit candidate = candidateOwner.getValue(); randomBrokerIndex--; // skip broker which is not ranked. this should never happen except in unit test if (!resourceUnitRankings.containsKey(candidate)) { continue; } ResourceUnitRanking ranking = resourceUnitRankings.get(candidate); // check if this ServiceUnit is already loaded if (ranking.isServiceUnitLoaded(serviceUnitId)) { ranking.removeLoadedServiceUnit(serviceUnitId, this.getResourceQuota(serviceUnitId)); } // record a random broker if ((randomBrokerIndex < 0) && (randomRU == null)) { randomRU = candidate; } // check the available capacity double loadPercentage = ranking.getEstimatedLoadPercentage(); double v97 = Math.max(0, (100 - loadPercentage) / 100); long availability = ((long) (ranking.estimateMaxCapacity(defaultQuota) * v97)); if (availability > maxAvailability) { maxAvailability = availability; maxAvailableRU = candidate; } // check the load percentage if (ranking.isIdle()) { if (idleRU == null) { idleRU = candidate; } } else if (selectedRU == null) { selectedRU = candidate; v89 = ranking; minLoadPercentage = loadPercentage; } else if ((unboundedRanks ? ranking.compareMessageRateTo(v89) : ranking.compareTo(v89)) < 0) { minLoadPercentage = loadPercentage; selectedRU = candidate; v89 = ranking; } } if (((minLoadPercentage > underloadThreshold) && (idleRU != null)) || (selectedRU == null)) { // assigned to idle broker is the least loaded broker already have optimum load (which means NOT // underloaded), or all brokers are idle selectedRU = idleRU; } else if (((minLoadPercentage >= 100.0) && (randomRU != null)) && (!unboundedRanks)) { // all brokers are full, assign to a random one selectedRU = randomRU; } else if ((minLoadPercentage > overloadThreshold) && (!unboundedRanks)) { // assign to the broker with maximum available capacity if all brokers are overloaded selectedRU = maxAvailableRU; } // re-calculate load level for selected broker if (selectedRU != null) { this.brokerRotationCursor = (this.brokerRotationCursor + 1) % 1000000; ResourceUnitRanking ranking = resourceUnitRankings.get(selectedRU); String loadPercentageDesc = ranking.getEstimatedLoadPercentageString(); log.info("Assign {} to {} with ({}).", serviceUnitId, selectedRU.getResourceId(), loadPercentageDesc); if (!ranking.isServiceUnitPreAllocated(serviceUnitId)) { final String namespaceName = LoadManagerShared.getNamespaceNameFromBundleName(serviceUnitId); final String v102 = LoadManagerShared.getBundleRangeFromBundleName(serviceUnitId); ResourceQuota quota = this.getResourceQuota(serviceUnitId); // Add preallocated bundle range so incoming bundles from the same namespace are not assigned to the // same broker. brokerToNamespaceToBundleRange.computeIfAbsent(selectedRU.getResourceId().replace("http://", ""), k -> ConcurrentOpenHashMap.<String, ConcurrentOpenHashSet<String>>newBuilder().build()).computeIfAbsent(namespaceName, k -> ConcurrentOpenHashSet.<String>newBuilder().build()).add(v102); ranking.addPreAllocatedServiceUnit(serviceUnitId, quota);resourceUnitRankings.put(selectedRU, ranking); } } return selectedRU; }
3.26
pulsar_SimpleLoadManagerImpl_isBrokerAvailableForRebalancing_rdh
// todo: changeme: this can be optimized, we don't have to iterate through everytime private boolean isBrokerAvailableForRebalancing(String bundleName, long maxLoadLevel) { NamespaceName namespaceName = NamespaceName.get(LoadManagerShared.getNamespaceNameFromBundleName(bundleName)); Map<Long, Set<ResourceUnit>> availableBrokers = sortedRankings.get(); // this does not have "http://" in front, hacky but no time to pretty up Multimap<Long, ResourceUnit> brokers = getFinalCandidates(namespaceName, availableBrokers); for (ResourceUnit broker : brokers.values()) { LoadReport currentLoadReport = currentLoadReports.get(broker); if (isBelowLoadLevel(currentLoadReport.getSystemResourceUsage(), maxLoadLevel)) { return true; } }return false; }
3.26