001    /*
002     * Copyright 2008-2016 UnboundID Corp.
003     * All Rights Reserved.
004     */
005    /*
006     * Copyright (C) 2008-2016 UnboundID Corp.
007     *
008     * This program is free software; you can redistribute it and/or modify
009     * it under the terms of the GNU General Public License (GPLv2 only)
010     * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
011     * as published by the Free Software Foundation.
012     *
013     * This program is distributed in the hope that it will be useful,
014     * but WITHOUT ANY WARRANTY; without even the implied warranty of
015     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016     * GNU General Public License for more details.
017     *
018     * You should have received a copy of the GNU General Public License
019     * along with this program; if not, see <http://www.gnu.org/licenses>.
020     */
021    package com.unboundid.ldap.sdk.examples;
022    
023    
024    
025    import java.io.IOException;
026    import java.io.OutputStream;
027    import java.io.Serializable;
028    import java.text.ParseException;
029    import java.util.LinkedHashMap;
030    import java.util.LinkedHashSet;
031    import java.util.List;
032    import java.util.concurrent.CyclicBarrier;
033    import java.util.concurrent.Semaphore;
034    import java.util.concurrent.atomic.AtomicBoolean;
035    import java.util.concurrent.atomic.AtomicLong;
036    
037    import com.unboundid.ldap.sdk.LDAPConnection;
038    import com.unboundid.ldap.sdk.LDAPConnectionOptions;
039    import com.unboundid.ldap.sdk.LDAPException;
040    import com.unboundid.ldap.sdk.ResultCode;
041    import com.unboundid.ldap.sdk.SearchScope;
042    import com.unboundid.ldap.sdk.Version;
043    import com.unboundid.util.ColumnFormatter;
044    import com.unboundid.util.FixedRateBarrier;
045    import com.unboundid.util.FormattableColumn;
046    import com.unboundid.util.HorizontalAlignment;
047    import com.unboundid.util.LDAPCommandLineTool;
048    import com.unboundid.util.ObjectPair;
049    import com.unboundid.util.OutputFormat;
050    import com.unboundid.util.RateAdjustor;
051    import com.unboundid.util.ResultCodeCounter;
052    import com.unboundid.util.ThreadSafety;
053    import com.unboundid.util.ThreadSafetyLevel;
054    import com.unboundid.util.WakeableSleeper;
055    import com.unboundid.util.ValuePattern;
056    import com.unboundid.util.args.ArgumentException;
057    import com.unboundid.util.args.ArgumentParser;
058    import com.unboundid.util.args.BooleanArgument;
059    import com.unboundid.util.args.FileArgument;
060    import com.unboundid.util.args.IntegerArgument;
061    import com.unboundid.util.args.ScopeArgument;
062    import com.unboundid.util.args.StringArgument;
063    
064    import static com.unboundid.util.Debug.*;
065    import static com.unboundid.util.StaticUtils.*;
066    
067    
068    
069    /**
070     * This class provides a tool that can be used to search an LDAP directory
071     * server repeatedly using multiple threads.  It can help provide an estimate of
072     * the search performance that a directory server is able to achieve.  Either or
073     * both of the base DN and the search filter may be a value pattern as
074     * described in the {@link ValuePattern} class.  This makes it possible to
075     * search over a range of entries rather than repeatedly performing searches
076     * with the same base DN and filter.
077     * <BR><BR>
078     * Some of the APIs demonstrated by this example include:
079     * <UL>
080     *   <LI>Argument Parsing (from the {@code com.unboundid.util.args}
081     *       package)</LI>
082     *   <LI>LDAP Command-Line Tool (from the {@code com.unboundid.util}
083     *       package)</LI>
084     *   <LI>LDAP Communication (from the {@code com.unboundid.ldap.sdk}
085     *       package)</LI>
086     *   <LI>Value Patterns (from the {@code com.unboundid.util} package)</LI>
087     * </UL>
088     * <BR><BR>
089     * All of the necessary information is provided using command line arguments.
090     * Supported arguments include those allowed by the {@link LDAPCommandLineTool}
091     * class, as well as the following additional arguments:
092     * <UL>
093     *   <LI>"-b {baseDN}" or "--baseDN {baseDN}" -- specifies the base DN to use
094     *       for the searches.  This must be provided.  It may be a simple DN, or it
095     *       may be a value pattern to express a range of base DNs.</LI>
096     *   <LI>"-s {scope}" or "--scope {scope}" -- specifies the scope to use for the
097     *       search.  The scope value should be one of "base", "one", "sub", or
098     *       "subord".  If this isn't specified, then a scope of "sub" will be
099     *       used.</LI>
100     *   <LI>"-f {filter}" or "--filter {filter}" -- specifies the filter to use for
101     *       the searches.  This must be provided.  It may be a simple filter, or it
102     *       may be a value pattern to express a range of filters.</LI>
103     *   <LI>"-A {name}" or "--attribute {name}" -- specifies the name of an
104     *       attribute that should be included in entries returned from the server.
105     *       If this is not provided, then all user attributes will be requested.
106     *       This may include special tokens that the server may interpret, like
107     *       "1.1" to indicate that no attributes should be returned, "*", for all
108     *       user attributes, or "+" for all operational attributes.  Multiple
109     *       attributes may be requested with multiple instances of this
110     *       argument.</LI>
111     *   <LI>"-t {num}" or "--numThreads {num}" -- specifies the number of
112     *       concurrent threads to use when performing the searches.  If this is not
113     *       provided, then a default of one thread will be used.</LI>
114     *   <LI>"-i {sec}" or "--intervalDuration {sec}" -- specifies the length of
115     *       time in seconds between lines out output.  If this is not provided,
116     *       then a default interval duration of five seconds will be used.</LI>
117     *   <LI>"-I {num}" or "--numIntervals {num}" -- specifies the maximum number of
118     *       intervals for which to run.  If this is not provided, then it will
119     *       run forever.</LI>
120     *   <LI>"--iterationsBeforeReconnect {num}" -- specifies the number of search
121     *       iterations that should be performed on a connection before that
122     *       connection is closed and replaced with a newly-established (and
123     *       authenticated, if appropriate) connection.</LI>
124     *   <LI>"-r {searches-per-second}" or "--ratePerSecond {searches-per-second}"
125     *       -- specifies the target number of searches to perform per second.  It
126     *       is still necessary to specify a sufficient number of threads for
127     *       achieving this rate.  If this option is not provided, then the tool
128     *       will run at the maximum rate for the specified number of threads.</LI>
129     *   <LI>"--variableRateData {path}" -- specifies the path to a file containing
130     *       information needed to allow the tool to vary the target rate over time.
131     *       If this option is not provided, then the tool will either use a fixed
132     *       target rate as specified by the "--ratePerSecond" argument, or it will
133     *       run at the maximum rate.</LI>
134     *   <LI>"--generateSampleRateFile {path}" -- specifies the path to a file to
135     *       which sample data will be written illustrating and describing the
136     *       format of the file expected to be used in conjunction with the
137     *       "--variableRateData" argument.</LI>
138     *   <LI>"--warmUpIntervals {num}" -- specifies the number of intervals to
139     *       complete before beginning overall statistics collection.</LI>
140     *   <LI>"--timestampFormat {format}" -- specifies the format to use for
141     *       timestamps included before each output line.  The format may be one of
142     *       "none" (for no timestamps), "with-date" (to include both the date and
143     *       the time), or "without-date" (to include only time time).</LI>
144     *   <LI>"-Y {authzID}" or "--proxyAs {authzID}" -- Use the proxied
145     *       authorization v2 control to request that the operation be processed
146     *       using an alternate authorization identity.  In this case, the bind DN
147     *       should be that of a user that has permission to use this control.  The
148     *       authorization identity may be a value pattern.</LI>
149     *   <LI>"-a" or "--asynchronous" -- Indicates that searches should be performed
150     *       in asynchronous mode, in which the client will not wait for a response
151     *       to a previous request before sending the next request.  Either the
152     *       "--ratePerSecond" or "--maxOutstandingRequests" arguments must be
153     *       provided to limit the number of outstanding requests.</LI>
154     *   <LI>"-O {num}" or "--maxOutstandingRequests {num}" -- Specifies the maximum
155     *       number of outstanding requests that will be allowed in asynchronous
156     *       mode.</LI>
157     *   <LI>"--suppressErrorResultCodes" -- Indicates that information about the
158     *       result codes for failed operations should not be displayed.</LI>
159     *   <LI>"-c" or "--csv" -- Generate output in CSV format rather than a
160     *       display-friendly format.</LI>
161     * </UL>
162     */
163    @ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE)
164    public final class SearchRate
165           extends LDAPCommandLineTool
166           implements Serializable
167    {
168      /**
169       * The serial version UID for this serializable class.
170       */
171      private static final long serialVersionUID = 3345838530404592182L;
172    
173    
174    
175      // Indicates whether a request has been made to stop running.
176      private final AtomicBoolean stopRequested;
177    
178      // The argument used to indicate whether to operate in asynchronous mode.
179      private BooleanArgument asynchronousMode;
180    
181      // The argument used to indicate whether to generate output in CSV format.
182      private BooleanArgument csvFormat;
183    
184      // The argument used to indicate whether to suppress information about error
185      // result codes.
186      private BooleanArgument suppressErrors;
187    
188      // The argument used to specify the collection interval.
189      private IntegerArgument collectionInterval;
190    
191      // The argument used to specify the number of search iterations on a
192      // connection before it is closed and re-established.
193      private IntegerArgument iterationsBeforeReconnect;
194    
195      // The argument used to specify the maximum number of outstanding asynchronous
196      // requests.
197      private IntegerArgument maxOutstandingRequests;
198    
199      // The argument used to specify the number of intervals.
200      private IntegerArgument numIntervals;
201    
202      // The argument used to specify the number of threads.
203      private IntegerArgument numThreads;
204    
205      // The argument used to specify the seed to use for the random number
206      // generator.
207      private IntegerArgument randomSeed;
208    
209      // The target rate of searches per second.
210      private IntegerArgument ratePerSecond;
211    
212      // The argument used to specify a variable rate file.
213      private FileArgument sampleRateFile;
214    
215      // The argument used to specify a variable rate file.
216      private FileArgument variableRateData;
217    
218      // The number of warm-up intervals to perform.
219      private IntegerArgument warmUpIntervals;
220    
221      // The argument used to specify the scope for the searches.
222      private ScopeArgument scopeArg;
223    
224      // The argument used to specify the attributes to return.
225      private StringArgument attributes;
226    
227      // The argument used to specify the base DNs for the searches.
228      private StringArgument baseDN;
229    
230      // The argument used to specify the filters for the searches.
231      private StringArgument filter;
232    
233      // The argument used to specify the proxied authorization identity.
234      private StringArgument proxyAs;
235    
236      // The argument used to specify the timestamp format.
237      private StringArgument timestampFormat;
238    
239      // The thread currently being used to run the searchrate tool.
240      private volatile Thread runningThread;
241    
242      // A wakeable sleeper that will be used to sleep between reporting intervals.
243      private final WakeableSleeper sleeper;
244    
245    
246    
247      /**
248       * Parse the provided command line arguments and make the appropriate set of
249       * changes.
250       *
251       * @param  args  The command line arguments provided to this program.
252       */
253      public static void main(final String[] args)
254      {
255        final ResultCode resultCode = main(args, System.out, System.err);
256        if (resultCode != ResultCode.SUCCESS)
257        {
258          System.exit(resultCode.intValue());
259        }
260      }
261    
262    
263    
264      /**
265       * Parse the provided command line arguments and make the appropriate set of
266       * changes.
267       *
268       * @param  args       The command line arguments provided to this program.
269       * @param  outStream  The output stream to which standard out should be
270       *                    written.  It may be {@code null} if output should be
271       *                    suppressed.
272       * @param  errStream  The output stream to which standard error should be
273       *                    written.  It may be {@code null} if error messages
274       *                    should be suppressed.
275       *
276       * @return  A result code indicating whether the processing was successful.
277       */
278      public static ResultCode main(final String[] args,
279                                    final OutputStream outStream,
280                                    final OutputStream errStream)
281      {
282        final SearchRate searchRate = new SearchRate(outStream, errStream);
283        return searchRate.runTool(args);
284      }
285    
286    
287    
288      /**
289       * Creates a new instance of this tool.
290       *
291       * @param  outStream  The output stream to which standard out should be
292       *                    written.  It may be {@code null} if output should be
293       *                    suppressed.
294       * @param  errStream  The output stream to which standard error should be
295       *                    written.  It may be {@code null} if error messages
296       *                    should be suppressed.
297       */
298      public SearchRate(final OutputStream outStream, final OutputStream errStream)
299      {
300        super(outStream, errStream);
301    
302        stopRequested = new AtomicBoolean(false);
303        sleeper = new WakeableSleeper();
304      }
305    
306    
307    
308      /**
309       * Retrieves the name for this tool.
310       *
311       * @return  The name for this tool.
312       */
313      @Override()
314      public String getToolName()
315      {
316        return "searchrate";
317      }
318    
319    
320    
321      /**
322       * Retrieves the description for this tool.
323       *
324       * @return  The description for this tool.
325       */
326      @Override()
327      public String getToolDescription()
328      {
329        return "Perform repeated searches against an " +
330               "LDAP directory server.";
331      }
332    
333    
334    
335      /**
336       * Retrieves the version string for this tool.
337       *
338       * @return  The version string for this tool.
339       */
340      @Override()
341      public String getToolVersion()
342      {
343        return Version.NUMERIC_VERSION_STRING;
344      }
345    
346    
347    
348      /**
349       * Indicates whether this tool should provide support for an interactive mode,
350       * in which the tool offers a mode in which the arguments can be provided in
351       * a text-driven menu rather than requiring them to be given on the command
352       * line.  If interactive mode is supported, it may be invoked using the
353       * "--interactive" argument.  Alternately, if interactive mode is supported
354       * and {@link #defaultsToInteractiveMode()} returns {@code true}, then
355       * interactive mode may be invoked by simply launching the tool without any
356       * arguments.
357       *
358       * @return  {@code true} if this tool supports interactive mode, or
359       *          {@code false} if not.
360       */
361      @Override()
362      public boolean supportsInteractiveMode()
363      {
364        return true;
365      }
366    
367    
368    
369      /**
370       * Indicates whether this tool defaults to launching in interactive mode if
371       * the tool is invoked without any command-line arguments.  This will only be
372       * used if {@link #supportsInteractiveMode()} returns {@code true}.
373       *
374       * @return  {@code true} if this tool defaults to using interactive mode if
375       *          launched without any command-line arguments, or {@code false} if
376       *          not.
377       */
378      @Override()
379      public boolean defaultsToInteractiveMode()
380      {
381        return true;
382      }
383    
384    
385    
386      /**
387       * Indicates whether this tool supports the use of a properties file for
388       * specifying default values for arguments that aren't specified on the
389       * command line.
390       *
391       * @return  {@code true} if this tool supports the use of a properties file
392       *          for specifying default values for arguments that aren't specified
393       *          on the command line, or {@code false} if not.
394       */
395      @Override()
396      public boolean supportsPropertiesFile()
397      {
398        return true;
399      }
400    
401    
402    
403      /**
404       * Indicates whether the LDAP-specific arguments should include alternate
405       * versions of all long identifiers that consist of multiple words so that
406       * they are available in both camelCase and dash-separated versions.
407       *
408       * @return  {@code true} if this tool should provide multiple versions of
409       *          long identifiers for LDAP-specific arguments, or {@code false} if
410       *          not.
411       */
412      @Override()
413      protected boolean includeAlternateLongIdentifiers()
414      {
415        return true;
416      }
417    
418    
419    
420      /**
421       * Adds the arguments used by this program that aren't already provided by the
422       * generic {@code LDAPCommandLineTool} framework.
423       *
424       * @param  parser  The argument parser to which the arguments should be added.
425       *
426       * @throws  ArgumentException  If a problem occurs while adding the arguments.
427       */
428      @Override()
429      public void addNonLDAPArguments(final ArgumentParser parser)
430             throws ArgumentException
431      {
432        String description = "The base DN to use for the searches.  It may be a " +
433             "simple DN or a value pattern to specify a range of DNs (e.g., " +
434             "\"uid=user.[1-1000],ou=People,dc=example,dc=com\").  See " +
435             ValuePattern.PUBLIC_JAVADOC_URL + " for complete details about the " +
436             "value pattern syntax.  This must be provided.";
437        baseDN = new StringArgument('b', "baseDN", true, 1, "{dn}", description);
438        baseDN.setArgumentGroupName("Search Arguments");
439        baseDN.addLongIdentifier("base-dn");
440        parser.addArgument(baseDN);
441    
442    
443        description = "The scope to use for the searches.  It should be 'base', " +
444                      "'one', 'sub', or 'subord'.  If this is not provided, then " +
445                      "a default scope of 'sub' will be used.";
446        scopeArg = new ScopeArgument('s', "scope", false, "{scope}", description,
447                                     SearchScope.SUB);
448        scopeArg.setArgumentGroupName("Search Arguments");
449        parser.addArgument(scopeArg);
450    
451    
452        description = "The filter to use for the searches.  It may be a simple " +
453                      "filter or a value pattern to specify a range of filters " +
454                      "(e.g., \"(uid=user.[1-1000])\").  See " +
455                      ValuePattern.PUBLIC_JAVADOC_URL + " for complete details " +
456                      "about the value pattern syntax.  This must be provided.";
457        filter = new StringArgument('f', "filter", true, 1, "{filter}",
458                                    description);
459        filter.setArgumentGroupName("Search Arguments");
460        parser.addArgument(filter);
461    
462    
463        description = "The name of an attribute to include in entries returned " +
464                      "from the searches.  Multiple attributes may be requested " +
465                      "by providing this argument multiple times.  If no request " +
466                      "attributes are provided, then the entries returned will " +
467                      "include all user attributes.";
468        attributes = new StringArgument('A', "attribute", false, 0, "{name}",
469                                        description);
470        attributes.setArgumentGroupName("Search Arguments");
471        parser.addArgument(attributes);
472    
473    
474        description = "The number of threads to use to perform the searches.  If " +
475                      "this is not provided, then a default of one thread will " +
476                      "be used.";
477        numThreads = new IntegerArgument('t', "numThreads", true, 1, "{num}",
478                                         description, 1, Integer.MAX_VALUE, 1);
479        numThreads.setArgumentGroupName("Rate Management Arguments");
480        numThreads.addLongIdentifier("num-threads");
481        parser.addArgument(numThreads);
482    
483    
484        description = "The length of time in seconds between output lines.  If " +
485                      "this is not provided, then a default interval of five " +
486                      "seconds will be used.";
487        collectionInterval = new IntegerArgument('i', "intervalDuration", true, 1,
488                                                 "{num}", description, 1,
489                                                 Integer.MAX_VALUE, 5);
490        collectionInterval.setArgumentGroupName("Rate Management Arguments");
491        collectionInterval.addLongIdentifier("interval-duration");
492        parser.addArgument(collectionInterval);
493    
494    
495        description = "The maximum number of intervals for which to run.  If " +
496                      "this is not provided, then the tool will run until it is " +
497                      "interrupted.";
498        numIntervals = new IntegerArgument('I', "numIntervals", true, 1, "{num}",
499                                           description, 1, Integer.MAX_VALUE,
500                                           Integer.MAX_VALUE);
501        numIntervals.setArgumentGroupName("Rate Management Arguments");
502        numIntervals.addLongIdentifier("num-intervals");
503        parser.addArgument(numIntervals);
504    
505        description = "The number of search iterations that should be processed " +
506                      "on a connection before that connection is closed and " +
507                      "replaced with a newly-established (and authenticated, if " +
508                      "appropriate) connection.  If this is not provided, then " +
509                      "connections will not be periodically closed and " +
510                      "re-established.";
511        iterationsBeforeReconnect = new IntegerArgument(null,
512             "iterationsBeforeReconnect", false, 1, "{num}", description, 0);
513        iterationsBeforeReconnect.setArgumentGroupName("Rate Management Arguments");
514        iterationsBeforeReconnect.addLongIdentifier("iterations-before-reconnect");
515        parser.addArgument(iterationsBeforeReconnect);
516    
517        description = "The target number of searches to perform per second.  It " +
518                      "is still necessary to specify a sufficient number of " +
519                      "threads for achieving this rate.  If neither this option " +
520                      "nor --variableRateData is provided, then the tool will " +
521                      "run at the maximum rate for the specified number of " +
522                      "threads.";
523        ratePerSecond = new IntegerArgument('r', "ratePerSecond", false, 1,
524                                            "{searches-per-second}", description,
525                                            1, Integer.MAX_VALUE);
526        ratePerSecond.setArgumentGroupName("Rate Management Arguments");
527        ratePerSecond.addLongIdentifier("rate-per-second");
528        parser.addArgument(ratePerSecond);
529    
530        final String variableRateDataArgName = "variableRateData";
531        final String generateSampleRateFileArgName = "generateSampleRateFile";
532        description = RateAdjustor.getVariableRateDataArgumentDescription(
533             generateSampleRateFileArgName);
534        variableRateData = new FileArgument(null, variableRateDataArgName, false, 1,
535                                            "{path}", description, true, true, true,
536                                            false);
537        variableRateData.setArgumentGroupName("Rate Management Arguments");
538        variableRateData.addLongIdentifier("variable-rate-data");
539        parser.addArgument(variableRateData);
540    
541        description = RateAdjustor.getGenerateSampleVariableRateFileDescription(
542             variableRateDataArgName);
543        sampleRateFile = new FileArgument(null, generateSampleRateFileArgName,
544                                          false, 1, "{path}", description, false,
545                                          true, true, false);
546        sampleRateFile.setArgumentGroupName("Rate Management Arguments");
547        sampleRateFile.addLongIdentifier("generate-sample-rate-file");
548        sampleRateFile.setUsageArgument(true);
549        parser.addArgument(sampleRateFile);
550        parser.addExclusiveArgumentSet(variableRateData, sampleRateFile);
551    
552        description = "The number of intervals to complete before beginning " +
553                      "overall statistics collection.  Specifying a nonzero " +
554                      "number of warm-up intervals gives the client and server " +
555                      "a chance to warm up without skewing performance results.";
556        warmUpIntervals = new IntegerArgument(null, "warmUpIntervals", true, 1,
557             "{num}", description, 0, Integer.MAX_VALUE, 0);
558        warmUpIntervals.setArgumentGroupName("Rate Management Arguments");
559        warmUpIntervals.addLongIdentifier("warm-up-intervals");
560        parser.addArgument(warmUpIntervals);
561    
562        description = "Indicates the format to use for timestamps included in " +
563                      "the output.  A value of 'none' indicates that no " +
564                      "timestamps should be included.  A value of 'with-date' " +
565                      "indicates that both the date and the time should be " +
566                      "included.  A value of 'without-date' indicates that only " +
567                      "the time should be included.";
568        final LinkedHashSet<String> allowedFormats = new LinkedHashSet<String>(3);
569        allowedFormats.add("none");
570        allowedFormats.add("with-date");
571        allowedFormats.add("without-date");
572        timestampFormat = new StringArgument(null, "timestampFormat", true, 1,
573             "{format}", description, allowedFormats, "none");
574        timestampFormat.addLongIdentifier("timestamp-format");
575        parser.addArgument(timestampFormat);
576    
577        description = "Indicates that the proxied authorization control (as " +
578                      "defined in RFC 4370) should be used to request that " +
579                      "operations be processed using an alternate authorization " +
580                      "identity.  This may be a simple authorization ID or it " +
581                      "may be a value pattern to specify a range of " +
582                      "identities.  See " + ValuePattern.PUBLIC_JAVADOC_URL +
583                      " for complete details about the value pattern syntax.";
584        proxyAs = new StringArgument('Y', "proxyAs", false, 1, "{authzID}",
585                                     description);
586        proxyAs.addLongIdentifier("proxy-as");
587        parser.addArgument(proxyAs);
588    
589        description = "Indicates that the client should operate in asynchronous " +
590                      "mode, in which it will not be necessary to wait for a " +
591                      "response to a previous request before sending the next " +
592                      "request.  Either the '--ratePerSecond' or the " +
593                      "'--maxOutstandingRequests' argument must be provided to " +
594                      "limit the number of outstanding requests.";
595        asynchronousMode = new BooleanArgument('a', "asynchronous", description);
596        parser.addArgument(asynchronousMode);
597    
598        description = "Specifies the maximum number of outstanding requests " +
599                      "that should be allowed when operating in asynchronous mode.";
600        maxOutstandingRequests = new IntegerArgument('O', "maxOutstandingRequests",
601             false, 1, "{num}", description, 1, Integer.MAX_VALUE, (Integer) null);
602        maxOutstandingRequests.addLongIdentifier("max-outstanding-requests");
603        parser.addArgument(maxOutstandingRequests);
604    
605        description = "Indicates that information about the result codes for " +
606                      "failed operations should not be displayed.";
607        suppressErrors = new BooleanArgument(null,
608             "suppressErrorResultCodes", 1, description);
609        suppressErrors.addLongIdentifier("suppress-error-result-codes");
610        parser.addArgument(suppressErrors);
611    
612        description = "Generate output in CSV format rather than a " +
613                      "display-friendly format";
614        csvFormat = new BooleanArgument('c', "csv", 1, description);
615        parser.addArgument(csvFormat);
616    
617        description = "Specifies the seed to use for the random number generator.";
618        randomSeed = new IntegerArgument('R', "randomSeed", false, 1, "{value}",
619             description);
620        randomSeed.addLongIdentifier("random-seed");
621        parser.addArgument(randomSeed);
622    
623    
624        parser.addDependentArgumentSet(asynchronousMode, ratePerSecond,
625             maxOutstandingRequests);
626        parser.addDependentArgumentSet(maxOutstandingRequests, asynchronousMode);
627      }
628    
629    
630    
631      /**
632       * Indicates whether this tool supports creating connections to multiple
633       * servers.  If it is to support multiple servers, then the "--hostname" and
634       * "--port" arguments will be allowed to be provided multiple times, and
635       * will be required to be provided the same number of times.  The same type of
636       * communication security and bind credentials will be used for all servers.
637       *
638       * @return  {@code true} if this tool supports creating connections to
639       *          multiple servers, or {@code false} if not.
640       */
641      @Override()
642      protected boolean supportsMultipleServers()
643      {
644        return true;
645      }
646    
647    
648    
649      /**
650       * Retrieves the connection options that should be used for connections
651       * created for use with this tool.
652       *
653       * @return  The connection options that should be used for connections created
654       *          for use with this tool.
655       */
656      @Override()
657      public LDAPConnectionOptions getConnectionOptions()
658      {
659        final LDAPConnectionOptions options = new LDAPConnectionOptions();
660        options.setUseSynchronousMode(! asynchronousMode.isPresent());
661        return options;
662      }
663    
664    
665    
666      /**
667       * Performs the actual processing for this tool.  In this case, it gets a
668       * connection to the directory server and uses it to perform the requested
669       * searches.
670       *
671       * @return  The result code for the processing that was performed.
672       */
673      @Override()
674      public ResultCode doToolProcessing()
675      {
676        runningThread = Thread.currentThread();
677    
678        try
679        {
680          return doToolProcessingInternal();
681        }
682        finally
683        {
684          runningThread = null;
685        }
686      }
687    
688    
689    
690      /**
691       * Performs the actual processing for this tool.  In this case, it gets a
692       * connection to the directory server and uses it to perform the requested
693       * searches.
694       *
695       * @return  The result code for the processing that was performed.
696       */
697      private ResultCode doToolProcessingInternal()
698      {
699        // If the sample rate file argument was specified, then generate the sample
700        // variable rate data file and return.
701        if (sampleRateFile.isPresent())
702        {
703          try
704          {
705            RateAdjustor.writeSampleVariableRateFile(sampleRateFile.getValue());
706            return ResultCode.SUCCESS;
707          }
708          catch (final Exception e)
709          {
710            debugException(e);
711            err("An error occurred while trying to write sample variable data " +
712                 "rate file '", sampleRateFile.getValue().getAbsolutePath(),
713                 "':  ", getExceptionMessage(e));
714            return ResultCode.LOCAL_ERROR;
715          }
716        }
717    
718    
719        // Determine the random seed to use.
720        final Long seed;
721        if (randomSeed.isPresent())
722        {
723          seed = Long.valueOf(randomSeed.getValue());
724        }
725        else
726        {
727          seed = null;
728        }
729    
730        // Create value patterns for the base DN, filter, and proxied authorization
731        // DN.
732        final ValuePattern dnPattern;
733        try
734        {
735          dnPattern = new ValuePattern(baseDN.getValue(), seed);
736        }
737        catch (final ParseException pe)
738        {
739          debugException(pe);
740          err("Unable to parse the base DN value pattern:  ", pe.getMessage());
741          return ResultCode.PARAM_ERROR;
742        }
743    
744        final ValuePattern filterPattern;
745        try
746        {
747          filterPattern = new ValuePattern(filter.getValue(), seed);
748        }
749        catch (final ParseException pe)
750        {
751          debugException(pe);
752          err("Unable to parse the filter pattern:  ", pe.getMessage());
753          return ResultCode.PARAM_ERROR;
754        }
755    
756        final ValuePattern authzIDPattern;
757        if (proxyAs.isPresent())
758        {
759          try
760          {
761            authzIDPattern = new ValuePattern(proxyAs.getValue(), seed);
762          }
763          catch (final ParseException pe)
764          {
765            debugException(pe);
766            err("Unable to parse the proxied authorization pattern:  ",
767                pe.getMessage());
768            return ResultCode.PARAM_ERROR;
769          }
770        }
771        else
772        {
773          authzIDPattern = null;
774        }
775    
776    
777        // Get the attributes to return.
778        final String[] attrs;
779        if (attributes.isPresent())
780        {
781          final List<String> attrList = attributes.getValues();
782          attrs = new String[attrList.size()];
783          attrList.toArray(attrs);
784        }
785        else
786        {
787          attrs = NO_STRINGS;
788        }
789    
790    
791        // If the --ratePerSecond option was specified, then limit the rate
792        // accordingly.
793        FixedRateBarrier fixedRateBarrier = null;
794        if (ratePerSecond.isPresent() || variableRateData.isPresent())
795        {
796          // We might not have a rate per second if --variableRateData is specified.
797          // The rate typically doesn't matter except when we have warm-up
798          // intervals.  In this case, we'll run at the max rate.
799          final int intervalSeconds = collectionInterval.getValue();
800          final int ratePerInterval =
801               (ratePerSecond.getValue() == null)
802               ? Integer.MAX_VALUE
803               : ratePerSecond.getValue() * intervalSeconds;
804          fixedRateBarrier =
805               new FixedRateBarrier(1000L * intervalSeconds, ratePerInterval);
806        }
807    
808    
809        // If --variableRateData was specified, then initialize a RateAdjustor.
810        RateAdjustor rateAdjustor = null;
811        if (variableRateData.isPresent())
812        {
813          try
814          {
815            rateAdjustor = RateAdjustor.newInstance(fixedRateBarrier,
816                 ratePerSecond.getValue(), variableRateData.getValue());
817          }
818          catch (final IOException e)
819          {
820            debugException(e);
821            err("Initializing the variable rates failed: " + e.getMessage());
822            return ResultCode.PARAM_ERROR;
823          }
824          catch (final IllegalArgumentException e)
825          {
826            debugException(e);
827            err("Initializing the variable rates failed: " + e.getMessage());
828            return ResultCode.PARAM_ERROR;
829          }
830        }
831    
832    
833        // If the --maxOutstandingRequests option was specified, then create the
834        // semaphore used to enforce that limit.
835        final Semaphore asyncSemaphore;
836        if (maxOutstandingRequests.isPresent())
837        {
838          asyncSemaphore = new Semaphore(maxOutstandingRequests.getValue());
839        }
840        else
841        {
842          asyncSemaphore = null;
843        }
844    
845    
846        // Determine whether to include timestamps in the output and if so what
847        // format should be used for them.
848        final boolean includeTimestamp;
849        final String timeFormat;
850        if (timestampFormat.getValue().equalsIgnoreCase("with-date"))
851        {
852          includeTimestamp = true;
853          timeFormat       = "dd/MM/yyyy HH:mm:ss";
854        }
855        else if (timestampFormat.getValue().equalsIgnoreCase("without-date"))
856        {
857          includeTimestamp = true;
858          timeFormat       = "HH:mm:ss";
859        }
860        else
861        {
862          includeTimestamp = false;
863          timeFormat       = null;
864        }
865    
866    
867        // Determine whether any warm-up intervals should be run.
868        final long totalIntervals;
869        final boolean warmUp;
870        int remainingWarmUpIntervals = warmUpIntervals.getValue();
871        if (remainingWarmUpIntervals > 0)
872        {
873          warmUp = true;
874          totalIntervals = 0L + numIntervals.getValue() + remainingWarmUpIntervals;
875        }
876        else
877        {
878          warmUp = true;
879          totalIntervals = 0L + numIntervals.getValue();
880        }
881    
882    
883        // Create the table that will be used to format the output.
884        final OutputFormat outputFormat;
885        if (csvFormat.isPresent())
886        {
887          outputFormat = OutputFormat.CSV;
888        }
889        else
890        {
891          outputFormat = OutputFormat.COLUMNS;
892        }
893    
894        final ColumnFormatter formatter = new ColumnFormatter(includeTimestamp,
895             timeFormat, outputFormat, " ",
896             new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent",
897                      "Searches/Sec"),
898             new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent",
899                      "Avg Dur ms"),
900             new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent",
901                      "Entries/Srch"),
902             new FormattableColumn(12, HorizontalAlignment.RIGHT, "Recent",
903                      "Errors/Sec"),
904             new FormattableColumn(12, HorizontalAlignment.RIGHT, "Overall",
905                      "Searches/Sec"),
906             new FormattableColumn(12, HorizontalAlignment.RIGHT, "Overall",
907                      "Avg Dur ms"));
908    
909    
910        // Create values to use for statistics collection.
911        final AtomicLong        searchCounter   = new AtomicLong(0L);
912        final AtomicLong        entryCounter    = new AtomicLong(0L);
913        final AtomicLong        errorCounter    = new AtomicLong(0L);
914        final AtomicLong        searchDurations = new AtomicLong(0L);
915        final ResultCodeCounter rcCounter       = new ResultCodeCounter();
916    
917    
918        // Determine the length of each interval in milliseconds.
919        final long intervalMillis = 1000L * collectionInterval.getValue();
920    
921    
922        // Create the threads to use for the searches.
923        final CyclicBarrier barrier = new CyclicBarrier(numThreads.getValue() + 1);
924        final SearchRateThread[] threads =
925             new SearchRateThread[numThreads.getValue()];
926        for (int i=0; i < threads.length; i++)
927        {
928          final LDAPConnection connection;
929          try
930          {
931            connection = getConnection();
932          }
933          catch (final LDAPException le)
934          {
935            debugException(le);
936            err("Unable to connect to the directory server:  ",
937                getExceptionMessage(le));
938            return le.getResultCode();
939          }
940    
941          threads[i] = new SearchRateThread(this, i, connection,
942               asynchronousMode.isPresent(), dnPattern, scopeArg.getValue(),
943               filterPattern, attrs, authzIDPattern,
944               iterationsBeforeReconnect.getValue(), barrier, searchCounter,
945               entryCounter, searchDurations, errorCounter, rcCounter,
946               fixedRateBarrier, asyncSemaphore);
947          threads[i].start();
948        }
949    
950    
951        // Display the table header.
952        for (final String headerLine : formatter.getHeaderLines(true))
953        {
954          out(headerLine);
955        }
956    
957    
958        // Start the RateAdjustor before the threads so that the initial value is
959        // in place before any load is generated unless we're doing a warm-up in
960        // which case, we'll start it after the warm-up is complete.
961        if ((rateAdjustor != null) && (remainingWarmUpIntervals <= 0))
962        {
963          rateAdjustor.start();
964        }
965    
966    
967        // Indicate that the threads can start running.
968        try
969        {
970          barrier.await();
971        }
972        catch (final Exception e)
973        {
974          debugException(e);
975        }
976    
977        long overallStartTime = System.nanoTime();
978        long nextIntervalStartTime = System.currentTimeMillis() + intervalMillis;
979    
980    
981        boolean setOverallStartTime = false;
982        long    lastDuration        = 0L;
983        long    lastNumEntries      = 0L;
984        long    lastNumErrors       = 0L;
985        long    lastNumSearches     = 0L;
986        long    lastEndTime         = System.nanoTime();
987        for (long i=0; i < totalIntervals; i++)
988        {
989          if (rateAdjustor != null)
990          {
991            if (! rateAdjustor.isAlive())
992            {
993              out("All of the rates in " + variableRateData.getValue().getName() +
994                  " have been completed.");
995              break;
996            }
997          }
998    
999          final long startTimeMillis = System.currentTimeMillis();
1000          final long sleepTimeMillis = nextIntervalStartTime - startTimeMillis;
1001          nextIntervalStartTime += intervalMillis;
1002          if (sleepTimeMillis > 0)
1003          {
1004            sleeper.sleep(sleepTimeMillis);
1005          }
1006    
1007          if (stopRequested.get())
1008          {
1009            break;
1010          }
1011    
1012          final long endTime          = System.nanoTime();
1013          final long intervalDuration = endTime - lastEndTime;
1014    
1015          final long numSearches;
1016          final long numEntries;
1017          final long numErrors;
1018          final long totalDuration;
1019          if (warmUp && (remainingWarmUpIntervals > 0))
1020          {
1021            numSearches   = searchCounter.getAndSet(0L);
1022            numEntries    = entryCounter.getAndSet(0L);
1023            numErrors     = errorCounter.getAndSet(0L);
1024            totalDuration = searchDurations.getAndSet(0L);
1025          }
1026          else
1027          {
1028            numSearches   = searchCounter.get();
1029            numEntries    = entryCounter.get();
1030            numErrors     = errorCounter.get();
1031            totalDuration = searchDurations.get();
1032          }
1033    
1034          final long recentNumSearches = numSearches - lastNumSearches;
1035          final long recentNumEntries = numEntries - lastNumEntries;
1036          final long recentNumErrors = numErrors - lastNumErrors;
1037          final long recentDuration = totalDuration - lastDuration;
1038    
1039          final double numSeconds = intervalDuration / 1000000000.0d;
1040          final double recentSearchRate = recentNumSearches / numSeconds;
1041          final double recentErrorRate  = recentNumErrors / numSeconds;
1042    
1043          final double recentAvgDuration;
1044          final double recentEntriesPerSearch;
1045          if (recentNumSearches > 0L)
1046          {
1047            recentEntriesPerSearch = 1.0d * recentNumEntries / recentNumSearches;
1048            recentAvgDuration = 1.0d * recentDuration / recentNumSearches / 1000000;
1049          }
1050          else
1051          {
1052            recentEntriesPerSearch = 0.0d;
1053            recentAvgDuration = 0.0d;
1054          }
1055    
1056    
1057          if (warmUp && (remainingWarmUpIntervals > 0))
1058          {
1059            out(formatter.formatRow(recentSearchRate, recentAvgDuration,
1060                 recentEntriesPerSearch, recentErrorRate, "warming up",
1061                 "warming up"));
1062    
1063            remainingWarmUpIntervals--;
1064            if (remainingWarmUpIntervals == 0)
1065            {
1066              out("Warm-up completed.  Beginning overall statistics collection.");
1067              setOverallStartTime = true;
1068              if (rateAdjustor != null)
1069              {
1070                rateAdjustor.start();
1071              }
1072            }
1073          }
1074          else
1075          {
1076            if (setOverallStartTime)
1077            {
1078              overallStartTime    = lastEndTime;
1079              setOverallStartTime = false;
1080            }
1081    
1082            final double numOverallSeconds =
1083                 (endTime - overallStartTime) / 1000000000.0d;
1084            final double overallSearchRate = numSearches / numOverallSeconds;
1085    
1086            final double overallAvgDuration;
1087            if (numSearches > 0L)
1088            {
1089              overallAvgDuration = 1.0d * totalDuration / numSearches / 1000000;
1090            }
1091            else
1092            {
1093              overallAvgDuration = 0.0d;
1094            }
1095    
1096            out(formatter.formatRow(recentSearchRate, recentAvgDuration,
1097                 recentEntriesPerSearch, recentErrorRate, overallSearchRate,
1098                 overallAvgDuration));
1099    
1100            lastNumSearches = numSearches;
1101            lastNumEntries  = numEntries;
1102            lastNumErrors   = numErrors;
1103            lastDuration    = totalDuration;
1104          }
1105    
1106          final List<ObjectPair<ResultCode,Long>> rcCounts =
1107               rcCounter.getCounts(true);
1108          if ((! suppressErrors.isPresent()) && (! rcCounts.isEmpty()))
1109          {
1110            err("\tError Results:");
1111            for (final ObjectPair<ResultCode,Long> p : rcCounts)
1112            {
1113              err("\t", p.getFirst().getName(), ":  ", p.getSecond());
1114            }
1115          }
1116    
1117          lastEndTime = endTime;
1118        }
1119    
1120    
1121        // Shut down the RateAdjustor if we have one.
1122        if (rateAdjustor != null)
1123        {
1124          rateAdjustor.shutDown();
1125        }
1126    
1127    
1128        // Stop all of the threads.
1129        ResultCode resultCode = ResultCode.SUCCESS;
1130        for (final SearchRateThread t : threads)
1131        {
1132          t.signalShutdown();
1133        }
1134        for (final SearchRateThread t : threads)
1135        {
1136          final ResultCode r = t.waitForShutdown();
1137          if (resultCode == ResultCode.SUCCESS)
1138          {
1139            resultCode = r;
1140          }
1141        }
1142    
1143        return resultCode;
1144      }
1145    
1146    
1147    
1148      /**
1149       * Requests that this tool stop running.  This method will attempt to wait
1150       * for all threads to complete before returning control to the caller.
1151       */
1152      public void stopRunning()
1153      {
1154        stopRequested.set(true);
1155        sleeper.wakeup();
1156    
1157        final Thread t = runningThread;
1158        if (t != null)
1159        {
1160          try
1161          {
1162            t.join();
1163          }
1164          catch (final Exception e)
1165          {
1166            debugException(e);
1167          }
1168        }
1169      }
1170    
1171    
1172    
1173      /**
1174       * Retrieves the maximum number of outstanding requests that may be in
1175       * progress at any time, if appropriate.
1176       *
1177       * @return  The maximum number of outstanding requests that may be in progress
1178       *          at any time, or -1 if the tool was not configured to perform
1179       *          asynchronous searches with a maximum number of outstanding
1180       *          requests.
1181       */
1182      int getMaxOutstandingRequests()
1183      {
1184        if (maxOutstandingRequests.isPresent())
1185        {
1186          return maxOutstandingRequests.getValue();
1187        }
1188        else
1189        {
1190          return -1;
1191        }
1192      }
1193    
1194    
1195    
1196      /**
1197       * {@inheritDoc}
1198       */
1199      @Override()
1200      public LinkedHashMap<String[],String> getExampleUsages()
1201      {
1202        final LinkedHashMap<String[],String> examples =
1203             new LinkedHashMap<String[],String>(2);
1204    
1205        String[] args =
1206        {
1207          "--hostname", "server.example.com",
1208          "--port", "389",
1209          "--bindDN", "uid=admin,dc=example,dc=com",
1210          "--bindPassword", "password",
1211          "--baseDN", "dc=example,dc=com",
1212          "--scope", "sub",
1213          "--filter", "(uid=user.[1-1000000])",
1214          "--attribute", "givenName",
1215          "--attribute", "sn",
1216          "--attribute", "mail",
1217          "--numThreads", "10"
1218        };
1219        String description =
1220             "Test search performance by searching randomly across a set " +
1221             "of one million users located below 'dc=example,dc=com' with ten " +
1222             "concurrent threads.  The entries returned to the client will " +
1223             "include the givenName, sn, and mail attributes.";
1224        examples.put(args, description);
1225    
1226        args = new String[]
1227        {
1228          "--generateSampleRateFile", "variable-rate-data.txt"
1229        };
1230        description =
1231             "Generate a sample variable rate definition file that may be used " +
1232             "in conjunction with the --variableRateData argument.  The sample " +
1233             "file will include comments that describe the format for data to be " +
1234             "included in this file.";
1235        examples.put(args, description);
1236    
1237        return examples;
1238      }
1239    }