use of com.unboundid.ldap.sdk.experimental.DraftBeheraLDAPPasswordPolicy10RequestControl in project ldapsdk by pingidentity.
the class AuthRate method doToolProcessing.
/**
* Performs the actual processing for this tool. In this case, it gets a
* connection to the directory server and uses it to perform the requested
* searches.
*
* @return The result code for the processing that was performed.
*/
@Override()
@NotNull()
public ResultCode doToolProcessing() {
// variable rate data file and return.
if (sampleRateFile.isPresent()) {
try {
RateAdjustor.writeSampleVariableRateFile(sampleRateFile.getValue());
return ResultCode.SUCCESS;
} catch (final Exception e) {
Debug.debugException(e);
err("An error occurred while trying to write sample variable data " + "rate file '", sampleRateFile.getValue().getAbsolutePath(), "': ", StaticUtils.getExceptionMessage(e));
return ResultCode.LOCAL_ERROR;
}
}
// Determine the random seed to use.
final Long seed;
if (randomSeed.isPresent()) {
seed = Long.valueOf(randomSeed.getValue());
} else {
seed = null;
}
// Create value patterns for the base DN and filter.
final ValuePattern dnPattern;
try {
dnPattern = new ValuePattern(baseDN.getValue(), seed);
} catch (final ParseException pe) {
Debug.debugException(pe);
err("Unable to parse the base DN value pattern: ", pe.getMessage());
return ResultCode.PARAM_ERROR;
}
final ValuePattern filterPattern;
if (filter.isPresent()) {
try {
filterPattern = new ValuePattern(filter.getValue(), seed);
} catch (final ParseException pe) {
Debug.debugException(pe);
err("Unable to parse the filter pattern: ", pe.getMessage());
return ResultCode.PARAM_ERROR;
}
} else {
filterPattern = null;
}
// Get the attributes to return.
final String[] attrs;
if (attributes.isPresent()) {
final List<String> attrList = attributes.getValues();
attrs = new String[attrList.size()];
attrList.toArray(attrs);
} else {
attrs = StaticUtils.NO_STRINGS;
}
// If the --ratePerSecond option was specified, then limit the rate
// accordingly.
FixedRateBarrier fixedRateBarrier = null;
if (ratePerSecond.isPresent() || variableRateData.isPresent()) {
// We might not have a rate per second if --variableRateData is specified.
// The rate typically doesn't matter except when we have warm-up
// intervals. In this case, we'll run at the max rate.
final int intervalSeconds = collectionInterval.getValue();
final int ratePerInterval = (ratePerSecond.getValue() == null) ? Integer.MAX_VALUE : ratePerSecond.getValue() * intervalSeconds;
fixedRateBarrier = new FixedRateBarrier(1000L * intervalSeconds, ratePerInterval);
}
// If --variableRateData was specified, then initialize a RateAdjustor.
RateAdjustor rateAdjustor = null;
if (variableRateData.isPresent()) {
try {
rateAdjustor = RateAdjustor.newInstance(fixedRateBarrier, ratePerSecond.getValue(), variableRateData.getValue());
} catch (final IOException | IllegalArgumentException e) {
Debug.debugException(e);
err("Initializing the variable rates failed: " + e.getMessage());
return ResultCode.PARAM_ERROR;
}
}
// Determine whether to include timestamps in the output and if so what
// format should be used for them.
final boolean includeTimestamp;
final String timeFormat;
if (timestampFormat.getValue().equalsIgnoreCase("with-date")) {
includeTimestamp = true;
timeFormat = "dd/MM/yyyy HH:mm:ss";
} else if (timestampFormat.getValue().equalsIgnoreCase("without-date")) {
includeTimestamp = true;
timeFormat = "HH:mm:ss";
} else {
includeTimestamp = false;
timeFormat = null;
}
// Get the controls to include in bind requests.
final ArrayList<Control> bindControls = new ArrayList<>(5);
if (authorizationIdentityRequestControl.isPresent()) {
bindControls.add(new AuthorizationIdentityRequestControl());
}
if (passwordPolicyRequestControl.isPresent()) {
bindControls.add(new DraftBeheraLDAPPasswordPolicy10RequestControl());
}
bindControls.addAll(bindControl.getValues());
// Determine whether any warm-up intervals should be run.
final long totalIntervals;
final boolean warmUp;
int remainingWarmUpIntervals = warmUpIntervals.getValue();
if (remainingWarmUpIntervals > 0) {
warmUp = true;
totalIntervals = 0L + numIntervals.getValue() + remainingWarmUpIntervals;
} else {
warmUp = true;
totalIntervals = 0L + numIntervals.getValue();
}
// Create the table that will be used to format the output.
final OutputFormat outputFormat;
if (csvFormat.isPresent()) {
outputFormat = OutputFormat.CSV;
} else {
outputFormat = OutputFormat.COLUMNS;
}
final ColumnFormatter formatter = new ColumnFormatter(includeTimestamp, timeFormat, outputFormat, " ", new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent", "Auths/Sec"), new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent", "Avg Dur ms"), new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent", "Errors/Sec"), new FormattableColumn(12, HorizontalAlignment.RIGHT, "Overall", "Auths/Sec"), new FormattableColumn(12, HorizontalAlignment.RIGHT, "Overall", "Avg Dur ms"));
// Create values to use for statistics collection.
final AtomicLong authCounter = new AtomicLong(0L);
final AtomicLong errorCounter = new AtomicLong(0L);
final AtomicLong authDurations = new AtomicLong(0L);
final ResultCodeCounter rcCounter = new ResultCodeCounter();
// Determine the length of each interval in milliseconds.
final long intervalMillis = 1000L * collectionInterval.getValue();
// Create the threads to use for the searches.
final CyclicBarrier barrier = new CyclicBarrier(numThreads.getValue() + 1);
final AuthRateThread[] threads = new AuthRateThread[numThreads.getValue()];
for (int i = 0; i < threads.length; i++) {
final LDAPConnection searchConnection;
final LDAPConnection bindConnection;
try {
searchConnection = getConnection();
bindConnection = getConnection();
} catch (final LDAPException le) {
Debug.debugException(le);
err("Unable to connect to the directory server: ", StaticUtils.getExceptionMessage(le));
return le.getResultCode();
}
threads[i] = new AuthRateThread(this, i, searchConnection, bindConnection, dnPattern, scopeArg.getValue(), filterPattern, attrs, userPassword.getValue(), bindOnly.isPresent(), authType.getValue(), searchControl.getValues(), bindControls, runningThreads, barrier, authCounter, authDurations, errorCounter, rcCounter, fixedRateBarrier);
threads[i].start();
}
// Display the table header.
for (final String headerLine : formatter.getHeaderLines(true)) {
out(headerLine);
}
// which case, we'll start it after the warm-up is complete.
if ((rateAdjustor != null) && (remainingWarmUpIntervals <= 0)) {
rateAdjustor.start();
}
// Indicate that the threads can start running.
try {
barrier.await();
} catch (final Exception e) {
Debug.debugException(e);
}
long overallStartTime = System.nanoTime();
long nextIntervalStartTime = System.currentTimeMillis() + intervalMillis;
boolean setOverallStartTime = false;
long lastDuration = 0L;
long lastNumErrors = 0L;
long lastNumAuths = 0L;
long lastEndTime = System.nanoTime();
for (long i = 0; i < totalIntervals; i++) {
if (rateAdjustor != null) {
if (!rateAdjustor.isAlive()) {
out("All of the rates in " + variableRateData.getValue().getName() + " have been completed.");
break;
}
}
final long startTimeMillis = System.currentTimeMillis();
final long sleepTimeMillis = nextIntervalStartTime - startTimeMillis;
nextIntervalStartTime += intervalMillis;
if (sleepTimeMillis > 0) {
sleeper.sleep(sleepTimeMillis);
}
if (stopRequested.get()) {
break;
}
final long endTime = System.nanoTime();
final long intervalDuration = endTime - lastEndTime;
final long numAuths;
final long numErrors;
final long totalDuration;
if (warmUp && (remainingWarmUpIntervals > 0)) {
numAuths = authCounter.getAndSet(0L);
numErrors = errorCounter.getAndSet(0L);
totalDuration = authDurations.getAndSet(0L);
} else {
numAuths = authCounter.get();
numErrors = errorCounter.get();
totalDuration = authDurations.get();
}
final long recentNumAuths = numAuths - lastNumAuths;
final long recentNumErrors = numErrors - lastNumErrors;
final long recentDuration = totalDuration - lastDuration;
final double numSeconds = intervalDuration / 1_000_000_000.0d;
final double recentAuthRate = recentNumAuths / numSeconds;
final double recentErrorRate = recentNumErrors / numSeconds;
final double recentAvgDuration;
if (recentNumAuths > 0L) {
recentAvgDuration = 1.0d * recentDuration / recentNumAuths / 1_000_000;
} else {
recentAvgDuration = 0.0d;
}
if (warmUp && (remainingWarmUpIntervals > 0)) {
out(formatter.formatRow(recentAuthRate, recentAvgDuration, recentErrorRate, "warming up", "warming up"));
remainingWarmUpIntervals--;
if (remainingWarmUpIntervals == 0) {
out("Warm-up completed. Beginning overall statistics collection.");
setOverallStartTime = true;
if (rateAdjustor != null) {
rateAdjustor.start();
}
}
} else {
if (setOverallStartTime) {
overallStartTime = lastEndTime;
setOverallStartTime = false;
}
final double numOverallSeconds = (endTime - overallStartTime) / 1_000_000_000.0d;
final double overallAuthRate = numAuths / numOverallSeconds;
final double overallAvgDuration;
if (numAuths > 0L) {
overallAvgDuration = 1.0d * totalDuration / numAuths / 1_000_000;
} else {
overallAvgDuration = 0.0d;
}
out(formatter.formatRow(recentAuthRate, recentAvgDuration, recentErrorRate, overallAuthRate, overallAvgDuration));
lastNumAuths = numAuths;
lastNumErrors = numErrors;
lastDuration = totalDuration;
}
final List<ObjectPair<ResultCode, Long>> rcCounts = rcCounter.getCounts(true);
if ((!suppressErrorsArgument.isPresent()) && (!rcCounts.isEmpty())) {
err("\tError Results:");
for (final ObjectPair<ResultCode, Long> p : rcCounts) {
err("\t", p.getFirst().getName(), ": ", p.getSecond());
}
}
lastEndTime = endTime;
}
// Shut down the RateAdjustor if we have one.
if (rateAdjustor != null) {
rateAdjustor.shutDown();
}
// Stop all of the threads.
ResultCode resultCode = ResultCode.SUCCESS;
for (final AuthRateThread t : threads) {
final ResultCode r = t.stopRunning();
if (resultCode == ResultCode.SUCCESS) {
resultCode = r;
}
}
return resultCode;
}
Aggregations