mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Gaetan Boismal
27.32.2016 df993e4e7a2b5af0c8e0907a80e1a4cef10ee56d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Portions Copyright 2015-2016 ForgeRock AS.
 */
package org.opends.server.backends.pluggable;
 
import static org.opends.messages.ToolMessages.*;
import static org.opends.server.util.StaticUtils.*;
 
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.cli.Utils.*;
 
import java.io.OutputStream;
import java.io.PrintStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.config.SizeUnit;
import org.forgerock.opendj.config.server.ConfigException;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.util.Option;
import org.forgerock.util.Options;
import org.opends.server.admin.std.server.BackendCfg;
import org.opends.server.admin.std.server.PluggableBackendCfg;
import org.opends.server.api.Backend;
import org.opends.server.backends.pluggable.spi.Cursor;
import org.opends.server.backends.pluggable.spi.ReadOperation;
import org.opends.server.backends.pluggable.spi.ReadableTransaction;
import org.opends.server.backends.pluggable.spi.StorageRuntimeException;
import org.opends.server.backends.pluggable.spi.TreeName;
import org.opends.server.core.CoreConfigManager;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
import org.opends.server.core.LockFileManager;
import org.opends.server.extensions.ConfigFileHandler;
import org.opends.server.loggers.JDKLogging;
import org.opends.server.tools.BackendToolUtils;
import org.opends.server.types.DN;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.InitializationException;
import org.opends.server.types.NullOutputStream;
import org.opends.server.util.BuildVersion;
import org.opends.server.util.StaticUtils;
 
import com.forgerock.opendj.cli.Argument;
import com.forgerock.opendj.cli.ArgumentException;
import com.forgerock.opendj.cli.BooleanArgument;
import com.forgerock.opendj.cli.CommonArguments;
import com.forgerock.opendj.cli.IntegerArgument;
import com.forgerock.opendj.cli.StringArgument;
import com.forgerock.opendj.cli.SubCommand;
import com.forgerock.opendj.cli.SubCommandArgumentParser;
import com.forgerock.opendj.cli.TableBuilder;
import com.forgerock.opendj.cli.TextTablePrinter;
 
/**
 * This program provides a utility that may be used to debug a Pluggable Backend.
 * This tool provides the ability to:
 * <ul>
 * <li>list root containers</li>
 * <li>list entry containers</li>
 * <li>list Trees in a Backend or Storage</li>
 * <li>gather information about Backend indexes</li>
 * <li>dump the contents of a Tree either at the Backend or the Storage layer.</li>
 * </ul>
 * This will be a process that is intended to run outside of Directory Server and not
 * internally within the server process (e.g., via the tasks interface); it still
 * requires configuration information and access to Directory Server instance data.
 */
public class BackendStat
{
  /**
   * Collects all necessary interaction interfaces with either a Backend using TreeNames
   * or a storage using Trees.
   */
  private interface TreeKeyValue
  {
    /**
     * Returns a key given a string representation of it.
     *
     * @param data a string representation of the key.
     *             Prefixing with "0x" will interpret the rest of the string as an hex dump
     *             of the intended value.
     * @return a key given a string representation of it
     */
    ByteString getTreeKey(String data);
 
    /**
     * Returns a printable string for the given key.
     *
     * @param key a key from the Tree
     * @return a printable string for the given key
     */
    String keyDecoder(ByteString key);
 
    /**
     * Returns a printable string for the given value.
     *
     * @param value a value from the tree
     * @return a printable string for the given value
     */
    String valueDecoder(ByteString value);
 
    /**
     * Returns the TreeName for this storage Tree.
     *
     * @return the TreeName for this storage Tree
     */
    TreeName getTreeName();
  }
 
  /** Stays at the storage level when cursoring Trees. */
  private static class StorageTreeKeyValue implements TreeKeyValue
  {
    private final TreeName treeName;
 
    private StorageTreeKeyValue(TreeName treeName)
    {
      this.treeName = treeName;
    }
 
    @Override
    public TreeName getTreeName()
    {
      return treeName;
    }
 
    @Override
    public ByteString getTreeKey(String data)
    {
      return ByteString.valueOfUtf8(data);
    }
 
    @Override
    public String keyDecoder(ByteString key)
    {
      throw new UnsupportedOperationException(ERR_BACKEND_TOOL_DECODER_NOT_AVAILABLE.get().toString());
    }
 
    @Override
    public String valueDecoder(ByteString value)
    {
      throw new UnsupportedOperationException(ERR_BACKEND_TOOL_DECODER_NOT_AVAILABLE.get().toString());
    }
  }
 
  /** Delegate key semantics to the backend. */
  private static class BackendTreeKeyValue implements TreeKeyValue
  {
    private final TreeName name;
    private final Tree tree;
 
    private BackendTreeKeyValue(Tree tree)
    {
      this.tree = tree;
      this.name = tree.getName();
    }
 
    @Override
    public ByteString getTreeKey(String data)
    {
      if (data.length() == 0)
      {
        return ByteString.empty();
      }
      return tree.generateKey(data);
    }
 
    @Override
    public String keyDecoder(ByteString key)
    {
      return tree.keyToString(key);
    }
 
    @Override
    public String valueDecoder(ByteString value)
    {
      return tree.valueToString(value);
    }
 
    @Override
    public TreeName getTreeName()
    {
      return name;
    }
  }
 
  /** Statistics collector. */
  private class TreeStats
  {
    private final long count;
    private final long totalKeySize;
    private final long totalDataSize;
 
    private TreeStats(long count, long tks, long tds)
    {
      this.count = count;
      this.totalKeySize = tks;
      this.totalDataSize = tds;
    }
  }
 
  private static final Option<Boolean> DUMP_DECODE_VALUE = Option.withDefault(true);
  private static final Option<Boolean> DUMP_STATS_ONLY = Option.withDefault(false);
  private static final Option<Boolean> DUMP_SINGLE_LINE = Option.withDefault(false);
  private static final Option<Argument> DUMP_MIN_KEY_VALUE = Option.of(Argument.class, null);
  private static final Option<Argument> DUMP_MAX_KEY_VALUE = Option.of(Argument.class, null);
  private static final Option<Boolean> DUMP_MIN_KEY_VALUE_IS_HEX = Option.withDefault(false);
  private static final Option<Boolean> DUMP_MAX_KEY_VALUE_IS_HEX = Option.withDefault(false);
  private static final Option<Integer> DUMP_MIN_DATA_SIZE = Option.of(Integer.class, 0);
  private static final Option<Integer> DUMP_MAX_DATA_SIZE = Option.of(Integer.class, Integer.MAX_VALUE);
  private static final Option<Integer> DUMP_INDENT = Option.of(Integer.class, 4);
 
  // Sub-command names.
  private static final String LIST_BACKENDS = "list-backends";
  private static final String LIST_BASE_DNS = "list-base-dns";
  private static final String LIST_INDEXES = "list-indexes";
  private static final String SHOW_INDEX_STATUS = "show-index-status";
  private static final String DUMP_INDEX = "dump-index";
  private static final String LIST_RAW_DBS = "list-raw-dbs";
  private static final String DUMP_RAW_DB = "dump-raw-db";
 
  private static final String BACKENDID_NAME = "backendid";
  private static final String BACKENDID = "backendID";
  private static final String BASEDN_NAME = "basedn";
  private static final String BASEDN = "baseDN";
  private static final String USESIUNITS_NAME = "usesiunits";
  private static final String USESIUNITS = "useSIUnits";
  private static final String MAXDATASIZE_NAME = "maxdatasize";
  private static final String MAXDATASIZE = "maxDataSize";
  private static final String MAXKEYVALUE_NAME = "maxkeyvalue";
  private static final String MAXKEYVALUE = "maxKeyValue";
  private static final String MAXHEXKEYVALUE_NAME = "maxhexkeyvalue";
  private static final String MAXHEXKEYVALUE = "maxHexKeyValue";
  private static final String MINDATASIZE_NAME = "mindatasize";
  private static final String MINDATASIZE = "minDataSize";
  private static final String MINKEYVALUE_NAME = "minkeyvalue";
  private static final String MINKEYVALUE = "minKeyValue";
  private static final String MINHEXKEYVALUE_NAME = "minhexkeyvalue";
  private static final String MINHEXKEYVALUE = "minHexKeyValue";
  private static final String SKIPDECODE_NAME = "skipdecode";
  private static final String SKIPDECODE = "skipDecode";
  private static final String STATSONLY_NAME = "statsonly";
  private static final String STATSONLY = "statsOnly";
  private static final String INDEXNAME_NAME = "indexname";
  private static final String INDEXNAME = "indexName";
  private static final String DBNAME_NAME = "dbname";
  private static final String DBNAME = "dbName";
  private static final String SINGLELINE_NAME = "singleline";
  private static final String SINGLELINE = "singleLine";
 
  private static final String HEXDUMP_LINE_FORMAT = "%s%s %s%n";
 
  /** The error stream which this application should use. */
  private final PrintStream err;
  /** The output stream which this application should use. */
  private final PrintStream out;
 
  /** The command-line argument parser. */
  private final SubCommandArgumentParser parser;
  /** The argument which should be used to request usage information. */
  private BooleanArgument showUsageArgument;
  /** The argument which should be used to specify the config class. */
  private StringArgument configClass;
  /** The argument which should be used to specify the config file. */
  private StringArgument configFile;
 
  /** Flag indicating whether or not the sub-commands have already been initialized. */
  private boolean subCommandsInitialized;
  /** Flag indicating whether or not the global arguments have already been initialized. */
  private boolean globalArgumentsInitialized;
 
  private DirectoryServer directoryServer;
 
  /**
   * Provides the command-line arguments to the main application for
   * processing.
   *
   * @param args The set of command-line arguments provided to this
   *             program.
   */
  public static void main(String[] args)
  {
    int exitCode = main(args, System.out, System.err);
    if (exitCode != 0)
    {
      System.exit(filterExitCode(exitCode));
    }
  }
 
  /**
   * Provides the command-line arguments to the main application for
   * processing and returns the exit code as an integer.
   *
   * @param args      The set of command-line arguments provided to this
   *                  program.
   * @param outStream The output stream for standard output.
   * @param errStream The output stream for standard error.
   * @return Zero to indicate that the program completed successfully,
   * or non-zero to indicate that an error occurred.
   */
  public static int main(String[] args, OutputStream outStream, OutputStream errStream)
  {
    BackendStat app = new BackendStat(outStream, errStream);
    return app.run(args);
  }
 
  /**
   * Creates a new dsconfig application instance.
   *
   * @param out The application output stream.
   * @param err The application error stream.
   */
  public BackendStat(OutputStream out, OutputStream err)
  {
    this.out = NullOutputStream.wrapOrNullStream(out);
    this.err = NullOutputStream.wrapOrNullStream(err);
    JDKLogging.disableLogging();
 
    LocalizableMessage toolDescription = INFO_DESCRIPTION_BACKEND_TOOL.get();
    this.parser = new SubCommandArgumentParser(getClass().getName(), toolDescription, false);
    this.parser.setShortToolDescription(REF_SHORT_DESC_BACKEND_TOOL.get());
    this.parser.setVersionHandler(new DirectoryServerVersionHandler());
  }
 
  /**
   * Registers the global arguments with the argument parser.
   *
   * @throws ArgumentException If a global argument could not be registered.
   */
  private void initializeGlobalArguments() throws ArgumentException
  {
    if (!globalArgumentsInitialized)
    {
      configClass =
              StringArgument.builder(OPTION_LONG_CONFIG_CLASS)
                      .shortIdentifier(OPTION_SHORT_CONFIG_CLASS)
                      .description(INFO_DESCRIPTION_CONFIG_CLASS.get())
                      .hidden()
                      .required()
                      .defaultValue(ConfigFileHandler.class.getName())
                      .valuePlaceholder(INFO_CONFIGCLASS_PLACEHOLDER.get())
                      .buildArgument();
      configFile =
              StringArgument.builder("configFile")
                      .shortIdentifier('f')
                      .description(INFO_DESCRIPTION_CONFIG_FILE.get())
                      .hidden()
                      .required()
                      .valuePlaceholder(INFO_CONFIGFILE_PLACEHOLDER.get())
                      .buildArgument();
 
      showUsageArgument = CommonArguments.getShowUsage();
 
      // Register the global arguments.
      parser.addGlobalArgument(showUsageArgument);
      parser.setUsageArgument(showUsageArgument, out);
      parser.addGlobalArgument(configClass);
      parser.addGlobalArgument(configFile);
 
      globalArgumentsInitialized = true;
    }
  }
 
  /**
   * Registers the sub-commands with the argument parser.
   *
   * @throws ArgumentException If a sub-command could not be created.
   */
  private void initializeSubCommands() throws ArgumentException
  {
    if (!subCommandsInitialized)
    {
      // list-backends
      new SubCommand(parser, LIST_BACKENDS,
                           INFO_DESCRIPTION_BACKEND_TOOL_SUBCMD_LIST_BACKENDS.get());
 
      // list-base-dns
      addBackendArgument(new SubCommand(
              parser, LIST_BASE_DNS, INFO_DESCRIPTION_BACKEND_DEBUG_SUBCMD_LIST_ENTRY_CONTAINERS.get()));
 
      // list-indexes
      final SubCommand listIndexes = new SubCommand(
              parser, LIST_INDEXES, INFO_DESCRIPTION_BACKEND_TOOL_SUBCMD_LIST_INDEXES.get());
      addBackendBaseDNArguments(listIndexes, false, false);
 
      // show-index-status
      final SubCommand showIndexStatus = new SubCommand(
              parser, SHOW_INDEX_STATUS, INFO_DESCRIPTION_BACKEND_DEBUG_SUBCMD_LIST_INDEX_STATUS.get());
      showIndexStatus.setDocDescriptionSupplement(SUPPLEMENT_DESCRIPTION_BACKEND_TOOL_SUBCMD_LIST_INDEX_STATUS.get());
      addBackendBaseDNArguments(showIndexStatus, true, true);
 
      // dump-index
      final SubCommand dumpIndex = new SubCommand(
              parser, DUMP_INDEX, INFO_DESCRIPTION_BACKEND_TOOL_SUBCMD_DUMP_INDEX.get());
      addBackendBaseDNArguments(dumpIndex, true, false);
      dumpIndex.addArgument(StringArgument.builder(INDEXNAME)
              .shortIdentifier('i')
              .description(INFO_DESCRIPTION_BACKEND_DEBUG_INDEX_NAME.get())
              .required()
              .valuePlaceholder(INFO_INDEX_NAME_PLACEHOLDER.get())
              .buildArgument());
      addDumpSubCommandArguments(dumpIndex);
      dumpIndex.addArgument(BooleanArgument.builder(SKIPDECODE)
              .shortIdentifier('p')
              .description(INFO_DESCRIPTION_BACKEND_DEBUG_SKIP_DECODE.get())
              .buildArgument());
 
      // list-raw-dbs
      final SubCommand listRawDBs = new SubCommand(
              parser, LIST_RAW_DBS, INFO_DESCRIPTION_BACKEND_TOOL_SUBCMD_LIST_RAW_DBS.get());
      addBackendArgument(listRawDBs);
      listRawDBs.addArgument(BooleanArgument.builder(USESIUNITS)
              .shortIdentifier('u')
              .description(INFO_DESCRIPTION_BACKEND_TOOL_USE_SI_UNITS.get())
              .buildArgument());
 
      // dump-raw-db
      final SubCommand dumbRawDB = new SubCommand(
              parser, DUMP_RAW_DB, INFO_DESCRIPTION_BACKEND_TOOL_SUBCMD_DUMP_RAW_DB.get());
      addBackendArgument(dumbRawDB);
      dumbRawDB.addArgument(StringArgument.builder(DBNAME)
              .shortIdentifier('d')
              .description(INFO_DESCRIPTION_BACKEND_DEBUG_RAW_DB_NAME.get())
              .required()
              .valuePlaceholder(INFO_DATABASE_NAME_PLACEHOLDER.get())
              .buildArgument());
      addDumpSubCommandArguments(dumbRawDB);
      dumbRawDB.addArgument(BooleanArgument.builder(SINGLELINE)
              .shortIdentifier('l')
              .description(INFO_DESCRIPTION_BACKEND_TOOL_SUBCMD_SINGLE_LINE.get())
              .buildArgument());
 
      subCommandsInitialized = true;
    }
  }
 
  private void addBackendArgument(SubCommand sub) throws ArgumentException
  {
    sub.addArgument(
            StringArgument.builder(BACKENDID)
                    .shortIdentifier('n')
                    .description(INFO_DESCRIPTION_BACKEND_DEBUG_BACKEND_ID.get())
                    .required()
                    .valuePlaceholder(INFO_BACKENDNAME_PLACEHOLDER.get())
                    .buildArgument());
  }
 
  private void addBackendBaseDNArguments(SubCommand sub, boolean isRequired, boolean isMultiValued)
      throws ArgumentException
  {
    addBackendArgument(sub);
    final StringArgument.Builder builder = StringArgument.builder(BASEDN)
            .shortIdentifier('b')
            .description(INFO_DESCRIPTION_BACKEND_DEBUG_BASE_DN.get())
            .valuePlaceholder(INFO_BASEDN_PLACEHOLDER.get());
    if (isMultiValued)
    {
      builder.multiValued();
    }
    if (isRequired) {
      builder.required();
    }
    sub.addArgument(builder.buildArgument());
  }
 
  private void addDumpSubCommandArguments(SubCommand sub) throws ArgumentException
  {
    sub.addArgument(BooleanArgument.builder(STATSONLY)
            .shortIdentifier('q')
            .description(INFO_DESCRIPTION_BACKEND_DEBUG_STATS_ONLY.get())
            .buildArgument());
 
    sub.addArgument(newMaxKeyValueArg());
    sub.addArgument(newMinKeyValueArg());
    sub.addArgument(StringArgument.builder(MAXHEXKEYVALUE)
            .shortIdentifier('X')
            .description(INFO_DESCRIPTION_BACKEND_DEBUG_MAX_KEY_VALUE.get())
            .valuePlaceholder(INFO_MAX_KEY_VALUE_PLACEHOLDER.get())
            .buildArgument());
 
    sub.addArgument(StringArgument.builder(MINHEXKEYVALUE)
            .shortIdentifier('x')
            .description(INFO_DESCRIPTION_BACKEND_DEBUG_MIN_KEY_VALUE.get())
            .valuePlaceholder(INFO_MIN_KEY_VALUE_PLACEHOLDER.get())
            .buildArgument());
 
    sub.addArgument(IntegerArgument.builder(MAXDATASIZE)
            .shortIdentifier('S')
            .description(INFO_DESCRIPTION_BACKEND_DEBUG_MAX_DATA_SIZE.get())
            .defaultValue(-1)
            .valuePlaceholder(INFO_MAX_DATA_SIZE_PLACEHOLDER.get())
            .buildArgument());
 
    sub.addArgument(IntegerArgument.builder(MINDATASIZE)
            .shortIdentifier('s')
            .description(INFO_DESCRIPTION_BACKEND_DEBUG_MIN_DATA_SIZE.get())
            .defaultValue(-1)
            .valuePlaceholder(INFO_MIN_DATA_SIZE_PLACEHOLDER.get())
            .buildArgument());
  }
 
  private StringArgument newMinKeyValueArg() throws ArgumentException
  {
    return StringArgument.builder(MINKEYVALUE)
            .shortIdentifier('k')
            .description(INFO_DESCRIPTION_BACKEND_DEBUG_MIN_KEY_VALUE.get())
            .valuePlaceholder(INFO_MIN_KEY_VALUE_PLACEHOLDER.get())
            .buildArgument();
  }
 
  private StringArgument newMaxKeyValueArg() throws ArgumentException
  {
    return StringArgument.builder(MAXKEYVALUE)
            .shortIdentifier('K')
            .description(INFO_DESCRIPTION_BACKEND_DEBUG_MAX_KEY_VALUE.get())
            .valuePlaceholder(INFO_MAX_KEY_VALUE_PLACEHOLDER.get())
            .buildArgument();
  }
 
  /**
   * Parses the provided command-line arguments and makes the
   * appropriate changes to the Directory Server configuration.
   *
   * @param args The command-line arguments provided to this program.
   * @return The exit code from the configuration processing. A
   * nonzero value indicates that there was some kind of
   * problem during the configuration processing.
   */
  private int run(String[] args)
  {
    // Register global arguments and sub-commands.
    try
    {
      initializeGlobalArguments();
      initializeSubCommands();
    }
    catch (ArgumentException e)
    {
      printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(e.getMessage()));
      return 1;
    }
 
    try
    {
      parser.parseArguments(args);
    }
    catch (ArgumentException ae)
    {
      parser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
      return 1;
    }
 
    if (parser.usageOrVersionDisplayed())
    {
      return 0;
    }
 
    if (parser.getSubCommand() == null)
    {
      parser.displayMessageAndUsageReference(err, ERR_BACKEND_DEBUG_MISSING_SUBCOMMAND.get());
      return 1;
    }
 
    try
    {
      BuildVersion.checkVersionMismatch();
    }
    catch (InitializationException e)
    {
      printWrappedText(err, e.getMessageObject());
      return 1;
    }
 
    // Perform the initial bootstrap of the Directory Server and process the configuration.
    directoryServer = DirectoryServer.getInstance();
    try
    {
      DirectoryServer.bootstrapClient();
      DirectoryServer.initializeJMX();
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_SERVER_BOOTSTRAP_ERROR.get(getStartUpExceptionMessage(e)));
      return 1;
    }
 
    try
    {
      directoryServer.initializeConfiguration(configClass.getValue(), configFile.getValue());
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_CANNOT_LOAD_CONFIG.get(getStartUpExceptionMessage(e)));
      return 1;
    }
 
    try
    {
      directoryServer.initializeSchema();
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_CANNOT_LOAD_SCHEMA.get(getStartUpExceptionMessage(e)));
      return 1;
    }
 
    try
    {
      CoreConfigManager coreConfigManager = new CoreConfigManager(directoryServer.getServerContext());
      coreConfigManager.initializeCoreConfig();
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_CANNOT_INITIALIZE_CORE_CONFIG.get(getStartUpExceptionMessage(e)));
      return 1;
    }
 
    try
    {
      directoryServer.initializeCryptoManager();
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_CANNOT_INITIALIZE_CRYPTO_MANAGER.get(getStartUpExceptionMessage(e)));
      return 1;
    }
 
    SubCommand subCommand = parser.getSubCommand();
    if (LIST_BACKENDS.equals(subCommand.getName()))
    {
      return listRootContainers();
    }
    BackendImpl backend = getBackendById(subCommand.getArgument(BACKENDID_NAME));
    if (backend == null)
    {
      return 1;
    }
    RootContainer rootContainer = getAndLockRootContainer(backend);
    if (rootContainer == null)
    {
      return 1;
    }
    try
    {
      switch (subCommand.getName())
      {
      case LIST_BASE_DNS:
        return listBaseDNs(rootContainer);
      case LIST_RAW_DBS:
        return listRawDBs(rootContainer, subCommand.getArgument(USESIUNITS_NAME));
      case LIST_INDEXES:
        return listIndexes(rootContainer, backend, subCommand.getArgument(BASEDN_NAME));
      case DUMP_RAW_DB:
        return dumpTree(rootContainer, backend, subCommand, false);
      case DUMP_INDEX:
        return dumpTree(rootContainer, backend, subCommand, true);
      case SHOW_INDEX_STATUS:
        return showIndexStatus(rootContainer, backend, subCommand.getArgument(BASEDN_NAME));
      default:
        return 1;
      }
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_EXECUTING_COMMAND.get(subCommand.getName(),
          StaticUtils.stackTraceToString(e)));
      return 1;
    }
    finally
    {
      close(rootContainer);
      releaseExclusiveLock(backend);
    }
  }
 
  private String getStartUpExceptionMessage(Exception e)
  {
    if (e instanceof ConfigException || e instanceof InitializationException)
    {
      return e.getMessage();
    }
    return getExceptionMessage(e).toString();
  }
 
  private int dumpTree(RootContainer rc, BackendImpl backend, SubCommand subCommand, boolean isBackendTree)
      throws ArgumentException, DirectoryException
  {
    Options options = Options.defaultOptions();
    if (!setDumpTreeOptionArguments(subCommand, options))
    {
      return 1;
    }
    if (isBackendTree)
    {
      return dumpBackendTree(rc, backend, subCommand.getArgument(BASEDN_NAME), subCommand.getArgument(INDEXNAME_NAME),
          options);
    }
    return dumpStorageTree(rc, backend, subCommand.getArgument(DBNAME_NAME), options);
  }
 
  private boolean setDumpTreeOptionArguments(SubCommand subCommand, Options options) throws ArgumentException
  {
    try
    {
      Argument arg = subCommand.getArgument(SINGLELINE_NAME);
      if (arg != null && arg.isPresent())
      {
        options.set(DUMP_SINGLE_LINE, true);
      }
      if (subCommand.getArgument(STATSONLY_NAME).isPresent())
      {
        options.set(DUMP_STATS_ONLY, true);
      }
      arg = subCommand.getArgument(SKIPDECODE_NAME);
      if (arg == null || arg.isPresent())
      {
        options.set(DUMP_DECODE_VALUE, false);
      }
      if (subCommand.getArgument(MINDATASIZE_NAME).isPresent())
      {
        options.set(DUMP_MIN_DATA_SIZE, subCommand.getArgument(MINDATASIZE_NAME).getIntValue());
      }
      if (subCommand.getArgument(MAXDATASIZE_NAME).isPresent())
      {
        options.set(DUMP_MAX_DATA_SIZE, subCommand.getArgument(MAXDATASIZE_NAME).getIntValue());
      }
 
      options.set(DUMP_MIN_KEY_VALUE, subCommand.getArgument(MINKEYVALUE_NAME));
      if (subCommand.getArgument(MINHEXKEYVALUE_NAME).isPresent())
      {
        if (subCommand.getArgument(MINKEYVALUE_NAME).isPresent())
        {
          printWrappedText(err, ERR_BACKEND_TOOL_ONLY_ONE_MIN_KEY.get());
          return false;
        }
        options.set(DUMP_MIN_KEY_VALUE_IS_HEX, true);
        options.set(DUMP_MIN_KEY_VALUE, subCommand.getArgument(MINHEXKEYVALUE_NAME));
      }
 
      options.set(DUMP_MAX_KEY_VALUE, subCommand.getArgument(MAXKEYVALUE_NAME));
      if (subCommand.getArgument(MAXHEXKEYVALUE_NAME).isPresent())
      {
        if (subCommand.getArgument(MAXKEYVALUE_NAME).isPresent())
        {
          printWrappedText(err, ERR_BACKEND_TOOL_ONLY_ONE_MAX_KEY.get());
          return false;
        }
        options.set(DUMP_MAX_KEY_VALUE_IS_HEX, true);
        options.set(DUMP_MAX_KEY_VALUE, subCommand.getArgument(MAXHEXKEYVALUE_NAME));
      }
      return true;
    }
    catch (ArgumentException ae)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_PROCESSING_ARGUMENT.get(StaticUtils.stackTraceToString(ae)));
      throw ae;
    }
  }
 
  private int listRootContainers()
  {
    TableBuilder builder = new TableBuilder();
 
    builder.appendHeading(INFO_LABEL_BACKEND_DEBUG_BACKEND_ID.get());
    builder.appendHeading(INFO_LABEL_BACKEND_TOOL_STORAGE.get());
 
    final Map<PluggableBackendCfg, BackendImpl> pluggableBackends = getPluggableBackends();
    for (Map.Entry<PluggableBackendCfg, BackendImpl> backend : pluggableBackends.entrySet())
    {
      builder.startRow();
      builder.appendCell(backend.getValue().getBackendID());
      builder.appendCell(backend.getKey().getJavaClass());
    }
 
    builder.print(new TextTablePrinter(out));
    out.format(INFO_LABEL_BACKEND_TOOL_TOTAL.get(pluggableBackends.size()).toString());
 
    return 0;
  }
 
  private int listBaseDNs(RootContainer rc)
  {
    try
    {
      TableBuilder builder = new TableBuilder();
      builder.appendHeading(INFO_LABEL_BACKEND_DEBUG_BASE_DN.get());
      Collection<EntryContainer> entryContainers = rc.getEntryContainers();
      for (EntryContainer ec : entryContainers)
      {
        builder.startRow();
        builder.appendCell(ec.getBaseDN());
      }
 
      builder.print(new TextTablePrinter(out));
      out.format(INFO_LABEL_BACKEND_TOOL_TOTAL.get(entryContainers.size()).toString());
 
      return 0;
    }
    catch (StorageRuntimeException de)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_ERROR_LISTING_BASE_DNS.get(stackTraceToSingleLineString(de)));
      return 1;
    }
  }
 
  private int listRawDBs(RootContainer rc, Argument useSIUnits)
  {
    try
    {
      TableBuilder builder = new TableBuilder();
 
      builder.appendHeading(INFO_LABEL_BACKEND_TOOL_RAW_DB_NAME.get());
      builder.appendHeading(INFO_LABEL_BACKEND_TOOL_TOTAL_KEYS.get());
      builder.appendHeading(INFO_LABEL_BACKEND_TOOL_KEYS_SIZE.get());
      builder.appendHeading(INFO_LABEL_BACKEND_TOOL_VALUES_SIZE.get());
      builder.appendHeading(INFO_LABEL_BACKEND_TOOL_TOTAL_SIZES.get());
 
      SortedSet<TreeName> treeNames = new TreeSet<>(rc.getStorage().listTrees());
      for (TreeName tree: treeNames)
      {
        builder.startRow();
        builder.appendCell(tree);
        appendStorageTreeStats(builder, rc, new StorageTreeKeyValue(tree), useSIUnits.isPresent());
      }
 
      builder.print(new TextTablePrinter(out));
      out.format(INFO_LABEL_BACKEND_TOOL_TOTAL.get(treeNames.size()).toString());
 
      return 0;
    }
    catch (StorageRuntimeException de)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_ERROR_LISTING_TREES.get(stackTraceToSingleLineString(de)));
      return 1;
    }
  }
 
  private void appendStorageTreeStats(TableBuilder builder, RootContainer rc, TreeKeyValue targetTree,
      boolean useSIUnit)
  {
    Options options = Options.defaultOptions();
    options.set(DUMP_STATS_ONLY, true);
    try
    {
      options.set(DUMP_MIN_KEY_VALUE, newMinKeyValueArg());
      options.set(DUMP_MAX_KEY_VALUE, newMaxKeyValueArg());
      TreeStats treeStats = cursorTreeToDump(rc, targetTree, options);
      builder.appendCell(treeStats.count);
      builder.appendCell(appendKeyValueSize(treeStats.totalKeySize, useSIUnit));
      builder.appendCell(appendKeyValueSize(treeStats.totalDataSize, useSIUnit));
      builder.appendCell(appendKeyValueSize(treeStats.totalKeySize + treeStats.totalDataSize, useSIUnit));
    }
    catch (Exception e)
    {
      appendStatsNoData(builder, 3);
    }
  }
 
  private String appendKeyValueSize(long size, boolean useSIUnit)
  {
    if (useSIUnit && size > SizeUnit.KILO_BYTES.getSize())
    {
      NumberFormat format = NumberFormat.getNumberInstance();
      format.setMaximumFractionDigits(2);
      SizeUnit unit = SizeUnit.getBestFitUnit(size);
      return format.format(unit.fromBytes(size)) + " " + unit;
    }
    else
    {
      return String.valueOf(size);
    }
  }
 
  private int listIndexes(RootContainer rc, BackendImpl backend, Argument baseDNArg) throws DirectoryException
  {
    DN base = null;
    if (baseDNArg.isPresent())
    {
      base = getBaseDNFromArg(baseDNArg);
    }
 
    try
    {
      TableBuilder builder = new TableBuilder();
      int count = 0;
 
      builder.appendHeading(INFO_LABEL_BACKEND_DEBUG_INDEX_NAME.get());
      builder.appendHeading(INFO_LABEL_BACKEND_TOOL_RAW_DB_NAME.get());
      builder.appendHeading(INFO_LABEL_BACKEND_DEBUG_INDEX_TYPE.get());
      builder.appendHeading(INFO_LABEL_BACKEND_DEBUG_RECORD_COUNT.get());
 
      if (base != null)
      {
        EntryContainer ec = rc.getEntryContainer(base);
        if (ec == null)
        {
          return printEntryContainerError(backend, base);
        }
        count = appendTreeRows(builder, ec);
      }
      else
      {
        for (EntryContainer ec : rc.getEntryContainers())
        {
          builder.startRow();
          builder.appendCell("Base DN: " + ec.getBaseDN());
          count += appendTreeRows(builder, ec);
        }
      }
 
      builder.print(new TextTablePrinter(out));
      out.format(INFO_LABEL_BACKEND_TOOL_TOTAL.get(count).toString());
 
      return 0;
    }
    catch (StorageRuntimeException de)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_ERROR_LISTING_TREES.get(stackTraceToSingleLineString(de)));
      return 1;
    }
  }
 
  private int printEntryContainerError(BackendImpl backend, DN base)
  {
    printWrappedText(err, ERR_BACKEND_DEBUG_NO_ENTRY_CONTAINERS_FOR_BASE_DN.get(base, backend.getBackendID()));
    return 1;
  }
 
  private DN getBaseDNFromArg(Argument baseDNArg) throws DirectoryException
  {
    try
    {
      return DN.valueOf(baseDNArg.getValue());
    }
    catch (DirectoryException de)
    {
      printWrappedText(err, ERR_BACKEND_DEBUG_DECODE_BASE_DN.get(baseDNArg.getValue(), getExceptionMessage(de)));
      throw de;
    }
  }
 
  private RootContainer getAndLockRootContainer(BackendImpl backend)
  {
    try
    {
      String lockFile = LockFileManager.getBackendLockFileName(backend);
      StringBuilder failureReason = new StringBuilder();
      if (!LockFileManager.acquireExclusiveLock(lockFile, failureReason))
      {
        printWrappedText(err, ERR_BACKEND_DEBUG_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason));
        return null;
      }
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_BACKEND_DEBUG_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), StaticUtils
          .getExceptionMessage(e)));
      return null;
    }
 
    try
    {
      return backend.getReadOnlyRootContainer();
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_ERROR_INITIALIZING_BACKEND.get(backend.getBackendID(),
          stackTraceToSingleLineString(e)));
      return null;
    }
  }
 
  private int appendTreeRows(TableBuilder builder, EntryContainer ec)
  {
    int count = 0;
    for (final Tree tree : ec.listTrees())
    {
      builder.startRow();
      builder.appendCell(tree.getName().getIndexId());
      builder.appendCell(tree.getName());
      builder.appendCell(tree.getClass().getSimpleName());
      builder.appendCell(getTreeRecordCount(ec, tree));
      count++;
    }
    return count;
  }
 
  private long getTreeRecordCount(EntryContainer ec, final Tree tree)
  {
    try
    {
      return ec.getRootContainer().getStorage().read(new ReadOperation<Long>()
      {
        @Override
        public Long run(ReadableTransaction txn) throws Exception
        {
          return tree.getRecordCount(txn);
        }
      });
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_ERROR_READING_TREE.get(stackTraceToSingleLineString(e)));
      return -1;
    }
  }
 
  private void close(RootContainer rc)
  {
    try
    {
      rc.close();
    }
    catch (StorageRuntimeException ignored)
    {
      // Ignore.
    }
  }
 
  private void releaseExclusiveLock(BackendImpl backend)
  {
    try
    {
      String lockFile = LockFileManager.getBackendLockFileName(backend);
      StringBuilder failureReason = new StringBuilder();
      if (!LockFileManager.releaseLock(lockFile, failureReason))
      {
        printWrappedText(err, WARN_BACKEND_DEBUG_CANNOT_UNLOCK_BACKEND.get(backend.getBackendID(), failureReason));
      }
    }
    catch (Exception e)
    {
      printWrappedText(err, WARN_BACKEND_DEBUG_CANNOT_UNLOCK_BACKEND.get(backend.getBackendID(),
          StaticUtils.getExceptionMessage(e)));
    }
  }
 
  private BackendImpl getBackendById(Argument backendIdArg)
  {
    final String backendID = backendIdArg.getValue();
    final Map<PluggableBackendCfg, BackendImpl> pluggableBackends = getPluggableBackends();
 
    for (Map.Entry<PluggableBackendCfg, BackendImpl> backend : pluggableBackends.entrySet())
    {
      final BackendImpl b = backend.getValue();
      if (b.getBackendID().equalsIgnoreCase(backendID))
      {
        try
        {
          b.configureBackend(backend.getKey(), directoryServer.getServerContext());
          return b;
        }
        catch (ConfigException ce)
        {
          printWrappedText(err, ERR_BACKEND_TOOL_CANNOT_CONFIGURE_BACKEND.get(backendID, ce));
          return null;
        }
      }
    }
 
    printWrappedText(err, ERR_BACKEND_DEBUG_NO_BACKENDS_FOR_ID.get(backendID));
    return null;
  }
 
  private int showIndexStatus(RootContainer rc, BackendImpl backend, Argument baseDNArg) throws DirectoryException
  {
    DN base = getBaseDNFromArg(baseDNArg);
 
    try
    {
      // Create a table of their properties.
      TableBuilder builder = new TableBuilder();
      int count = 0;
 
      builder.appendHeading(INFO_LABEL_BACKEND_DEBUG_INDEX_NAME.get());
      builder.appendHeading(INFO_LABEL_BACKEND_TOOL_RAW_DB_NAME.get());
      builder.appendHeading(INFO_LABEL_BACKEND_DEBUG_INDEX_STATUS.get());
      builder.appendHeading(INFO_LABEL_BACKEND_DEBUG_RECORD_COUNT.get());
      builder.appendHeading(INFO_LABEL_BACKEND_TOOL_INDEX_UNDEFINED_RECORD_COUNT.get());
      builder.appendHeading(LocalizableMessage.raw("95%"));
      builder.appendHeading(LocalizableMessage.raw("90%"));
      builder.appendHeading(LocalizableMessage.raw("85%"));
 
      EntryContainer ec = rc.getEntryContainer(base);
      if (ec == null)
      {
        return printEntryContainerError(backend, base);
      }
 
      Map<Index, StringBuilder> undefinedKeys = new HashMap<>();
      for (AttributeIndex attrIndex : ec.getAttributeIndexes())
      {
        for (AttributeIndex.MatchingRuleIndex index : attrIndex.getNameToIndexes().values())
        {
          builder.startRow();
          builder.appendCell(index.getName().getIndexId());
          builder.appendCell(index.getName());
          builder.appendCell(index.isTrusted());
          if (index.isTrusted())
          {
            appendIndexStats(builder, ec, index, undefinedKeys);
          }
          else
          {
            appendStatsNoData(builder, 5);
          }
          count++;
        }
      }
 
      for (VLVIndex vlvIndex : ec.getVLVIndexes())
      {
        builder.startRow();
        builder.appendCell(vlvIndex.getName().getIndexId());
        builder.appendCell(vlvIndex.getName());
        builder.appendCell(vlvIndex.isTrusted());
        builder.appendCell(getTreeRecordCount(ec, vlvIndex));
        appendStatsNoData(builder, 4);
        count++;
      }
 
      builder.print(new TextTablePrinter(out));
      out.format(INFO_LABEL_BACKEND_TOOL_TOTAL.get(count).toString());
      for (Map.Entry<Index, StringBuilder> e : undefinedKeys.entrySet())
      {
        out.format(INFO_LABEL_BACKEND_TOOL_INDEX.get(e.getKey().getName()).toString());
        out.format(INFO_LABEL_BACKEND_TOOL_OVER_INDEX_LIMIT_KEYS.get(e.getValue()).toString());
      }
      return 0;
    }
    catch (StorageRuntimeException de)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_ERROR_READING_TREE.get(stackTraceToSingleLineString(de)));
      return 1;
    }
  }
 
  private void appendStatsNoData(TableBuilder builder, int columns)
  {
    while (columns > 0)
    {
      builder.appendCell("-");
      columns--;
    }
  }
 
  private void appendIndexStats(final TableBuilder builder, EntryContainer ec, final Index index,
      final Map<Index, StringBuilder> undefinedKeys)
  {
    final long entryLimit = index.getIndexEntryLimit();
 
    try
    {
      ec.getRootContainer().getStorage().read(new ReadOperation<Void>()
      {
        @Override
        public Void run(ReadableTransaction txn) throws Exception
        {
          long eighty = 0;
          long ninety = 0;
          long ninetyFive = 0;
          long undefined = 0;
          long count = 0;
          BackendTreeKeyValue keyDecoder = new BackendTreeKeyValue(index);
          try (Cursor<ByteString, EntryIDSet> cursor = index.openCursor(txn))
          {
            while (cursor.next())
            {
              count++;
              EntryIDSet entryIDSet;
              try
              {
                entryIDSet = cursor.getValue();
              }
              catch (Exception e)
              {
                continue;
              }
 
              if (entryIDSet.isDefined())
              {
                if (entryIDSet.size() >= entryLimit * 0.8)
                {
                  if (entryIDSet.size() >= entryLimit * 0.95)
                  {
                    ninetyFive++;
                  }
                  else if (entryIDSet.size() >= entryLimit * 0.9)
                  {
                    ninety++;
                  }
                  else
                  {
                    eighty++;
                  }
                }
              }
              else
              {
                undefined++;
                StringBuilder keyList = undefinedKeys.get(index);
                if (keyList == null)
                {
                  keyList = new StringBuilder();
                  undefinedKeys.put(index, keyList);
                }
                else
                {
                  keyList.append(" ");
                }
                keyList.append("[").append(keyDecoder.keyDecoder(cursor.getKey())).append("]");
              }
            }
          }
          builder.appendCell(count);
          builder.appendCell(undefined);
          builder.appendCell(ninetyFive);
          builder.appendCell(ninety);
          builder.appendCell(eighty);
          return null;
        }
      });
    }
    catch (Exception e)
    {
      appendStatsNoData(builder, 5);
      printWrappedText(err, ERR_BACKEND_TOOL_ERROR_READING_TREE.get(index.getName()));
    }
  }
 
  private int dumpStorageTree(RootContainer rc, BackendImpl backend, Argument treeNameArg, Options options)
  {
    TreeName targetTree = getStorageTreeName(treeNameArg, rc);
    if (targetTree == null)
    {
      printWrappedText(err,
          ERR_BACKEND_TOOL_NO_TREE_FOR_NAME_IN_STORAGE.get(treeNameArg.getValue(), backend.getBackendID()));
      return 1;
    }
 
    try
    {
      dumpActualTree(rc, new StorageTreeKeyValue(targetTree), options);
      return 0;
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_ERROR_READING_TREE.get(stackTraceToSingleLineString(e)));
      return 1;
    }
  }
 
  private TreeName getStorageTreeName(Argument treeNameArg, RootContainer rc)
  {
    for (TreeName tree : rc.getStorage().listTrees())
    {
      if (treeNameArg.getValue().equals(tree.toString()))
      {
        return tree;
      }
    }
    return null;
  }
 
  private int dumpBackendTree(RootContainer rc, BackendImpl backend, Argument baseDNArg, Argument treeNameArg,
      Options options) throws DirectoryException
  {
    DN base = getBaseDNFromArg(baseDNArg);
 
    EntryContainer ec = rc.getEntryContainer(base);
    if (ec == null)
    {
      return printEntryContainerError(backend, base);
    }
 
    Tree targetTree = getBackendTree(treeNameArg, ec);
    if (targetTree == null)
    {
      printWrappedText(err,
          ERR_BACKEND_TOOL_NO_TREE_FOR_NAME.get(treeNameArg.getValue(), base, backend.getBackendID()));
      return 1;
    }
 
    try
    {
      dumpActualTree(rc, new BackendTreeKeyValue(targetTree), options);
      return 0;
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_BACKEND_TOOL_ERROR_READING_TREE.get(stackTraceToSingleLineString(e)));
      return 1;
    }
  }
 
  private Tree getBackendTree(Argument treeNameArg, EntryContainer ec)
  {
    for (Tree tree : ec.listTrees())
    {
      if (treeNameArg.getValue().contains(tree.getName().getIndexId())
          || treeNameArg.getValue().equals(tree.getName().toString()))
      {
        return tree;
      }
    }
    return null;
  }
 
  private void dumpActualTree(RootContainer rc, final TreeKeyValue target, final Options options) throws Exception
  {
    TreeStats treeStats =  cursorTreeToDump(rc, target, options);
    out.format(INFO_LABEL_BACKEND_TOOL_TOTAL_RECORDS.get(treeStats.count).toString());
    if (treeStats.count > 0)
    {
      out.format(INFO_LABEL_BACKEND_TOOL_TOTAL_KEY_SIZE_AND_AVG.get(
          treeStats.totalKeySize, treeStats.totalKeySize / treeStats.count).toString());
      out.format(INFO_LABEL_BACKEND_TOOL_TOTAL_DATA_SIZE_AND_AVG.get(
          treeStats.totalDataSize, treeStats.totalDataSize / treeStats.count).toString());
    }
  }
 
  private TreeStats cursorTreeToDump(RootContainer rc, final TreeKeyValue target, final Options options)
      throws Exception
  {
    return rc.getStorage().read(new ReadOperation<TreeStats>()
      {
        @Override
        public TreeStats run(ReadableTransaction txn) throws Exception
        {
          long count = 0;
          long totalKeySize = 0;
          long totalDataSize = 0;
          try (final Cursor<ByteString, ByteString> cursor = txn.openCursor(target.getTreeName()))
          {
            ByteString key;
            ByteString maxKey = null;
            ByteString value;
 
            if (options.get(DUMP_MIN_KEY_VALUE).isPresent())
            {
              key = getMinOrMaxKey(options, DUMP_MIN_KEY_VALUE, DUMP_MIN_KEY_VALUE_IS_HEX);
              if (!cursor.positionToKeyOrNext(key))
              {
                return new TreeStats(0, 0, 0);
              }
            }
            else
            {
              if (!cursor.next())
              {
                return new TreeStats(0, 0, 0);
              }
            }
 
            if (options.get(DUMP_MAX_KEY_VALUE).isPresent())
            {
              maxKey = getMinOrMaxKey(options, DUMP_MAX_KEY_VALUE, DUMP_MAX_KEY_VALUE_IS_HEX);
            }
 
            do
            {
              key = cursor.getKey();
              if (maxKey != null && key.compareTo(maxKey) > 0)
              {
                break;
              }
              value = cursor.getValue();
              long valueLen = value.length();
              if (options.get(DUMP_MIN_DATA_SIZE) <= valueLen && valueLen <= options.get(DUMP_MAX_DATA_SIZE))
              {
                count++;
                int keyLen = key.length();
                totalKeySize += keyLen;
                totalDataSize += valueLen;
                if (!options.get(DUMP_STATS_ONLY))
                {
                  if (options.get(DUMP_DECODE_VALUE))
                  {
                    String k = target.keyDecoder(key);
                    String v = target.valueDecoder(value);
                    out.format(INFO_LABEL_BACKEND_TOOL_KEY_FORMAT.get(keyLen) + " %s%n"
                        + INFO_LABEL_BACKEND_TOOL_VALUE_FORMAT.get(valueLen) + " %s%n", k, v);
                  }
                  else
                  {
                    hexDumpRecord(key, value, out, options);
                  }
                }
              }
            }
            while (cursor.next());
          }
          catch (Exception e)
          {
            out.format(ERR_BACKEND_TOOL_CURSOR_AT_KEY_NUMBER.get(count, e.getCause()).toString());
            e.printStackTrace(out);
            out.format("%n");
            throw e;
          }
          return new TreeStats(count, totalKeySize, totalDataSize);
        }
 
      private ByteString getMinOrMaxKey(Options options, Option<Argument> keyOpt, Option<Boolean> isHexKey)
      {
        ByteString key;
        if (options.get(isHexKey))
        {
          key = ByteString.valueOfHex(options.get(keyOpt).getValue());
        }
        else
        {
          key = target.getTreeKey(options.get(keyOpt).getValue());
        }
        return key;
      }
    });
  }
 
  final void hexDumpRecord(ByteString key, ByteString value, PrintStream out, Options options)
  {
    if (options.get(DUMP_SINGLE_LINE))
    {
      out.format(INFO_LABEL_BACKEND_TOOL_KEY_FORMAT.get(key.length()) + " ");
      toHexDumpSingleLine(out, key);
      out.format(INFO_LABEL_BACKEND_TOOL_VALUE_FORMAT.get(value.length()) + " ");
      toHexDumpSingleLine(out, value);
    }
    else
    {
      out.format(INFO_LABEL_BACKEND_TOOL_KEY_FORMAT.get(key.length()) + "%n");
      toHexDumpWithAsciiCompact(key, options.get(DUMP_INDENT), out);
      out.format(INFO_LABEL_BACKEND_TOOL_VALUE_FORMAT.get(value.length()) + "%n");
      toHexDumpWithAsciiCompact(value, options.get(DUMP_INDENT), out);
    }
  }
 
  final void toHexDumpSingleLine(PrintStream out, ByteString data)
  {
    for (int i = 0; i < data.length(); i++)
    {
      out.format("%s", StaticUtils.byteToHex(data.byteAt(i)));
    }
    out.format("%n");
  }
 
  final void toHexDumpWithAsciiCompact(ByteString data, int indent, PrintStream out)
  {
    StringBuilder hexDump = new StringBuilder();
    StringBuilder indentBuilder = new StringBuilder();
    StringBuilder asciiDump = new StringBuilder();
    for (int i = 0; i < indent; i++)
    {
      indentBuilder.append(' ');
    }
    int pos = 0;
    while (pos < data.length())
    {
      byte val = data.byteAt(pos);
      hexDump.append(StaticUtils.byteToHex(val));
      hexDump.append(' ');
      asciiDump.append(val >= ' ' ? (char)val : ".");
      pos++;
      if (pos % 16 == 0)
      {
        out.format(HEXDUMP_LINE_FORMAT, indentBuilder.toString(), hexDump.toString(), asciiDump.toString());
        hexDump.setLength(0);
        asciiDump.setLength(0);
      }
    }
    while (pos % 16 != 0)
    {
      hexDump.append("   ");
      pos++;
    }
    out.format(HEXDUMP_LINE_FORMAT, indentBuilder.toString(), hexDump.toString(), asciiDump.toString());
  }
 
  private static Map<PluggableBackendCfg, BackendImpl> getPluggableBackends()
  {
    ArrayList<Backend> backendList = new ArrayList<>();
    ArrayList<BackendCfg> entryList = new ArrayList<>();
    ArrayList<List<DN>> dnList = new ArrayList<>();
    BackendToolUtils.getBackends(backendList, entryList, dnList);
 
    final Map<PluggableBackendCfg, BackendImpl> pluggableBackends = new LinkedHashMap<>();
    for (int i = 0; i < backendList.size(); i++)
    {
      Backend<?> backend = backendList.get(i);
      if (backend instanceof BackendImpl)
      {
        pluggableBackends.put((PluggableBackendCfg) entryList.get(i), (BackendImpl) backend);
      }
    }
    return pluggableBackends;
  }
}