name
stringlengths 12
178
| code_snippet
stringlengths 8
36.5k
| score
float64 3.26
3.68
|
---|---|---|
pulsar_FunctionRuntimeManager_findAssignment_rdh | /**
* Private methods for internal use. Should not be used outside of this class
*/
private Assignment findAssignment(String tenant,
String namespace, String functionName, int instanceId) {
String v95 = FunctionCommon.getFullyQualifiedInstanceId(tenant, namespace, functionName, instanceId);
for (Map.Entry<String, Map<String,
Assignment>> v96 : this.workerIdToAssignments.entrySet()) {
Map<String, Assignment> assignmentMap = v96.getValue();
Assignment existingAssignment = assignmentMap.get(v95);
if (existingAssignment != null) {
return existingAssignment;
}
}return null;
} | 3.26 |
pulsar_FunctionRuntimeManager_restartFunctionUsingPulsarAdmin_rdh | /**
* Restart the entire function or restart a single instance of the function.
*/
@VisibleForTesting
void restartFunctionUsingPulsarAdmin(Assignment assignment, String tenant, String namespace, String functionName, boolean restartEntireFunction) throws PulsarAdminException {
ComponentType componentType = assignment.getInstance().getFunctionMetaData().getFunctionDetails().getComponentType();
if (restartEntireFunction) {
if (ComponentType.SOURCE == componentType) {
this.functionAdmin.sources().restartSource(tenant, namespace, functionName);
} else if (ComponentType.SINK == componentType) {
this.functionAdmin.sinks().restartSink(tenant, namespace, functionName);
} else {
this.functionAdmin.functions().restartFunction(tenant, namespace, functionName);
}
} else // only restart single instance
if (ComponentType.SOURCE == componentType) {
this.functionAdmin.sources().restartSource(tenant, namespace, functionName, assignment.getInstance().getInstanceId());
} else if (ComponentType.SINK == componentType) {
this.functionAdmin.sinks().restartSink(tenant, namespace, functionName,
assignment.getInstance().getInstanceId());
} else {
this.functionAdmin.functions().restartFunction(tenant, namespace, functionName, assignment.getInstance().getInstanceId());
}
} | 3.26 |
pulsar_FunctionRuntimeManager_processAssignment_rdh | /**
* Process an assignment update from the assignment topic.
*
* @param newAssignment
* the assignment
*/
public synchronized void processAssignment(Assignment newAssignment) {
boolean exists = false;
for (Map<String, Assignment> entry : this.workerIdToAssignments.values()) {
if (entry.containsKey(FunctionCommon.getFullyQualifiedInstanceId(newAssignment.getInstance()))) {
exists = true;
}
}
if (exists) {
updateAssignment(newAssignment);
} else {
addAssignment(newAssignment);
}
} | 3.26 |
pulsar_FunctionRuntimeManager_findFunctionAssignments_rdh | /**
* Find all instance assignments of function.
*
* @param tenant
* @param namespace
* @param functionName
* @return */
public synchronized Collection<Assignment> findFunctionAssignments(String tenant, String namespace, String functionName) { return findFunctionAssignments(tenant, namespace, functionName, this.workerIdToAssignments);
} | 3.26 |
pulsar_FunctionRuntimeManager_removeAssignments_rdh | /**
* Removes a collection of assignments.
*
* @param assignments
* assignments to remove
*/
public synchronized void removeAssignments(Collection<Assignment> assignments) {
for (Assignment assignment : assignments) {
this.deleteAssignment(assignment);
}
} | 3.26 |
pulsar_FunctionRuntimeManager_findFunctionAssignment_rdh | /**
* Find a assignment of a function.
*
* @param tenant
* the tenant the function belongs to
* @param namespace
* the namespace the function belongs to
* @param functionName
* the function name
* @return the assignment of the function
*/
public synchronized Assignment findFunctionAssignment(String tenant, String namespace, String functionName, int instanceId) { return this.findAssignment(tenant, namespace, functionName, instanceId);
} | 3.26 |
pulsar_FunctionRuntimeManager_getMyInstances_rdh | /**
* Methods for metrics. *
*/
public int getMyInstances() {
Map<String, Assignment> myAssignments = workerIdToAssignments.get(workerConfig.getWorkerId());
return myAssignments == null ? 0 : myAssignments.size();
} | 3.26 |
pulsar_FunctionRuntimeManager_stopAllOwnedFunctions_rdh | /**
* It stops all functions instances owned by current worker.
*
* @throws Exception
*/
public void stopAllOwnedFunctions() {
if (runtimeFactory.externallyManaged()) {
log.warn("Will not stop any functions since they are externally managed");
return;
}
final String workerId = this.workerConfig.getWorkerId();
Map<String, Assignment> assignments = workerIdToAssignments.get(workerId);
if (assignments != null) {
// Take a copy of the map since the stopFunction will modify the same map
// and invalidate the iterator
Map<String, Assignment> copiedAssignments = new TreeMap<>(assignments);
copiedAssignments.values().forEach(assignment -> {
String fullyQualifiedInstanceId = FunctionCommon.getFullyQualifiedInstanceId(assignment.getInstance());
try {
stopFunction(fullyQualifiedInstanceId, false);
} catch (Exception e) {
log.warn("Failed to stop function {} - {}", fullyQualifiedInstanceId, e.getMessage());
}
});
}
} | 3.26 |
pulsar_FunctionRuntimeManager_getFunctionInstanceStats_rdh | /**
* Get stats of a function instance. If this worker is not running the function instance.
*
* @param tenant
* the tenant the function belongs to
* @param namespace
* the namespace the function belongs to
* @param functionName
* the function name
* @param instanceId
* the function instance id
* @return jsonObject containing stats for instance
*/
public FunctionInstanceStatsDataImpl getFunctionInstanceStats(String tenant, String namespace, String functionName, int instanceId, URI uri) {
Assignment assignment;
if (runtimeFactory.externallyManaged()) {
assignment = this.findAssignment(tenant, namespace, functionName, -1);
} else {
assignment = this.findAssignment(tenant, namespace, functionName, instanceId);
}
if (assignment == null) {
return new FunctionInstanceStatsDataImpl();
}
final String assignedWorkerId = assignment.getWorkerId();
final String workerId = this.workerConfig.getWorkerId();
// If I am running worker
if (assignedWorkerId.equals(workerId)) {
FunctionRuntimeInfo v48 = this.getFunctionRuntimeInfo(FunctionCommon.getFullyQualifiedInstanceId(assignment.getInstance()));
RuntimeSpawner runtimeSpawner = v48.getRuntimeSpawner();
if (runtimeSpawner != null) {
return ((FunctionInstanceStatsDataImpl) (WorkerUtils.getFunctionInstanceStats(FunctionCommon.getFullyQualifiedInstanceId(assignment.getInstance()),
v48, instanceId).getMetrics()));
}
return new FunctionInstanceStatsDataImpl();
} else {
// query other worker
List<WorkerInfo> workerInfoList = this.membershipManager.getCurrentMembership();
WorkerInfo workerInfo = null;
for (WorkerInfo entry : workerInfoList) {
if (assignment.getWorkerId().equals(entry.getWorkerId())) {
workerInfo = entry;
}
}if (workerInfo == null) {
return new FunctionInstanceStatsDataImpl();
}
if (uri == null) {
throw new WebApplicationException(Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
} else {
URI redirect = UriBuilder.fromUri(uri).host(workerInfo.getWorkerHostname()).port(workerInfo.getPort()).build();
throw new WebApplicationException(Response.temporaryRedirect(redirect).build());
}
}
} | 3.26 |
pulsar_FunctionRuntimeManager_initialize_rdh | /**
* Initializes the FunctionRuntimeManager. Does the following:
* 1. Consume all existing assignments to establish existing/latest set of assignments
* 2. After current assignments are read, assignments belonging to this worker will be processed
*
* @return the message id of the message processed during init phase
*/ public MessageId initialize() {
try (Reader<byte[]> reader = WorkerUtils.createReader(f0.getClient().newReader(),
workerConfig.getWorkerId() + "-function-assignment-initialize", workerConfig.getFunctionAssignmentTopic(), MessageId.earliest)) {
// start init phase
this.isInitializePhase = true;
// keep track of the last message read
MessageId lastMessageRead = MessageId.earliest;
// read all existing messages
while (reader.hasMessageAvailable()) {
Message<byte[]> message = reader.readNext();
lastMessageRead = message.getMessageId();
processAssignmentMessage(message);
}
// init phase is done
this.isInitializePhase = false;
// realize existing assignments
Map<String, Assignment> assignmentMap = workerIdToAssignments.get(this.workerConfig.getWorkerId());
if (assignmentMap != null) {
for (Assignment assignment
: assignmentMap.values()) {
if (needsStart(assignment)) {
startFunctionInstance(assignment);
}
}
}
// complete future to indicate initialization is complete
isInitialized.complete(null);return lastMessageRead;
} catch (Exception e) {
log.error("Failed to initialize function runtime manager: {}", e.getMessage(), e);
throw new RuntimeException(e);
}
}
/**
* Get current assignments.
*
* @return a map of current assignments in the following format
{workerId : {FullyQualifiedInstanceId : Assignment}} | 3.26 |
pulsar_RuntimeUtils_splitRuntimeArgs_rdh | /**
* Regex for splitting a string using space when not surrounded by single or double quotes.
*/
public static String[] splitRuntimeArgs(String input) {
return input.split("\\s(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
} | 3.26 |
pulsar_RuntimeUtils_getGoInstanceCmd_rdh | /**
* Different from python and java function, Go function uploads a complete executable file(including:
* instance file + user code file). Its parameter list is provided to the broker in the form of a yaml file,
* the advantage of this approach is that backward compatibility is guaranteed.
*
* In Java and Python the instance is managed by broker (or function worker) so the changes in command line
* is under control; but in Go the instance is compiled with the user function, so pulsar doesn't have the
* control what instance is used in the function. Hence in order to support BC for go function, we can't
* dynamically add more commandline arguments. Using an instance config to pass the parameters from function
* worker to go instance is the best way for maintaining the BC.
* <p>
* When we run the go function, we only need to specify the location of the go-function file and the yaml file.
* The content of the yaml file will be automatically generated according to the content provided by instanceConfig.
*/
public static List<String> getGoInstanceCmd(InstanceConfig instanceConfig, AuthenticationConfig authConfig, String originalCodeFileName, String
pulsarServiceUrl, String stateStorageServiceUrl, String pulsarWebServiceUrl, boolean k8sRuntime) throws IOException {
final List<String> args = new LinkedList<>();
GoInstanceConfig goInstanceConfig = new GoInstanceConfig();
if (instanceConfig.getClusterName() != null) {
goInstanceConfig.setClusterName(instanceConfig.getClusterName());
}
if (null != stateStorageServiceUrl) {
goInstanceConfig.setStateStorageServiceUrl(stateStorageServiceUrl);
}
if (instanceConfig.isExposePulsarAdminClientEnabled() && StringUtils.isNotBlank(pulsarWebServiceUrl)) {
goInstanceConfig.setPulsarWebServiceUrl(pulsarWebServiceUrl);
}if (instanceConfig.getInstanceId() != 0) {
goInstanceConfig.setInstanceID(instanceConfig.getInstanceId());
}
if (instanceConfig.getFunctionId() != null) {
goInstanceConfig.setFuncID(instanceConfig.getFunctionId());
}
if (instanceConfig.getFunctionVersion() != null) {
goInstanceConfig.setFuncVersion(instanceConfig.getFunctionVersion());
}
if (instanceConfig.getFunctionDetails().getAutoAck()) {
goInstanceConfig.setAutoAck(instanceConfig.getFunctionDetails().getAutoAck());
}
if (instanceConfig.getFunctionDetails().getTenant() != null) {
goInstanceConfig.setTenant(instanceConfig.getFunctionDetails().getTenant());
}
if (instanceConfig.getFunctionDetails().getNamespace() != null) {
goInstanceConfig.setNameSpace(instanceConfig.getFunctionDetails().getNamespace());
}
if
(instanceConfig.getFunctionDetails().getName() != null) {
goInstanceConfig.setName(instanceConfig.getFunctionDetails().getName());
}
if (instanceConfig.getFunctionDetails().getLogTopic() != null) {
goInstanceConfig.setLogTopic(instanceConfig.getFunctionDetails().getLogTopic());
}
if (instanceConfig.getFunctionDetails().getProcessingGuarantees() != null) {
goInstanceConfig.setProcessingGuarantees(instanceConfig.getFunctionDetails().getProcessingGuaranteesValue());
}
if (instanceConfig.getFunctionDetails().getRuntime() != null) {
goInstanceConfig.setRuntime(instanceConfig.getFunctionDetails().getRuntimeValue());
}
if (instanceConfig.getFunctionDetails().getSecretsMap() != null) {
goInstanceConfig.setSecretsMap(instanceConfig.getFunctionDetails().getSecretsMap());
}
if (instanceConfig.getFunctionDetails().getUserConfig() != null) {
goInstanceConfig.setUserConfig(instanceConfig.getFunctionDetails().getUserConfig());
}
if (instanceConfig.getFunctionDetails().getParallelism() != 0) {
goInstanceConfig.setParallelism(instanceConfig.getFunctionDetails().getParallelism());
}
if (authConfig != null) {if (isNotBlank(authConfig.getClientAuthenticationPlugin()) && isNotBlank(authConfig.getClientAuthenticationParameters())) {
goInstanceConfig.setClientAuthenticationPlugin(authConfig.getClientAuthenticationPlugin());
goInstanceConfig.setClientAuthenticationParameters(authConfig.getClientAuthenticationParameters());
}
goInstanceConfig.setTlsAllowInsecureConnection(authConfig.isTlsAllowInsecureConnection());
goInstanceConfig.setTlsHostnameVerificationEnable(authConfig.isTlsHostnameVerificationEnable());
if (isNotBlank(authConfig.getTlsTrustCertsFilePath()))
{
goInstanceConfig.setTlsTrustCertsFilePath(authConfig.getTlsTrustCertsFilePath());
}
}
if (instanceConfig.getMaxBufferedTuples() != 0) {
goInstanceConfig.setMaxBufTuples(instanceConfig.getMaxBufferedTuples());
}
if (pulsarServiceUrl != null) {
goInstanceConfig.setPulsarServiceURL(pulsarServiceUrl);
}
if (instanceConfig.getFunctionDetails().getSource().getCleanupSubscription()) {
goInstanceConfig.setCleanupSubscription(instanceConfig.getFunctionDetails().getSource().getCleanupSubscription());
}
if (instanceConfig.getFunctionDetails().getSource().getSubscriptionName() != null)
{
goInstanceConfig.setSubscriptionName(instanceConfig.getFunctionDetails().getSource().getSubscriptionName());
}
goInstanceConfig.setSubscriptionPosition(instanceConfig.getFunctionDetails().getSource().getSubscriptionPosition().getNumber());
if (instanceConfig.getFunctionDetails().getSource().getInputSpecsMap() != null) {
Map<String, String> sourceInputSpecs = new HashMap<>();
for (Map.Entry<String, Function.ConsumerSpec> entry : instanceConfig.getFunctionDetails().getSource().getInputSpecsMap().entrySet()) {
String topic = entry.getKey();
Function.ConsumerSpec spec = entry.getValue();
sourceInputSpecs.put(topic, JsonFormat.printer().omittingInsignificantWhitespace().print(spec));
goInstanceConfig.setSourceSpecsTopic(topic);
}
goInstanceConfig.setSourceInputSpecs(sourceInputSpecs);
}
if (instanceConfig.getFunctionDetails().getSource().getTimeoutMs() != 0) {
goInstanceConfig.setTimeoutMs(instanceConfig.getFunctionDetails().getSource().getTimeoutMs());}
if
(instanceConfig.getFunctionDetails().getSink().getTopic() != null) {
goInstanceConfig.setSinkSpecsTopic(instanceConfig.getFunctionDetails().getSink().getTopic());
}
if (instanceConfig.getFunctionDetails().getResources().getCpu() != 0) { goInstanceConfig.setCpu(instanceConfig.getFunctionDetails().getResources().getCpu());}
if (instanceConfig.getFunctionDetails().getResources().getRam() != 0) {
goInstanceConfig.setRam(instanceConfig.getFunctionDetails().getResources().getRam());
}
if (instanceConfig.getFunctionDetails().getResources().getDisk() != 0) {
goInstanceConfig.setDisk(instanceConfig.getFunctionDetails().getResources().getDisk());
}
if (instanceConfig.getFunctionDetails().getRetryDetails().getDeadLetterTopic() != null) {
goInstanceConfig.setDeadLetterTopic(instanceConfig.getFunctionDetails().getRetryDetails().getDeadLetterTopic());
}
if (instanceConfig.getFunctionDetails().getRetryDetails().getMaxMessageRetries() != 0) {
goInstanceConfig.setMaxMessageRetries(instanceConfig.getFunctionDetails().getRetryDetails().getMaxMessageRetries());
}
if (instanceConfig.hasValidMetricsPort()) {
goInstanceConfig.setMetricsPort(instanceConfig.getMetricsPort());
}
goInstanceConfig.setKillAfterIdleMs(0);
goInstanceConfig.setPort(instanceConfig.getPort());
// Parse the contents of goInstanceConfig into json form string
ObjectMapper v8 = ObjectMapperFactory.getMapper().getObjectMapper();
String configContent = v8.writeValueAsString(goInstanceConfig);
args.add(originalCodeFileName);
args.add("-instance-conf");
if (k8sRuntime) {args.add(("'" +
configContent) +
"'");
} else {
args.add(configContent);
}
return args;
} | 3.26 |
pulsar_ResourceGroup_accumulateBMCount_rdh | // Visibility for unit testing
protected static BytesAndMessagesCount accumulateBMCount(BytesAndMessagesCount... bmCounts) {
BytesAndMessagesCount retBMCount = new BytesAndMessagesCount();
for (int ix = 0; ix < bmCounts.length; ix++) {
retBMCount.f1 += bmCounts[ix].f1;
retBMCount.f0 += bmCounts[ix].f0;
}
return retBMCount;
} | 3.26 |
pulsar_ResourceGroup_getUsageFromMonitoredEntity_rdh | // Update fields in a particular monitoring class from a given broker in the
// transport-manager callback for listening to usage reports.
private void getUsageFromMonitoredEntity(ResourceGroupMonitoringClass monClass, NetworkUsage p, String broker) {
final int idx = monClass.ordinal();
PerMonitoringClassFields monEntity;
PerBrokerUsageStats usageStats;
PerBrokerUsageStats oldUsageStats;
long oldByteCount;
long oldMessageCount;
long newByteCount;
long newMessageCount;
monEntity
= this.monitoringClassFields[idx];
usageStats = monEntity.usageFromOtherBrokers.get(broker);
if (usageStats == null) {
usageStats = new PerBrokerUsageStats();
usageStats.usedValues = new BytesAndMessagesCount();
}
monEntity.usageFromOtherBrokersLock.lock();
try {
newByteCount = p.getBytesPerPeriod();
usageStats.usedValues.f0 = newByteCount;
newMessageCount = p.getMessagesPerPeriod();
usageStats.usedValues.f1 = newMessageCount;
usageStats.lastResourceUsageReadTimeMSecsSinceEpoch = System.currentTimeMillis();
oldUsageStats = monEntity.usageFromOtherBrokers.put(broker, usageStats);
} finally {
monEntity.usageFromOtherBrokersLock.unlock();
}
rgRemoteUsageReportsBytes.labels(this.ruConsumer.getID(), monClass.name(), broker).inc(newByteCount);
rgRemoteUsageReportsMessages.labels(this.ruConsumer.getID(), monClass.name(), broker).inc(newMessageCount);
oldByteCount = oldMessageCount = -1;
if (oldUsageStats != null) {
oldByteCount = oldUsageStats.usedValues.f0;
oldMessageCount = oldUsageStats.usedValues.f1;
}
if (log.isDebugEnabled()) {
log.debug("resourceUsageListener for RG={}: updated {} stats for broker={} " + "with bytes={} (old ={}), messages={} (old={})", this.resourceGroupName, monClass, broker, newByteCount, oldByteCount, newMessageCount, oldMessageCount);
}
} | 3.26 |
pulsar_ResourceGroup_rgFillResourceUsage_rdh | // Transport manager mandated op.
public void rgFillResourceUsage(ResourceUsage resourceUsage) {
NetworkUsage p;
resourceUsage.setOwner(this.getID());
p = resourceUsage.setPublish();
this.setUsageInMonitoredEntity(ResourceGroupMonitoringClass.Publish, p);
p = resourceUsage.setDispatch();
this.setUsageInMonitoredEntity(ResourceGroupMonitoringClass.Dispatch, p);
// Punt storage for now.
} | 3.26 |
pulsar_ResourceGroup_rgResourceUsageListener_rdh | // Transport manager mandated op.
public void rgResourceUsageListener(String broker, ResourceUsage resourceUsage) {
NetworkUsage p;
p = resourceUsage.getPublish();
this.getUsageFromMonitoredEntity(ResourceGroupMonitoringClass.Publish, p, broker);
p = resourceUsage.getDispatch();
this.getUsageFromMonitoredEntity(ResourceGroupMonitoringClass.Dispatch, p, broker);
// Punt storage for now.
} | 3.26 |
pulsar_ResourceGroup_getRgRemoteUsageMessageCount_rdh | // Visibility for unit testing
protected static double getRgRemoteUsageMessageCount(String rgName, String monClassName, String brokerName) {
return rgRemoteUsageReportsMessages.labels(rgName, monClassName, brokerName).get();
} | 3.26 |
pulsar_ResourceGroup_getRgUsageReportedCount_rdh | // Visibility for unit testing
protected static double getRgUsageReportedCount(String rgName, String monClassName) {
return rgLocalUsageReportCount.labels(rgName, monClassName).get();
} | 3.26 |
pulsar_ResourceGroup_getRgRemoteUsageByteCount_rdh | // Visibility for unit testing
protected static double getRgRemoteUsageByteCount(String rgName, String monClassName, String brokerName) {
return rgRemoteUsageReportsBytes.labels(rgName, monClassName, brokerName).get();
} | 3.26 |
pulsar_ResourceGroup_setUsageInMonitoredEntity_rdh | // Fill usage about a particular monitoring class in the transport-manager callback
// for reporting local stats to other brokers.
// Returns true if something was filled.
// Visibility for unit testing.
protected boolean setUsageInMonitoredEntity(ResourceGroupMonitoringClass monClass, NetworkUsage p) {
long bytesUsed;
long messagesUsed;
boolean sendReport;
int numSuppressions = 0;
PerMonitoringClassFields monEntity;
final int idx
= monClass.ordinal();
monEntity = this.monitoringClassFields[idx];
monEntity.localUsageStatsLock.lock();
try {
sendReport = this.rgs.quotaCalculator.needToReportLocalUsage(monEntity.usedLocallySinceLastReport.f0, monEntity.lastReportedValues.f0, monEntity.usedLocallySinceLastReport.f1, monEntity.lastReportedValues.f1, monEntity.lastResourceUsageFillTimeMSecsSinceEpoch);
bytesUsed = monEntity.usedLocallySinceLastReport.f0;
messagesUsed = monEntity.usedLocallySinceLastReport.f1;
monEntity.usedLocallySinceLastReport.f0 = monEntity.usedLocallySinceLastReport.f1 = 0;
monEntity.totalUsedLocally.f0 += bytesUsed;
monEntity.totalUsedLocally.f1 += messagesUsed;
monEntity.lastResourceUsageFillTimeMSecsSinceEpoch = System.currentTimeMillis();
if (sendReport) {
p.setBytesPerPeriod(bytesUsed);
p.setMessagesPerPeriod(messagesUsed);
monEntity.lastReportedValues.f0 = bytesUsed;
monEntity.lastReportedValues.f1 = messagesUsed;
monEntity.numSuppressedUsageReports = 0;
} else {
numSuppressions = monEntity.numSuppressedUsageReports++;
}
} finally {
monEntity.localUsageStatsLock.unlock();
}
final String
rgName = (this.ruPublisher != null) ? this.ruPublisher.getID() : this.resourceGroupName;
double sentCount = (sendReport) ? 1 : 0;
rgLocalUsageReportCount.labels(rgName, monClass.name()).inc(sentCount);
if (sendReport) {
if (log.isDebugEnabled()) {
log.debug("fillResourceUsage for RG={}: filled a {} update; bytes={}, messages={}", rgName, monClass, bytesUsed, messagesUsed);
}
} else
if
(log.isDebugEnabled()) {
log.debug("fillResourceUsage for RG={}: report for {} suppressed " + "(suppressions={} since last sent report)", rgName, monClass, numSuppressions);
}
return sendReport;
} | 3.26 |
pulsar_NonPersistentSubscriptionStatsImpl_add_rdh | // if the stats are added for the 1st time, we will need to make a copy of these stats and add it to the current
// stats
public NonPersistentSubscriptionStatsImpl add(NonPersistentSubscriptionStatsImpl stats) {Objects.requireNonNull(stats);
super.add(stats);
this.msgDropRate += stats.msgDropRate;
return this;
} | 3.26 |
pulsar_ImmutableBucket_recoverDelayedIndexBitMapAndNumber_rdh | /**
* Recover delayed index bit map and message numbers.
*
* @throws InvalidRoaringFormat
* invalid bitmap serialization format
*/
private void recoverDelayedIndexBitMapAndNumber(int startSnapshotIndex, List<SnapshotSegmentMetadata> segmentMetaList) {
delayedIndexBitMap.clear();// cleanup dirty bm
final var numberMessages = new MutableLong(0);
for (int i = startSnapshotIndex; i < segmentMetaList.size(); i++) {
for (final var v11 : segmentMetaList.get(i).getDelayedIndexBitMapMap().entrySet()) {
final var ledgerId = v11.getKey();
final var bs = v11.getValue();
final var sbm = new RoaringBitmap();
try {
sbm.deserialize(bs.asReadOnlyByteBuffer());
} catch (IOException e) {
throw new InvalidRoaringFormat(e.getMessage());
}
numberMessages.add(sbm.getCardinality());
delayedIndexBitMap.compute(ledgerId, (lId, bm) -> {
if (bm == null) {
return sbm;
}
bm.or(sbm);
return bm; });
}
}
// optimize bm
delayedIndexBitMap.values().forEach(RoaringBitmap::runOptimize);
setNumberBucketDelayedMessages(numberMessages.getValue());
} | 3.26 |
pulsar_ReaderListener_reachedEndOfTopic_rdh | /**
* Get the notification when a topic is terminated.
*
* @param reader
* the Reader object associated with the terminated topic
*/
default void reachedEndOfTopic(Reader reader) {
// By default ignore the notification
} | 3.26 |
pulsar_ConsumerConfigurationData_getMaxPendingChuckedMessage_rdh | /**
*
* @deprecated use {@link #getMaxPendingChunkedMessage()}
*/
@Deprecated
public int getMaxPendingChuckedMessage() {
return maxPendingChunkedMessage;
} | 3.26 |
pulsar_ConsumerConfigurationData_setMaxPendingChuckedMessage_rdh | /**
*
* @deprecated use {@link #setMaxPendingChunkedMessage(int)}
*/
@Deprecated
public void setMaxPendingChuckedMessage(int maxPendingChuckedMessage) {
this.maxPendingChunkedMessage = maxPendingChuckedMessage;
} | 3.26 |
pulsar_WaterMarkEventGenerator_track_rdh | /**
* Tracks the timestamp of the event from a topic, returns
* true if the event can be considered for processing or
* false if its a late event.
*/
public boolean track(String inputTopic, long ts) {
Long currentVal = f0.get(inputTopic);
if ((currentVal == null) || (ts > currentVal)) {
f0.put(inputTopic, ts);
}
checkFailures();
return ts >= lastWaterMarkTs;
} | 3.26 |
pulsar_WaterMarkEventGenerator_computeWaterMarkTs_rdh | /**
* Computes the min ts across all input topics.
*/
private long computeWaterMarkTs() {
long ts = 0;
// only if some data has arrived on each input topic
if (f0.size() >=
inputTopics.size()) {
ts = Long.MAX_VALUE;
for (Map.Entry<String, Long> entry : f0.entrySet()) {
ts = Math.min(ts, entry.getValue());
}
}
return ts - eventTsLagMs;} | 3.26 |
pulsar_ManagedLedgerOfflineBacklog_getNumberOfEntries_rdh | // need a better way than to duplicate the functionality below from ML
private long getNumberOfEntries(Range<PositionImpl> range, NavigableMap<Long, MLDataFormats.ManagedLedgerInfo.LedgerInfo> ledgers) {
PositionImpl fromPosition = range.lowerEndpoint();
boolean fromIncluded = range.lowerBoundType() == BoundType.CLOSED;
PositionImpl toPosition = range.upperEndpoint();
boolean toIncluded =
range.upperBoundType() == BoundType.CLOSED;
if (fromPosition.getLedgerId() == toPosition.getLedgerId()) {
// If the 2 positions are in the same ledger
long count = (toPosition.getEntryId() - fromPosition.getEntryId())
- 1;
count += (fromIncluded) ? 1 : 0;
count += (toIncluded) ? 1 : 0;
return count;
} else {
long count = 0;
// If the from & to are pointing to different ledgers, then we need to :
// 1. Add the entries in the ledger pointed by toPosition
count += toPosition.getEntryId();
count += (toIncluded) ? 1 : 0;
// 2. Add the entries in the ledger pointed by fromPosition
MLDataFormats.ManagedLedgerInfo.LedgerInfo li = ledgers.get(fromPosition.getLedgerId());
if (li != null) {
count += li.getEntries() - (fromPosition.getEntryId() + 1);
count += (fromIncluded) ? 1 : 0;
}
// 3. Add the whole ledgers entries in between
for (MLDataFormats.ManagedLedgerInfo.LedgerInfo ls : ledgers.subMap(fromPosition.getLedgerId(),
false, toPosition.getLedgerId(), false).values()) {
count += ls.getEntries();
}
return count;
}
} | 3.26 |
pulsar_OffloadPoliciesImpl_oldPoliciesCompatible_rdh | /**
* This method is used to make a compatible with old policies.
*
* <p>The filed {@link Policies#offload_threshold} is primitive, so it can't be known whether it had been set.
* In the old logic, if the field value is -1, it could be thought that the field had not been set.
*
* @param nsLevelPolicies
* namespace level offload policies
* @param policies
* namespace policies
* @return offload policies
*/
public static OffloadPoliciesImpl oldPoliciesCompatible(OffloadPoliciesImpl nsLevelPolicies, Policies policies) {
if ((policies == null) || (((policies.offload_threshold == (-1)) && (policies.offload_threshold_in_seconds == (-1))) && (policies.offload_deletion_lag_ms == null))) {
return nsLevelPolicies;
}if (nsLevelPolicies
== null) {nsLevelPolicies = new OffloadPoliciesImpl();
}
if
((nsLevelPolicies.getManagedLedgerOffloadThresholdInBytes() == null) && (policies.offload_threshold != (-1))) {
nsLevelPolicies.setManagedLedgerOffloadThresholdInBytes(policies.offload_threshold);
}
if ((nsLevelPolicies.getManagedLedgerOffloadThresholdInSeconds() ==
null) && (policies.offload_threshold_in_seconds != (-1)))
{
nsLevelPolicies.setManagedLedgerOffloadThresholdInSeconds(policies.offload_threshold_in_seconds);
}
if ((nsLevelPolicies.getManagedLedgerOffloadDeletionLagInMillis() == null) && (policies.offload_deletion_lag_ms != null)) {
nsLevelPolicies.setManagedLedgerOffloadDeletionLagInMillis(policies.offload_deletion_lag_ms);
}
return nsLevelPolicies;
} | 3.26 |
pulsar_OffloadPoliciesImpl_mergeConfiguration_rdh | /**
* Merge different level offload policies.
*
* <p>policies level priority: topic > namespace > broker
*
* @param topicLevelPolicies
* topic level offload policies
* @param nsLevelPolicies
* namespace level offload policies
* @param brokerProperties
* broker level offload configuration
* @return offload policies
*/
public static OffloadPoliciesImpl mergeConfiguration(OffloadPoliciesImpl topicLevelPolicies, OffloadPoliciesImpl nsLevelPolicies, Properties brokerProperties) {
try {
boolean allConfigValuesAreNull =
true;
OffloadPoliciesImpl offloadPolicies = new OffloadPoliciesImpl();
for (Field field : CONFIGURATION_FIELDS) {
Object object;
if ((topicLevelPolicies != null) && (field.get(topicLevelPolicies) != null)) {
object = field.get(topicLevelPolicies);
} else if ((nsLevelPolicies != null) && (field.get(nsLevelPolicies) != null)) {object = field.get(nsLevelPolicies);
} else {
object = getCompatibleValue(brokerProperties, field);}
if (object != null) {
field.set(offloadPolicies, object);
if (allConfigValuesAreNull) {
allConfigValuesAreNull = false;
}
}
}
if (allConfigValuesAreNull) {
return null;
} else {
return offloadPolicies;
} } catch (Exception e) {
log.error("Failed to merge configuration.", e);
return null;
}
} | 3.26 |
pulsar_OffloadPoliciesImpl_getCompatibleValue_rdh | /**
* Make configurations of the OffloadPolicies compatible with the config file.
*
* <p>The names of the fields {@link OffloadPoliciesImpl#managedLedgerOffloadDeletionLagInMillis}
* and {@link OffloadPoliciesImpl#managedLedgerOffloadThresholdInBytes} are not matched with
* config file (broker.conf or standalone.conf).
*
* @param properties
* broker configuration properties
* @param field
* filed
* @return field value
*/
private static Object getCompatibleValue(Properties properties, Field field) { Object object;
if (field.getName().equals("managedLedgerOffloadThresholdInBytes")) {
object = properties.getProperty("managedLedgerOffloadThresholdInBytes", properties.getProperty(OFFLOAD_THRESHOLD_NAME_IN_CONF_FILE));
} else if (field.getName().equals("managedLedgerOffloadDeletionLagInMillis")) {
object = properties.getProperty("managedLedgerOffloadDeletionLagInMillis", properties.getProperty(DELETION_LAG_NAME_IN_CONF_FILE));
} else if (field.getName().equals("managedLedgerOffloadedReadPriority")) {
object = properties.getProperty("managedLedgerOffloadedReadPriority", properties.getProperty(DATA_READ_PRIORITY_NAME_IN_CONF_FILE));
} else {
object = properties.get(field.getName());
}
return value(((String) (object)), field);
} | 3.26 |
pulsar_ConsumerImpl_createEncryptionContext_rdh | /**
* Create EncryptionContext if message payload is encrypted.
*
* @param msgMetadata
* @return {@link Optional}<{@link EncryptionContext}>
*/
private Optional<EncryptionContext> createEncryptionContext(MessageMetadata msgMetadata) {
EncryptionContext encryptionCtx = null;
if (msgMetadata.getEncryptionKeysCount() > 0) {
encryptionCtx = new EncryptionContext();
Map<String, EncryptionKey> keys = msgMetadata.getEncryptionKeysList().stream().collect(Collectors.toMap(EncryptionKeys::getKey, e -> new EncryptionKey(e.getValue(), e.getMetadatasList().stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue)))));
byte[] encParam = msgMetadata.getEncryptionParam();
Optional<Integer> batchSize
= Optional.ofNullable(msgMetadata.hasNumMessagesInBatch() ? msgMetadata.getNumMessagesInBatch() : null);
encryptionCtx.setKeys(keys);
encryptionCtx.setParam(encParam);
if (msgMetadata.hasEncryptionAlgo()) {encryptionCtx.setAlgorithm(msgMetadata.getEncryptionAlgo());
}
encryptionCtx.setCompressionType(CompressionCodecProvider.convertFromWireProtocol(msgMetadata.getCompression()));
encryptionCtx.setUncompressedMessageSize(msgMetadata.getUncompressedSize());
encryptionCtx.setBatchSize(batchSize);
}
return Optional.ofNullable(encryptionCtx);
} | 3.26 |
pulsar_ConsumerImpl_notifyPendingReceivedCallback_rdh | /**
* Notify waiting asyncReceive request with the received message.
*
* @param message
*/void notifyPendingReceivedCallback(final Message<T> message, Exception exception) {
if (pendingReceives.isEmpty()) {
return;
}
// fetch receivedCallback from queue
final CompletableFuture<Message<T>> receivedFuture = nextPendingReceive();
if (receivedFuture == null) {return;
}
if (exception != null) {
internalPinnedExecutor.execute(() -> receivedFuture.completeExceptionally(exception));
return;
}
if (message == null) {
IllegalStateException e = new IllegalStateException("received message can't be null");
internalPinnedExecutor.execute(() -> receivedFuture.completeExceptionally(e));return;
}
if (getCurrentReceiverQueueSize() == 0) {
// call interceptor and complete received callback
trackMessage(message);
interceptAndComplete(message, receivedFuture);
return;}
// increase permits for available message-queue
m1(message);
// call interceptor and complete received callback
interceptAndComplete(message, receivedFuture);
} | 3.26 |
pulsar_ConsumerImpl_m1_rdh | /**
* Record the event that one message has been processed by the application.
*
* Periodically, it sends a Flow command to notify the broker that it can push more messages
*/
@Override
protected synchronized void
m1(Message<?> msg) {
ClientCnx currentCnx = cnx();
ClientCnx msgCnx = ((MessageImpl<?>) (msg)).getCnx();
lastDequeuedMessageId = msg.getMessageId();
if (msgCnx != currentCnx) {
// The processed message did belong to the old queue that was cleared after reconnection.
} else {
if ((listener == null) && (!parentConsumerHasListener)) {
increaseAvailablePermits(currentCnx);
}
stats.updateNumMsgsReceived(msg);
trackMessage(msg);
}
decreaseIncomingMessageSize(msg);
} | 3.26 |
pulsar_ConsumerImpl_releasePooledMessagesAndStopAcceptNew_rdh | /**
* If enabled pooled messages, we should release the messages after closing consumer and stop accept the new
* messages.
*/
private void releasePooledMessagesAndStopAcceptNew() {
incomingMessages.terminate(message -> message.release());
clearIncomingMessages();
} | 3.26 |
pulsar_ConsumerImpl_m0_rdh | /**
* Clear the internal receiver queue and returns the message id of what was the 1st message in the queue that was
* not seen by the application.
*/
private MessageIdAdv m0() {
List<Message<?>> currentMessageQueue = new ArrayList<>(incomingMessages.size());
incomingMessages.drainTo(currentMessageQueue);resetIncomingMessageSize();
if (duringSeek.compareAndSet(true, false)) {
return seekMessageId;
} else if (subscriptionMode ==
SubscriptionMode.Durable) {
return startMessageId;
}
if (!currentMessageQueue.isEmpty()) {
MessageIdAdv nextMessageInQueue = ((MessageIdAdv) (currentMessageQueue.get(0).getMessageId()));
MessageIdAdv previousMessage;
if (MessageIdAdvUtils.isBatch(nextMessageInQueue)) {
// Get on the previous message within the current batch
previousMessage = new BatchMessageIdImpl(nextMessageInQueue.getLedgerId(), nextMessageInQueue.getEntryId(), nextMessageInQueue.getPartitionIndex(), nextMessageInQueue.getBatchIndex() - 1);
} else {
// Get on previous message in previous entry
previousMessage = MessageIdAdvUtils.prevMessageId(nextMessageInQueue);
}
// release messages if they are pooled messages
currentMessageQueue.forEach(Message::release);
return previousMessage;
} else if (!lastDequeuedMessageId.equals(MessageId.earliest)) {
// If the queue was empty we need to restart from the message just after the last one that has been dequeued
// in the past
return new BatchMessageIdImpl(((MessageIdImpl) (lastDequeuedMessageId)));}
else {
// No message was received or dequeued by this consumer. Next message would still be the startMessageId
return startMessageId;
}} | 3.26 |
pulsar_ConsumerImpl_cnx_rdh | // wrapper for connection methods
ClientCnx cnx() {
return this.connectionHandler.cnx();
} | 3.26 |
pulsar_SecurityUtility_getBCProviderFromClassPath_rdh | /**
* Get Bouncy Castle provider from classpath, and call Security.addProvider.
* Throw Exception if failed.
*/
public static Provider getBCProviderFromClassPath() throws Exception {
Class clazz;
try
{
// prefer non FIPS, for backward compatibility concern.
clazz = Class.forName(BC_NON_FIPS_PROVIDER_CLASS);
} catch (ClassNotFoundException cnf) {
log.warn("Not able to get Bouncy Castle provider: {}, try to get FIPS provider {}", BC_NON_FIPS_PROVIDER_CLASS, f0);
// attempt to use the FIPS provider.
clazz = Class.forName(f0);}
Provider provider = ((Provider) (clazz.getDeclaredConstructor().newInstance()));
Security.addProvider(provider);
if (log.isDebugEnabled()) {
log.debug("Found and Instantiated Bouncy Castle provider in classpath {}", provider.getName());
}
return provider;
} | 3.26 |
pulsar_SecurityUtility_processConscryptTrustManager_rdh | // workaround https://github.com/google/conscrypt/issues/1015
private static void processConscryptTrustManager(TrustManager trustManager) {
if (trustManager.getClass().getName().equals("org.conscrypt.TrustManagerImpl")) {
try {
Class<?> conscryptClazz = Class.forName("org.conscrypt.Conscrypt");
Object hostnameVerifier = conscryptClazz.getMethod("getHostnameVerifier", new Class[]{ TrustManager.class }).invoke(null, trustManager);
if (hostnameVerifier == null) {
Object defaultHostnameVerifier = conscryptClazz.getMethod("getDefaultHostnameVerifier", new Class[]{ TrustManager.class }).invoke(null, trustManager);
if (defaultHostnameVerifier != null) {
conscryptClazz.getMethod("setHostnameVerifier", new Class[]{ TrustManager.class, Class.forName("org.conscrypt.ConscryptHostnameVerifier") }).invoke(null, trustManager, defaultHostnameVerifier);
}
}
} catch (ReflectiveOperationException e) {
log.warn("Unable to set hostname verifier for Conscrypt TrustManager implementation", e);
}
}} | 3.26 |
pulsar_SecurityUtility_getProvider_rdh | /**
* Get Bouncy Castle provider, and call Security.addProvider(provider) if success.
* 1. try get from classpath.
* 2. try get from Nar.
*/
public static Provider getProvider() {
boolean isProviderInstalled = (Security.getProvider(BC) != null) || (Security.getProvider(BC_FIPS) !=
null);if (isProviderInstalled) {
Provider provider = (Security.getProvider(BC) != null) ? Security.getProvider(BC) : Security.getProvider(BC_FIPS);
if (log.isDebugEnabled()) {
log.debug("Already instantiated Bouncy Castle provider {}",
provider.getName());
}
return provider;
}
// Not installed, try load from class path
try {
return getBCProviderFromClassPath();
} catch (Exception e) {
log.warn("Not able to get Bouncy Castle provider for both FIPS and Non-FIPS from class path:", e);
throw new RuntimeException(e);
}
} | 3.26 |
pulsar_PerfClientUtils_printJVMInformation_rdh | /**
* Print useful JVM information, you need this information in order to be able
* to compare the results of executions in different environments.
*
* @param log
*/
public static void printJVMInformation(Logger log) {
log.info("JVM args {}", ManagementFactory.getRuntimeMXBean().getInputArguments());
log.info("Netty max memory (PlatformDependent.maxDirectMemory()) {}", FileUtils.byteCountToDisplaySize(DirectMemoryUtils.jvmMaxDirectMemory()));
log.info("JVM max heap memory (Runtime.getRuntime().maxMemory()) {}", FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory()));
} | 3.26 |
pulsar_PackagesStorageProvider_newProvider_rdh | /**
* Construct a provider from the provided class.
*
* @param providerClassName
* the provider class name
* @return an instance of package storage provider
* @throws IOException
*/
static PackagesStorageProvider newProvider(String providerClassName) throws IOException {
Class<?> providerClass;
try {
providerClass = Class.forName(providerClassName);
Object obj = providerClass.getDeclaredConstructor().newInstance();
checkArgument(obj
instanceof PackagesStorageProvider, "The package storage provider has to be an instance of " + PackagesStorageProvider.class.getName());
return ((PackagesStorageProvider) (obj));
} catch (Exception e) {
throw new IOException(e);
}
} | 3.26 |
pulsar_ManagedLedgerMetrics_groupLedgersByDimension_rdh | /**
* Build a map of dimensions key to list of topic stats (not thread-safe).
* <p>
*
* @return */
private Map<Metrics, List<ManagedLedgerImpl>> groupLedgersByDimension() {
ledgersByDimensionMap.clear(); // get the current topics statistics from StatsBrokerFilter
// Map : topic-name->dest-stat
for (Entry<String, ManagedLedgerImpl> e : getManagedLedgers().entrySet()) {
String ledgerName = e.getKey();
ManagedLedgerImpl v8 = e.getValue();
// we want to aggregate by NS dimension
String namespace = parseNamespaceFromLedgerName(ledgerName);
Metrics metrics = createMetricsByDimension(namespace);
populateDimensionMap(ledgersByDimensionMap, metrics, v8);
}
return ledgersByDimensionMap;
} | 3.26 |
pulsar_ManagedLedgerMetrics_aggregate_rdh | /**
* Aggregation by namespace (not thread-safe).
*
* @param ledgersByDimension
* @return */
private List<Metrics> aggregate(Map<Metrics, List<ManagedLedgerImpl>> ledgersByDimension) {
metricsCollection.clear();
for (Entry<Metrics, List<ManagedLedgerImpl>> e : ledgersByDimension.entrySet()) {
Metrics metrics = e.getKey();
List<ManagedLedgerImpl> ledgers = e.getValue();
// prepare aggregation map
tempAggregatedMetricsMap.clear();
// generate the collections by each metrics and then apply the aggregation
for (ManagedLedgerImpl ledger : ledgers) {
ManagedLedgerMXBean lStats = ledger.getStats();
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_AddEntryBytesRate", lStats.getAddEntryBytesRate());
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_AddEntryWithReplicasBytesRate", lStats.getAddEntryWithReplicasBytesRate());
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_AddEntryErrors", ((double) (lStats.getAddEntryErrors())));
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_AddEntryMessagesRate", lStats.getAddEntryMessagesRate());populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_AddEntrySucceed", ((double) (lStats.getAddEntrySucceed())));
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_NumberOfMessagesInBacklog", ((double) (lStats.getNumberOfMessagesInBacklog())));populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_ReadEntriesBytesRate", lStats.getReadEntriesBytesRate());
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_ReadEntriesErrors", ((double) (lStats.getReadEntriesErrors())));
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_ReadEntriesRate", lStats.getReadEntriesRate());
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_ReadEntriesOpsCacheMissesRate", lStats.getReadEntriesOpsCacheMissesRate());
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_ReadEntriesSucceeded", ((double) (lStats.getReadEntriesSucceeded())));
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_StoredMessagesSize", ((double) (lStats.getStoredMessagesSize())));
// handle bucket entries initialization here
BRK_ML_ADDENTRYLATENCYBUCKETS.populateBucketEntries(tempAggregatedMetricsMap, lStats.getAddEntryLatencyBuckets(), statsPeriodSeconds);
BRK_ML_LEDGERADDENTRYLATENCYBUCKETS.populateBucketEntries(tempAggregatedMetricsMap, lStats.getLedgerAddEntryLatencyBuckets(), statsPeriodSeconds);
BRK_ML_LEDGERSWITCHLATENCYBUCKETS.populateBucketEntries(tempAggregatedMetricsMap, lStats.getLedgerSwitchLatencyBuckets(), statsPeriodSeconds);
BRK_ML_ENTRYSIZEBUCKETS.populateBucketEntries(tempAggregatedMetricsMap, lStats.getEntrySizeBuckets(), statsPeriodSeconds);
populateAggregationMapWithSum(tempAggregatedMetricsMap, "brk_ml_MarkDeleteRate", lStats.getMarkDeleteRate());
}
// SUM up collections of each metrics
for (Entry<String, Double> ma : tempAggregatedMetricsMap.entrySet()) {
metrics.put(ma.getKey(), ma.getValue());
}
metricsCollection.add(metrics);}
return metricsCollection;
} | 3.26 |
pulsar_BlobStoreBackedReadHandleImpl_getState_rdh | // for testing
State getState() {
return this.state;
} | 3.26 |
pulsar_KubernetesServiceAccountTokenAuthProvider_cleanUpAuthData_rdh | /**
* No need to clean up anything. Kubernetes cleans up the secret when the pod is deleted.
*/
@Override
public void cleanUpAuthData(Function.FunctionDetails funcDetails, Optional<FunctionAuthData> functionAuthData) throws Exception {
} | 3.26 |
pulsar_KubernetesServiceAccountTokenAuthProvider_updateAuthData_rdh | /**
* No need to update anything. Kubernetes updates the token used for authentication.
*/
@Override
public Optional<FunctionAuthData> updateAuthData(Function.FunctionDetails funcDetails, Optional<FunctionAuthData> existingFunctionAuthData, AuthenticationDataSource authenticationDataSource) throws Exception {
return Optional.empty();
} | 3.26 |
pulsar_KubernetesServiceAccountTokenAuthProvider_cacheAuthData_rdh | /**
* No need to cache anything. Kubernetes generates the token used for authentication.
*/
@Override
public Optional<FunctionAuthData> cacheAuthData(Function.FunctionDetails funcDetails, AuthenticationDataSource authenticationDataSource) throws Exception {
return Optional.empty();
} | 3.26 |
pulsar_ConcurrentLongPairSet_remove_rdh | /**
* Remove an existing entry if found.
*
* @param item1
* @return true if removed or false if item was not present
*/
public boolean remove(long item1, long item2) {
checkBiggerEqualZero(item1);
long h = hash(item1, item2);
return getSection(h).remove(item1, item2, ((int) (h)));
} | 3.26 |
pulsar_ConcurrentLongPairSet_items_rdh | /**
*
* @return a new list of keys with max provided numberOfItems (makes a copy)
*/
public Set<LongPair> items(int numberOfItems) {
return items(numberOfItems, (item1, item2) -> new LongPair(item1, item2));
} | 3.26 |
pulsar_ConcurrentLongPairSet_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 processor to process the elements
*/
public void forEach(LongPairConsumer processor) {
for (int v16 = 0; v16 <
sections.length; v16++) {
sections[v16].forEach(processor);
}
}
/**
* Removes all of the elements of this collection that satisfy the given predicate.
*
* @param filter
* a predicate which returns {@code true} | 3.26 |
pulsar_PulsarZooKeeperClient_getSessionId_rdh | // inherits from ZooKeeper client for all operations
@Override
public long getSessionId() {
ZooKeeper zkHandle = zk.get();if (null == zkHandle) {
return super.getSessionId();
}
return zkHandle.getSessionId();
} | 3.26 |
pulsar_PulsarZooKeeperClient_isRecoverableException_rdh | /**
* Check whether the given exception is recoverable by retry.
*
* @param exception
* given exception
* @return true if given exception is recoverable.
*/
public static boolean isRecoverableException(KeeperException exception) {
return isRecoverableException(exception.code().intValue());
} | 3.26 |
pulsar_PulsarZooKeeperClient_syncCallWithRetries_rdh | /**
* Execute a sync zookeeper operation with a given retry policy.
*
* @param client
* ZooKeeper client.
* @param proc
* Synchronous zookeeper operation wrapped in a {@link Callable}.
* @param retryPolicy
* Retry policy to execute the synchronous operation.
* @param rateLimiter
* Rate limiter for zookeeper calls
* @param statsLogger
* Stats Logger for zookeeper client.
* @return result of the zookeeper operation
* @throws KeeperException
* any non-recoverable exception or recoverable exception exhausted all retires.
* @throws InterruptedException
* the operation is interrupted.
*/
public static <T> T syncCallWithRetries(PulsarZooKeeperClient client, ZooWorker.ZooCallable<T>
proc, RetryPolicy retryPolicy, RateLimiter rateLimiter, OpStatsLogger statsLogger) throws KeeperException, InterruptedException {
T result = null;
boolean isDone = false;
int attempts = 0;
long startTimeNanos = MathUtils.nowInNano();
while (!isDone) {
try {
if (null != client) {
client.waitForConnection();
}
log.debug("Execute {} at {} retry attempt.", proc, attempts);
if (null != rateLimiter) {
rateLimiter.acquire();
}
result = proc.call();
isDone = true;
statsLogger.registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS);
} catch (KeeperException e) {
++attempts;boolean rethrow = true;
long elapsedTime = MathUtils.elapsedMSec(startTimeNanos);
if ((((null != client) && isRecoverableException(e)) || (null == client))
&& retryPolicy.allowRetry(attempts, elapsedTime)) {
rethrow = false;
}
if (rethrow) {
statsLogger.registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS);
log.debug("Stopped executing {} after {} attempts.", proc, attempts);
throw e;
}
TimeUnit.MILLISECONDS.sleep(retryPolicy.nextRetryWaitTime(attempts, elapsedTime));
}
}
return result;
} | 3.26 |
pulsar_UniformLoadShedder_findBundlesForUnloading_rdh | /**
* Attempt to shed some bundles off every broker which is overloaded.
*
* @param loadData
* The load data to used to make the unloading decision.
* @param conf
* The service configuration.
* @return A map from bundles to unload to the brokers on which they are loaded.
*/
@Override
public Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) {
selectedBundlesCache.clear();
Map<String, BrokerData> brokersData = loadData.getBrokerData();
Map<String, BundleData> loadBundleData = loadData.getBundleDataForLoadShedding();
Map<String, Long> recentlyUnloadedBundles = loadData.getRecentlyUnloadedBundles();
MutableObject<String> v3 = new
MutableObject<>();
MutableObject<String> msgThroughputOverloadedBroker = new MutableObject<>();
MutableObject<String> msgRateUnderloadedBroker = new MutableObject<>();
MutableObject<String> msgThroughputUnderloadedBroker = new MutableObject<>();
MutableDouble maxMsgRate = new MutableDouble(-1);
MutableDouble maxThroughput = new MutableDouble(-1);
MutableDouble minMsgRate = new MutableDouble(Integer.MAX_VALUE);
MutableDouble minThroughput = new MutableDouble(Integer.MAX_VALUE);
brokersData.forEach((broker,
data) -> {
double msgRate = data.getLocalData().getMsgRateIn() + data.getLocalData().getMsgRateOut();
double throughputRate = data.getLocalData().getMsgThroughputIn() + data.getLocalData().getMsgThroughputOut();
if (msgRate > maxMsgRate.getValue()) {
v3.setValue(broker);
maxMsgRate.setValue(msgRate);
}
if (throughputRate > maxThroughput.getValue()) {msgThroughputOverloadedBroker.setValue(broker);
maxThroughput.setValue(throughputRate);
}
if (msgRate < minMsgRate.getValue()) {
msgRateUnderloadedBroker.setValue(broker);
minMsgRate.setValue(msgRate);
}
if
(throughputRate < minThroughput.getValue()) {
msgThroughputUnderloadedBroker.setValue(broker);
minThroughput.setValue(throughputRate);
}
});
// find the difference between two brokers based on msgRate and throughout and check if the load distribution
// discrepancy is higher than threshold. if that matches then try to unload bundle from overloaded brokers to
// give chance of uniform load distribution.
if ((minMsgRate.getValue() <= EPS) && (minMsgRate.getValue() >= (-EPS))) {minMsgRate.setValue(1.0);
}
if ((minThroughput.getValue() <= EPS) && (minThroughput.getValue() >= (-EPS))) {
minThroughput.setValue(1.0);
}
double v13 = ((maxMsgRate.getValue() - minMsgRate.getValue()) * 100) / minMsgRate.getValue();
double msgThroughputDifferenceRate = maxThroughput.getValue() / minThroughput.getValue();
// if the threshold matches then find out how much load needs to be unloaded by considering number of msgRate
// and throughput.
boolean isMsgRateThresholdExceeded = (conf.getLoadBalancerMsgRateDifferenceShedderThreshold() > 0) && (v13 > conf.getLoadBalancerMsgRateDifferenceShedderThreshold());
boolean isMsgThroughputThresholdExceeded = (conf.getLoadBalancerMsgThroughputMultiplierDifferenceShedderThreshold() > 0) && (msgThroughputDifferenceRate > conf.getLoadBalancerMsgThroughputMultiplierDifferenceShedderThreshold());
if (isMsgRateThresholdExceeded || isMsgThroughputThresholdExceeded) {
MutableInt msgRateRequiredFromUnloadedBundles = new MutableInt(((int) ((maxMsgRate.getValue() - minMsgRate.getValue()) * conf.getMaxUnloadPercentage())));
MutableInt msgThroughputRequiredFromUnloadedBundles = new MutableInt(((int) ((maxThroughput.getValue() - minThroughput.getValue()) * conf.getMaxUnloadPercentage())));
if (isMsgRateThresholdExceeded) {
if (log.isDebugEnabled()) {
log.debug(("Found bundles for uniform load balancing. " + "msgRate overloaded broker: {} with msgRate: {}, ") + "msgRate underloaded broker: {} with msgRate: {}", v3.getValue(), maxMsgRate.getValue(), msgRateUnderloadedBroker.getValue(),
minMsgRate.getValue());
}LocalBrokerData overloadedBrokerData = brokersData.get(v3.getValue()).getLocalData();
if ((overloadedBrokerData.getBundles().size() > 1) && (msgRateRequiredFromUnloadedBundles.getValue() >= conf.getMinUnloadMessage())) {
// Sort bundles by throughput, then pick the bundle which can help to reduce load uniformly with
// under-loaded broker
loadBundleData.entrySet().stream().filter(e -> overloadedBrokerData.getBundles().contains(e.getKey())).map(e -> {
String bundle = e.getKey();
TimeAverageMessageData shortTermData = e.getValue().getShortTermData();
double msgRate = shortTermData.getMsgRateIn() + shortTermData.getMsgRateOut();
return Pair.of(bundle, msgRate);
}).filter(e -> !recentlyUnloadedBundles.containsKey(e.getLeft())).sorted((e1, e2) -> Double.compare(e2.getRight(), e1.getRight())).forEach(e -> {
if ((conf.getMaxUnloadBundleNumPerShedding() != (-1)) && (selectedBundlesCache.size() >= conf.getMaxUnloadBundleNumPerShedding())) {
return;
}
String bundle = e.getLeft();
double bundleMsgRate = e.getRight();
if (bundleMsgRate <= (msgRateRequiredFromUnloadedBundles.getValue() + 1000/* delta */
)) {
log.info("Found bundle to unload with msgRate {}", bundleMsgRate);
msgRateRequiredFromUnloadedBundles.add(-bundleMsgRate);
selectedBundlesCache.put(v3.getValue(), bundle);
}
});
}
} else {
if (log.isDebugEnabled()) {
log.debug(("Found bundles for uniform load balancing. " + "msgThroughput overloaded broker: {} with msgThroughput {}, ") + "msgThroughput underloaded broker: {} with msgThroughput: {}", msgThroughputOverloadedBroker.getValue(), maxThroughput.getValue(), msgThroughputUnderloadedBroker.getValue(), minThroughput.getValue()); }
LocalBrokerData overloadedBrokerData = brokersData.get(msgThroughputOverloadedBroker.getValue()).getLocalData();
if ((overloadedBrokerData.getBundles().size() > 1) && (msgThroughputRequiredFromUnloadedBundles.getValue() >= conf.getMinUnloadMessageThroughput())) {
// Sort bundles by throughput, then pick the bundle which can help to reduce load uniformly with
// under-loaded broker
loadBundleData.entrySet().stream().filter(e -> overloadedBrokerData.getBundles().contains(e.getKey())).map(e -> {
String bundle = e.getKey();
TimeAverageMessageData shortTermData = e.getValue().getShortTermData(); double msgThroughtput = shortTermData.getMsgThroughputIn() + shortTermData.getMsgThroughputOut();
return Pair.of(bundle, msgThroughtput);
}).filter(e -> !recentlyUnloadedBundles.containsKey(e.getLeft())).sorted((e1, e2) -> Double.compare(e2.getRight(), e1.getRight())).forEach(e
-> {
if ((conf.getMaxUnloadBundleNumPerShedding() !=
(-1)) && (selectedBundlesCache.size() >= conf.getMaxUnloadBundleNumPerShedding())) {
return;
}String bundle = e.getLeft();
double msgThroughput = e.getRight();if (msgThroughput <= (msgThroughputRequiredFromUnloadedBundles.getValue() + 1000/* delta */
)) {
log.info("Found bundle to unload with msgThroughput {}", msgThroughput);
msgThroughputRequiredFromUnloadedBundles.add(-msgThroughput);
selectedBundlesCache.put(msgThroughputOverloadedBroker.getValue(), bundle);
}
});
}
}
}
return
selectedBundlesCache;
} | 3.26 |
pulsar_ConnectionPool_getConnection_rdh | /**
* Get a connection from the pool.
* <p>
* The connection can either be created or be coming from the pool itself.
* <p>
* When specifying multiple addresses, the logicalAddress is used as a tag for the broker, while the physicalAddress
* is where the connection is actually happening.
* <p>
* These two addresses can be different when the client is forced to connect through a proxy layer. Essentially, the
* pool is using the logical address as a way to decide whether to reuse a particular connection.
*
* @param logicalAddress
* the address to use as the broker tag
* @param physicalAddress
* the real address where the TCP connection should be made
* @return a future that will produce the ClientCnx object
*/
public CompletableFuture<ClientCnx> getConnection(InetSocketAddress logicalAddress, InetSocketAddress physicalAddress, final int randomKey) {
if (maxConnectionsPerHosts == 0) {
// Disable pooling
return createConnection(logicalAddress, physicalAddress, -1);
}
final ConcurrentMap<Integer, CompletableFuture<ClientCnx>> innerPool = pool.computeIfAbsent(logicalAddress, a -> new ConcurrentHashMap<>());
CompletableFuture<ClientCnx> completableFuture = innerPool.computeIfAbsent(randomKey, k -> createConnection(logicalAddress, physicalAddress, randomKey));
if
(completableFuture.isCompletedExceptionally()) {
// we cannot cache a failed connection, so we remove it from the pool
// there is a race condition in which
// cleanupConnection is called before caching this result
// and so the clean up fails
cleanupConnection(logicalAddress, randomKey, completableFuture);
return completableFuture;
}
return completableFuture.thenCompose(clientCnx -> {
// If connection already release, create a new one.
if (clientCnx.getIdleState().isReleased()) {cleanupConnection(logicalAddress, randomKey, completableFuture);
return innerPool.computeIfAbsent(randomKey, k -> createConnection(logicalAddress, physicalAddress, randomKey));
}
// Try use exists connection.
if (clientCnx.getIdleState().tryMarkUsingAndClearIdleTime()) {
return CompletableFuture.completedFuture(clientCnx);
} else {
// If connection already release, create a new one.
cleanupConnection(logicalAddress, randomKey, completableFuture);
return innerPool.computeIfAbsent(randomKey, k -> createConnection(logicalAddress, physicalAddress, randomKey));
}
});
} | 3.26 |
pulsar_ConnectionPool_createConnection_rdh | /**
* Resolve DNS asynchronously and attempt to connect to any IP address returned by DNS server.
*/
private CompletableFuture<Channel> createConnection(InetSocketAddress logicalAddress, InetSocketAddress unresolvedPhysicalAddress) {
CompletableFuture<List<InetSocketAddress>> resolvedAddress;
try {
if (isSniProxy) {
URI
proxyURI = new URI(clientConfig.getProxyServiceUrl());
resolvedAddress = resolveName(InetSocketAddress.createUnresolved(proxyURI.getHost(), proxyURI.getPort()));
} else {
resolvedAddress = resolveName(unresolvedPhysicalAddress);
}
return resolvedAddress.thenCompose(inetAddresses -> connectToResolvedAddresses(logicalAddress, unresolvedPhysicalAddress, inetAddresses.iterator(), isSniProxy ? unresolvedPhysicalAddress : null));
} catch (URISyntaxException e) {
log.error("Invalid Proxy url {}", clientConfig.getProxyServiceUrl(), e);
return FutureUtil.failedFuture(new InvalidServiceURL("Invalid url " + clientConfig.getProxyServiceUrl(), e));
}
} | 3.26 |
pulsar_ConnectionPool_connectToAddress_rdh | /**
* Attempt to establish a TCP connection to an already resolved single IP address.
*/
private CompletableFuture<Channel> connectToAddress(InetSocketAddress logicalAddress,
InetSocketAddress physicalAddress, InetSocketAddress unresolvedPhysicalAddress, InetSocketAddress sniHost) {
if (clientConfig.isUseTls()) {
return toCompletableFuture(bootstrap.register()).thenCompose(channel -> channelInitializerHandler.initTls(channel, sniHost != null ? sniHost : physicalAddress)).thenCompose(channelInitializerHandler::initSocks5IfConfig).thenCompose(ch -> channelInitializerHandler.initializeClientCnx(ch, logicalAddress, unresolvedPhysicalAddress)).thenCompose(channel -> toCompletableFuture(channel.connect(physicalAddress)));
} else {
return toCompletableFuture(bootstrap.register()).thenCompose(channelInitializerHandler::initSocks5IfConfig).thenCompose(ch -> channelInitializerHandler.initializeClientCnx(ch, logicalAddress, unresolvedPhysicalAddress)).thenCompose(channel -> toCompletableFuture(channel.connect(physicalAddress)));
}
} | 3.26 |
pulsar_AbstractSchema_m0_rdh | /**
* Decode a byteBuf into an object using a given version.
*
* @param byteBuf
* the byte array to decode
* @param schemaVersion
* the schema version to decode the object. null indicates using latest version.
* @return the deserialized object
*/
public T m0(ByteBuf byteBuf, byte[] schemaVersion) {
// ignore version by default (most of the primitive schema implementations ignore schema version)
return decode(byteBuf);
} | 3.26 |
pulsar_AbstractSchema_atSchemaVersion_rdh | /**
* Return an instance of this schema at the given version.
*
* @param schemaVersion
* the version
* @return the schema at that specific version
* @throws SchemaSerializationException
* in case of unknown schema version
* @throws NullPointerException
* in case of null schemaVersion and supportSchemaVersioning is true
*/
public Schema<?> atSchemaVersion(byte[] schemaVersion) throws SchemaSerializationException {
if (!supportSchemaVersioning()) {
return this;}
Objects.requireNonNull(schemaVersion);
throw new SchemaSerializationException("Not implemented for " + this.getClass());
} | 3.26 |
pulsar_AbstractSchema_validate_rdh | /**
* Check if the message read able length length is a valid object for this schema.
*
* <p>The implementation can choose what its most efficient approach to validate the schema.
* If the implementation doesn't provide it, it will attempt to use {@link #decode(ByteBuf)}
* to see if this schema can decode this message or not as a validation mechanism to verify
* the bytes.
*
* @param byteBuf
* the messages to verify
* @return true if it is a valid message
* @throws SchemaSerializationException
* if it is not a valid message
*/
void validate(ByteBuf byteBuf) {
throw new SchemaSerializationException("This method is not supported");
} | 3.26 |
pulsar_AuthenticationProviderOpenID_validateAllowedAudiences_rdh | /**
* Validate the configured allow list of allowedAudiences. The allowedAudiences must be set because
* JWT must have an audience claim.
* See https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation.
*
* @param allowedAudiences
* @return the validated audiences
*/
String[] validateAllowedAudiences(Set<String> allowedAudiences)
{
if ((allowedAudiences == null) ||
allowedAudiences.isEmpty()) {
throw new IllegalArgumentException("Missing configured value for: " + ALLOWED_AUDIENCES);
}
return allowedAudiences.toArray(new String[0]);
} | 3.26 |
pulsar_AuthenticationProviderOpenID_verifyJWT_rdh | /**
* Build and return a validator for the parameters.
*
* @param publicKey
* - the public key to use when configuring the validator
* @param publicKeyAlg
* - the algorithm for the parameterized public key
* @param jwt
* - jwt to be verified and returned (only if verified)
* @return a validator to use for validating a JWT associated with the parameterized public key.
* @throws AuthenticationException
* if the Public Key's algorithm is not supported or if the algorithm param does not
* match the Public Key's actual algorithm.
*/
DecodedJWT verifyJWT(PublicKey publicKey, String publicKeyAlg, DecodedJWT jwt) throws AuthenticationException {
if (publicKeyAlg == null) {
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ALGORITHM);
throw new AuthenticationException("PublicKey algorithm cannot be null");
}
Algorithm alg;
try {
switch (publicKeyAlg) {
case ALG_RS256 :alg = Algorithm.RSA256(((RSAPublicKey) (publicKey)), null);
break;
case ALG_RS384 :
alg = Algorithm.RSA384(((RSAPublicKey) (publicKey)), null);
break;
case ALG_RS512 : alg =
Algorithm.RSA512(((RSAPublicKey) (publicKey)), null);
break;
case ALG_ES256 :
alg = Algorithm.ECDSA256(((ECPublicKey) (publicKey)), null);
break;case ALG_ES384 :
alg = Algorithm.ECDSA384(((ECPublicKey) (publicKey)), null);
break;
case ALG_ES512 :
alg = Algorithm.ECDSA512(((ECPublicKey) (publicKey)), null);
break;
default :
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ALGORITHM);
throw new AuthenticationException("Unsupported algorithm: " + publicKeyAlg);}
} catch (ClassCastException e) {
incrementFailureMetric(AuthenticationExceptionCode.ALGORITHM_MISMATCH);
throw new AuthenticationException(("Expected PublicKey alg [" + publicKeyAlg) + "] does match actual alg.");
}
// We verify issuer when retrieving the PublicKey, so it is not verified here.
// The claim presence requirements are based on https://openid.net/specs/openid-connect-basic-1_0.html#IDToken
Verification
verifierBuilder = JWT.require(alg).acceptLeeway(acceptedTimeLeewaySeconds).withAnyOfAudience(allowedAudiences).withClaimPresence(RegisteredClaims.ISSUED_AT).withClaimPresence(RegisteredClaims.EXPIRES_AT).withClaimPresence(RegisteredClaims.NOT_BEFORE).withClaimPresence(RegisteredClaims.SUBJECT);
if (isRoleClaimNotSubject) {
verifierBuilder = verifierBuilder.withClaimPresence(roleClaim);
}
JWTVerifier verifier = verifierBuilder.build();
try {
return verifier.verify(jwt);
} catch (TokenExpiredException e) {
incrementFailureMetric(AuthenticationExceptionCode.EXPIRED_JWT);
throw new AuthenticationException("JWT expired: " + e.getMessage());
} catch (SignatureVerificationException e) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_VERIFYING_JWT_SIGNATURE);
throw new AuthenticationException("JWT signature verification exception: " + e.getMessage());
} catch (InvalidClaimException e) {
incrementFailureMetric(AuthenticationExceptionCode.INVALID_JWT_CLAIM);
throw new AuthenticationException("JWT contains invalid claim: " + e.getMessage());
} catch (AlgorithmMismatchException e) {
incrementFailureMetric(AuthenticationExceptionCode.ALGORITHM_MISMATCH);
throw new AuthenticationException("JWT algorithm does not match Public Key algorithm: "
+ e.getMessage());
} catch (JWTDecodeException e) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_DECODING_JWT);
throw new AuthenticationException("Error while decoding JWT: " + e.getMessage());
} catch (JWTVerificationException | IllegalArgumentException e) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_VERIFYING_JWT);
throw new AuthenticationException("JWT verification failed: " + e.getMessage());
}
} | 3.26 |
pulsar_AuthenticationProviderOpenID_getRole_rdh | /**
* Get the role from a JWT at the configured role claim field.
* NOTE: does not do any verification of the JWT
*
* @param jwt
* - token to get the role from
* @return the role, or null, if it is not set on the JWT
*/
String getRole(DecodedJWT jwt) {
try {
Claim roleClaim = jwt.getClaim(this.roleClaim);
if (roleClaim.isNull()) {
// The claim was not present in the JWT
return null;
}
String role = roleClaim.asString();
if (role != null) {
// The role is non null only if the JSON node is a text field
return role;
}
List<String> roles = jwt.getClaim(this.roleClaim).asList(String.class);
if ((roles == null) || (roles.size() == 0)) {
return null;
} else if (roles.size() == 1) {
return roles.get(0);} else {
log.debug("JWT for subject [{}] has multiple roles; using the first one.", jwt.getSubject());
return roles.get(0);
}
} catch (JWTDecodeException e) {
log.error("Exception while retrieving role from JWT", e);
return null;
}
} | 3.26 |
pulsar_AuthenticationProviderOpenID_verifyIssuerAndGetJwk_rdh | /**
* Verify the JWT's issuer (iss) claim is one of the allowed issuers and then retrieve the JWK from the issuer. If
* not, see {@link FallbackDiscoveryMode} for the fallback behavior.
*
* @param jwt
* - the token to use to discover the issuer's JWKS URI, which is then used to retrieve the issuer's
* current public keys.
* @return a JWK that can be used to verify the JWT's signature
*/
private CompletableFuture<Jwk> verifyIssuerAndGetJwk(DecodedJWT jwt) {
if (jwt.getIssuer() == null) {
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ISSUER);
return CompletableFuture.failedFuture(new AuthenticationException("Issuer cannot be null"));
} else if (this.issuers.contains(jwt.getIssuer())) {
// Retrieve the metadata: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
return openIDProviderMetadataCache.getOpenIDProviderMetadataForIssuer(jwt.getIssuer()).thenCompose(metadata
-> jwksCache.getJwk(metadata.getJwksUri(), jwt.getKeyId()));
} else if (fallbackDiscoveryMode == FallbackDiscoveryMode.KUBERNETES_DISCOVER_TRUSTED_ISSUER) {
return openIDProviderMetadataCache.getOpenIDProviderMetadataForKubernetesApiServer(jwt.getIssuer()).thenCompose(metadata -> openIDProviderMetadataCache.getOpenIDProviderMetadataForIssuer(metadata.getIssuer())).thenCompose(metadata -> jwksCache.getJwk(metadata.getJwksUri(), jwt.getKeyId()));
} else if (fallbackDiscoveryMode == FallbackDiscoveryMode.KUBERNETES_DISCOVER_PUBLIC_KEYS) {
return openIDProviderMetadataCache.getOpenIDProviderMetadataForKubernetesApiServer(jwt.getIssuer()).thenCompose(__ -> jwksCache.getJwkFromKubernetesApiServer(jwt.getKeyId()));
} else {
incrementFailureMetric(AuthenticationExceptionCode.UNSUPPORTED_ISSUER);
return CompletableFuture.failedFuture(new AuthenticationException("Issuer not allowed: " + jwt.getIssuer()));
}
} | 3.26 |
pulsar_AuthenticationProviderOpenID_authenticateTokenAsync_rdh | /**
* Authenticate the parameterized {@link AuthenticationDataSource} and return the decoded JWT.
*
* @param authData
* - the authData containing the token.
* @return a completed future with the decoded JWT, if the JWT is authenticated. Otherwise, a failed future.
*/ CompletableFuture<DecodedJWT> authenticateTokenAsync(AuthenticationDataSource authData) {
String token;
try {
token = AuthenticationProviderToken.getToken(authData);
} catch (AuthenticationException e) {incrementFailureMetric(AuthenticationExceptionCode.ERROR_DECODING_JWT);
return CompletableFuture.failedFuture(e);
}
return authenticateToken(token).whenComplete((jwt, e) -> {
if (jwt != null) {
AuthenticationMetrics.authenticateSuccess(getClass().getSimpleName(), getAuthMethodName());
}// Failure metrics are incremented within methods above
});} | 3.26 |
pulsar_AuthenticationProviderOpenID_decodeJWT_rdh | /**
* Convert a JWT string into a {@link DecodedJWT}
* The benefit of using this method is that it utilizes the already instantiated {@link JWT} parser.
* WARNING: this method does not verify the authenticity of the token. It only decodes it.
*
* @param token
* - string JWT to be decoded
* @return a decoded JWT
* @throws AuthenticationException
* if the token string is null or if any part of the token contains
* an invalid jwt or JSON format of each of the jwt parts.
*/
DecodedJWT decodeJWT(String token) throws AuthenticationException {
if (token == null) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_DECODING_JWT);
throw new AuthenticationException("Invalid token: cannot be null");
}
try {
return jwtLibrary.decodeJwt(token);
} catch (JWTDecodeException e) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_DECODING_JWT);
throw new AuthenticationException("Unable to decode JWT: "
+ e.getMessage());
}
} | 3.26 |
pulsar_AuthenticationProviderOpenID_authenticateAsync_rdh | /**
* Authenticate the parameterized {@link AuthenticationDataSource} by verifying the issuer is an allowed issuer,
* then retrieving the JWKS URI from the issuer, then retrieving the Public key from the JWKS URI, and finally
* verifying the JWT signature and claims.
*
* @param authData
* - the authData passed by the Pulsar Broker containing the token.
* @return the role, if the JWT is authenticated, otherwise a failed future.
*/@Override
public CompletableFuture<String> authenticateAsync(AuthenticationDataSource authData) {
return authenticateTokenAsync(authData).thenApply(this::getRole);
} | 3.26 |
pulsar_AuthenticationProviderOpenID_validateIssuers_rdh | /**
* Validate the configured allow list of allowedIssuers. The allowedIssuers set must be nonempty in order for
* the plugin to authenticate any token. Thus, it fails initialization if the configuration is
* missing. Each issuer URL should use the HTTPS scheme. The plugin fails initialization if any
* issuer url is insecure, unless requireHttps is false.
*
* @param allowedIssuers
* - issuers to validate
* @param requireHttps
* - whether to require https for issuers.
* @param allowEmptyIssuers
* - whether to allow empty issuers. This setting only makes sense when kubernetes is used
* as a fallback issuer.
* @return the validated issuers
* @throws IllegalArgumentException
* if the allowedIssuers is empty, or contains insecure issuers when required
*/
private Set<String> validateIssuers(Set<String> allowedIssuers, boolean requireHttps, boolean allowEmptyIssuers) {
if ((allowedIssuers == null) || (allowedIssuers.isEmpty() && (!allowEmptyIssuers))) {
throw new IllegalArgumentException("Missing configured value for: " + ALLOWED_TOKEN_ISSUERS);
}
for (String issuer : allowedIssuers) {
if (!issuer.toLowerCase().startsWith("https://")) {
log.warn("Allowed issuer is not using https scheme: {}", issuer);
if (requireHttps) {
throw new IllegalArgumentException("Issuer URL does not use https, but must: " + issuer);
}
}
}
return allowedIssuers;
} | 3.26 |
pulsar_AuthenticationProviderOpenID_authenticateToken_rdh | /**
* Authenticate the parameterized JWT.
*
* @param token
* - a nonnull JWT to authenticate
* @return a fully authenticated JWT, or AuthenticationException if the JWT is proven to be invalid in any way
*/
private CompletableFuture<DecodedJWT> authenticateToken(String token) {
if (token == null) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_DECODING_JWT);
return CompletableFuture.failedFuture(new AuthenticationException("JWT cannot be null"));
}
final DecodedJWT jwt;
try {
jwt = decodeJWT(token);
} catch (AuthenticationException e) {
incrementFailureMetric(AuthenticationExceptionCode.ERROR_DECODING_JWT);
return CompletableFuture.failedFuture(e);
}
return verifyIssuerAndGetJwk(jwt).thenCompose(jwk
-> {
try {
if (!jwt.getAlgorithm().equals(jwk.getAlgorithm())) {
incrementFailureMetric(AuthenticationExceptionCode.ALGORITHM_MISMATCH);
return CompletableFuture.failedFuture(new AuthenticationException(((("JWK's alg [" + jwk.getAlgorithm()) + "] does not match JWT's alg [") + jwt.getAlgorithm()) + "]"));
}
// Verify the JWT signature
// Throws exception if any verification check fails
return CompletableFuture.completedFuture(verifyJWT(jwk.getPublicKey(), jwt.getAlgorithm(), jwt));
} catch (InvalidPublicKeyException e) {
incrementFailureMetric(AuthenticationExceptionCode.INVALID_PUBLIC_KEY);
return CompletableFuture.failedFuture(new AuthenticationException("Invalid public key: " + e.getMessage()));
} catch (AuthenticationException e) {
return CompletableFuture.failedFuture(e);
}
});
} | 3.26 |
pulsar_ManagedLedgerInterceptor_processPayloadBeforeEntryCache_rdh | /**
* Intercept after entry is read from ledger, before it gets cached.
*
* @param dataReadFromLedger
* data from ledger
* @return handle to the processor
*/
default PayloadProcessorHandle processPayloadBeforeEntryCache(ByteBuf dataReadFromLedger) {
return null;
} | 3.26 |
pulsar_ManagedLedgerInterceptor_processPayloadBeforeLedgerWrite_rdh | /**
* Intercept before payload gets written to ledger.
*
* @param ledgerWriteOp
* OpAddEntry used to trigger ledger write.
* @param dataToBeStoredInLedger
* data to be stored in ledger
* @return handle to the processor
*/
default PayloadProcessorHandle processPayloadBeforeLedgerWrite(OpAddEntry ledgerWriteOp, ByteBuf dataToBeStoredInLedger)
{
return null;
} | 3.26 |
pulsar_ManagedLedgerInterceptor_afterFailedAddEntry_rdh | /**
* Intercept When add entry failed.
*
* @param numberOfMessages
*/
default void afterFailedAddEntry(int numberOfMessages) {
} | 3.26 |
pulsar_SSLContextValidatorEngine_validate_rdh | /**
* Validates TLS handshake up to TLSv1.2.
* TLSv1.3 has a differences in TLS handshake as described in https://stackoverflow.com/a/62465859
*/
public static void validate(SSLEngineProvider clientSslEngineSupplier, SSLEngineProvider serverSslEngineSupplier) throws SSLException {
SSLContextValidatorEngine clientEngine = new SSLContextValidatorEngine(clientSslEngineSupplier);
if (Arrays.stream(clientEngine.sslEngine.getEnabledProtocols()).anyMatch(s -> s.equals("TLSv1.3"))) {
throw new IllegalStateException("This validator doesn't support TLSv1.3");
}
SSLContextValidatorEngine v1 = new SSLContextValidatorEngine(serverSslEngineSupplier);
try {
clientEngine.beginHandshake();v1.beginHandshake();
while ((!v1.complete()) || (!clientEngine.complete())) {
clientEngine.handshake(v1);
v1.handshake(clientEngine);
}
} finally {
clientEngine.close();
v1.close();
}} | 3.26 |
pulsar_SSLContextValidatorEngine_ensureCapacity_rdh | /**
* Check if the given ByteBuffer capacity.
*
* @param existingBuffer
* ByteBuffer capacity to check
* @param newLength
* new length for the ByteBuffer.
* returns ByteBuffer
*/
public static ByteBuffer ensureCapacity(ByteBuffer existingBuffer, int newLength) {
if (newLength > existingBuffer.capacity()) {
ByteBuffer newBuffer = ByteBuffer.allocate(newLength);
existingBuffer.flip();
newBuffer.put(existingBuffer);
return newBuffer;
}
return existingBuffer;
} | 3.26 |
pulsar_SinkSchemaInfoProvider_addSchemaIfNeeded_rdh | /**
* Creates a new schema version with the info of the provided schema if the hash of the schema is a new one.
*
* @param schema
* schema for which we create a version
* @return the version of the schema
*/
public SchemaVersion addSchemaIfNeeded(Schema<?> schema) {
SchemaHash schemaHash = SchemaHash.of(schema);
return schemaVersions.computeIfAbsent(schemaHash, s -> createNewSchemaInfo(schema.getSchemaInfo()));
} | 3.26 |
pulsar_NonPersistentTopicStatsImpl_add_rdh | // if the stats are added for the 1st time, we will need to make a copy of these stats and add it to the current
// stats. This stat addition is not thread-safe.
public NonPersistentTopicStatsImpl add(NonPersistentTopicStats ts) {
NonPersistentTopicStatsImpl stats = ((NonPersistentTopicStatsImpl) (ts));
Objects.requireNonNull(stats);
super.add(stats);
this.msgDropRate += stats.msgDropRate;
List<NonPersistentPublisherStats> publisherStats = stats.getNonPersistentPublishers();
for (int index = 0; index < publisherStats.size(); index++) {
NonPersistentPublisherStats v3 = publisherStats.get(index);
if (v3.isSupportsPartialProducer() && (v3.getProducerName() != null)) {
((NonPersistentPublisherStatsImpl) (this.nonPersistentPublishersMap.computeIfAbsent(v3.getProducerName(), key -> {
final NonPersistentPublisherStatsImpl newStats = new NonPersistentPublisherStatsImpl();
newStats.setSupportsPartialProducer(true);
newStats.setProducerName(v3.getProducerName());
return newStats;
}))).add(((NonPersistentPublisherStatsImpl) (v3)));
} else {
// Add a non-persistent publisher stat entry to this.nonPersistentPublishers
// if this.nonPersistentPublishers.size() is smaller than
// the input stats.nonPersistentPublishers.size().
// Here, index == this.nonPersistentPublishers.size() means
// this.nonPersistentPublishers.size() is smaller than the input stats.nonPersistentPublishers.size()
if (index == this.nonPersistentPublishers.size()) {
NonPersistentPublisherStatsImpl newStats = new NonPersistentPublisherStatsImpl();
newStats.setSupportsPartialProducer(false);
this.nonPersistentPublishers.add(newStats);
}
((NonPersistentPublisherStatsImpl) (this.nonPersistentPublishers.get(index))).add(((NonPersistentPublisherStatsImpl) (v3)));
}
}
for (Map.Entry<String, NonPersistentSubscriptionStats> entry : stats.getNonPersistentSubscriptions().entrySet()) {
NonPersistentSubscriptionStatsImpl subscriptionStats = ((NonPersistentSubscriptionStatsImpl) (this.getNonPersistentSubscriptions().computeIfAbsent(entry.getKey(), k -> new NonPersistentSubscriptionStatsImpl())));
subscriptionStats.add(((NonPersistentSubscriptionStatsImpl) (entry.getValue())));
}
for (Map.Entry<String, NonPersistentReplicatorStats> entry : stats.getNonPersistentReplicators().entrySet()) {
NonPersistentReplicatorStatsImpl replStats = ((NonPersistentReplicatorStatsImpl) (this.getNonPersistentReplicators().computeIfAbsent(entry.getKey(), k -> {
NonPersistentReplicatorStatsImpl r = new NonPersistentReplicatorStatsImpl();
return r;
})));
replStats.add(((NonPersistentReplicatorStatsImpl) (entry.getValue())));
}
return this;
} | 3.26 |
pulsar_WebSocketWebResource_validateUserAccess_rdh | /**
* Checks if user has super-user access or user is authorized to produce/consume on a given topic.
*
* @param topic
* @throws RestException
*/
protected void validateUserAccess(TopicName topic)
{
boolean isAuthorized = false;
try {
validateSuperUserAccess();isAuthorized = true;
} catch (Exception e) {
try {
isAuthorized = isAuthorized(topic);
} catch
(Exception ne) {
throw new RestException(ne);
}
}
if (!isAuthorized) {throw new RestException(Status.UNAUTHORIZED, "Don't have permission to access this topic");
}
} | 3.26 |
pulsar_WebSocketWebResource_isAuthorized_rdh | /**
* Checks if user is authorized to produce/consume on a given topic.
*
* @param topic
* @return * @throws Exception
*/
protected boolean isAuthorized(TopicName topic) throws Exception {
if (service().isAuthorizationEnabled()) {
return service().getAuthorizationService().canLookup(topic, clientAppId(), authData());
}
return true;
} | 3.26 |
pulsar_WebSocketWebResource_clientAppId_rdh | /**
* Gets a caller id (IP + role).
*
* @return the web service caller identification
*/
public String clientAppId() {
if (isBlank(clientId))
{
try {
String authMethodName = httpRequest.getHeader(AuthenticationFilter.PULSAR_AUTH_METHOD_NAME);
if ((authMethodName != null) && (service().getAuthenticationService().getAuthenticationProvider(authMethodName)
!= null)) {
authenticationDataSource = service().getAuthenticationService().getAuthenticationProvider(authMethodName).newHttpAuthState(httpRequest).getAuthDataSource();
clientId = service().getAuthenticationService().authenticateHttpRequest(httpRequest, authenticationDataSource);
} else {
clientId = service().getAuthenticationService().authenticateHttpRequest(httpRequest);
authenticationDataSource = new AuthenticationDataHttps(httpRequest);
}
} catch (AuthenticationException e) {
if (service().getConfig().isAuthenticationEnabled()) {throw new RestException(Status.UNAUTHORIZED, "Failed to get clientId from request");
}
}
if (isBlank(clientId) && service().getConfig().isAuthenticationEnabled()) {
throw new RestException(Status.UNAUTHORIZED, "Failed to get auth data from the request");
}
}
return clientId;
} | 3.26 |
pulsar_WebSocketWebResource_validateSuperUserAccess_rdh | /**
* Checks whether the user has Pulsar Super-User access to the system.
*
* @throws RestException
* if not authorized
*/
protected void validateSuperUserAccess() {
if (service().getConfig().isAuthenticationEnabled()) {
String appId = clientAppId();
if (log.isDebugEnabled()) {
log.debug("[{}] Check super user access: Authenticated: {} -- Role: {}", uri.getRequestUri(), clientAppId(), appId);
}
if (!service().getConfig().getSuperUserRoles().contains(appId)) {
throw new RestException(Status.UNAUTHORIZED, "This operation requires super-user access");
}
}
} | 3.26 |
pulsar_BundleData_update_rdh | /**
* Update the historical data for this bundle.
*
* @param newSample
* The bundle stats to update this data with.
*/
public void update(final NamespaceBundleStats newSample) {
shortTermData.update(newSample);
longTermData.update(newSample);
this.topics = ((int) (newSample.topics));
} | 3.26 |
pulsar_ConfigUtils_getConfigValueAsBoolean_rdh | /**
* Utility method to get a boolean from the {@link ServiceConfiguration}. If the key is present in the conf,
* return the default value. If key is present the value is not a valid boolean, the result will be false.
*
* @param conf
* - the map of configuration properties
* @param configProp
* - the property (key) to get
* @param defaultValue
* - the value to use if the property is missing from the conf
* @return a boolean
*/
static boolean getConfigValueAsBoolean(ServiceConfiguration conf, String configProp, boolean defaultValue) {
Object value = conf.getProperty(configProp);
if (value instanceof Boolean) {
log.info("Configuration for [{}] is [{}]", configProp, value);
return ((boolean) (value));
} else if (value instanceof String) {
boolean result = Boolean.parseBoolean(((String) (value)));
log.info("Configuration for [{}] is [{}]", configProp, result);
return result;} else {log.info("Configuration for [{}] is using the default value: [{}]", configProp, defaultValue);
return defaultValue;
}
} | 3.26 |
pulsar_ConfigUtils_m0_rdh | /**
* Get configured property as a string. If not configured, return null.
*
* @param conf
* - the configuration map
* @param configProp
* - the property to get
* @param defaultValue
* - the value to use if the configuration value is not set
* @return a string from the conf or the default value
*/
static String m0(ServiceConfiguration conf, String configProp, String defaultValue) throws IllegalArgumentException {
String value = getConfigValueAsStringImpl(conf, configProp);
if (value == null) {
value = defaultValue;
}
log.info("Configuration for [{}] is [{}]", configProp, value);
return value;
} | 3.26 |
pulsar_ConfigUtils_getConfigValueAsSet_rdh | /**
* Get configured property as a set. Split using a comma delimiter and remove any extra whitespace surrounding
* the commas. If not configured, return the empty set.
*
* @param conf
* - the map of configuration properties
* @param configProp
* - the property (key) to get
* @return a set of strings from the conf
*/
static Set<String> getConfigValueAsSet(ServiceConfiguration conf, String configProp) {
String value = getConfigValueAsStringImpl(conf, configProp);
if (StringUtils.isBlank(value)) {
log.info("Configuration for [{}] is the empty set.", configProp);
return Collections.emptySet();
}
Set<String> set = Arrays.stream(value.trim().split("\\s*,\\s*")).collect(Collectors.toSet());
log.info("Configuration for [{}] is [{}].", configProp, String.join(", ", set));
return set;
} | 3.26 |
pulsar_ConfigUtils_getConfigValueAsString_rdh | /**
* Get configured property as a string. If not configured, return null.
*
* @param conf
* - the configuration map
* @param configProp
* - the property to get
* @return a string from the conf or null, if the configuration property was not set
*/
static String getConfigValueAsString(ServiceConfiguration conf, String configProp) throws IllegalArgumentException {
String value = getConfigValueAsStringImpl(conf, configProp);
log.info("Configuration for [{}] is [{}]", configProp, value);
return value;
} | 3.26 |
pulsar_ClassLoaderUtils_loadJar_rdh | /**
* Helper methods wrt Classloading.
*/
@Slf4jpublic class ClassLoaderUtils {
/**
* Load a jar.
*
* @param jar
* file of jar
* @return classloader
* @throws MalformedURLException
*/
public static ClassLoader loadJar(File jar) throws MalformedURLException {
URL v0 = jar.toURI().toURL();
return AccessController.doPrivileged(((PrivilegedAction<URLClassLoader>) (() -> new URLClassLoader(new URL[]{ v0 }))));
} | 3.26 |
pulsar_ConfigValidationUtils_listFv_rdh | /**
* Returns a new NestableFieldValidator for a List where each item is validated by validator.
*
* @param validator
* used to validate each item in the list
* @param notNull
* whether or not a value of null is valid
* @return a NestableFieldValidator for a list with each item validated by a different validator.
*/
public static NestableFieldValidator listFv(final NestableFieldValidator validator, final boolean notNull) {return new NestableFieldValidator() {
@Override
public void validateField(String pd, String name, Object field) throws IllegalArgumentException {
if (field == null) {
if (notNull) {
throw new IllegalArgumentException(("Field " + name) + " must not be null");
} else {
return;
} }
if (field instanceof Iterable) {
for (Object e : ((Iterable) (field))) {
validator.validateField(pd + "Each element of the list ", name, e);}
return;
}
throw new IllegalArgumentException((("Field " + name) + " must be an Iterable but was a ") + field.getClass());
}
};
} | 3.26 |
pulsar_ConfigValidationUtils_fv_rdh | /**
* Returns a new NestableFieldValidator for a given class.
*
* @param cls
* the Class the field should be a type of
* @param notNull
* whether or not a value of null is valid
* @return a NestableFieldValidator for that class
*/
public static NestableFieldValidator fv(final Class cls, final boolean notNull) {
return new NestableFieldValidator() {
@Override
public void validateField(String pd, String name, Object
field) throws IllegalArgumentException {
if (field == null) {
if (notNull) {
throw new IllegalArgumentException(("Field " + name) + " must not be null");
} else {
return;
}
}
if (!cls.isInstance(field)) {
throw new IllegalArgumentException((((((pd + name) + " must be a ") + cls.getName()) + ". (") + field) + ")");}
}
};
} | 3.26 |
pulsar_ConfigValidationUtils_mapFv_rdh | /**
* Returns a new NestableFieldValidator for a Map.
*
* @param key
* a validator for the keys in the map
* @param val
* a validator for the values in the map
* @param notNull
* whether or not a value of null is valid
* @return a NestableFieldValidator for a Map
*/
public static NestableFieldValidator mapFv(final NestableFieldValidator key, final NestableFieldValidator val, final boolean notNull) {return new NestableFieldValidator() {
@SuppressWarnings("unchecked")
@Override
public void validateField(String pd, String name, Object field) throws IllegalArgumentException {
if (field == null) {
if (notNull) {
throw new IllegalArgumentException(("Field " + name) + " must not be null");
} else {
return;
}}
if (field instanceof Map) {
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) (field)).entrySet()) {
key.validateField("Each key of the map ", name, entry.getKey());
val.validateField("Each value in the map ",
name, entry.getValue());
}
return;
}
throw new IllegalArgumentException(("Field " + name) + " must be a Map");
}
};
} | 3.26 |
pulsar_ObjectMapperFactory_clearCaches_rdh | /**
* Clears the caches tied to the ObjectMapper instances and replaces the singleton ObjectMapper instance.
*
* This can be used in tests to ensure that classloaders and class references don't leak across tests.
*/public static void clearCaches() {
clearTypeFactoryCache(getMapper().getObjectMapper());
clearTypeFactoryCache(getYamlMapper().getObjectMapper());
clearTypeFactoryCache(getMapperWithIncludeAlways().getObjectMapper());
replaceSingletonInstances();
} | 3.26 |
pulsar_ObjectMapperFactory_m1_rdh | /**
* This method is deprecated. Use {@link #getYamlMapper()} and {@link MapperReference#getObjectMapper()}
*/
@Deprecated
public static ObjectMapper m1() {
return getYamlMapper().getObjectMapper();} | 3.26 |
pulsar_ObjectMapperFactory_getThreadLocal_rdh | /**
* This method is deprecated. Use {@link #getMapper()} and {@link MapperReference#getObjectMapper()}
*/
@Deprecated
public static ObjectMapper getThreadLocal() {
return getMapper().getObjectMapper();
} | 3.26 |
pulsar_PrecisePublishLimiter_tryReleaseConnectionThrottle_rdh | // If all rate limiters are not exceeded, re-enable auto read from socket.
private void tryReleaseConnectionThrottle() {
RateLimiter currentTopicPublishRateLimiterOnMessage = topicPublishRateLimiterOnMessage;
RateLimiter currentTopicPublishRateLimiterOnByte = topicPublishRateLimiterOnByte;
if (((currentTopicPublishRateLimiterOnMessage != null) && (currentTopicPublishRateLimiterOnMessage.getAvailablePermits() <= 0)) || ((currentTopicPublishRateLimiterOnByte != null)
&& (currentTopicPublishRateLimiterOnByte.getAvailablePermits() <= 0))) {
return;
}
this.f0.apply();
} | 3.26 |
pulsar_ResourceGroupService_updateStatsWithDiff_rdh | // Find the difference between the last time stats were updated for this topic, and the current
// time. If the difference is positive, update the stats.
private void updateStatsWithDiff(String topicName, String tenantString, String nsString, long accByteCount, long accMesgCount, ResourceGroupMonitoringClass monClass) {
ConcurrentHashMap<String, BytesAndMessagesCount> hm;
switch (monClass) {default :
log.error("updateStatsWithDiff: Unknown monitoring class={}; ignoring", monClass);
return;
case Publish :
hm = this.topicProduceStats;
break;
case
Dispatch :
hm = this.topicConsumeStats;
break;
}
BytesAndMessagesCount bmDiff = new BytesAndMessagesCount();
BytesAndMessagesCount bmOldCount;
BytesAndMessagesCount bmNewCount = new BytesAndMessagesCount();
bmNewCount.bytes = accByteCount;
bmNewCount.messages = accMesgCount;
bmOldCount = hm.get(topicName);
if (bmOldCount == null) {
bmDiff.bytes = bmNewCount.bytes;
bmDiff.messages = bmNewCount.messages;
} else {bmDiff.bytes
= bmNewCount.bytes - bmOldCount.bytes;
bmDiff.messages = bmNewCount.messages
- bmOldCount.messages;
}
if ((bmDiff.bytes <= 0) || (bmDiff.messages <= 0)) {
return;
}
try {
boolean statsUpdated = this.incrementUsage(tenantString, nsString, monClass,
bmDiff);
if (log.isDebugEnabled()) {
log.debug("updateStatsWithDiff for topic={}: monclass={} statsUpdated={} for tenant={}, namespace={}; " + "by {} bytes, {} mesgs", topicName, monClass, statsUpdated, tenantString, nsString, bmDiff.bytes, bmDiff.messages);
}
hm.put(topicName, bmNewCount);
} catch (Throwable t) {
log.error("updateStatsWithDiff: got ex={} while aggregating for {} side", t.getMessage(), monClass);
}
} | 3.26 |
pulsar_ResourceGroupService_getNumResourceGroups_rdh | /**
* Get the current number of RGs. For testing.
*/
protected long getNumResourceGroups() {
return
resourceGroupsMap.mappingCount();
} | 3.26 |
pulsar_ResourceGroupService_getRgNamespaceRegistersCount_rdh | // Visibility for testing.
protected static double getRgNamespaceRegistersCount(String rgName) {
return rgNamespaceRegisters.labels(rgName).get();
} | 3.26 |
pulsar_ResourceGroupService_getNamespaceResourceGroup_rdh | /**
* Return the resource group associated with a namespace.
*
* @param namespaceName
* @throws if
* the RG does not exist, or if the NS already references the RG.
*/
public ResourceGroup getNamespaceResourceGroup(NamespaceName namespaceName) {
return this.namespaceToRGsMap.get(namespaceName);
} | 3.26 |
pulsar_ResourceGroupService_getRgQuotaMessageCount_rdh | // Visibility for testing.
protected static double getRgQuotaMessageCount(String rgName, String monClassName) {
return rgCalculatedQuotaMessages.labels(rgName, monClassName).get();
} | 3.26 |
pulsar_ResourceGroupService_registerNameSpace_rdh | /**
* Registers a namespace as a user of a resource group.
*
* @param resourceGroupName
* @param fqNamespaceName
* (i.e., in "tenant/Namespace" format)
* @throws if
* the RG does not exist, or if the NS already references the RG.
*/public void registerNameSpace(String resourceGroupName, NamespaceName fqNamespaceName) throws PulsarAdminException {
ResourceGroup rg = checkResourceGroupExists(resourceGroupName);
// Check that the NS-name doesn't already have a RG association.
// [If it does, that should be unregistered before putting a different association.]
ResourceGroup oldRG = this.namespaceToRGsMap.get(fqNamespaceName);
if (oldRG != null) {
String errMesg = (("Namespace " + fqNamespaceName) + " already references a resource group: ") + oldRG.getID();
throw new PulsarAdminException(errMesg);
}
ResourceGroupOpStatus status = rg.registerUsage(fqNamespaceName.toString(), ResourceGroupRefTypes.Namespaces, true, this.resourceUsageTransportManagerMgr);
if (status == ResourceGroupOpStatus.Exists) {
String errMesg = String.format("Namespace %s already references the target resource group %s", fqNamespaceName, resourceGroupName); throw new PulsarAdminException(errMesg);
}
// Associate this NS-name with the RG.
this.namespaceToRGsMap.put(fqNamespaceName, rg);
rgNamespaceRegisters.labels(resourceGroupName).inc();
} | 3.26 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.